Statistics
| Branch: | Revision:

root / vl.c @ bd9bdce6

History | View | Annotate | Download (224.1 kB)

1
/*
2
 * QEMU System Emulator
3
 *
4
 * Copyright (c) 2003-2007 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/fdc.h"
30
#include "hw/audiodev.h"
31
#include "hw/isa.h"
32
#include "net.h"
33
#include "console.h"
34
#include "sysemu.h"
35
#include "gdbstub.h"
36
#include "qemu-timer.h"
37
#include "qemu-char.h"
38
#include "block.h"
39
#include "audio/audio.h"
40

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

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

    
77
/* For the benefit of older linux systems which don't supply it,
78
   we use a local copy of hpet.h. */
79
/* #include <linux/hpet.h> */
80
#include "hpet.h"
81

    
82
#include <linux/ppdev.h>
83
#include <linux/parport.h>
84
#else
85
#include <sys/stat.h>
86
#include <sys/ethernet.h>
87
#include <sys/sockio.h>
88
#include <netinet/arp.h>
89
#include <netinet/in.h>
90
#include <netinet/in_systm.h>
91
#include <netinet/ip.h>
92
#include <netinet/ip_icmp.h> // must come after ip.h
93
#include <netinet/udp.h>
94
#include <netinet/tcp.h>
95
#include <net/if.h>
96
#include <syslog.h>
97
#include <stropts.h>
98
#endif
99
#endif
100
#else
101
#include <winsock2.h>
102
int inet_aton(const char *cp, struct in_addr *ia);
103
#endif
104

    
105
#if defined(CONFIG_SLIRP)
106
#include "libslirp.h"
107
#endif
108

    
109
#ifdef _WIN32
110
#include <malloc.h>
111
#include <sys/timeb.h>
112
#include <windows.h>
113
#define getopt_long_only getopt_long
114
#define memalign(align, size) malloc(size)
115
#endif
116

    
117
#include "qemu_socket.h"
118

    
119
#ifdef CONFIG_SDL
120
#ifdef __APPLE__
121
#include <SDL/SDL.h>
122
#endif
123
#endif /* CONFIG_SDL */
124

    
125
#ifdef CONFIG_COCOA
126
#undef main
127
#define main qemu_main
128
#endif /* CONFIG_COCOA */
129

    
130
#include "disas.h"
131

    
132
#include "exec-all.h"
133

    
134
#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
135
#define DEFAULT_NETWORK_DOWN_SCRIPT "/etc/qemu-ifdown"
136
#ifdef __sun__
137
#define SMBD_COMMAND "/usr/sfw/sbin/smbd"
138
#else
139
#define SMBD_COMMAND "/usr/sbin/smbd"
140
#endif
141

    
142
//#define DEBUG_UNUSED_IOPORT
143
//#define DEBUG_IOPORT
144

    
145
#define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
146

    
147
#ifdef TARGET_PPC
148
#define DEFAULT_RAM_SIZE 144
149
#else
150
#define DEFAULT_RAM_SIZE 128
151
#endif
152
/* in ms */
153
#define GUI_REFRESH_INTERVAL 30
154

    
155
/* Max number of USB devices that can be specified on the commandline.  */
156
#define MAX_USB_CMDLINE 8
157

    
158
/* XXX: use a two level table to limit memory usage */
159
#define MAX_IOPORTS 65536
160

    
161
const char *bios_dir = CONFIG_QEMU_SHAREDIR;
162
const char *bios_name = NULL;
163
void *ioport_opaque[MAX_IOPORTS];
164
IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
165
IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
166
/* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
167
   to store the VM snapshots */
168
BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
169
BlockDriverState *pflash_table[MAX_PFLASH];
170
BlockDriverState *sd_bdrv;
171
BlockDriverState *mtd_bdrv;
172
/* point to the block driver where the snapshots are managed */
173
BlockDriverState *bs_snapshots;
174
int vga_ram_size;
175
static DisplayState display_state;
176
int nographic;
177
const char* keyboard_layout = NULL;
178
int64_t ticks_per_sec;
179
int ram_size;
180
int pit_min_timer_count = 0;
181
int nb_nics;
182
NICInfo nd_table[MAX_NICS];
183
int vm_running;
184
int rtc_utc = 1;
185
int rtc_start_date = -1; /* -1 means now */
186
int cirrus_vga_enabled = 1;
187
int vmsvga_enabled = 0;
188
#ifdef TARGET_SPARC
189
int graphic_width = 1024;
190
int graphic_height = 768;
191
int graphic_depth = 8;
192
#else
193
int graphic_width = 800;
194
int graphic_height = 600;
195
int graphic_depth = 15;
196
#endif
197
int full_screen = 0;
198
int no_frame = 0;
199
int no_quit = 0;
200
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
201
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
202
#ifdef TARGET_I386
203
int win2k_install_hack = 0;
204
#endif
205
int usb_enabled = 0;
206
static VLANState *first_vlan;
207
int smp_cpus = 1;
208
const char *vnc_display;
209
#if defined(TARGET_SPARC)
210
#define MAX_CPUS 16
211
#elif defined(TARGET_I386)
212
#define MAX_CPUS 255
213
#else
214
#define MAX_CPUS 1
215
#endif
216
int acpi_enabled = 1;
217
int fd_bootchk = 1;
218
int no_reboot = 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
int autostart = 1;
226
#ifdef TARGET_ARM
227
int old_param = 0;
228
#endif
229
const char *qemu_name;
230
int alt_grab = 0;
231
#ifdef TARGET_SPARC
232
unsigned int nb_prom_envs = 0;
233
const char *prom_envs[MAX_PROM_ENVS];
234
#endif
235

    
236
#define TFR(expr) do { if ((expr) != -1) break; } while (errno == EINTR)
237

    
238
/***********************************************************/
239
/* x86 ISA bus support */
240

    
241
target_phys_addr_t isa_mem_base = 0;
242
PicState2 *isa_pic;
243

    
244
static uint32_t default_ioport_readb(void *opaque, uint32_t address)
245
{
246
#ifdef DEBUG_UNUSED_IOPORT
247
    fprintf(stderr, "unused inb: port=0x%04x\n", address);
248
#endif
249
    return 0xff;
250
}
251

    
252
static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
253
{
254
#ifdef DEBUG_UNUSED_IOPORT
255
    fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
256
#endif
257
}
258

    
259
/* default is to make two byte accesses */
260
static uint32_t default_ioport_readw(void *opaque, uint32_t address)
261
{
262
    uint32_t data;
263
    data = ioport_read_table[0][address](ioport_opaque[address], address);
264
    address = (address + 1) & (MAX_IOPORTS - 1);
265
    data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
266
    return data;
267
}
268

    
269
static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
270
{
271
    ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
272
    address = (address + 1) & (MAX_IOPORTS - 1);
273
    ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
274
}
275

    
276
static uint32_t default_ioport_readl(void *opaque, uint32_t address)
277
{
278
#ifdef DEBUG_UNUSED_IOPORT
279
    fprintf(stderr, "unused inl: port=0x%04x\n", address);
280
#endif
281
    return 0xffffffff;
282
}
283

    
284
static void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
285
{
286
#ifdef DEBUG_UNUSED_IOPORT
287
    fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
288
#endif
289
}
290

    
291
static void init_ioports(void)
292
{
293
    int i;
294

    
295
    for(i = 0; i < MAX_IOPORTS; i++) {
296
        ioport_read_table[0][i] = default_ioport_readb;
297
        ioport_write_table[0][i] = default_ioport_writeb;
298
        ioport_read_table[1][i] = default_ioport_readw;
299
        ioport_write_table[1][i] = default_ioport_writew;
300
        ioport_read_table[2][i] = default_ioport_readl;
301
        ioport_write_table[2][i] = default_ioport_writel;
302
    }
303
}
304

    
305
/* size is the word size in byte */
306
int register_ioport_read(int start, int length, int size,
307
                         IOPortReadFunc *func, void *opaque)
308
{
309
    int i, bsize;
310

    
311
    if (size == 1) {
312
        bsize = 0;
313
    } else if (size == 2) {
314
        bsize = 1;
315
    } else if (size == 4) {
316
        bsize = 2;
317
    } else {
318
        hw_error("register_ioport_read: invalid size");
319
        return -1;
320
    }
321
    for(i = start; i < start + length; i += size) {
322
        ioport_read_table[bsize][i] = func;
323
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
324
            hw_error("register_ioport_read: invalid opaque");
325
        ioport_opaque[i] = opaque;
326
    }
327
    return 0;
328
}
329

    
330
/* size is the word size in byte */
331
int register_ioport_write(int start, int length, int size,
332
                          IOPortWriteFunc *func, void *opaque)
333
{
334
    int i, bsize;
335

    
336
    if (size == 1) {
337
        bsize = 0;
338
    } else if (size == 2) {
339
        bsize = 1;
340
    } else if (size == 4) {
341
        bsize = 2;
342
    } else {
343
        hw_error("register_ioport_write: invalid size");
344
        return -1;
345
    }
346
    for(i = start; i < start + length; i += size) {
347
        ioport_write_table[bsize][i] = func;
348
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
349
            hw_error("register_ioport_write: invalid opaque");
350
        ioport_opaque[i] = opaque;
351
    }
352
    return 0;
353
}
354

    
355
void isa_unassign_ioport(int start, int length)
356
{
357
    int i;
358

    
359
    for(i = start; i < start + length; i++) {
360
        ioport_read_table[0][i] = default_ioport_readb;
361
        ioport_read_table[1][i] = default_ioport_readw;
362
        ioport_read_table[2][i] = default_ioport_readl;
363

    
364
        ioport_write_table[0][i] = default_ioport_writeb;
365
        ioport_write_table[1][i] = default_ioport_writew;
366
        ioport_write_table[2][i] = default_ioport_writel;
367
    }
368
}
369

    
370
/***********************************************************/
371

    
372
void cpu_outb(CPUState *env, int addr, int val)
373
{
374
#ifdef DEBUG_IOPORT
375
    if (loglevel & CPU_LOG_IOPORT)
376
        fprintf(logfile, "outb: %04x %02x\n", addr, val);
377
#endif
378
    ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
379
#ifdef USE_KQEMU
380
    if (env)
381
        env->last_io_time = cpu_get_time_fast();
382
#endif
383
}
384

    
385
void cpu_outw(CPUState *env, int addr, int val)
386
{
387
#ifdef DEBUG_IOPORT
388
    if (loglevel & CPU_LOG_IOPORT)
389
        fprintf(logfile, "outw: %04x %04x\n", addr, val);
390
#endif
391
    ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
392
#ifdef USE_KQEMU
393
    if (env)
394
        env->last_io_time = cpu_get_time_fast();
395
#endif
396
}
397

    
398
void cpu_outl(CPUState *env, int addr, int val)
399
{
400
#ifdef DEBUG_IOPORT
401
    if (loglevel & CPU_LOG_IOPORT)
402
        fprintf(logfile, "outl: %04x %08x\n", addr, val);
403
#endif
404
    ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
405
#ifdef USE_KQEMU
406
    if (env)
407
        env->last_io_time = cpu_get_time_fast();
408
#endif
409
}
410

    
411
int cpu_inb(CPUState *env, int addr)
412
{
413
    int val;
414
    val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
415
#ifdef DEBUG_IOPORT
416
    if (loglevel & CPU_LOG_IOPORT)
417
        fprintf(logfile, "inb : %04x %02x\n", addr, val);
418
#endif
419
#ifdef USE_KQEMU
420
    if (env)
421
        env->last_io_time = cpu_get_time_fast();
422
#endif
423
    return val;
424
}
425

    
426
int cpu_inw(CPUState *env, int addr)
427
{
428
    int val;
429
    val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
430
#ifdef DEBUG_IOPORT
431
    if (loglevel & CPU_LOG_IOPORT)
432
        fprintf(logfile, "inw : %04x %04x\n", addr, val);
433
#endif
434
#ifdef USE_KQEMU
435
    if (env)
436
        env->last_io_time = cpu_get_time_fast();
437
#endif
438
    return val;
439
}
440

    
441
int cpu_inl(CPUState *env, int addr)
442
{
443
    int val;
444
    val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
445
#ifdef DEBUG_IOPORT
446
    if (loglevel & CPU_LOG_IOPORT)
447
        fprintf(logfile, "inl : %04x %08x\n", addr, val);
448
#endif
449
#ifdef USE_KQEMU
450
    if (env)
451
        env->last_io_time = cpu_get_time_fast();
452
#endif
453
    return val;
454
}
455

    
456
/***********************************************************/
457
void hw_error(const char *fmt, ...)
458
{
459
    va_list ap;
460
    CPUState *env;
461

    
462
    va_start(ap, fmt);
463
    fprintf(stderr, "qemu: hardware error: ");
464
    vfprintf(stderr, fmt, ap);
465
    fprintf(stderr, "\n");
466
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
467
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
468
#ifdef TARGET_I386
469
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
470
#else
471
        cpu_dump_state(env, stderr, fprintf, 0);
472
#endif
473
    }
474
    va_end(ap);
475
    abort();
476
}
477

    
478
/***********************************************************/
479
/* keyboard/mouse */
480

    
481
static QEMUPutKBDEvent *qemu_put_kbd_event;
482
static void *qemu_put_kbd_event_opaque;
483
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
484
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
485

    
486
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
487
{
488
    qemu_put_kbd_event_opaque = opaque;
489
    qemu_put_kbd_event = func;
490
}
491

    
492
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
493
                                                void *opaque, int absolute,
494
                                                const char *name)
495
{
496
    QEMUPutMouseEntry *s, *cursor;
497

    
498
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
499
    if (!s)
500
        return NULL;
501

    
502
    s->qemu_put_mouse_event = func;
503
    s->qemu_put_mouse_event_opaque = opaque;
504
    s->qemu_put_mouse_event_absolute = absolute;
505
    s->qemu_put_mouse_event_name = qemu_strdup(name);
506
    s->next = NULL;
507

    
508
    if (!qemu_put_mouse_event_head) {
509
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
510
        return s;
511
    }
512

    
513
    cursor = qemu_put_mouse_event_head;
514
    while (cursor->next != NULL)
515
        cursor = cursor->next;
516

    
517
    cursor->next = s;
518
    qemu_put_mouse_event_current = s;
519

    
520
    return s;
521
}
522

    
523
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
524
{
525
    QEMUPutMouseEntry *prev = NULL, *cursor;
526

    
527
    if (!qemu_put_mouse_event_head || entry == NULL)
528
        return;
529

    
530
    cursor = qemu_put_mouse_event_head;
531
    while (cursor != NULL && cursor != entry) {
532
        prev = cursor;
533
        cursor = cursor->next;
534
    }
535

    
536
    if (cursor == NULL) // does not exist or list empty
537
        return;
538
    else if (prev == NULL) { // entry is head
539
        qemu_put_mouse_event_head = cursor->next;
540
        if (qemu_put_mouse_event_current == entry)
541
            qemu_put_mouse_event_current = cursor->next;
542
        qemu_free(entry->qemu_put_mouse_event_name);
543
        qemu_free(entry);
544
        return;
545
    }
546

    
547
    prev->next = entry->next;
548

    
549
    if (qemu_put_mouse_event_current == entry)
550
        qemu_put_mouse_event_current = prev;
551

    
552
    qemu_free(entry->qemu_put_mouse_event_name);
553
    qemu_free(entry);
554
}
555

    
556
void kbd_put_keycode(int keycode)
557
{
558
    if (qemu_put_kbd_event) {
559
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
560
    }
561
}
562

    
563
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
564
{
565
    QEMUPutMouseEvent *mouse_event;
566
    void *mouse_event_opaque;
567
    int width;
568

    
569
    if (!qemu_put_mouse_event_current) {
570
        return;
571
    }
572

    
573
    mouse_event =
574
        qemu_put_mouse_event_current->qemu_put_mouse_event;
575
    mouse_event_opaque =
576
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
577

    
578
    if (mouse_event) {
579
        if (graphic_rotate) {
580
            if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
581
                width = 0x7fff;
582
            else
583
                width = graphic_width;
584
            mouse_event(mouse_event_opaque,
585
                                 width - dy, dx, dz, buttons_state);
586
        } else
587
            mouse_event(mouse_event_opaque,
588
                                 dx, dy, dz, buttons_state);
589
    }
590
}
591

    
592
int kbd_mouse_is_absolute(void)
593
{
594
    if (!qemu_put_mouse_event_current)
595
        return 0;
596

    
597
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
598
}
599

    
600
void do_info_mice(void)
601
{
602
    QEMUPutMouseEntry *cursor;
603
    int index = 0;
604

    
605
    if (!qemu_put_mouse_event_head) {
606
        term_printf("No mouse devices connected\n");
607
        return;
608
    }
609

    
610
    term_printf("Mouse devices available:\n");
611
    cursor = qemu_put_mouse_event_head;
612
    while (cursor != NULL) {
613
        term_printf("%c Mouse #%d: %s\n",
614
                    (cursor == qemu_put_mouse_event_current ? '*' : ' '),
615
                    index, cursor->qemu_put_mouse_event_name);
616
        index++;
617
        cursor = cursor->next;
618
    }
619
}
620

    
621
void do_mouse_set(int index)
622
{
623
    QEMUPutMouseEntry *cursor;
624
    int i = 0;
625

    
626
    if (!qemu_put_mouse_event_head) {
627
        term_printf("No mouse devices connected\n");
628
        return;
629
    }
630

    
631
    cursor = qemu_put_mouse_event_head;
632
    while (cursor != NULL && index != i) {
633
        i++;
634
        cursor = cursor->next;
635
    }
636

    
637
    if (cursor != NULL)
638
        qemu_put_mouse_event_current = cursor;
639
    else
640
        term_printf("Mouse at given index not found\n");
641
}
642

    
643
/* compute with 96 bit intermediate result: (a*b)/c */
644
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
645
{
646
    union {
647
        uint64_t ll;
648
        struct {
649
#ifdef WORDS_BIGENDIAN
650
            uint32_t high, low;
651
#else
652
            uint32_t low, high;
653
#endif
654
        } l;
655
    } u, res;
656
    uint64_t rl, rh;
657

    
658
    u.ll = a;
659
    rl = (uint64_t)u.l.low * (uint64_t)b;
660
    rh = (uint64_t)u.l.high * (uint64_t)b;
661
    rh += (rl >> 32);
662
    res.l.high = rh / c;
663
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
664
    return res.ll;
665
}
666

    
667
/***********************************************************/
668
/* real time host monotonic timer */
669

    
670
#define QEMU_TIMER_BASE 1000000000LL
671

    
672
#ifdef WIN32
673

    
674
static int64_t clock_freq;
675

    
676
static void init_get_clock(void)
677
{
678
    LARGE_INTEGER freq;
679
    int ret;
680
    ret = QueryPerformanceFrequency(&freq);
681
    if (ret == 0) {
682
        fprintf(stderr, "Could not calibrate ticks\n");
683
        exit(1);
684
    }
685
    clock_freq = freq.QuadPart;
686
}
687

    
688
static int64_t get_clock(void)
689
{
690
    LARGE_INTEGER ti;
691
    QueryPerformanceCounter(&ti);
692
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
693
}
694

    
695
#else
696

    
697
static int use_rt_clock;
698

    
699
static void init_get_clock(void)
700
{
701
    use_rt_clock = 0;
702
#if defined(__linux__)
703
    {
704
        struct timespec ts;
705
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
706
            use_rt_clock = 1;
707
        }
708
    }
709
#endif
710
}
711

    
712
static int64_t get_clock(void)
713
{
714
#if defined(__linux__)
715
    if (use_rt_clock) {
716
        struct timespec ts;
717
        clock_gettime(CLOCK_MONOTONIC, &ts);
718
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
719
    } else
720
#endif
721
    {
722
        /* XXX: using gettimeofday leads to problems if the date
723
           changes, so it should be avoided. */
724
        struct timeval tv;
725
        gettimeofday(&tv, NULL);
726
        return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
727
    }
728
}
729

    
730
#endif
731

    
732
/***********************************************************/
733
/* guest cycle counter */
734

    
735
static int64_t cpu_ticks_prev;
736
static int64_t cpu_ticks_offset;
737
static int64_t cpu_clock_offset;
738
static int cpu_ticks_enabled;
739

    
740
/* return the host CPU cycle counter and handle stop/restart */
741
int64_t cpu_get_ticks(void)
742
{
743
    if (!cpu_ticks_enabled) {
744
        return cpu_ticks_offset;
745
    } else {
746
        int64_t ticks;
747
        ticks = cpu_get_real_ticks();
748
        if (cpu_ticks_prev > ticks) {
749
            /* Note: non increasing ticks may happen if the host uses
750
               software suspend */
751
            cpu_ticks_offset += cpu_ticks_prev - ticks;
752
        }
753
        cpu_ticks_prev = ticks;
754
        return ticks + cpu_ticks_offset;
755
    }
756
}
757

    
758
/* return the host CPU monotonic timer and handle stop/restart */
759
static int64_t cpu_get_clock(void)
760
{
761
    int64_t ti;
762
    if (!cpu_ticks_enabled) {
763
        return cpu_clock_offset;
764
    } else {
765
        ti = get_clock();
766
        return ti + cpu_clock_offset;
767
    }
768
}
769

    
770
/* enable cpu_get_ticks() */
771
void cpu_enable_ticks(void)
772
{
773
    if (!cpu_ticks_enabled) {
774
        cpu_ticks_offset -= cpu_get_real_ticks();
775
        cpu_clock_offset -= get_clock();
776
        cpu_ticks_enabled = 1;
777
    }
778
}
779

    
780
/* disable cpu_get_ticks() : the clock is stopped. You must not call
781
   cpu_get_ticks() after that.  */
782
void cpu_disable_ticks(void)
783
{
784
    if (cpu_ticks_enabled) {
785
        cpu_ticks_offset = cpu_get_ticks();
786
        cpu_clock_offset = cpu_get_clock();
787
        cpu_ticks_enabled = 0;
788
    }
789
}
790

    
791
/***********************************************************/
792
/* timers */
793

    
794
#define QEMU_TIMER_REALTIME 0
795
#define QEMU_TIMER_VIRTUAL  1
796

    
797
struct QEMUClock {
798
    int type;
799
    /* XXX: add frequency */
800
};
801

    
802
struct QEMUTimer {
803
    QEMUClock *clock;
804
    int64_t expire_time;
805
    QEMUTimerCB *cb;
806
    void *opaque;
807
    struct QEMUTimer *next;
808
};
809

    
810
struct qemu_alarm_timer {
811
    char const *name;
812
    unsigned int flags;
813

    
814
    int (*start)(struct qemu_alarm_timer *t);
815
    void (*stop)(struct qemu_alarm_timer *t);
816
    void (*rearm)(struct qemu_alarm_timer *t);
817
    void *priv;
818
};
819

    
820
#define ALARM_FLAG_DYNTICKS  0x1
821

    
822
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
823
{
824
    return t->flags & ALARM_FLAG_DYNTICKS;
825
}
826

    
827
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
828
{
829
    if (!alarm_has_dynticks(t))
830
        return;
831

    
832
    t->rearm(t);
833
}
834

    
835
/* TODO: MIN_TIMER_REARM_US should be optimized */
836
#define MIN_TIMER_REARM_US 250
837

    
838
static struct qemu_alarm_timer *alarm_timer;
839

    
840
#ifdef _WIN32
841

    
842
struct qemu_alarm_win32 {
843
    MMRESULT timerId;
844
    HANDLE host_alarm;
845
    unsigned int period;
846
} alarm_win32_data = {0, NULL, -1};
847

    
848
static int win32_start_timer(struct qemu_alarm_timer *t);
849
static void win32_stop_timer(struct qemu_alarm_timer *t);
850
static void win32_rearm_timer(struct qemu_alarm_timer *t);
851

    
852
#else
853

    
854
static int unix_start_timer(struct qemu_alarm_timer *t);
855
static void unix_stop_timer(struct qemu_alarm_timer *t);
856

    
857
#ifdef __linux__
858

    
859
static int dynticks_start_timer(struct qemu_alarm_timer *t);
860
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
861
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
862

    
863
static int hpet_start_timer(struct qemu_alarm_timer *t);
864
static void hpet_stop_timer(struct qemu_alarm_timer *t);
865

    
866
static int rtc_start_timer(struct qemu_alarm_timer *t);
867
static void rtc_stop_timer(struct qemu_alarm_timer *t);
868

    
869
#endif /* __linux__ */
870

    
871
#endif /* _WIN32 */
872

    
873
static struct qemu_alarm_timer alarm_timers[] = {
874
#ifndef _WIN32
875
#ifdef __linux__
876
    {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
877
     dynticks_stop_timer, dynticks_rearm_timer, NULL},
878
    /* HPET - if available - is preferred */
879
    {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
880
    /* ...otherwise try RTC */
881
    {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
882
#endif
883
    {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
884
#else
885
    {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
886
     win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
887
    {"win32", 0, win32_start_timer,
888
     win32_stop_timer, NULL, &alarm_win32_data},
889
#endif
890
    {NULL, }
891
};
892

    
893
static void show_available_alarms()
894
{
895
    int i;
896

    
897
    printf("Available alarm timers, in order of precedence:\n");
898
    for (i = 0; alarm_timers[i].name; i++)
899
        printf("%s\n", alarm_timers[i].name);
900
}
901

    
902
static void configure_alarms(char const *opt)
903
{
904
    int i;
905
    int cur = 0;
906
    int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
907
    char *arg;
908
    char *name;
909

    
910
    if (!strcmp(opt, "help")) {
911
        show_available_alarms();
912
        exit(0);
913
    }
914

    
915
    arg = strdup(opt);
916

    
917
    /* Reorder the array */
918
    name = strtok(arg, ",");
919
    while (name) {
920
        struct qemu_alarm_timer tmp;
921

    
922
        for (i = 0; i < count && alarm_timers[i].name; i++) {
923
            if (!strcmp(alarm_timers[i].name, name))
924
                break;
925
        }
926

    
927
        if (i == count) {
928
            fprintf(stderr, "Unknown clock %s\n", name);
929
            goto next;
930
        }
931

    
932
        if (i < cur)
933
            /* Ignore */
934
            goto next;
935

    
936
        /* Swap */
937
        tmp = alarm_timers[i];
938
        alarm_timers[i] = alarm_timers[cur];
939
        alarm_timers[cur] = tmp;
940

    
941
        cur++;
942
next:
943
        name = strtok(NULL, ",");
944
    }
945

    
946
    free(arg);
947

    
948
    if (cur) {
949
        /* Disable remaining timers */
950
        for (i = cur; i < count; i++)
951
            alarm_timers[i].name = NULL;
952
    }
953

    
954
    /* debug */
955
    show_available_alarms();
956
}
957

    
958
QEMUClock *rt_clock;
959
QEMUClock *vm_clock;
960

    
961
static QEMUTimer *active_timers[2];
962

    
963
static QEMUClock *qemu_new_clock(int type)
964
{
965
    QEMUClock *clock;
966
    clock = qemu_mallocz(sizeof(QEMUClock));
967
    if (!clock)
968
        return NULL;
969
    clock->type = type;
970
    return clock;
971
}
972

    
973
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
974
{
975
    QEMUTimer *ts;
976

    
977
    ts = qemu_mallocz(sizeof(QEMUTimer));
978
    ts->clock = clock;
979
    ts->cb = cb;
980
    ts->opaque = opaque;
981
    return ts;
982
}
983

    
984
void qemu_free_timer(QEMUTimer *ts)
985
{
986
    qemu_free(ts);
987
}
988

    
989
/* stop a timer, but do not dealloc it */
990
void qemu_del_timer(QEMUTimer *ts)
991
{
992
    QEMUTimer **pt, *t;
993

    
994
    /* NOTE: this code must be signal safe because
995
       qemu_timer_expired() can be called from a signal. */
996
    pt = &active_timers[ts->clock->type];
997
    for(;;) {
998
        t = *pt;
999
        if (!t)
1000
            break;
1001
        if (t == ts) {
1002
            *pt = t->next;
1003
            break;
1004
        }
1005
        pt = &t->next;
1006
    }
1007
}
1008

    
1009
/* modify the current timer so that it will be fired when current_time
1010
   >= expire_time. The corresponding callback will be called. */
1011
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1012
{
1013
    QEMUTimer **pt, *t;
1014

    
1015
    qemu_del_timer(ts);
1016

    
1017
    /* add the timer in the sorted list */
1018
    /* NOTE: this code must be signal safe because
1019
       qemu_timer_expired() can be called from a signal. */
1020
    pt = &active_timers[ts->clock->type];
1021
    for(;;) {
1022
        t = *pt;
1023
        if (!t)
1024
            break;
1025
        if (t->expire_time > expire_time)
1026
            break;
1027
        pt = &t->next;
1028
    }
1029
    ts->expire_time = expire_time;
1030
    ts->next = *pt;
1031
    *pt = ts;
1032
}
1033

    
1034
int qemu_timer_pending(QEMUTimer *ts)
1035
{
1036
    QEMUTimer *t;
1037
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1038
        if (t == ts)
1039
            return 1;
1040
    }
1041
    return 0;
1042
}
1043

    
1044
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1045
{
1046
    if (!timer_head)
1047
        return 0;
1048
    return (timer_head->expire_time <= current_time);
1049
}
1050

    
1051
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1052
{
1053
    QEMUTimer *ts;
1054

    
1055
    for(;;) {
1056
        ts = *ptimer_head;
1057
        if (!ts || ts->expire_time > current_time)
1058
            break;
1059
        /* remove timer from the list before calling the callback */
1060
        *ptimer_head = ts->next;
1061
        ts->next = NULL;
1062

    
1063
        /* run the callback (the timer list can be modified) */
1064
        ts->cb(ts->opaque);
1065
    }
1066
    qemu_rearm_alarm_timer(alarm_timer);
1067
}
1068

    
1069
int64_t qemu_get_clock(QEMUClock *clock)
1070
{
1071
    switch(clock->type) {
1072
    case QEMU_TIMER_REALTIME:
1073
        return get_clock() / 1000000;
1074
    default:
1075
    case QEMU_TIMER_VIRTUAL:
1076
        return cpu_get_clock();
1077
    }
1078
}
1079

    
1080
static void init_timers(void)
1081
{
1082
    init_get_clock();
1083
    ticks_per_sec = QEMU_TIMER_BASE;
1084
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1085
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1086
}
1087

    
1088
/* save a timer */
1089
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1090
{
1091
    uint64_t expire_time;
1092

    
1093
    if (qemu_timer_pending(ts)) {
1094
        expire_time = ts->expire_time;
1095
    } else {
1096
        expire_time = -1;
1097
    }
1098
    qemu_put_be64(f, expire_time);
1099
}
1100

    
1101
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1102
{
1103
    uint64_t expire_time;
1104

    
1105
    expire_time = qemu_get_be64(f);
1106
    if (expire_time != -1) {
1107
        qemu_mod_timer(ts, expire_time);
1108
    } else {
1109
        qemu_del_timer(ts);
1110
    }
1111
}
1112

    
1113
static void timer_save(QEMUFile *f, void *opaque)
1114
{
1115
    if (cpu_ticks_enabled) {
1116
        hw_error("cannot save state if virtual timers are running");
1117
    }
1118
    qemu_put_be64s(f, &cpu_ticks_offset);
1119
    qemu_put_be64s(f, &ticks_per_sec);
1120
    qemu_put_be64s(f, &cpu_clock_offset);
1121
}
1122

    
1123
static int timer_load(QEMUFile *f, void *opaque, int version_id)
1124
{
1125
    if (version_id != 1 && version_id != 2)
1126
        return -EINVAL;
1127
    if (cpu_ticks_enabled) {
1128
        return -EINVAL;
1129
    }
1130
    qemu_get_be64s(f, &cpu_ticks_offset);
1131
    qemu_get_be64s(f, &ticks_per_sec);
1132
    if (version_id == 2) {
1133
        qemu_get_be64s(f, &cpu_clock_offset);
1134
    }
1135
    return 0;
1136
}
1137

    
1138
#ifdef _WIN32
1139
void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1140
                                 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1141
#else
1142
static void host_alarm_handler(int host_signum)
1143
#endif
1144
{
1145
#if 0
1146
#define DISP_FREQ 1000
1147
    {
1148
        static int64_t delta_min = INT64_MAX;
1149
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
1150
        static int count;
1151
        ti = qemu_get_clock(vm_clock);
1152
        if (last_clock != 0) {
1153
            delta = ti - last_clock;
1154
            if (delta < delta_min)
1155
                delta_min = delta;
1156
            if (delta > delta_max)
1157
                delta_max = delta;
1158
            delta_cum += delta;
1159
            if (++count == DISP_FREQ) {
1160
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1161
                       muldiv64(delta_min, 1000000, ticks_per_sec),
1162
                       muldiv64(delta_max, 1000000, ticks_per_sec),
1163
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1164
                       (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1165
                count = 0;
1166
                delta_min = INT64_MAX;
1167
                delta_max = 0;
1168
                delta_cum = 0;
1169
            }
1170
        }
1171
        last_clock = ti;
1172
    }
1173
#endif
1174
    if (alarm_has_dynticks(alarm_timer) ||
1175
        qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1176
                           qemu_get_clock(vm_clock)) ||
1177
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1178
                           qemu_get_clock(rt_clock))) {
1179
#ifdef _WIN32
1180
        struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1181
        SetEvent(data->host_alarm);
1182
#endif
1183
        CPUState *env = cpu_single_env;
1184
        if (env) {
1185
            /* stop the currently executing cpu because a timer occured */
1186
            cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1187
#ifdef USE_KQEMU
1188
            if (env->kqemu_enabled) {
1189
                kqemu_cpu_interrupt(env);
1190
            }
1191
#endif
1192
        }
1193
    }
1194
}
1195

    
1196
static uint64_t qemu_next_deadline(void)
1197
{
1198
    int64_t nearest_delta_us = INT64_MAX;
1199
    int64_t vmdelta_us;
1200

    
1201
    if (active_timers[QEMU_TIMER_REALTIME])
1202
        nearest_delta_us = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1203
                            qemu_get_clock(rt_clock))*1000;
1204

    
1205
    if (active_timers[QEMU_TIMER_VIRTUAL]) {
1206
        /* round up */
1207
        vmdelta_us = (active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1208
                      qemu_get_clock(vm_clock)+999)/1000;
1209
        if (vmdelta_us < nearest_delta_us)
1210
            nearest_delta_us = vmdelta_us;
1211
    }
1212

    
1213
    /* Avoid arming the timer to negative, zero, or too low values */
1214
    if (nearest_delta_us <= MIN_TIMER_REARM_US)
1215
        nearest_delta_us = MIN_TIMER_REARM_US;
1216

    
1217
    return nearest_delta_us;
1218
}
1219

    
1220
#ifndef _WIN32
1221

    
1222
#if defined(__linux__)
1223

    
1224
#define RTC_FREQ 1024
1225

    
1226
static void enable_sigio_timer(int fd)
1227
{
1228
    struct sigaction act;
1229

    
1230
    /* timer signal */
1231
    sigfillset(&act.sa_mask);
1232
    act.sa_flags = 0;
1233
    act.sa_handler = host_alarm_handler;
1234

    
1235
    sigaction(SIGIO, &act, NULL);
1236
    fcntl(fd, F_SETFL, O_ASYNC);
1237
    fcntl(fd, F_SETOWN, getpid());
1238
}
1239

    
1240
static int hpet_start_timer(struct qemu_alarm_timer *t)
1241
{
1242
    struct hpet_info info;
1243
    int r, fd;
1244

    
1245
    fd = open("/dev/hpet", O_RDONLY);
1246
    if (fd < 0)
1247
        return -1;
1248

    
1249
    /* Set frequency */
1250
    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1251
    if (r < 0) {
1252
        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1253
                "error, but for better emulation accuracy type:\n"
1254
                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1255
        goto fail;
1256
    }
1257

    
1258
    /* Check capabilities */
1259
    r = ioctl(fd, HPET_INFO, &info);
1260
    if (r < 0)
1261
        goto fail;
1262

    
1263
    /* Enable periodic mode */
1264
    r = ioctl(fd, HPET_EPI, 0);
1265
    if (info.hi_flags && (r < 0))
1266
        goto fail;
1267

    
1268
    /* Enable interrupt */
1269
    r = ioctl(fd, HPET_IE_ON, 0);
1270
    if (r < 0)
1271
        goto fail;
1272

    
1273
    enable_sigio_timer(fd);
1274
    t->priv = (void *)(long)fd;
1275

    
1276
    return 0;
1277
fail:
1278
    close(fd);
1279
    return -1;
1280
}
1281

    
1282
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1283
{
1284
    int fd = (long)t->priv;
1285

    
1286
    close(fd);
1287
}
1288

    
1289
static int rtc_start_timer(struct qemu_alarm_timer *t)
1290
{
1291
    int rtc_fd;
1292

    
1293
    TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1294
    if (rtc_fd < 0)
1295
        return -1;
1296
    if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1297
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1298
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1299
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1300
        goto fail;
1301
    }
1302
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1303
    fail:
1304
        close(rtc_fd);
1305
        return -1;
1306
    }
1307

    
1308
    enable_sigio_timer(rtc_fd);
1309

    
1310
    t->priv = (void *)(long)rtc_fd;
1311

    
1312
    return 0;
1313
}
1314

    
1315
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1316
{
1317
    int rtc_fd = (long)t->priv;
1318

    
1319
    close(rtc_fd);
1320
}
1321

    
1322
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1323
{
1324
    struct sigevent ev;
1325
    timer_t host_timer;
1326
    struct sigaction act;
1327

    
1328
    sigfillset(&act.sa_mask);
1329
    act.sa_flags = 0;
1330
    act.sa_handler = host_alarm_handler;
1331

    
1332
    sigaction(SIGALRM, &act, NULL);
1333

    
1334
    ev.sigev_value.sival_int = 0;
1335
    ev.sigev_notify = SIGEV_SIGNAL;
1336
    ev.sigev_signo = SIGALRM;
1337

    
1338
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1339
        perror("timer_create");
1340

    
1341
        /* disable dynticks */
1342
        fprintf(stderr, "Dynamic Ticks disabled\n");
1343

    
1344
        return -1;
1345
    }
1346

    
1347
    t->priv = (void *)host_timer;
1348

    
1349
    return 0;
1350
}
1351

    
1352
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1353
{
1354
    timer_t host_timer = (timer_t)t->priv;
1355

    
1356
    timer_delete(host_timer);
1357
}
1358

    
1359
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1360
{
1361
    timer_t host_timer = (timer_t)t->priv;
1362
    struct itimerspec timeout;
1363
    int64_t nearest_delta_us = INT64_MAX;
1364
    int64_t current_us;
1365

    
1366
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1367
                !active_timers[QEMU_TIMER_VIRTUAL])
1368
            return;
1369

    
1370
    nearest_delta_us = qemu_next_deadline();
1371

    
1372
    /* check whether a timer is already running */
1373
    if (timer_gettime(host_timer, &timeout)) {
1374
        perror("gettime");
1375
        fprintf(stderr, "Internal timer error: aborting\n");
1376
        exit(1);
1377
    }
1378
    current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1379
    if (current_us && current_us <= nearest_delta_us)
1380
        return;
1381

    
1382
    timeout.it_interval.tv_sec = 0;
1383
    timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1384
    timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
1385
    timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1386
    if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1387
        perror("settime");
1388
        fprintf(stderr, "Internal timer error: aborting\n");
1389
        exit(1);
1390
    }
1391
}
1392

    
1393
#endif /* defined(__linux__) */
1394

    
1395
static int unix_start_timer(struct qemu_alarm_timer *t)
1396
{
1397
    struct sigaction act;
1398
    struct itimerval itv;
1399
    int err;
1400

    
1401
    /* timer signal */
1402
    sigfillset(&act.sa_mask);
1403
    act.sa_flags = 0;
1404
    act.sa_handler = host_alarm_handler;
1405

    
1406
    sigaction(SIGALRM, &act, NULL);
1407

    
1408
    itv.it_interval.tv_sec = 0;
1409
    /* for i386 kernel 2.6 to get 1 ms */
1410
    itv.it_interval.tv_usec = 999;
1411
    itv.it_value.tv_sec = 0;
1412
    itv.it_value.tv_usec = 10 * 1000;
1413

    
1414
    err = setitimer(ITIMER_REAL, &itv, NULL);
1415
    if (err)
1416
        return -1;
1417

    
1418
    return 0;
1419
}
1420

    
1421
static void unix_stop_timer(struct qemu_alarm_timer *t)
1422
{
1423
    struct itimerval itv;
1424

    
1425
    memset(&itv, 0, sizeof(itv));
1426
    setitimer(ITIMER_REAL, &itv, NULL);
1427
}
1428

    
1429
#endif /* !defined(_WIN32) */
1430

    
1431
#ifdef _WIN32
1432

    
1433
static int win32_start_timer(struct qemu_alarm_timer *t)
1434
{
1435
    TIMECAPS tc;
1436
    struct qemu_alarm_win32 *data = t->priv;
1437
    UINT flags;
1438

    
1439
    data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1440
    if (!data->host_alarm) {
1441
        perror("Failed CreateEvent");
1442
        return -1;
1443
    }
1444

    
1445
    memset(&tc, 0, sizeof(tc));
1446
    timeGetDevCaps(&tc, sizeof(tc));
1447

    
1448
    if (data->period < tc.wPeriodMin)
1449
        data->period = tc.wPeriodMin;
1450

    
1451
    timeBeginPeriod(data->period);
1452

    
1453
    flags = TIME_CALLBACK_FUNCTION;
1454
    if (alarm_has_dynticks(t))
1455
        flags |= TIME_ONESHOT;
1456
    else
1457
        flags |= TIME_PERIODIC;
1458

    
1459
    data->timerId = timeSetEvent(1,         // interval (ms)
1460
                        data->period,       // resolution
1461
                        host_alarm_handler, // function
1462
                        (DWORD)t,           // parameter
1463
                        flags);
1464

    
1465
    if (!data->timerId) {
1466
        perror("Failed to initialize win32 alarm timer");
1467

    
1468
        timeEndPeriod(data->period);
1469
        CloseHandle(data->host_alarm);
1470
        return -1;
1471
    }
1472

    
1473
    qemu_add_wait_object(data->host_alarm, NULL, NULL);
1474

    
1475
    return 0;
1476
}
1477

    
1478
static void win32_stop_timer(struct qemu_alarm_timer *t)
1479
{
1480
    struct qemu_alarm_win32 *data = t->priv;
1481

    
1482
    timeKillEvent(data->timerId);
1483
    timeEndPeriod(data->period);
1484

    
1485
    CloseHandle(data->host_alarm);
1486
}
1487

    
1488
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1489
{
1490
    struct qemu_alarm_win32 *data = t->priv;
1491
    uint64_t nearest_delta_us;
1492

    
1493
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1494
                !active_timers[QEMU_TIMER_VIRTUAL])
1495
            return;
1496

    
1497
    nearest_delta_us = qemu_next_deadline();
1498
    nearest_delta_us /= 1000;
1499

    
1500
    timeKillEvent(data->timerId);
1501

    
1502
    data->timerId = timeSetEvent(1,
1503
                        data->period,
1504
                        host_alarm_handler,
1505
                        (DWORD)t,
1506
                        TIME_ONESHOT | TIME_PERIODIC);
1507

    
1508
    if (!data->timerId) {
1509
        perror("Failed to re-arm win32 alarm timer");
1510

    
1511
        timeEndPeriod(data->period);
1512
        CloseHandle(data->host_alarm);
1513
        exit(1);
1514
    }
1515
}
1516

    
1517
#endif /* _WIN32 */
1518

    
1519
static void init_timer_alarm(void)
1520
{
1521
    struct qemu_alarm_timer *t;
1522
    int i, err = -1;
1523

    
1524
    for (i = 0; alarm_timers[i].name; i++) {
1525
        t = &alarm_timers[i];
1526

    
1527
        err = t->start(t);
1528
        if (!err)
1529
            break;
1530
    }
1531

    
1532
    if (err) {
1533
        fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1534
        fprintf(stderr, "Terminating\n");
1535
        exit(1);
1536
    }
1537

    
1538
    alarm_timer = t;
1539
}
1540

    
1541
static void quit_timers(void)
1542
{
1543
    alarm_timer->stop(alarm_timer);
1544
    alarm_timer = NULL;
1545
}
1546

    
1547
/***********************************************************/
1548
/* character device */
1549

    
1550
static void qemu_chr_event(CharDriverState *s, int event)
1551
{
1552
    if (!s->chr_event)
1553
        return;
1554
    s->chr_event(s->handler_opaque, event);
1555
}
1556

    
1557
static void qemu_chr_reset_bh(void *opaque)
1558
{
1559
    CharDriverState *s = opaque;
1560
    qemu_chr_event(s, CHR_EVENT_RESET);
1561
    qemu_bh_delete(s->bh);
1562
    s->bh = NULL;
1563
}
1564

    
1565
void qemu_chr_reset(CharDriverState *s)
1566
{
1567
    if (s->bh == NULL) {
1568
        s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1569
        qemu_bh_schedule(s->bh);
1570
    }
1571
}
1572

    
1573
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1574
{
1575
    return s->chr_write(s, buf, len);
1576
}
1577

    
1578
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1579
{
1580
    if (!s->chr_ioctl)
1581
        return -ENOTSUP;
1582
    return s->chr_ioctl(s, cmd, arg);
1583
}
1584

    
1585
int qemu_chr_can_read(CharDriverState *s)
1586
{
1587
    if (!s->chr_can_read)
1588
        return 0;
1589
    return s->chr_can_read(s->handler_opaque);
1590
}
1591

    
1592
void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1593
{
1594
    s->chr_read(s->handler_opaque, buf, len);
1595
}
1596

    
1597
void qemu_chr_accept_input(CharDriverState *s)
1598
{
1599
    if (s->chr_accept_input)
1600
        s->chr_accept_input(s);
1601
}
1602

    
1603
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1604
{
1605
    char buf[4096];
1606
    va_list ap;
1607
    va_start(ap, fmt);
1608
    vsnprintf(buf, sizeof(buf), fmt, ap);
1609
    qemu_chr_write(s, buf, strlen(buf));
1610
    va_end(ap);
1611
}
1612

    
1613
void qemu_chr_send_event(CharDriverState *s, int event)
1614
{
1615
    if (s->chr_send_event)
1616
        s->chr_send_event(s, event);
1617
}
1618

    
1619
void qemu_chr_add_handlers(CharDriverState *s,
1620
                           IOCanRWHandler *fd_can_read,
1621
                           IOReadHandler *fd_read,
1622
                           IOEventHandler *fd_event,
1623
                           void *opaque)
1624
{
1625
    s->chr_can_read = fd_can_read;
1626
    s->chr_read = fd_read;
1627
    s->chr_event = fd_event;
1628
    s->handler_opaque = opaque;
1629
    if (s->chr_update_read_handler)
1630
        s->chr_update_read_handler(s);
1631
}
1632

    
1633
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1634
{
1635
    return len;
1636
}
1637

    
1638
static CharDriverState *qemu_chr_open_null(void)
1639
{
1640
    CharDriverState *chr;
1641

    
1642
    chr = qemu_mallocz(sizeof(CharDriverState));
1643
    if (!chr)
1644
        return NULL;
1645
    chr->chr_write = null_chr_write;
1646
    return chr;
1647
}
1648

    
1649
/* MUX driver for serial I/O splitting */
1650
static int term_timestamps;
1651
static int64_t term_timestamps_start;
1652
#define MAX_MUX 4
1653
#define MUX_BUFFER_SIZE 32        /* Must be a power of 2.  */
1654
#define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1655
typedef struct {
1656
    IOCanRWHandler *chr_can_read[MAX_MUX];
1657
    IOReadHandler *chr_read[MAX_MUX];
1658
    IOEventHandler *chr_event[MAX_MUX];
1659
    void *ext_opaque[MAX_MUX];
1660
    CharDriverState *drv;
1661
    unsigned char buffer[MUX_BUFFER_SIZE];
1662
    int prod;
1663
    int cons;
1664
    int mux_cnt;
1665
    int term_got_escape;
1666
    int max_size;
1667
} MuxDriver;
1668

    
1669

    
1670
static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1671
{
1672
    MuxDriver *d = chr->opaque;
1673
    int ret;
1674
    if (!term_timestamps) {
1675
        ret = d->drv->chr_write(d->drv, buf, len);
1676
    } else {
1677
        int i;
1678

    
1679
        ret = 0;
1680
        for(i = 0; i < len; i++) {
1681
            ret += d->drv->chr_write(d->drv, buf+i, 1);
1682
            if (buf[i] == '\n') {
1683
                char buf1[64];
1684
                int64_t ti;
1685
                int secs;
1686

    
1687
                ti = get_clock();
1688
                if (term_timestamps_start == -1)
1689
                    term_timestamps_start = ti;
1690
                ti -= term_timestamps_start;
1691
                secs = ti / 1000000000;
1692
                snprintf(buf1, sizeof(buf1),
1693
                         "[%02d:%02d:%02d.%03d] ",
1694
                         secs / 3600,
1695
                         (secs / 60) % 60,
1696
                         secs % 60,
1697
                         (int)((ti / 1000000) % 1000));
1698
                d->drv->chr_write(d->drv, buf1, strlen(buf1));
1699
            }
1700
        }
1701
    }
1702
    return ret;
1703
}
1704

    
1705
static char *mux_help[] = {
1706
    "% h    print this help\n\r",
1707
    "% x    exit emulator\n\r",
1708
    "% s    save disk data back to file (if -snapshot)\n\r",
1709
    "% t    toggle console timestamps\n\r"
1710
    "% b    send break (magic sysrq)\n\r",
1711
    "% c    switch between console and monitor\n\r",
1712
    "% %  sends %\n\r",
1713
    NULL
1714
};
1715

    
1716
static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1717
static void mux_print_help(CharDriverState *chr)
1718
{
1719
    int i, j;
1720
    char ebuf[15] = "Escape-Char";
1721
    char cbuf[50] = "\n\r";
1722

    
1723
    if (term_escape_char > 0 && term_escape_char < 26) {
1724
        sprintf(cbuf,"\n\r");
1725
        sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1726
    } else {
1727
        sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1728
    }
1729
    chr->chr_write(chr, cbuf, strlen(cbuf));
1730
    for (i = 0; mux_help[i] != NULL; i++) {
1731
        for (j=0; mux_help[i][j] != '\0'; j++) {
1732
            if (mux_help[i][j] == '%')
1733
                chr->chr_write(chr, ebuf, strlen(ebuf));
1734
            else
1735
                chr->chr_write(chr, &mux_help[i][j], 1);
1736
        }
1737
    }
1738
}
1739

    
1740
static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1741
{
1742
    if (d->term_got_escape) {
1743
        d->term_got_escape = 0;
1744
        if (ch == term_escape_char)
1745
            goto send_char;
1746
        switch(ch) {
1747
        case '?':
1748
        case 'h':
1749
            mux_print_help(chr);
1750
            break;
1751
        case 'x':
1752
            {
1753
                 char *term =  "QEMU: Terminated\n\r";
1754
                 chr->chr_write(chr,term,strlen(term));
1755
                 exit(0);
1756
                 break;
1757
            }
1758
        case 's':
1759
            {
1760
                int i;
1761
                for (i = 0; i < MAX_DISKS; i++) {
1762
                    if (bs_table[i])
1763
                        bdrv_commit(bs_table[i]);
1764
                }
1765
                if (mtd_bdrv)
1766
                    bdrv_commit(mtd_bdrv);
1767
            }
1768
            break;
1769
        case 'b':
1770
            qemu_chr_event(chr, CHR_EVENT_BREAK);
1771
            break;
1772
        case 'c':
1773
            /* Switch to the next registered device */
1774
            chr->focus++;
1775
            if (chr->focus >= d->mux_cnt)
1776
                chr->focus = 0;
1777
            break;
1778
       case 't':
1779
           term_timestamps = !term_timestamps;
1780
           term_timestamps_start = -1;
1781
           break;
1782
        }
1783
    } else if (ch == term_escape_char) {
1784
        d->term_got_escape = 1;
1785
    } else {
1786
    send_char:
1787
        return 1;
1788
    }
1789
    return 0;
1790
}
1791

    
1792
static void mux_chr_accept_input(CharDriverState *chr)
1793
{
1794
    int m = chr->focus;
1795
    MuxDriver *d = chr->opaque;
1796

    
1797
    while (d->prod != d->cons &&
1798
           d->chr_can_read[m] &&
1799
           d->chr_can_read[m](d->ext_opaque[m])) {
1800
        d->chr_read[m](d->ext_opaque[m],
1801
                       &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1802
    }
1803
}
1804

    
1805
static int mux_chr_can_read(void *opaque)
1806
{
1807
    CharDriverState *chr = opaque;
1808
    MuxDriver *d = chr->opaque;
1809

    
1810
    if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1811
        return 1;
1812
    if (d->chr_can_read[chr->focus])
1813
        return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1814
    return 0;
1815
}
1816

    
1817
static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1818
{
1819
    CharDriverState *chr = opaque;
1820
    MuxDriver *d = chr->opaque;
1821
    int m = chr->focus;
1822
    int i;
1823

    
1824
    mux_chr_accept_input (opaque);
1825

    
1826
    for(i = 0; i < size; i++)
1827
        if (mux_proc_byte(chr, d, buf[i])) {
1828
            if (d->prod == d->cons &&
1829
                d->chr_can_read[m] &&
1830
                d->chr_can_read[m](d->ext_opaque[m]))
1831
                d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
1832
            else
1833
                d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
1834
        }
1835
}
1836

    
1837
static void mux_chr_event(void *opaque, int event)
1838
{
1839
    CharDriverState *chr = opaque;
1840
    MuxDriver *d = chr->opaque;
1841
    int i;
1842

    
1843
    /* Send the event to all registered listeners */
1844
    for (i = 0; i < d->mux_cnt; i++)
1845
        if (d->chr_event[i])
1846
            d->chr_event[i](d->ext_opaque[i], event);
1847
}
1848

    
1849
static void mux_chr_update_read_handler(CharDriverState *chr)
1850
{
1851
    MuxDriver *d = chr->opaque;
1852

    
1853
    if (d->mux_cnt >= MAX_MUX) {
1854
        fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1855
        return;
1856
    }
1857
    d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1858
    d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1859
    d->chr_read[d->mux_cnt] = chr->chr_read;
1860
    d->chr_event[d->mux_cnt] = chr->chr_event;
1861
    /* Fix up the real driver with mux routines */
1862
    if (d->mux_cnt == 0) {
1863
        qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1864
                              mux_chr_event, chr);
1865
    }
1866
    chr->focus = d->mux_cnt;
1867
    d->mux_cnt++;
1868
}
1869

    
1870
static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1871
{
1872
    CharDriverState *chr;
1873
    MuxDriver *d;
1874

    
1875
    chr = qemu_mallocz(sizeof(CharDriverState));
1876
    if (!chr)
1877
        return NULL;
1878
    d = qemu_mallocz(sizeof(MuxDriver));
1879
    if (!d) {
1880
        free(chr);
1881
        return NULL;
1882
    }
1883

    
1884
    chr->opaque = d;
1885
    d->drv = drv;
1886
    chr->focus = -1;
1887
    chr->chr_write = mux_chr_write;
1888
    chr->chr_update_read_handler = mux_chr_update_read_handler;
1889
    chr->chr_accept_input = mux_chr_accept_input;
1890
    return chr;
1891
}
1892

    
1893

    
1894
#ifdef _WIN32
1895

    
1896
static void socket_cleanup(void)
1897
{
1898
    WSACleanup();
1899
}
1900

    
1901
static int socket_init(void)
1902
{
1903
    WSADATA Data;
1904
    int ret, err;
1905

    
1906
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1907
    if (ret != 0) {
1908
        err = WSAGetLastError();
1909
        fprintf(stderr, "WSAStartup: %d\n", err);
1910
        return -1;
1911
    }
1912
    atexit(socket_cleanup);
1913
    return 0;
1914
}
1915

    
1916
static int send_all(int fd, const uint8_t *buf, int len1)
1917
{
1918
    int ret, len;
1919

    
1920
    len = len1;
1921
    while (len > 0) {
1922
        ret = send(fd, buf, len, 0);
1923
        if (ret < 0) {
1924
            int errno;
1925
            errno = WSAGetLastError();
1926
            if (errno != WSAEWOULDBLOCK) {
1927
                return -1;
1928
            }
1929
        } else if (ret == 0) {
1930
            break;
1931
        } else {
1932
            buf += ret;
1933
            len -= ret;
1934
        }
1935
    }
1936
    return len1 - len;
1937
}
1938

    
1939
void socket_set_nonblock(int fd)
1940
{
1941
    unsigned long opt = 1;
1942
    ioctlsocket(fd, FIONBIO, &opt);
1943
}
1944

    
1945
#else
1946

    
1947
static int unix_write(int fd, const uint8_t *buf, int len1)
1948
{
1949
    int ret, len;
1950

    
1951
    len = len1;
1952
    while (len > 0) {
1953
        ret = write(fd, buf, len);
1954
        if (ret < 0) {
1955
            if (errno != EINTR && errno != EAGAIN)
1956
                return -1;
1957
        } else if (ret == 0) {
1958
            break;
1959
        } else {
1960
            buf += ret;
1961
            len -= ret;
1962
        }
1963
    }
1964
    return len1 - len;
1965
}
1966

    
1967
static inline int send_all(int fd, const uint8_t *buf, int len1)
1968
{
1969
    return unix_write(fd, buf, len1);
1970
}
1971

    
1972
void socket_set_nonblock(int fd)
1973
{
1974
    fcntl(fd, F_SETFL, O_NONBLOCK);
1975
}
1976
#endif /* !_WIN32 */
1977

    
1978
#ifndef _WIN32
1979

    
1980
typedef struct {
1981
    int fd_in, fd_out;
1982
    int max_size;
1983
} FDCharDriver;
1984

    
1985
#define STDIO_MAX_CLIENTS 1
1986
static int stdio_nb_clients = 0;
1987

    
1988
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1989
{
1990
    FDCharDriver *s = chr->opaque;
1991
    return unix_write(s->fd_out, buf, len);
1992
}
1993

    
1994
static int fd_chr_read_poll(void *opaque)
1995
{
1996
    CharDriverState *chr = opaque;
1997
    FDCharDriver *s = chr->opaque;
1998

    
1999
    s->max_size = qemu_chr_can_read(chr);
2000
    return s->max_size;
2001
}
2002

    
2003
static void fd_chr_read(void *opaque)
2004
{
2005
    CharDriverState *chr = opaque;
2006
    FDCharDriver *s = chr->opaque;
2007
    int size, len;
2008
    uint8_t buf[1024];
2009

    
2010
    len = sizeof(buf);
2011
    if (len > s->max_size)
2012
        len = s->max_size;
2013
    if (len == 0)
2014
        return;
2015
    size = read(s->fd_in, buf, len);
2016
    if (size == 0) {
2017
        /* FD has been closed. Remove it from the active list.  */
2018
        qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2019
        return;
2020
    }
2021
    if (size > 0) {
2022
        qemu_chr_read(chr, buf, size);
2023
    }
2024
}
2025

    
2026
static void fd_chr_update_read_handler(CharDriverState *chr)
2027
{
2028
    FDCharDriver *s = chr->opaque;
2029

    
2030
    if (s->fd_in >= 0) {
2031
        if (nographic && s->fd_in == 0) {
2032
        } else {
2033
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2034
                                 fd_chr_read, NULL, chr);
2035
        }
2036
    }
2037
}
2038

    
2039
/* open a character device to a unix fd */
2040
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2041
{
2042
    CharDriverState *chr;
2043
    FDCharDriver *s;
2044

    
2045
    chr = qemu_mallocz(sizeof(CharDriverState));
2046
    if (!chr)
2047
        return NULL;
2048
    s = qemu_mallocz(sizeof(FDCharDriver));
2049
    if (!s) {
2050
        free(chr);
2051
        return NULL;
2052
    }
2053
    s->fd_in = fd_in;
2054
    s->fd_out = fd_out;
2055
    chr->opaque = s;
2056
    chr->chr_write = fd_chr_write;
2057
    chr->chr_update_read_handler = fd_chr_update_read_handler;
2058

    
2059
    qemu_chr_reset(chr);
2060

    
2061
    return chr;
2062
}
2063

    
2064
static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2065
{
2066
    int fd_out;
2067

    
2068
    TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2069
    if (fd_out < 0)
2070
        return NULL;
2071
    return qemu_chr_open_fd(-1, fd_out);
2072
}
2073

    
2074
static CharDriverState *qemu_chr_open_pipe(const char *filename)
2075
{
2076
    int fd_in, fd_out;
2077
    char filename_in[256], filename_out[256];
2078

    
2079
    snprintf(filename_in, 256, "%s.in", filename);
2080
    snprintf(filename_out, 256, "%s.out", filename);
2081
    TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2082
    TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2083
    if (fd_in < 0 || fd_out < 0) {
2084
        if (fd_in >= 0)
2085
            close(fd_in);
2086
        if (fd_out >= 0)
2087
            close(fd_out);
2088
        TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2089
        if (fd_in < 0)
2090
            return NULL;
2091
    }
2092
    return qemu_chr_open_fd(fd_in, fd_out);
2093
}
2094

    
2095

    
2096
/* for STDIO, we handle the case where several clients use it
2097
   (nographic mode) */
2098

    
2099
#define TERM_FIFO_MAX_SIZE 1
2100

    
2101
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2102
static int term_fifo_size;
2103

    
2104
static int stdio_read_poll(void *opaque)
2105
{
2106
    CharDriverState *chr = opaque;
2107

    
2108
    /* try to flush the queue if needed */
2109
    if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2110
        qemu_chr_read(chr, term_fifo, 1);
2111
        term_fifo_size = 0;
2112
    }
2113
    /* see if we can absorb more chars */
2114
    if (term_fifo_size == 0)
2115
        return 1;
2116
    else
2117
        return 0;
2118
}
2119

    
2120
static void stdio_read(void *opaque)
2121
{
2122
    int size;
2123
    uint8_t buf[1];
2124
    CharDriverState *chr = opaque;
2125

    
2126
    size = read(0, buf, 1);
2127
    if (size == 0) {
2128
        /* stdin has been closed. Remove it from the active list.  */
2129
        qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2130
        return;
2131
    }
2132
    if (size > 0) {
2133
        if (qemu_chr_can_read(chr) > 0) {
2134
            qemu_chr_read(chr, buf, 1);
2135
        } else if (term_fifo_size == 0) {
2136
            term_fifo[term_fifo_size++] = buf[0];
2137
        }
2138
    }
2139
}
2140

    
2141
/* init terminal so that we can grab keys */
2142
static struct termios oldtty;
2143
static int old_fd0_flags;
2144

    
2145
static void term_exit(void)
2146
{
2147
    tcsetattr (0, TCSANOW, &oldtty);
2148
    fcntl(0, F_SETFL, old_fd0_flags);
2149
}
2150

    
2151
static void term_init(void)
2152
{
2153
    struct termios tty;
2154

    
2155
    tcgetattr (0, &tty);
2156
    oldtty = tty;
2157
    old_fd0_flags = fcntl(0, F_GETFL);
2158

    
2159
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2160
                          |INLCR|IGNCR|ICRNL|IXON);
2161
    tty.c_oflag |= OPOST;
2162
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2163
    /* if graphical mode, we allow Ctrl-C handling */
2164
    if (nographic)
2165
        tty.c_lflag &= ~ISIG;
2166
    tty.c_cflag &= ~(CSIZE|PARENB);
2167
    tty.c_cflag |= CS8;
2168
    tty.c_cc[VMIN] = 1;
2169
    tty.c_cc[VTIME] = 0;
2170

    
2171
    tcsetattr (0, TCSANOW, &tty);
2172

    
2173
    atexit(term_exit);
2174

    
2175
    fcntl(0, F_SETFL, O_NONBLOCK);
2176
}
2177

    
2178
static CharDriverState *qemu_chr_open_stdio(void)
2179
{
2180
    CharDriverState *chr;
2181

    
2182
    if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2183
        return NULL;
2184
    chr = qemu_chr_open_fd(0, 1);
2185
    qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2186
    stdio_nb_clients++;
2187
    term_init();
2188

    
2189
    return chr;
2190
}
2191

    
2192
#if defined(__linux__) || defined(__sun__)
2193
static CharDriverState *qemu_chr_open_pty(void)
2194
{
2195
    struct termios tty;
2196
    char slave_name[1024];
2197
    int master_fd, slave_fd;
2198

    
2199
#if defined(__linux__)
2200
    /* Not satisfying */
2201
    if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
2202
        return NULL;
2203
    }
2204
#endif
2205

    
2206
    /* Disabling local echo and line-buffered output */
2207
    tcgetattr (master_fd, &tty);
2208
    tty.c_lflag &= ~(ECHO|ICANON|ISIG);
2209
    tty.c_cc[VMIN] = 1;
2210
    tty.c_cc[VTIME] = 0;
2211
    tcsetattr (master_fd, TCSAFLUSH, &tty);
2212

    
2213
    fprintf(stderr, "char device redirected to %s\n", slave_name);
2214
    return qemu_chr_open_fd(master_fd, master_fd);
2215
}
2216

    
2217
static void tty_serial_init(int fd, int speed,
2218
                            int parity, int data_bits, int stop_bits)
2219
{
2220
    struct termios tty;
2221
    speed_t spd;
2222

    
2223
#if 0
2224
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2225
           speed, parity, data_bits, stop_bits);
2226
#endif
2227
    tcgetattr (fd, &tty);
2228

    
2229
    switch(speed) {
2230
    case 50:
2231
        spd = B50;
2232
        break;
2233
    case 75:
2234
        spd = B75;
2235
        break;
2236
    case 300:
2237
        spd = B300;
2238
        break;
2239
    case 600:
2240
        spd = B600;
2241
        break;
2242
    case 1200:
2243
        spd = B1200;
2244
        break;
2245
    case 2400:
2246
        spd = B2400;
2247
        break;
2248
    case 4800:
2249
        spd = B4800;
2250
        break;
2251
    case 9600:
2252
        spd = B9600;
2253
        break;
2254
    case 19200:
2255
        spd = B19200;
2256
        break;
2257
    case 38400:
2258
        spd = B38400;
2259
        break;
2260
    case 57600:
2261
        spd = B57600;
2262
        break;
2263
    default:
2264
    case 115200:
2265
        spd = B115200;
2266
        break;
2267
    }
2268

    
2269
    cfsetispeed(&tty, spd);
2270
    cfsetospeed(&tty, spd);
2271

    
2272
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2273
                          |INLCR|IGNCR|ICRNL|IXON);
2274
    tty.c_oflag |= OPOST;
2275
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2276
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2277
    switch(data_bits) {
2278
    default:
2279
    case 8:
2280
        tty.c_cflag |= CS8;
2281
        break;
2282
    case 7:
2283
        tty.c_cflag |= CS7;
2284
        break;
2285
    case 6:
2286
        tty.c_cflag |= CS6;
2287
        break;
2288
    case 5:
2289
        tty.c_cflag |= CS5;
2290
        break;
2291
    }
2292
    switch(parity) {
2293
    default:
2294
    case 'N':
2295
        break;
2296
    case 'E':
2297
        tty.c_cflag |= PARENB;
2298
        break;
2299
    case 'O':
2300
        tty.c_cflag |= PARENB | PARODD;
2301
        break;
2302
    }
2303
    if (stop_bits == 2)
2304
        tty.c_cflag |= CSTOPB;
2305

    
2306
    tcsetattr (fd, TCSANOW, &tty);
2307
}
2308

    
2309
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2310
{
2311
    FDCharDriver *s = chr->opaque;
2312

    
2313
    switch(cmd) {
2314
    case CHR_IOCTL_SERIAL_SET_PARAMS:
2315
        {
2316
            QEMUSerialSetParams *ssp = arg;
2317
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2318
                            ssp->data_bits, ssp->stop_bits);
2319
        }
2320
        break;
2321
    case CHR_IOCTL_SERIAL_SET_BREAK:
2322
        {
2323
            int enable = *(int *)arg;
2324
            if (enable)
2325
                tcsendbreak(s->fd_in, 1);
2326
        }
2327
        break;
2328
    default:
2329
        return -ENOTSUP;
2330
    }
2331
    return 0;
2332
}
2333

    
2334
static CharDriverState *qemu_chr_open_tty(const char *filename)
2335
{
2336
    CharDriverState *chr;
2337
    int fd;
2338

    
2339
    TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2340
    fcntl(fd, F_SETFL, O_NONBLOCK);
2341
    tty_serial_init(fd, 115200, 'N', 8, 1);
2342
    chr = qemu_chr_open_fd(fd, fd);
2343
    if (!chr) {
2344
        close(fd);
2345
        return NULL;
2346
    }
2347
    chr->chr_ioctl = tty_serial_ioctl;
2348
    qemu_chr_reset(chr);
2349
    return chr;
2350
}
2351
#else  /* ! __linux__ && ! __sun__ */
2352
static CharDriverState *qemu_chr_open_pty(void)
2353
{
2354
    return NULL;
2355
}
2356
#endif /* __linux__ || __sun__ */
2357

    
2358
#if defined(__linux__)
2359
typedef struct {
2360
    int fd;
2361
    int mode;
2362
} ParallelCharDriver;
2363

    
2364
static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2365
{
2366
    if (s->mode != mode) {
2367
        int m = mode;
2368
        if (ioctl(s->fd, PPSETMODE, &m) < 0)
2369
            return 0;
2370
        s->mode = mode;
2371
    }
2372
    return 1;
2373
}
2374

    
2375
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2376
{
2377
    ParallelCharDriver *drv = chr->opaque;
2378
    int fd = drv->fd;
2379
    uint8_t b;
2380

    
2381
    switch(cmd) {
2382
    case CHR_IOCTL_PP_READ_DATA:
2383
        if (ioctl(fd, PPRDATA, &b) < 0)
2384
            return -ENOTSUP;
2385
        *(uint8_t *)arg = b;
2386
        break;
2387
    case CHR_IOCTL_PP_WRITE_DATA:
2388
        b = *(uint8_t *)arg;
2389
        if (ioctl(fd, PPWDATA, &b) < 0)
2390
            return -ENOTSUP;
2391
        break;
2392
    case CHR_IOCTL_PP_READ_CONTROL:
2393
        if (ioctl(fd, PPRCONTROL, &b) < 0)
2394
            return -ENOTSUP;
2395
        /* Linux gives only the lowest bits, and no way to know data
2396
           direction! For better compatibility set the fixed upper
2397
           bits. */
2398
        *(uint8_t *)arg = b | 0xc0;
2399
        break;
2400
    case CHR_IOCTL_PP_WRITE_CONTROL:
2401
        b = *(uint8_t *)arg;
2402
        if (ioctl(fd, PPWCONTROL, &b) < 0)
2403
            return -ENOTSUP;
2404
        break;
2405
    case CHR_IOCTL_PP_READ_STATUS:
2406
        if (ioctl(fd, PPRSTATUS, &b) < 0)
2407
            return -ENOTSUP;
2408
        *(uint8_t *)arg = b;
2409
        break;
2410
    case CHR_IOCTL_PP_EPP_READ_ADDR:
2411
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2412
            struct ParallelIOArg *parg = arg;
2413
            int n = read(fd, parg->buffer, parg->count);
2414
            if (n != parg->count) {
2415
                return -EIO;
2416
            }
2417
        }
2418
        break;
2419
    case CHR_IOCTL_PP_EPP_READ:
2420
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2421
            struct ParallelIOArg *parg = arg;
2422
            int n = read(fd, parg->buffer, parg->count);
2423
            if (n != parg->count) {
2424
                return -EIO;
2425
            }
2426
        }
2427
        break;
2428
    case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2429
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2430
            struct ParallelIOArg *parg = arg;
2431
            int n = write(fd, parg->buffer, parg->count);
2432
            if (n != parg->count) {
2433
                return -EIO;
2434
            }
2435
        }
2436
        break;
2437
    case CHR_IOCTL_PP_EPP_WRITE:
2438
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2439
            struct ParallelIOArg *parg = arg;
2440
            int n = write(fd, parg->buffer, parg->count);
2441
            if (n != parg->count) {
2442
                return -EIO;
2443
            }
2444
        }
2445
        break;
2446
    default:
2447
        return -ENOTSUP;
2448
    }
2449
    return 0;
2450
}
2451

    
2452
static void pp_close(CharDriverState *chr)
2453
{
2454
    ParallelCharDriver *drv = chr->opaque;
2455
    int fd = drv->fd;
2456

    
2457
    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2458
    ioctl(fd, PPRELEASE);
2459
    close(fd);
2460
    qemu_free(drv);
2461
}
2462

    
2463
static CharDriverState *qemu_chr_open_pp(const char *filename)
2464
{
2465
    CharDriverState *chr;
2466
    ParallelCharDriver *drv;
2467
    int fd;
2468

    
2469
    TFR(fd = open(filename, O_RDWR));
2470
    if (fd < 0)
2471
        return NULL;
2472

    
2473
    if (ioctl(fd, PPCLAIM) < 0) {
2474
        close(fd);
2475
        return NULL;
2476
    }
2477

    
2478
    drv = qemu_mallocz(sizeof(ParallelCharDriver));
2479
    if (!drv) {
2480
        close(fd);
2481
        return NULL;
2482
    }
2483
    drv->fd = fd;
2484
    drv->mode = IEEE1284_MODE_COMPAT;
2485

    
2486
    chr = qemu_mallocz(sizeof(CharDriverState));
2487
    if (!chr) {
2488
        qemu_free(drv);
2489
        close(fd);
2490
        return NULL;
2491
    }
2492
    chr->chr_write = null_chr_write;
2493
    chr->chr_ioctl = pp_ioctl;
2494
    chr->chr_close = pp_close;
2495
    chr->opaque = drv;
2496

    
2497
    qemu_chr_reset(chr);
2498

    
2499
    return chr;
2500
}
2501
#endif /* __linux__ */
2502

    
2503
#else /* _WIN32 */
2504

    
2505
typedef struct {
2506
    int max_size;
2507
    HANDLE hcom, hrecv, hsend;
2508
    OVERLAPPED orecv, osend;
2509
    BOOL fpipe;
2510
    DWORD len;
2511
} WinCharState;
2512

    
2513
#define NSENDBUF 2048
2514
#define NRECVBUF 2048
2515
#define MAXCONNECT 1
2516
#define NTIMEOUT 5000
2517

    
2518
static int win_chr_poll(void *opaque);
2519
static int win_chr_pipe_poll(void *opaque);
2520

    
2521
static void win_chr_close(CharDriverState *chr)
2522
{
2523
    WinCharState *s = chr->opaque;
2524

    
2525
    if (s->hsend) {
2526
        CloseHandle(s->hsend);
2527
        s->hsend = NULL;
2528
    }
2529
    if (s->hrecv) {
2530
        CloseHandle(s->hrecv);
2531
        s->hrecv = NULL;
2532
    }
2533
    if (s->hcom) {
2534
        CloseHandle(s->hcom);
2535
        s->hcom = NULL;
2536
    }
2537
    if (s->fpipe)
2538
        qemu_del_polling_cb(win_chr_pipe_poll, chr);
2539
    else
2540
        qemu_del_polling_cb(win_chr_poll, chr);
2541
}
2542

    
2543
static int win_chr_init(CharDriverState *chr, const char *filename)
2544
{
2545
    WinCharState *s = chr->opaque;
2546
    COMMCONFIG comcfg;
2547
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2548
    COMSTAT comstat;
2549
    DWORD size;
2550
    DWORD err;
2551

    
2552
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2553
    if (!s->hsend) {
2554
        fprintf(stderr, "Failed CreateEvent\n");
2555
        goto fail;
2556
    }
2557
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2558
    if (!s->hrecv) {
2559
        fprintf(stderr, "Failed CreateEvent\n");
2560
        goto fail;
2561
    }
2562

    
2563
    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2564
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2565
    if (s->hcom == INVALID_HANDLE_VALUE) {
2566
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2567
        s->hcom = NULL;
2568
        goto fail;
2569
    }
2570

    
2571
    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2572
        fprintf(stderr, "Failed SetupComm\n");
2573
        goto fail;
2574
    }
2575

    
2576
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2577
    size = sizeof(COMMCONFIG);
2578
    GetDefaultCommConfig(filename, &comcfg, &size);
2579
    comcfg.dcb.DCBlength = sizeof(DCB);
2580
    CommConfigDialog(filename, NULL, &comcfg);
2581

    
2582
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
2583
        fprintf(stderr, "Failed SetCommState\n");
2584
        goto fail;
2585
    }
2586

    
2587
    if (!SetCommMask(s->hcom, EV_ERR)) {
2588
        fprintf(stderr, "Failed SetCommMask\n");
2589
        goto fail;
2590
    }
2591

    
2592
    cto.ReadIntervalTimeout = MAXDWORD;
2593
    if (!SetCommTimeouts(s->hcom, &cto)) {
2594
        fprintf(stderr, "Failed SetCommTimeouts\n");
2595
        goto fail;
2596
    }
2597

    
2598
    if (!ClearCommError(s->hcom, &err, &comstat)) {
2599
        fprintf(stderr, "Failed ClearCommError\n");
2600
        goto fail;
2601
    }
2602
    qemu_add_polling_cb(win_chr_poll, chr);
2603
    return 0;
2604

    
2605
 fail:
2606
    win_chr_close(chr);
2607
    return -1;
2608
}
2609

    
2610
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2611
{
2612
    WinCharState *s = chr->opaque;
2613
    DWORD len, ret, size, err;
2614

    
2615
    len = len1;
2616
    ZeroMemory(&s->osend, sizeof(s->osend));
2617
    s->osend.hEvent = s->hsend;
2618
    while (len > 0) {
2619
        if (s->hsend)
2620
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2621
        else
2622
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
2623
        if (!ret) {
2624
            err = GetLastError();
2625
            if (err == ERROR_IO_PENDING) {
2626
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2627
                if (ret) {
2628
                    buf += size;
2629
                    len -= size;
2630
                } else {
2631
                    break;
2632
                }
2633
            } else {
2634
                break;
2635
            }
2636
        } else {
2637
            buf += size;
2638
            len -= size;
2639
        }
2640
    }
2641
    return len1 - len;
2642
}
2643

    
2644
static int win_chr_read_poll(CharDriverState *chr)
2645
{
2646
    WinCharState *s = chr->opaque;
2647

    
2648
    s->max_size = qemu_chr_can_read(chr);
2649
    return s->max_size;
2650
}
2651

    
2652
static void win_chr_readfile(CharDriverState *chr)
2653
{
2654
    WinCharState *s = chr->opaque;
2655
    int ret, err;
2656
    uint8_t buf[1024];
2657
    DWORD size;
2658

    
2659
    ZeroMemory(&s->orecv, sizeof(s->orecv));
2660
    s->orecv.hEvent = s->hrecv;
2661
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2662
    if (!ret) {
2663
        err = GetLastError();
2664
        if (err == ERROR_IO_PENDING) {
2665
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2666
        }
2667
    }
2668

    
2669
    if (size > 0) {
2670
        qemu_chr_read(chr, buf, size);
2671
    }
2672
}
2673

    
2674
static void win_chr_read(CharDriverState *chr)
2675
{
2676
    WinCharState *s = chr->opaque;
2677

    
2678
    if (s->len > s->max_size)
2679
        s->len = s->max_size;
2680
    if (s->len == 0)
2681
        return;
2682

    
2683
    win_chr_readfile(chr);
2684
}
2685

    
2686
static int win_chr_poll(void *opaque)
2687
{
2688
    CharDriverState *chr = opaque;
2689
    WinCharState *s = chr->opaque;
2690
    COMSTAT status;
2691
    DWORD comerr;
2692

    
2693
    ClearCommError(s->hcom, &comerr, &status);
2694
    if (status.cbInQue > 0) {
2695
        s->len = status.cbInQue;
2696
        win_chr_read_poll(chr);
2697
        win_chr_read(chr);
2698
        return 1;
2699
    }
2700
    return 0;
2701
}
2702

    
2703
static CharDriverState *qemu_chr_open_win(const char *filename)
2704
{
2705
    CharDriverState *chr;
2706
    WinCharState *s;
2707

    
2708
    chr = qemu_mallocz(sizeof(CharDriverState));
2709
    if (!chr)
2710
        return NULL;
2711
    s = qemu_mallocz(sizeof(WinCharState));
2712
    if (!s) {
2713
        free(chr);
2714
        return NULL;
2715
    }
2716
    chr->opaque = s;
2717
    chr->chr_write = win_chr_write;
2718
    chr->chr_close = win_chr_close;
2719

    
2720
    if (win_chr_init(chr, filename) < 0) {
2721
        free(s);
2722
        free(chr);
2723
        return NULL;
2724
    }
2725
    qemu_chr_reset(chr);
2726
    return chr;
2727
}
2728

    
2729
static int win_chr_pipe_poll(void *opaque)
2730
{
2731
    CharDriverState *chr = opaque;
2732
    WinCharState *s = chr->opaque;
2733
    DWORD size;
2734

    
2735
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2736
    if (size > 0) {
2737
        s->len = size;
2738
        win_chr_read_poll(chr);
2739
        win_chr_read(chr);
2740
        return 1;
2741
    }
2742
    return 0;
2743
}
2744

    
2745
static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2746
{
2747
    WinCharState *s = chr->opaque;
2748
    OVERLAPPED ov;
2749
    int ret;
2750
    DWORD size;
2751
    char openname[256];
2752

    
2753
    s->fpipe = TRUE;
2754

    
2755
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2756
    if (!s->hsend) {
2757
        fprintf(stderr, "Failed CreateEvent\n");
2758
        goto fail;
2759
    }
2760
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2761
    if (!s->hrecv) {
2762
        fprintf(stderr, "Failed CreateEvent\n");
2763
        goto fail;
2764
    }
2765

    
2766
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2767
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2768
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2769
                              PIPE_WAIT,
2770
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2771
    if (s->hcom == INVALID_HANDLE_VALUE) {
2772
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2773
        s->hcom = NULL;
2774
        goto fail;
2775
    }
2776

    
2777
    ZeroMemory(&ov, sizeof(ov));
2778
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2779
    ret = ConnectNamedPipe(s->hcom, &ov);
2780
    if (ret) {
2781
        fprintf(stderr, "Failed ConnectNamedPipe\n");
2782
        goto fail;
2783
    }
2784

    
2785
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2786
    if (!ret) {
2787
        fprintf(stderr, "Failed GetOverlappedResult\n");
2788
        if (ov.hEvent) {
2789
            CloseHandle(ov.hEvent);
2790
            ov.hEvent = NULL;
2791
        }
2792
        goto fail;
2793
    }
2794

    
2795
    if (ov.hEvent) {
2796
        CloseHandle(ov.hEvent);
2797
        ov.hEvent = NULL;
2798
    }
2799
    qemu_add_polling_cb(win_chr_pipe_poll, chr);
2800
    return 0;
2801

    
2802
 fail:
2803
    win_chr_close(chr);
2804
    return -1;
2805
}
2806

    
2807

    
2808
static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2809
{
2810
    CharDriverState *chr;
2811
    WinCharState *s;
2812

    
2813
    chr = qemu_mallocz(sizeof(CharDriverState));
2814
    if (!chr)
2815
        return NULL;
2816
    s = qemu_mallocz(sizeof(WinCharState));
2817
    if (!s) {
2818
        free(chr);
2819
        return NULL;
2820
    }
2821
    chr->opaque = s;
2822
    chr->chr_write = win_chr_write;
2823
    chr->chr_close = win_chr_close;
2824

    
2825
    if (win_chr_pipe_init(chr, filename) < 0) {
2826
        free(s);
2827
        free(chr);
2828
        return NULL;
2829
    }
2830
    qemu_chr_reset(chr);
2831
    return chr;
2832
}
2833

    
2834
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2835
{
2836
    CharDriverState *chr;
2837
    WinCharState *s;
2838

    
2839
    chr = qemu_mallocz(sizeof(CharDriverState));
2840
    if (!chr)
2841
        return NULL;
2842
    s = qemu_mallocz(sizeof(WinCharState));
2843
    if (!s) {
2844
        free(chr);
2845
        return NULL;
2846
    }
2847
    s->hcom = fd_out;
2848
    chr->opaque = s;
2849
    chr->chr_write = win_chr_write;
2850
    qemu_chr_reset(chr);
2851
    return chr;
2852
}
2853

    
2854
static CharDriverState *qemu_chr_open_win_con(const char *filename)
2855
{
2856
    return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
2857
}
2858

    
2859
static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2860
{
2861
    HANDLE fd_out;
2862

    
2863
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2864
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2865
    if (fd_out == INVALID_HANDLE_VALUE)
2866
        return NULL;
2867

    
2868
    return qemu_chr_open_win_file(fd_out);
2869
}
2870
#endif /* !_WIN32 */
2871

    
2872
/***********************************************************/
2873
/* UDP Net console */
2874

    
2875
typedef struct {
2876
    int fd;
2877
    struct sockaddr_in daddr;
2878
    char buf[1024];
2879
    int bufcnt;
2880
    int bufptr;
2881
    int max_size;
2882
} NetCharDriver;
2883

    
2884
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2885
{
2886
    NetCharDriver *s = chr->opaque;
2887

    
2888
    return sendto(s->fd, buf, len, 0,
2889
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2890
}
2891

    
2892
static int udp_chr_read_poll(void *opaque)
2893
{
2894
    CharDriverState *chr = opaque;
2895
    NetCharDriver *s = chr->opaque;
2896

    
2897
    s->max_size = qemu_chr_can_read(chr);
2898

    
2899
    /* If there were any stray characters in the queue process them
2900
     * first
2901
     */
2902
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2903
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2904
        s->bufptr++;
2905
        s->max_size = qemu_chr_can_read(chr);
2906
    }
2907
    return s->max_size;
2908
}
2909

    
2910
static void udp_chr_read(void *opaque)
2911
{
2912
    CharDriverState *chr = opaque;
2913
    NetCharDriver *s = chr->opaque;
2914

    
2915
    if (s->max_size == 0)
2916
        return;
2917
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2918
    s->bufptr = s->bufcnt;
2919
    if (s->bufcnt <= 0)
2920
        return;
2921

    
2922
    s->bufptr = 0;
2923
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2924
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2925
        s->bufptr++;
2926
        s->max_size = qemu_chr_can_read(chr);
2927
    }
2928
}
2929

    
2930
static void udp_chr_update_read_handler(CharDriverState *chr)
2931
{
2932
    NetCharDriver *s = chr->opaque;
2933

    
2934
    if (s->fd >= 0) {
2935
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2936
                             udp_chr_read, NULL, chr);
2937
    }
2938
}
2939

    
2940
int parse_host_port(struct sockaddr_in *saddr, const char *str);
2941
#ifndef _WIN32
2942
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2943
#endif
2944
int parse_host_src_port(struct sockaddr_in *haddr,
2945
                        struct sockaddr_in *saddr,
2946
                        const char *str);
2947

    
2948
static CharDriverState *qemu_chr_open_udp(const char *def)
2949
{
2950
    CharDriverState *chr = NULL;
2951
    NetCharDriver *s = NULL;
2952
    int fd = -1;
2953
    struct sockaddr_in saddr;
2954

    
2955
    chr = qemu_mallocz(sizeof(CharDriverState));
2956
    if (!chr)
2957
        goto return_err;
2958
    s = qemu_mallocz(sizeof(NetCharDriver));
2959
    if (!s)
2960
        goto return_err;
2961

    
2962
    fd = socket(PF_INET, SOCK_DGRAM, 0);
2963
    if (fd < 0) {
2964
        perror("socket(PF_INET, SOCK_DGRAM)");
2965
        goto return_err;
2966
    }
2967

    
2968
    if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2969
        printf("Could not parse: %s\n", def);
2970
        goto return_err;
2971
    }
2972

    
2973
    if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2974
    {
2975
        perror("bind");
2976
        goto return_err;
2977
    }
2978

    
2979
    s->fd = fd;
2980
    s->bufcnt = 0;
2981
    s->bufptr = 0;
2982
    chr->opaque = s;
2983
    chr->chr_write = udp_chr_write;
2984
    chr->chr_update_read_handler = udp_chr_update_read_handler;
2985
    return chr;
2986

    
2987
return_err:
2988
    if (chr)
2989
        free(chr);
2990
    if (s)
2991
        free(s);
2992
    if (fd >= 0)
2993
        closesocket(fd);
2994
    return NULL;
2995
}
2996

    
2997
/***********************************************************/
2998
/* TCP Net console */
2999

    
3000
typedef struct {
3001
    int fd, listen_fd;
3002
    int connected;
3003
    int max_size;
3004
    int do_telnetopt;
3005
    int do_nodelay;
3006
    int is_unix;
3007
} TCPCharDriver;
3008

    
3009
static void tcp_chr_accept(void *opaque);
3010

    
3011
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3012
{
3013
    TCPCharDriver *s = chr->opaque;
3014
    if (s->connected) {
3015
        return send_all(s->fd, buf, len);
3016
    } else {
3017
        /* XXX: indicate an error ? */
3018
        return len;
3019
    }
3020
}
3021

    
3022
static int tcp_chr_read_poll(void *opaque)
3023
{
3024
    CharDriverState *chr = opaque;
3025
    TCPCharDriver *s = chr->opaque;
3026
    if (!s->connected)
3027
        return 0;
3028
    s->max_size = qemu_chr_can_read(chr);
3029
    return s->max_size;
3030
}
3031

    
3032
#define IAC 255
3033
#define IAC_BREAK 243
3034
static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3035
                                      TCPCharDriver *s,
3036
                                      char *buf, int *size)
3037
{
3038
    /* Handle any telnet client's basic IAC options to satisfy char by
3039
     * char mode with no echo.  All IAC options will be removed from
3040
     * the buf and the do_telnetopt variable will be used to track the
3041
     * state of the width of the IAC information.
3042
     *
3043
     * IAC commands come in sets of 3 bytes with the exception of the
3044
     * "IAC BREAK" command and the double IAC.
3045
     */
3046

    
3047
    int i;
3048
    int j = 0;
3049

    
3050
    for (i = 0; i < *size; i++) {
3051
        if (s->do_telnetopt > 1) {
3052
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3053
                /* Double IAC means send an IAC */
3054
                if (j != i)
3055
                    buf[j] = buf[i];
3056
                j++;
3057
                s->do_telnetopt = 1;
3058
            } else {
3059
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3060
                    /* Handle IAC break commands by sending a serial break */
3061
                    qemu_chr_event(chr, CHR_EVENT_BREAK);
3062
                    s->do_telnetopt++;
3063
                }
3064
                s->do_telnetopt++;
3065
            }
3066
            if (s->do_telnetopt >= 4) {
3067
                s->do_telnetopt = 1;
3068
            }
3069
        } else {
3070
            if ((unsigned char)buf[i] == IAC) {
3071
                s->do_telnetopt = 2;
3072
            } else {
3073
                if (j != i)
3074
                    buf[j] = buf[i];
3075
                j++;
3076
            }
3077
        }
3078
    }
3079
    *size = j;
3080
}
3081

    
3082
static void tcp_chr_read(void *opaque)
3083
{
3084
    CharDriverState *chr = opaque;
3085
    TCPCharDriver *s = chr->opaque;
3086
    uint8_t buf[1024];
3087
    int len, size;
3088

    
3089
    if (!s->connected || s->max_size <= 0)
3090
        return;
3091
    len = sizeof(buf);
3092
    if (len > s->max_size)
3093
        len = s->max_size;
3094
    size = recv(s->fd, buf, len, 0);
3095
    if (size == 0) {
3096
        /* connection closed */
3097
        s->connected = 0;
3098
        if (s->listen_fd >= 0) {
3099
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3100
        }
3101
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3102
        closesocket(s->fd);
3103
        s->fd = -1;
3104
    } else if (size > 0) {
3105
        if (s->do_telnetopt)
3106
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3107
        if (size > 0)
3108
            qemu_chr_read(chr, buf, size);
3109
    }
3110
}
3111

    
3112
static void tcp_chr_connect(void *opaque)
3113
{
3114
    CharDriverState *chr = opaque;
3115
    TCPCharDriver *s = chr->opaque;
3116

    
3117
    s->connected = 1;
3118
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3119
                         tcp_chr_read, NULL, chr);
3120
    qemu_chr_reset(chr);
3121
}
3122

    
3123
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3124
static void tcp_chr_telnet_init(int fd)
3125
{
3126
    char buf[3];
3127
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3128
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
3129
    send(fd, (char *)buf, 3, 0);
3130
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
3131
    send(fd, (char *)buf, 3, 0);
3132
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
3133
    send(fd, (char *)buf, 3, 0);
3134
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
3135
    send(fd, (char *)buf, 3, 0);
3136
}
3137

    
3138
static void socket_set_nodelay(int fd)
3139
{
3140
    int val = 1;
3141
    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3142
}
3143

    
3144
static void tcp_chr_accept(void *opaque)
3145
{
3146
    CharDriverState *chr = opaque;
3147
    TCPCharDriver *s = chr->opaque;
3148
    struct sockaddr_in saddr;
3149
#ifndef _WIN32
3150
    struct sockaddr_un uaddr;
3151
#endif
3152
    struct sockaddr *addr;
3153
    socklen_t len;
3154
    int fd;
3155

    
3156
    for(;;) {
3157
#ifndef _WIN32
3158
        if (s->is_unix) {
3159
            len = sizeof(uaddr);
3160
            addr = (struct sockaddr *)&uaddr;
3161
        } else
3162
#endif
3163
        {
3164
            len = sizeof(saddr);
3165
            addr = (struct sockaddr *)&saddr;
3166
        }
3167
        fd = accept(s->listen_fd, addr, &len);
3168
        if (fd < 0 && errno != EINTR) {
3169
            return;
3170
        } else if (fd >= 0) {
3171
            if (s->do_telnetopt)
3172
                tcp_chr_telnet_init(fd);
3173
            break;
3174
        }
3175
    }
3176
    socket_set_nonblock(fd);
3177
    if (s->do_nodelay)
3178
        socket_set_nodelay(fd);
3179
    s->fd = fd;
3180
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3181
    tcp_chr_connect(chr);
3182
}
3183

    
3184
static void tcp_chr_close(CharDriverState *chr)
3185
{
3186
    TCPCharDriver *s = chr->opaque;
3187
    if (s->fd >= 0)
3188
        closesocket(s->fd);
3189
    if (s->listen_fd >= 0)
3190
        closesocket(s->listen_fd);
3191
    qemu_free(s);
3192
}
3193

    
3194
static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3195
                                          int is_telnet,
3196
                                          int is_unix)
3197
{
3198
    CharDriverState *chr = NULL;
3199
    TCPCharDriver *s = NULL;
3200
    int fd = -1, ret, err, val;
3201
    int is_listen = 0;
3202
    int is_waitconnect = 1;
3203
    int do_nodelay = 0;
3204
    const char *ptr;
3205
    struct sockaddr_in saddr;
3206
#ifndef _WIN32
3207
    struct sockaddr_un uaddr;
3208
#endif
3209
    struct sockaddr *addr;
3210
    socklen_t addrlen;
3211

    
3212
#ifndef _WIN32
3213
    if (is_unix) {
3214
        addr = (struct sockaddr *)&uaddr;
3215
        addrlen = sizeof(uaddr);
3216
        if (parse_unix_path(&uaddr, host_str) < 0)
3217
            goto fail;
3218
    } else
3219
#endif
3220
    {
3221
        addr = (struct sockaddr *)&saddr;
3222
        addrlen = sizeof(saddr);
3223
        if (parse_host_port(&saddr, host_str) < 0)
3224
            goto fail;
3225
    }
3226

    
3227
    ptr = host_str;
3228
    while((ptr = strchr(ptr,','))) {
3229
        ptr++;
3230
        if (!strncmp(ptr,"server",6)) {
3231
            is_listen = 1;
3232
        } else if (!strncmp(ptr,"nowait",6)) {
3233
            is_waitconnect = 0;
3234
        } else if (!strncmp(ptr,"nodelay",6)) {
3235
            do_nodelay = 1;
3236
        } else {
3237
            printf("Unknown option: %s\n", ptr);
3238
            goto fail;
3239
        }
3240
    }
3241
    if (!is_listen)
3242
        is_waitconnect = 0;
3243

    
3244
    chr = qemu_mallocz(sizeof(CharDriverState));
3245
    if (!chr)
3246
        goto fail;
3247
    s = qemu_mallocz(sizeof(TCPCharDriver));
3248
    if (!s)
3249
        goto fail;
3250

    
3251
#ifndef _WIN32
3252
    if (is_unix)
3253
        fd = socket(PF_UNIX, SOCK_STREAM, 0);
3254
    else
3255
#endif
3256
        fd = socket(PF_INET, SOCK_STREAM, 0);
3257

    
3258
    if (fd < 0)
3259
        goto fail;
3260

    
3261
    if (!is_waitconnect)
3262
        socket_set_nonblock(fd);
3263

    
3264
    s->connected = 0;
3265
    s->fd = -1;
3266
    s->listen_fd = -1;
3267
    s->is_unix = is_unix;
3268
    s->do_nodelay = do_nodelay && !is_unix;
3269

    
3270
    chr->opaque = s;
3271
    chr->chr_write = tcp_chr_write;
3272
    chr->chr_close = tcp_chr_close;
3273

    
3274
    if (is_listen) {
3275
        /* allow fast reuse */
3276
#ifndef _WIN32
3277
        if (is_unix) {
3278
            char path[109];
3279
            strncpy(path, uaddr.sun_path, 108);
3280
            path[108] = 0;
3281
            unlink(path);
3282
        } else
3283
#endif
3284
        {
3285
            val = 1;
3286
            setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3287
        }
3288

    
3289
        ret = bind(fd, addr, addrlen);
3290
        if (ret < 0)
3291
            goto fail;
3292

    
3293
        ret = listen(fd, 0);
3294
        if (ret < 0)
3295
            goto fail;
3296

    
3297
        s->listen_fd = fd;
3298
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3299
        if (is_telnet)
3300
            s->do_telnetopt = 1;
3301
    } else {
3302
        for(;;) {
3303
            ret = connect(fd, addr, addrlen);
3304
            if (ret < 0) {
3305
                err = socket_error();
3306
                if (err == EINTR || err == EWOULDBLOCK) {
3307
                } else if (err == EINPROGRESS) {
3308
                    break;
3309
#ifdef _WIN32
3310
                } else if (err == WSAEALREADY) {
3311
                    break;
3312
#endif
3313
                } else {
3314
                    goto fail;
3315
                }
3316
            } else {
3317
                s->connected = 1;
3318
                break;
3319
            }
3320
        }
3321
        s->fd = fd;
3322
        socket_set_nodelay(fd);
3323
        if (s->connected)
3324
            tcp_chr_connect(chr);
3325
        else
3326
            qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3327
    }
3328

    
3329
    if (is_listen && is_waitconnect) {
3330
        printf("QEMU waiting for connection on: %s\n", host_str);
3331
        tcp_chr_accept(chr);
3332
        socket_set_nonblock(s->listen_fd);
3333
    }
3334

    
3335
    return chr;
3336
 fail:
3337
    if (fd >= 0)
3338
        closesocket(fd);
3339
    qemu_free(s);
3340
    qemu_free(chr);
3341
    return NULL;
3342
}
3343

    
3344
CharDriverState *qemu_chr_open(const char *filename)
3345
{
3346
    const char *p;
3347

    
3348
    if (!strcmp(filename, "vc")) {
3349
        return text_console_init(&display_state, 0);
3350
    } else if (strstart(filename, "vc:", &p)) {
3351
        return text_console_init(&display_state, p);
3352
    } else if (!strcmp(filename, "null")) {
3353
        return qemu_chr_open_null();
3354
    } else
3355
    if (strstart(filename, "tcp:", &p)) {
3356
        return qemu_chr_open_tcp(p, 0, 0);
3357
    } else
3358
    if (strstart(filename, "telnet:", &p)) {
3359
        return qemu_chr_open_tcp(p, 1, 0);
3360
    } else
3361
    if (strstart(filename, "udp:", &p)) {
3362
        return qemu_chr_open_udp(p);
3363
    } else
3364
    if (strstart(filename, "mon:", &p)) {
3365
        CharDriverState *drv = qemu_chr_open(p);
3366
        if (drv) {
3367
            drv = qemu_chr_open_mux(drv);
3368
            monitor_init(drv, !nographic);
3369
            return drv;
3370
        }
3371
        printf("Unable to open driver: %s\n", p);
3372
        return 0;
3373
    } else
3374
#ifndef _WIN32
3375
    if (strstart(filename, "unix:", &p)) {
3376
        return qemu_chr_open_tcp(p, 0, 1);
3377
    } else if (strstart(filename, "file:", &p)) {
3378
        return qemu_chr_open_file_out(p);
3379
    } else if (strstart(filename, "pipe:", &p)) {
3380
        return qemu_chr_open_pipe(p);
3381
    } else if (!strcmp(filename, "pty")) {
3382
        return qemu_chr_open_pty();
3383
    } else if (!strcmp(filename, "stdio")) {
3384
        return qemu_chr_open_stdio();
3385
    } else
3386
#if defined(__linux__)
3387
    if (strstart(filename, "/dev/parport", NULL)) {
3388
        return qemu_chr_open_pp(filename);
3389
    } else
3390
#endif
3391
#if defined(__linux__) || defined(__sun__)
3392
    if (strstart(filename, "/dev/", NULL)) {
3393
        return qemu_chr_open_tty(filename);
3394
    } else
3395
#endif
3396
#else /* !_WIN32 */
3397
    if (strstart(filename, "COM", NULL)) {
3398
        return qemu_chr_open_win(filename);
3399
    } else
3400
    if (strstart(filename, "pipe:", &p)) {
3401
        return qemu_chr_open_win_pipe(p);
3402
    } else
3403
    if (strstart(filename, "con:", NULL)) {
3404
        return qemu_chr_open_win_con(filename);
3405
    } else
3406
    if (strstart(filename, "file:", &p)) {
3407
        return qemu_chr_open_win_file_out(p);
3408
    }
3409
#endif
3410
    {
3411
        return NULL;
3412
    }
3413
}
3414

    
3415
void qemu_chr_close(CharDriverState *chr)
3416
{
3417
    if (chr->chr_close)
3418
        chr->chr_close(chr);
3419
}
3420

    
3421
/***********************************************************/
3422
/* network device redirectors */
3423

    
3424
__attribute__ (( unused ))
3425
static void hex_dump(FILE *f, const uint8_t *buf, int size)
3426
{
3427
    int len, i, j, c;
3428

    
3429
    for(i=0;i<size;i+=16) {
3430
        len = size - i;
3431
        if (len > 16)
3432
            len = 16;
3433
        fprintf(f, "%08x ", i);
3434
        for(j=0;j<16;j++) {
3435
            if (j < len)
3436
                fprintf(f, " %02x", buf[i+j]);
3437
            else
3438
                fprintf(f, "   ");
3439
        }
3440
        fprintf(f, " ");
3441
        for(j=0;j<len;j++) {
3442
            c = buf[i+j];
3443
            if (c < ' ' || c > '~')
3444
                c = '.';
3445
            fprintf(f, "%c", c);
3446
        }
3447
        fprintf(f, "\n");
3448
    }
3449
}
3450

    
3451
static int parse_macaddr(uint8_t *macaddr, const char *p)
3452
{
3453
    int i;
3454
    for(i = 0; i < 6; i++) {
3455
        macaddr[i] = strtol(p, (char **)&p, 16);
3456
        if (i == 5) {
3457
            if (*p != '\0')
3458
                return -1;
3459
        } else {
3460
            if (*p != ':')
3461
                return -1;
3462
            p++;
3463
        }
3464
    }
3465
    return 0;
3466
}
3467

    
3468
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3469
{
3470
    const char *p, *p1;
3471
    int len;
3472
    p = *pp;
3473
    p1 = strchr(p, sep);
3474
    if (!p1)
3475
        return -1;
3476
    len = p1 - p;
3477
    p1++;
3478
    if (buf_size > 0) {
3479
        if (len > buf_size - 1)
3480
            len = buf_size - 1;
3481
        memcpy(buf, p, len);
3482
        buf[len] = '\0';
3483
    }
3484
    *pp = p1;
3485
    return 0;
3486
}
3487

    
3488
int parse_host_src_port(struct sockaddr_in *haddr,
3489
                        struct sockaddr_in *saddr,
3490
                        const char *input_str)
3491
{
3492
    char *str = strdup(input_str);
3493
    char *host_str = str;
3494
    char *src_str;
3495
    char *ptr;
3496

    
3497
    /*
3498
     * Chop off any extra arguments at the end of the string which
3499
     * would start with a comma, then fill in the src port information
3500
     * if it was provided else use the "any address" and "any port".
3501
     */
3502
    if ((ptr = strchr(str,',')))
3503
        *ptr = '\0';
3504

    
3505
    if ((src_str = strchr(input_str,'@'))) {
3506
        *src_str = '\0';
3507
        src_str++;
3508
    }
3509

    
3510
    if (parse_host_port(haddr, host_str) < 0)
3511
        goto fail;
3512

    
3513
    if (!src_str || *src_str == '\0')
3514
        src_str = ":0";
3515

    
3516
    if (parse_host_port(saddr, src_str) < 0)
3517
        goto fail;
3518

    
3519
    free(str);
3520
    return(0);
3521

    
3522
fail:
3523
    free(str);
3524
    return -1;
3525
}
3526

    
3527
int parse_host_port(struct sockaddr_in *saddr, const char *str)
3528
{
3529
    char buf[512];
3530
    struct hostent *he;
3531
    const char *p, *r;
3532
    int port;
3533

    
3534
    p = str;
3535
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3536
        return -1;
3537
    saddr->sin_family = AF_INET;
3538
    if (buf[0] == '\0') {
3539
        saddr->sin_addr.s_addr = 0;
3540
    } else {
3541
        if (isdigit(buf[0])) {
3542
            if (!inet_aton(buf, &saddr->sin_addr))
3543
                return -1;
3544
        } else {
3545
            if ((he = gethostbyname(buf)) == NULL)
3546
                return - 1;
3547
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
3548
        }
3549
    }
3550
    port = strtol(p, (char **)&r, 0);
3551
    if (r == p)
3552
        return -1;
3553
    saddr->sin_port = htons(port);
3554
    return 0;
3555
}
3556

    
3557
#ifndef _WIN32
3558
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3559
{
3560
    const char *p;
3561
    int len;
3562

    
3563
    len = MIN(108, strlen(str));
3564
    p = strchr(str, ',');
3565
    if (p)
3566
        len = MIN(len, p - str);
3567

    
3568
    memset(uaddr, 0, sizeof(*uaddr));
3569

    
3570
    uaddr->sun_family = AF_UNIX;
3571
    memcpy(uaddr->sun_path, str, len);
3572

    
3573
    return 0;
3574
}
3575
#endif
3576

    
3577
/* find or alloc a new VLAN */
3578
VLANState *qemu_find_vlan(int id)
3579
{
3580
    VLANState **pvlan, *vlan;
3581
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3582
        if (vlan->id == id)
3583
            return vlan;
3584
    }
3585
    vlan = qemu_mallocz(sizeof(VLANState));
3586
    if (!vlan)
3587
        return NULL;
3588
    vlan->id = id;
3589
    vlan->next = NULL;
3590
    pvlan = &first_vlan;
3591
    while (*pvlan != NULL)
3592
        pvlan = &(*pvlan)->next;
3593
    *pvlan = vlan;
3594
    return vlan;
3595
}
3596

    
3597
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3598
                                      IOReadHandler *fd_read,
3599
                                      IOCanRWHandler *fd_can_read,
3600
                                      void *opaque)
3601
{
3602
    VLANClientState *vc, **pvc;
3603
    vc = qemu_mallocz(sizeof(VLANClientState));
3604
    if (!vc)
3605
        return NULL;
3606
    vc->fd_read = fd_read;
3607
    vc->fd_can_read = fd_can_read;
3608
    vc->opaque = opaque;
3609
    vc->vlan = vlan;
3610

    
3611
    vc->next = NULL;
3612
    pvc = &vlan->first_client;
3613
    while (*pvc != NULL)
3614
        pvc = &(*pvc)->next;
3615
    *pvc = vc;
3616
    return vc;
3617
}
3618

    
3619
int qemu_can_send_packet(VLANClientState *vc1)
3620
{
3621
    VLANState *vlan = vc1->vlan;
3622
    VLANClientState *vc;
3623

    
3624
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3625
        if (vc != vc1) {
3626
            if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3627
                return 1;
3628
        }
3629
    }
3630
    return 0;
3631
}
3632

    
3633
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3634
{
3635
    VLANState *vlan = vc1->vlan;
3636
    VLANClientState *vc;
3637

    
3638
#if 0
3639
    printf("vlan %d send:\n", vlan->id);
3640
    hex_dump(stdout, buf, size);
3641
#endif
3642
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3643
        if (vc != vc1) {
3644
            vc->fd_read(vc->opaque, buf, size);
3645
        }
3646
    }
3647
}
3648

    
3649
#if defined(CONFIG_SLIRP)
3650

    
3651
/* slirp network adapter */
3652

    
3653
static int slirp_inited;
3654
static VLANClientState *slirp_vc;
3655

    
3656
int slirp_can_output(void)
3657
{
3658
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
3659
}
3660

    
3661
void slirp_output(const uint8_t *pkt, int pkt_len)
3662
{
3663
#if 0
3664
    printf("slirp output:\n");
3665
    hex_dump(stdout, pkt, pkt_len);
3666
#endif
3667
    if (!slirp_vc)
3668
        return;
3669
    qemu_send_packet(slirp_vc, pkt, pkt_len);
3670
}
3671

    
3672
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3673
{
3674
#if 0
3675
    printf("slirp input:\n");
3676
    hex_dump(stdout, buf, size);
3677
#endif
3678
    slirp_input(buf, size);
3679
}
3680

    
3681
static int net_slirp_init(VLANState *vlan)
3682
{
3683
    if (!slirp_inited) {
3684
        slirp_inited = 1;
3685
        slirp_init();
3686
    }
3687
    slirp_vc = qemu_new_vlan_client(vlan,
3688
                                    slirp_receive, NULL, NULL);
3689
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3690
    return 0;
3691
}
3692

    
3693
static void net_slirp_redir(const char *redir_str)
3694
{
3695
    int is_udp;
3696
    char buf[256], *r;
3697
    const char *p;
3698
    struct in_addr guest_addr;
3699
    int host_port, guest_port;
3700

    
3701
    if (!slirp_inited) {
3702
        slirp_inited = 1;
3703
        slirp_init();
3704
    }
3705

    
3706
    p = redir_str;
3707
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3708
        goto fail;
3709
    if (!strcmp(buf, "tcp")) {
3710
        is_udp = 0;
3711
    } else if (!strcmp(buf, "udp")) {
3712
        is_udp = 1;
3713
    } else {
3714
        goto fail;
3715
    }
3716

    
3717
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3718
        goto fail;
3719
    host_port = strtol(buf, &r, 0);
3720
    if (r == buf)
3721
        goto fail;
3722

    
3723
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3724
        goto fail;
3725
    if (buf[0] == '\0') {
3726
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
3727
    }
3728
    if (!inet_aton(buf, &guest_addr))
3729
        goto fail;
3730

    
3731
    guest_port = strtol(p, &r, 0);
3732
    if (r == p)
3733
        goto fail;
3734

    
3735
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3736
        fprintf(stderr, "qemu: could not set up redirection\n");
3737
        exit(1);
3738
    }
3739
    return;
3740
 fail:
3741
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3742
    exit(1);
3743
}
3744

    
3745
#ifndef _WIN32
3746

    
3747
char smb_dir[1024];
3748

    
3749
static void smb_exit(void)
3750
{
3751
    DIR *d;
3752
    struct dirent *de;
3753
    char filename[1024];
3754

    
3755
    /* erase all the files in the directory */
3756
    d = opendir(smb_dir);
3757
    for(;;) {
3758
        de = readdir(d);
3759
        if (!de)
3760
            break;
3761
        if (strcmp(de->d_name, ".") != 0 &&
3762
            strcmp(de->d_name, "..") != 0) {
3763
            snprintf(filename, sizeof(filename), "%s/%s",
3764
                     smb_dir, de->d_name);
3765
            unlink(filename);
3766
        }
3767
    }
3768
    closedir(d);
3769
    rmdir(smb_dir);
3770
}
3771

    
3772
/* automatic user mode samba server configuration */
3773
static void net_slirp_smb(const char *exported_dir)
3774
{
3775
    char smb_conf[1024];
3776
    char smb_cmdline[1024];
3777
    FILE *f;
3778

    
3779
    if (!slirp_inited) {
3780
        slirp_inited = 1;
3781
        slirp_init();
3782
    }
3783

    
3784
    /* XXX: better tmp dir construction */
3785
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3786
    if (mkdir(smb_dir, 0700) < 0) {
3787
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3788
        exit(1);
3789
    }
3790
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3791

    
3792
    f = fopen(smb_conf, "w");
3793
    if (!f) {
3794
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3795
        exit(1);
3796
    }
3797
    fprintf(f,
3798
            "[global]\n"
3799
            "private dir=%s\n"
3800
            "smb ports=0\n"
3801
            "socket address=127.0.0.1\n"
3802
            "pid directory=%s\n"
3803
            "lock directory=%s\n"
3804
            "log file=%s/log.smbd\n"
3805
            "smb passwd file=%s/smbpasswd\n"
3806
            "security = share\n"
3807
            "[qemu]\n"
3808
            "path=%s\n"
3809
            "read only=no\n"
3810
            "guest ok=yes\n",
3811
            smb_dir,
3812
            smb_dir,
3813
            smb_dir,
3814
            smb_dir,
3815
            smb_dir,
3816
            exported_dir
3817
            );
3818
    fclose(f);
3819
    atexit(smb_exit);
3820

    
3821
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3822
             SMBD_COMMAND, smb_conf);
3823

    
3824
    slirp_add_exec(0, smb_cmdline, 4, 139);
3825
}
3826

    
3827
#endif /* !defined(_WIN32) */
3828
void do_info_slirp(void)
3829
{
3830
    slirp_stats();
3831
}
3832

    
3833
#endif /* CONFIG_SLIRP */
3834

    
3835
#if !defined(_WIN32)
3836

    
3837
typedef struct TAPState {
3838
    VLANClientState *vc;
3839
    int fd;
3840
    char down_script[1024];
3841
} TAPState;
3842

    
3843
static void tap_receive(void *opaque, const uint8_t *buf, int size)
3844
{
3845
    TAPState *s = opaque;
3846
    int ret;
3847
    for(;;) {
3848
        ret = write(s->fd, buf, size);
3849
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3850
        } else {
3851
            break;
3852
        }
3853
    }
3854
}
3855

    
3856
static void tap_send(void *opaque)
3857
{
3858
    TAPState *s = opaque;
3859
    uint8_t buf[4096];
3860
    int size;
3861

    
3862
#ifdef __sun__
3863
    struct strbuf sbuf;
3864
    int f = 0;
3865
    sbuf.maxlen = sizeof(buf);
3866
    sbuf.buf = buf;
3867
    size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3868
#else
3869
    size = read(s->fd, buf, sizeof(buf));
3870
#endif
3871
    if (size > 0) {
3872
        qemu_send_packet(s->vc, buf, size);
3873
    }
3874
}
3875

    
3876
/* fd support */
3877

    
3878
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3879
{
3880
    TAPState *s;
3881

    
3882
    s = qemu_mallocz(sizeof(TAPState));
3883
    if (!s)
3884
        return NULL;
3885
    s->fd = fd;
3886
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3887
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3888
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3889
    return s;
3890
}
3891

    
3892
#if defined (_BSD) || defined (__FreeBSD_kernel__)
3893
static int tap_open(char *ifname, int ifname_size)
3894
{
3895
    int fd;
3896
    char *dev;
3897
    struct stat s;
3898

    
3899
    TFR(fd = open("/dev/tap", O_RDWR));
3900
    if (fd < 0) {
3901
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3902
        return -1;
3903
    }
3904

    
3905
    fstat(fd, &s);
3906
    dev = devname(s.st_rdev, S_IFCHR);
3907
    pstrcpy(ifname, ifname_size, dev);
3908

    
3909
    fcntl(fd, F_SETFL, O_NONBLOCK);
3910
    return fd;
3911
}
3912
#elif defined(__sun__)
3913
#define TUNNEWPPA       (('T'<<16) | 0x0001)
3914
/*
3915
 * Allocate TAP device, returns opened fd.
3916
 * Stores dev name in the first arg(must be large enough).
3917
 */
3918
int tap_alloc(char *dev)
3919
{
3920
    int tap_fd, if_fd, ppa = -1;
3921
    static int ip_fd = 0;
3922
    char *ptr;
3923

    
3924
    static int arp_fd = 0;
3925
    int ip_muxid, arp_muxid;
3926
    struct strioctl  strioc_if, strioc_ppa;
3927
    int link_type = I_PLINK;;
3928
    struct lifreq ifr;
3929
    char actual_name[32] = "";
3930

    
3931
    memset(&ifr, 0x0, sizeof(ifr));
3932

    
3933
    if( *dev ){
3934
       ptr = dev;
3935
       while( *ptr && !isdigit((int)*ptr) ) ptr++;
3936
       ppa = atoi(ptr);
3937
    }
3938

    
3939
    /* Check if IP device was opened */
3940
    if( ip_fd )
3941
       close(ip_fd);
3942

    
3943
    TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
3944
    if (ip_fd < 0) {
3945
       syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3946
       return -1;
3947
    }
3948

    
3949
    TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
3950
    if (tap_fd < 0) {
3951
       syslog(LOG_ERR, "Can't open /dev/tap");
3952
       return -1;
3953
    }
3954

    
3955
    /* Assign a new PPA and get its unit number. */
3956
    strioc_ppa.ic_cmd = TUNNEWPPA;
3957
    strioc_ppa.ic_timout = 0;
3958
    strioc_ppa.ic_len = sizeof(ppa);
3959
    strioc_ppa.ic_dp = (char *)&ppa;
3960
    if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3961
       syslog (LOG_ERR, "Can't assign new interface");
3962

    
3963
    TFR(if_fd = open("/dev/tap", O_RDWR, 0));
3964
    if (if_fd < 0) {
3965
       syslog(LOG_ERR, "Can't open /dev/tap (2)");
3966
       return -1;
3967
    }
3968
    if(ioctl(if_fd, I_PUSH, "ip") < 0){
3969
       syslog(LOG_ERR, "Can't push IP module");
3970
       return -1;
3971
    }
3972

    
3973
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3974
        syslog(LOG_ERR, "Can't get flags\n");
3975

    
3976
    snprintf (actual_name, 32, "tap%d", ppa);
3977
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3978

    
3979
    ifr.lifr_ppa = ppa;
3980
    /* Assign ppa according to the unit number returned by tun device */
3981

    
3982
    if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3983
        syslog (LOG_ERR, "Can't set PPA %d", ppa);
3984
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3985
        syslog (LOG_ERR, "Can't get flags\n");
3986
    /* Push arp module to if_fd */
3987
    if (ioctl (if_fd, I_PUSH, "arp") < 0)
3988
        syslog (LOG_ERR, "Can't push ARP module (2)");
3989

    
3990
    /* Push arp module to ip_fd */
3991
    if (ioctl (ip_fd, I_POP, NULL) < 0)
3992
        syslog (LOG_ERR, "I_POP failed\n");
3993
    if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3994
        syslog (LOG_ERR, "Can't push ARP module (3)\n");
3995
    /* Open arp_fd */
3996
    TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
3997
    if (arp_fd < 0)
3998
       syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3999

    
4000
    /* Set ifname to arp */
4001
    strioc_if.ic_cmd = SIOCSLIFNAME;
4002
    strioc_if.ic_timout = 0;
4003
    strioc_if.ic_len = sizeof(ifr);
4004
    strioc_if.ic_dp = (char *)&ifr;
4005
    if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4006
        syslog (LOG_ERR, "Can't set ifname to arp\n");
4007
    }
4008

    
4009
    if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4010
       syslog(LOG_ERR, "Can't link TAP device to IP");
4011
       return -1;
4012
    }
4013

    
4014
    if ((arp_muxid = ioctl (ip_fd, link_type, arp_fd)) < 0)
4015
        syslog (LOG_ERR, "Can't link TAP device to ARP");
4016

    
4017
    close (if_fd);
4018

    
4019
    memset(&ifr, 0x0, sizeof(ifr));
4020
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4021
    ifr.lifr_ip_muxid  = ip_muxid;
4022
    ifr.lifr_arp_muxid = arp_muxid;
4023

    
4024
    if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4025
    {
4026
      ioctl (ip_fd, I_PUNLINK , arp_muxid);
4027
      ioctl (ip_fd, I_PUNLINK, ip_muxid);
4028
      syslog (LOG_ERR, "Can't set multiplexor id");
4029
    }
4030

    
4031
    sprintf(dev, "tap%d", ppa);
4032
    return tap_fd;
4033
}
4034

    
4035
static int tap_open(char *ifname, int ifname_size)
4036
{
4037
    char  dev[10]="";
4038
    int fd;
4039
    if( (fd = tap_alloc(dev)) < 0 ){
4040
       fprintf(stderr, "Cannot allocate TAP device\n");
4041
       return -1;
4042
    }
4043
    pstrcpy(ifname, ifname_size, dev);
4044
    fcntl(fd, F_SETFL, O_NONBLOCK);
4045
    return fd;
4046
}
4047
#else
4048
static int tap_open(char *ifname, int ifname_size)
4049
{
4050
    struct ifreq ifr;
4051
    int fd, ret;
4052

    
4053
    TFR(fd = open("/dev/net/tun", O_RDWR));
4054
    if (fd < 0) {
4055
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4056
        return -1;
4057
    }
4058
    memset(&ifr, 0, sizeof(ifr));
4059
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4060
    if (ifname[0] != '\0')
4061
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4062
    else
4063
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4064
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4065
    if (ret != 0) {
4066
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4067
        close(fd);
4068
        return -1;
4069
    }
4070
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
4071
    fcntl(fd, F_SETFL, O_NONBLOCK);
4072
    return fd;
4073
}
4074
#endif
4075

    
4076
static int launch_script(const char *setup_script, const char *ifname, int fd)
4077
{
4078
    int pid, status;
4079
    char *args[3];
4080
    char **parg;
4081

    
4082
        /* try to launch network script */
4083
        pid = fork();
4084
        if (pid >= 0) {
4085
            if (pid == 0) {
4086
                int open_max = sysconf (_SC_OPEN_MAX), i;
4087
                for (i = 0; i < open_max; i++)
4088
                    if (i != STDIN_FILENO &&
4089
                        i != STDOUT_FILENO &&
4090
                        i != STDERR_FILENO &&
4091
                        i != fd)
4092
                        close(i);
4093

    
4094
                parg = args;
4095
                *parg++ = (char *)setup_script;
4096
                *parg++ = (char *)ifname;
4097
                *parg++ = NULL;
4098
                execv(setup_script, args);
4099
                _exit(1);
4100
            }
4101
            while (waitpid(pid, &status, 0) != pid);
4102
            if (!WIFEXITED(status) ||
4103
                WEXITSTATUS(status) != 0) {
4104
                fprintf(stderr, "%s: could not launch network script\n",
4105
                        setup_script);
4106
                return -1;
4107
            }
4108
        }
4109
    return 0;
4110
}
4111

    
4112
static int net_tap_init(VLANState *vlan, const char *ifname1,
4113
                        const char *setup_script, const char *down_script)
4114
{
4115
    TAPState *s;
4116
    int fd;
4117
    char ifname[128];
4118

    
4119
    if (ifname1 != NULL)
4120
        pstrcpy(ifname, sizeof(ifname), ifname1);
4121
    else
4122
        ifname[0] = '\0';
4123
    TFR(fd = tap_open(ifname, sizeof(ifname)));
4124
    if (fd < 0)
4125
        return -1;
4126

    
4127
    if (!setup_script || !strcmp(setup_script, "no"))
4128
        setup_script = "";
4129
    if (setup_script[0] != '\0') {
4130
        if (launch_script(setup_script, ifname, fd))
4131
            return -1;
4132
    }
4133
    s = net_tap_fd_init(vlan, fd);
4134
    if (!s)
4135
        return -1;
4136
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4137
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
4138
    if (down_script && strcmp(down_script, "no"))
4139
        snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4140
    return 0;
4141
}
4142

    
4143
#endif /* !_WIN32 */
4144

    
4145
/* network connection */
4146
typedef struct NetSocketState {
4147
    VLANClientState *vc;
4148
    int fd;
4149
    int state; /* 0 = getting length, 1 = getting data */
4150
    int index;
4151
    int packet_len;
4152
    uint8_t buf[4096];
4153
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4154
} NetSocketState;
4155

    
4156
typedef struct NetSocketListenState {
4157
    VLANState *vlan;
4158
    int fd;
4159
} NetSocketListenState;
4160

    
4161
/* XXX: we consider we can send the whole packet without blocking */
4162
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4163
{
4164
    NetSocketState *s = opaque;
4165
    uint32_t len;
4166
    len = htonl(size);
4167

    
4168
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4169
    send_all(s->fd, buf, size);
4170
}
4171

    
4172
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4173
{
4174
    NetSocketState *s = opaque;
4175
    sendto(s->fd, buf, size, 0,
4176
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4177
}
4178

    
4179
static void net_socket_send(void *opaque)
4180
{
4181
    NetSocketState *s = opaque;
4182
    int l, size, err;
4183
    uint8_t buf1[4096];
4184
    const uint8_t *buf;
4185

    
4186
    size = recv(s->fd, buf1, sizeof(buf1), 0);
4187
    if (size < 0) {
4188
        err = socket_error();
4189
        if (err != EWOULDBLOCK)
4190
            goto eoc;
4191
    } else if (size == 0) {
4192
        /* end of connection */
4193
    eoc:
4194
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4195
        closesocket(s->fd);
4196
        return;
4197
    }
4198
    buf = buf1;
4199
    while (size > 0) {
4200
        /* reassemble a packet from the network */
4201
        switch(s->state) {
4202
        case 0:
4203
            l = 4 - s->index;
4204
            if (l > size)
4205
                l = size;
4206
            memcpy(s->buf + s->index, buf, l);
4207
            buf += l;
4208
            size -= l;
4209
            s->index += l;
4210
            if (s->index == 4) {
4211
                /* got length */
4212
                s->packet_len = ntohl(*(uint32_t *)s->buf);
4213
                s->index = 0;
4214
                s->state = 1;
4215
            }
4216
            break;
4217
        case 1:
4218
            l = s->packet_len - s->index;
4219
            if (l > size)
4220
                l = size;
4221
            memcpy(s->buf + s->index, buf, l);
4222
            s->index += l;
4223
            buf += l;
4224
            size -= l;
4225
            if (s->index >= s->packet_len) {
4226
                qemu_send_packet(s->vc, s->buf, s->packet_len);
4227
                s->index = 0;
4228
                s->state = 0;
4229
            }
4230
            break;
4231
        }
4232
    }
4233
}
4234

    
4235
static void net_socket_send_dgram(void *opaque)
4236
{
4237
    NetSocketState *s = opaque;
4238
    int size;
4239

    
4240
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4241
    if (size < 0)
4242
        return;
4243
    if (size == 0) {
4244
        /* end of connection */
4245
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4246
        return;
4247
    }
4248
    qemu_send_packet(s->vc, s->buf, size);
4249
}
4250

    
4251
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4252
{
4253
    struct ip_mreq imr;
4254
    int fd;
4255
    int val, ret;
4256
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4257
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4258
                inet_ntoa(mcastaddr->sin_addr),
4259
                (int)ntohl(mcastaddr->sin_addr.s_addr));
4260
        return -1;
4261

    
4262
    }
4263
    fd = socket(PF_INET, SOCK_DGRAM, 0);
4264
    if (fd < 0) {
4265
        perror("socket(PF_INET, SOCK_DGRAM)");
4266
        return -1;
4267
    }
4268

    
4269
    val = 1;
4270
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4271
                   (const char *)&val, sizeof(val));
4272
    if (ret < 0) {
4273
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4274
        goto fail;
4275
    }
4276

    
4277
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4278
    if (ret < 0) {
4279
        perror("bind");
4280
        goto fail;
4281
    }
4282

    
4283
    /* Add host to multicast group */
4284
    imr.imr_multiaddr = mcastaddr->sin_addr;
4285
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
4286

    
4287
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4288
                     (const char *)&imr, sizeof(struct ip_mreq));
4289
    if (ret < 0) {
4290
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
4291
        goto fail;
4292
    }
4293

    
4294
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4295
    val = 1;
4296
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4297
                   (const char *)&val, sizeof(val));
4298
    if (ret < 0) {
4299
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4300
        goto fail;
4301
    }
4302

    
4303
    socket_set_nonblock(fd);
4304
    return fd;
4305
fail:
4306
    if (fd >= 0)
4307
        closesocket(fd);
4308
    return -1;
4309
}
4310

    
4311
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4312
                                          int is_connected)
4313
{
4314
    struct sockaddr_in saddr;
4315
    int newfd;
4316
    socklen_t saddr_len;
4317
    NetSocketState *s;
4318

    
4319
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4320
     * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4321
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
4322
     */
4323

    
4324
    if (is_connected) {
4325
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4326
            /* must be bound */
4327
            if (saddr.sin_addr.s_addr==0) {
4328
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4329
                        fd);
4330
                return NULL;
4331
            }
4332
            /* clone dgram socket */
4333
            newfd = net_socket_mcast_create(&saddr);
4334
            if (newfd < 0) {
4335
                /* error already reported by net_socket_mcast_create() */
4336
                close(fd);
4337
                return NULL;
4338
            }
4339
            /* clone newfd to fd, close newfd */
4340
            dup2(newfd, fd);
4341
            close(newfd);
4342

    
4343
        } else {
4344
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4345
                    fd, strerror(errno));
4346
            return NULL;
4347
        }
4348
    }
4349

    
4350
    s = qemu_mallocz(sizeof(NetSocketState));
4351
    if (!s)
4352
        return NULL;
4353
    s->fd = fd;
4354

    
4355
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4356
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4357

    
4358
    /* mcast: save bound address as dst */
4359
    if (is_connected) s->dgram_dst=saddr;
4360

    
4361
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4362
            "socket: fd=%d (%s mcast=%s:%d)",
4363
            fd, is_connected? "cloned" : "",
4364
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4365
    return s;
4366
}
4367

    
4368
static void net_socket_connect(void *opaque)
4369
{
4370
    NetSocketState *s = opaque;
4371
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4372
}
4373

    
4374
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4375
                                          int is_connected)
4376
{
4377
    NetSocketState *s;
4378
    s = qemu_mallocz(sizeof(NetSocketState));
4379
    if (!s)
4380
        return NULL;
4381
    s->fd = fd;
4382
    s->vc = qemu_new_vlan_client(vlan,
4383
                                 net_socket_receive, NULL, s);
4384
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4385
             "socket: fd=%d", fd);
4386
    if (is_connected) {
4387
        net_socket_connect(s);
4388
    } else {
4389
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4390
    }
4391
    return s;
4392
}
4393

    
4394
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4395
                                          int is_connected)
4396
{
4397
    int so_type=-1, optlen=sizeof(so_type);
4398

    
4399
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
4400
        fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4401
        return NULL;
4402
    }
4403
    switch(so_type) {
4404
    case SOCK_DGRAM:
4405
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
4406
    case SOCK_STREAM:
4407
        return net_socket_fd_init_stream(vlan, fd, is_connected);
4408
    default:
4409
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4410
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4411
        return net_socket_fd_init_stream(vlan, fd, is_connected);
4412
    }
4413
    return NULL;
4414
}
4415

    
4416
static void net_socket_accept(void *opaque)
4417
{
4418
    NetSocketListenState *s = opaque;
4419
    NetSocketState *s1;
4420
    struct sockaddr_in saddr;
4421
    socklen_t len;
4422
    int fd;
4423

    
4424
    for(;;) {
4425
        len = sizeof(saddr);
4426
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4427
        if (fd < 0 && errno != EINTR) {
4428
            return;
4429
        } else if (fd >= 0) {
4430
            break;
4431
        }
4432
    }
4433
    s1 = net_socket_fd_init(s->vlan, fd, 1);
4434
    if (!s1) {
4435
        closesocket(fd);
4436
    } else {
4437
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4438
                 "socket: connection from %s:%d",
4439
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4440
    }
4441
}
4442

    
4443
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4444
{
4445
    NetSocketListenState *s;
4446
    int fd, val, ret;
4447
    struct sockaddr_in saddr;
4448

    
4449
    if (parse_host_port(&saddr, host_str) < 0)
4450
        return -1;
4451

    
4452
    s = qemu_mallocz(sizeof(NetSocketListenState));
4453
    if (!s)
4454
        return -1;
4455

    
4456
    fd = socket(PF_INET, SOCK_STREAM, 0);
4457
    if (fd < 0) {
4458
        perror("socket");
4459
        return -1;
4460
    }
4461
    socket_set_nonblock(fd);
4462

    
4463
    /* allow fast reuse */
4464
    val = 1;
4465
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4466

    
4467
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4468
    if (ret < 0) {
4469
        perror("bind");
4470
        return -1;
4471
    }
4472
    ret = listen(fd, 0);
4473
    if (ret < 0) {
4474
        perror("listen");
4475
        return -1;
4476
    }
4477
    s->vlan = vlan;
4478
    s->fd = fd;
4479
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4480
    return 0;
4481
}
4482

    
4483
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4484
{
4485
    NetSocketState *s;
4486
    int fd, connected, ret, err;
4487
    struct sockaddr_in saddr;
4488

    
4489
    if (parse_host_port(&saddr, host_str) < 0)
4490
        return -1;
4491

    
4492
    fd = socket(PF_INET, SOCK_STREAM, 0);
4493
    if (fd < 0) {
4494
        perror("socket");
4495
        return -1;
4496
    }
4497
    socket_set_nonblock(fd);
4498

    
4499
    connected = 0;
4500
    for(;;) {
4501
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4502
        if (ret < 0) {
4503
            err = socket_error();
4504
            if (err == EINTR || err == EWOULDBLOCK) {
4505
            } else if (err == EINPROGRESS) {
4506
                break;
4507
#ifdef _WIN32
4508
            } else if (err == WSAEALREADY) {
4509
                break;
4510
#endif
4511
            } else {
4512
                perror("connect");
4513
                closesocket(fd);
4514
                return -1;
4515
            }
4516
        } else {
4517
            connected = 1;
4518
            break;
4519
        }
4520
    }
4521
    s = net_socket_fd_init(vlan, fd, connected);
4522
    if (!s)
4523
        return -1;
4524
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4525
             "socket: connect to %s:%d",
4526
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4527
    return 0;
4528
}
4529

    
4530
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4531
{
4532
    NetSocketState *s;
4533
    int fd;
4534
    struct sockaddr_in saddr;
4535

    
4536
    if (parse_host_port(&saddr, host_str) < 0)
4537
        return -1;
4538

    
4539

    
4540
    fd = net_socket_mcast_create(&saddr);
4541
    if (fd < 0)
4542
        return -1;
4543

    
4544
    s = net_socket_fd_init(vlan, fd, 0);
4545
    if (!s)
4546
        return -1;
4547

    
4548
    s->dgram_dst = saddr;
4549

    
4550
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4551
             "socket: mcast=%s:%d",
4552
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4553
    return 0;
4554

    
4555
}
4556

    
4557
static int get_param_value(char *buf, int buf_size,
4558
                           const char *tag, const char *str)
4559
{
4560
    const char *p;
4561
    char *q;
4562
    char option[128];
4563

    
4564
    p = str;
4565
    for(;;) {
4566
        q = option;
4567
        while (*p != '\0' && *p != '=') {
4568
            if ((q - option) < sizeof(option) - 1)
4569
                *q++ = *p;
4570
            p++;
4571
        }
4572
        *q = '\0';
4573
        if (*p != '=')
4574
            break;
4575
        p++;
4576
        if (!strcmp(tag, option)) {
4577
            q = buf;
4578
            while (*p != '\0' && *p != ',') {
4579
                if ((q - buf) < buf_size - 1)
4580
                    *q++ = *p;
4581
                p++;
4582
            }
4583
            *q = '\0';
4584
            return q - buf;
4585
        } else {
4586
            while (*p != '\0' && *p != ',') {
4587
                p++;
4588
            }
4589
        }
4590
        if (*p != ',')
4591
            break;
4592
        p++;
4593
    }
4594
    return 0;
4595
}
4596

    
4597
static int net_client_init(const char *str)
4598
{
4599
    const char *p;
4600
    char *q;
4601
    char device[64];
4602
    char buf[1024];
4603
    int vlan_id, ret;
4604
    VLANState *vlan;
4605

    
4606
    p = str;
4607
    q = device;
4608
    while (*p != '\0' && *p != ',') {
4609
        if ((q - device) < sizeof(device) - 1)
4610
            *q++ = *p;
4611
        p++;
4612
    }
4613
    *q = '\0';
4614
    if (*p == ',')
4615
        p++;
4616
    vlan_id = 0;
4617
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4618
        vlan_id = strtol(buf, NULL, 0);
4619
    }
4620
    vlan = qemu_find_vlan(vlan_id);
4621
    if (!vlan) {
4622
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4623
        return -1;
4624
    }
4625
    if (!strcmp(device, "nic")) {
4626
        NICInfo *nd;
4627
        uint8_t *macaddr;
4628

    
4629
        if (nb_nics >= MAX_NICS) {
4630
            fprintf(stderr, "Too Many NICs\n");
4631
            return -1;
4632
        }
4633
        nd = &nd_table[nb_nics];
4634
        macaddr = nd->macaddr;
4635
        macaddr[0] = 0x52;
4636
        macaddr[1] = 0x54;
4637
        macaddr[2] = 0x00;
4638
        macaddr[3] = 0x12;
4639
        macaddr[4] = 0x34;
4640
        macaddr[5] = 0x56 + nb_nics;
4641

    
4642
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4643
            if (parse_macaddr(macaddr, buf) < 0) {
4644
                fprintf(stderr, "invalid syntax for ethernet address\n");
4645
                return -1;
4646
            }
4647
        }
4648
        if (get_param_value(buf, sizeof(buf), "model", p)) {
4649
            nd->model = strdup(buf);
4650
        }
4651
        nd->vlan = vlan;
4652
        nb_nics++;
4653
        vlan->nb_guest_devs++;
4654
        ret = 0;
4655
    } else
4656
    if (!strcmp(device, "none")) {
4657
        /* does nothing. It is needed to signal that no network cards
4658
           are wanted */
4659
        ret = 0;
4660
    } else
4661
#ifdef CONFIG_SLIRP
4662
    if (!strcmp(device, "user")) {
4663
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4664
            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4665
        }
4666
        vlan->nb_host_devs++;
4667
        ret = net_slirp_init(vlan);
4668
    } else
4669
#endif
4670
#ifdef _WIN32
4671
    if (!strcmp(device, "tap")) {
4672
        char ifname[64];
4673
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4674
            fprintf(stderr, "tap: no interface name\n");
4675
            return -1;
4676
        }
4677
        vlan->nb_host_devs++;
4678
        ret = tap_win32_init(vlan, ifname);
4679
    } else
4680
#else
4681
    if (!strcmp(device, "tap")) {
4682
        char ifname[64];
4683
        char setup_script[1024], down_script[1024];
4684
        int fd;
4685
        vlan->nb_host_devs++;
4686
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4687
            fd = strtol(buf, NULL, 0);
4688
            ret = -1;
4689
            if (net_tap_fd_init(vlan, fd))
4690
                ret = 0;
4691
        } else {
4692
            if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4693
                ifname[0] = '\0';
4694
            }
4695
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4696
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4697
            }
4698
            if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
4699
                pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
4700
            }
4701
            ret = net_tap_init(vlan, ifname, setup_script, down_script);
4702
        }
4703
    } else
4704
#endif
4705
    if (!strcmp(device, "socket")) {
4706
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4707
            int fd;
4708
            fd = strtol(buf, NULL, 0);
4709
            ret = -1;
4710
            if (net_socket_fd_init(vlan, fd, 1))
4711
                ret = 0;
4712
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4713
            ret = net_socket_listen_init(vlan, buf);
4714
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4715
            ret = net_socket_connect_init(vlan, buf);
4716
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4717
            ret = net_socket_mcast_init(vlan, buf);
4718
        } else {
4719
            fprintf(stderr, "Unknown socket options: %s\n", p);
4720
            return -1;
4721
        }
4722
        vlan->nb_host_devs++;
4723
    } else
4724
    {
4725
        fprintf(stderr, "Unknown network device: %s\n", device);
4726
        return -1;
4727
    }
4728
    if (ret < 0) {
4729
        fprintf(stderr, "Could not initialize device '%s'\n", device);
4730
    }
4731

    
4732
    return ret;
4733
}
4734

    
4735
void do_info_network(void)
4736
{
4737
    VLANState *vlan;
4738
    VLANClientState *vc;
4739

    
4740
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4741
        term_printf("VLAN %d devices:\n", vlan->id);
4742
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4743
            term_printf("  %s\n", vc->info_str);
4744
    }
4745
}
4746

    
4747
/***********************************************************/
4748
/* USB devices */
4749

    
4750
static USBPort *used_usb_ports;
4751
static USBPort *free_usb_ports;
4752

    
4753
/* ??? Maybe change this to register a hub to keep track of the topology.  */
4754
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4755
                            usb_attachfn attach)
4756
{
4757
    port->opaque = opaque;
4758
    port->index = index;
4759
    port->attach = attach;
4760
    port->next = free_usb_ports;
4761
    free_usb_ports = port;
4762
}
4763

    
4764
static int usb_device_add(const char *devname)
4765
{
4766
    const char *p;
4767
    USBDevice *dev;
4768
    USBPort *port;
4769

    
4770
    if (!free_usb_ports)
4771
        return -1;
4772

    
4773
    if (strstart(devname, "host:", &p)) {
4774
        dev = usb_host_device_open(p);
4775
    } else if (!strcmp(devname, "mouse")) {
4776
        dev = usb_mouse_init();
4777
    } else if (!strcmp(devname, "tablet")) {
4778
        dev = usb_tablet_init();
4779
    } else if (!strcmp(devname, "keyboard")) {
4780
        dev = usb_keyboard_init();
4781
    } else if (strstart(devname, "disk:", &p)) {
4782
        dev = usb_msd_init(p);
4783
    } else if (!strcmp(devname, "wacom-tablet")) {
4784
        dev = usb_wacom_init();
4785
    } else {
4786
        return -1;
4787
    }
4788
    if (!dev)
4789
        return -1;
4790

    
4791
    /* Find a USB port to add the device to.  */
4792
    port = free_usb_ports;
4793
    if (!port->next) {
4794
        USBDevice *hub;
4795

    
4796
        /* Create a new hub and chain it on.  */
4797
        free_usb_ports = NULL;
4798
        port->next = used_usb_ports;
4799
        used_usb_ports = port;
4800

    
4801
        hub = usb_hub_init(VM_USB_HUB_SIZE);
4802
        usb_attach(port, hub);
4803
        port = free_usb_ports;
4804
    }
4805

    
4806
    free_usb_ports = port->next;
4807
    port->next = used_usb_ports;
4808
    used_usb_ports = port;
4809
    usb_attach(port, dev);
4810
    return 0;
4811
}
4812

    
4813
static int usb_device_del(const char *devname)
4814
{
4815
    USBPort *port;
4816
    USBPort **lastp;
4817
    USBDevice *dev;
4818
    int bus_num, addr;
4819
    const char *p;
4820

    
4821
    if (!used_usb_ports)
4822
        return -1;
4823

    
4824
    p = strchr(devname, '.');
4825
    if (!p)
4826
        return -1;
4827
    bus_num = strtoul(devname, NULL, 0);
4828
    addr = strtoul(p + 1, NULL, 0);
4829
    if (bus_num != 0)
4830
        return -1;
4831

    
4832
    lastp = &used_usb_ports;
4833
    port = used_usb_ports;
4834
    while (port && port->dev->addr != addr) {
4835
        lastp = &port->next;
4836
        port = port->next;
4837
    }
4838

    
4839
    if (!port)
4840
        return -1;
4841

    
4842
    dev = port->dev;
4843
    *lastp = port->next;
4844
    usb_attach(port, NULL);
4845
    dev->handle_destroy(dev);
4846
    port->next = free_usb_ports;
4847
    free_usb_ports = port;
4848
    return 0;
4849
}
4850

    
4851
void do_usb_add(const char *devname)
4852
{
4853
    int ret;
4854
    ret = usb_device_add(devname);
4855
    if (ret < 0)
4856
        term_printf("Could not add USB device '%s'\n", devname);
4857
}
4858

    
4859
void do_usb_del(const char *devname)
4860
{
4861
    int ret;
4862
    ret = usb_device_del(devname);
4863
    if (ret < 0)
4864
        term_printf("Could not remove USB device '%s'\n", devname);
4865
}
4866

    
4867
void usb_info(void)
4868
{
4869
    USBDevice *dev;
4870
    USBPort *port;
4871
    const char *speed_str;
4872

    
4873
    if (!usb_enabled) {
4874
        term_printf("USB support not enabled\n");
4875
        return;
4876
    }
4877

    
4878
    for (port = used_usb_ports; port; port = port->next) {
4879
        dev = port->dev;
4880
        if (!dev)
4881
            continue;
4882
        switch(dev->speed) {
4883
        case USB_SPEED_LOW:
4884
            speed_str = "1.5";
4885
            break;
4886
        case USB_SPEED_FULL:
4887
            speed_str = "12";
4888
            break;
4889
        case USB_SPEED_HIGH:
4890
            speed_str = "480";
4891
            break;
4892
        default:
4893
            speed_str = "?";
4894
            break;
4895
        }
4896
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n",
4897
                    0, dev->addr, speed_str, dev->devname);
4898
    }
4899
}
4900

    
4901
/***********************************************************/
4902
/* PCMCIA/Cardbus */
4903

    
4904
static struct pcmcia_socket_entry_s {
4905
    struct pcmcia_socket_s *socket;
4906
    struct pcmcia_socket_entry_s *next;
4907
} *pcmcia_sockets = 0;
4908

    
4909
void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4910
{
4911
    struct pcmcia_socket_entry_s *entry;
4912

    
4913
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4914
    entry->socket = socket;
4915
    entry->next = pcmcia_sockets;
4916
    pcmcia_sockets = entry;
4917
}
4918

    
4919
void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4920
{
4921
    struct pcmcia_socket_entry_s *entry, **ptr;
4922

    
4923
    ptr = &pcmcia_sockets;
4924
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4925
        if (entry->socket == socket) {
4926
            *ptr = entry->next;
4927
            qemu_free(entry);
4928
        }
4929
}
4930

    
4931
void pcmcia_info(void)
4932
{
4933
    struct pcmcia_socket_entry_s *iter;
4934
    if (!pcmcia_sockets)
4935
        term_printf("No PCMCIA sockets\n");
4936

    
4937
    for (iter = pcmcia_sockets; iter; iter = iter->next)
4938
        term_printf("%s: %s\n", iter->socket->slot_string,
4939
                    iter->socket->attached ? iter->socket->card_string :
4940
                    "Empty");
4941
}
4942

    
4943
/***********************************************************/
4944
/* dumb display */
4945

    
4946
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4947
{
4948
}
4949

    
4950
static void dumb_resize(DisplayState *ds, int w, int h)
4951
{
4952
}
4953

    
4954
static void dumb_refresh(DisplayState *ds)
4955
{
4956
#if defined(CONFIG_SDL)
4957
    vga_hw_update();
4958
#endif
4959
}
4960

    
4961
static void dumb_display_init(DisplayState *ds)
4962
{
4963
    ds->data = NULL;
4964
    ds->linesize = 0;
4965
    ds->depth = 0;
4966
    ds->dpy_update = dumb_update;
4967
    ds->dpy_resize = dumb_resize;
4968
    ds->dpy_refresh = dumb_refresh;
4969
}
4970

    
4971
/***********************************************************/
4972
/* I/O handling */
4973

    
4974
#define MAX_IO_HANDLERS 64
4975

    
4976
typedef struct IOHandlerRecord {
4977
    int fd;
4978
    IOCanRWHandler *fd_read_poll;
4979
    IOHandler *fd_read;
4980
    IOHandler *fd_write;
4981
    int deleted;
4982
    void *opaque;
4983
    /* temporary data */
4984
    struct pollfd *ufd;
4985
    struct IOHandlerRecord *next;
4986
} IOHandlerRecord;
4987

    
4988
static IOHandlerRecord *first_io_handler;
4989

    
4990
/* XXX: fd_read_poll should be suppressed, but an API change is
4991
   necessary in the character devices to suppress fd_can_read(). */
4992
int qemu_set_fd_handler2(int fd,
4993
                         IOCanRWHandler *fd_read_poll,
4994
                         IOHandler *fd_read,
4995
                         IOHandler *fd_write,
4996
                         void *opaque)
4997
{
4998
    IOHandlerRecord **pioh, *ioh;
4999

    
5000
    if (!fd_read && !fd_write) {
5001
        pioh = &first_io_handler;
5002
        for(;;) {
5003
            ioh = *pioh;
5004
            if (ioh == NULL)
5005
                break;
5006
            if (ioh->fd == fd) {
5007
                ioh->deleted = 1;
5008
                break;
5009
            }
5010
            pioh = &ioh->next;
5011
        }
5012
    } else {
5013
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5014
            if (ioh->fd == fd)
5015
                goto found;
5016
        }
5017
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5018
        if (!ioh)
5019
            return -1;
5020
        ioh->next = first_io_handler;
5021
        first_io_handler = ioh;
5022
    found:
5023
        ioh->fd = fd;
5024
        ioh->fd_read_poll = fd_read_poll;
5025
        ioh->fd_read = fd_read;
5026
        ioh->fd_write = fd_write;
5027
        ioh->opaque = opaque;
5028
        ioh->deleted = 0;
5029
    }
5030
    return 0;
5031
}
5032

    
5033
int qemu_set_fd_handler(int fd,
5034
                        IOHandler *fd_read,
5035
                        IOHandler *fd_write,
5036
                        void *opaque)
5037
{
5038
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5039
}
5040

    
5041
/***********************************************************/
5042
/* Polling handling */
5043

    
5044
typedef struct PollingEntry {
5045
    PollingFunc *func;
5046
    void *opaque;
5047
    struct PollingEntry *next;
5048
} PollingEntry;
5049

    
5050
static PollingEntry *first_polling_entry;
5051

    
5052
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5053
{
5054
    PollingEntry **ppe, *pe;
5055
    pe = qemu_mallocz(sizeof(PollingEntry));
5056
    if (!pe)
5057
        return -1;
5058
    pe->func = func;
5059
    pe->opaque = opaque;
5060
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5061
    *ppe = pe;
5062
    return 0;
5063
}
5064

    
5065
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5066
{
5067
    PollingEntry **ppe, *pe;
5068
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5069
        pe = *ppe;
5070
        if (pe->func == func && pe->opaque == opaque) {
5071
            *ppe = pe->next;
5072
            qemu_free(pe);
5073
            break;
5074
        }
5075
    }
5076
}
5077

    
5078
#ifdef _WIN32
5079
/***********************************************************/
5080
/* Wait objects support */
5081
typedef struct WaitObjects {
5082
    int num;
5083
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5084
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5085
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5086
} WaitObjects;
5087

    
5088
static WaitObjects wait_objects = {0};
5089

    
5090
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5091
{
5092
    WaitObjects *w = &wait_objects;
5093

    
5094
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
5095
        return -1;
5096
    w->events[w->num] = handle;
5097
    w->func[w->num] = func;
5098
    w->opaque[w->num] = opaque;
5099
    w->num++;
5100
    return 0;
5101
}
5102

    
5103
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5104
{
5105
    int i, found;
5106
    WaitObjects *w = &wait_objects;
5107

    
5108
    found = 0;
5109
    for (i = 0; i < w->num; i++) {
5110
        if (w->events[i] == handle)
5111
            found = 1;
5112
        if (found) {
5113
            w->events[i] = w->events[i + 1];
5114
            w->func[i] = w->func[i + 1];
5115
            w->opaque[i] = w->opaque[i + 1];
5116
        }
5117
    }
5118
    if (found)
5119
        w->num--;
5120
}
5121
#endif
5122

    
5123
/***********************************************************/
5124
/* savevm/loadvm support */
5125

    
5126
#define IO_BUF_SIZE 32768
5127

    
5128
struct QEMUFile {
5129
    FILE *outfile;
5130
    BlockDriverState *bs;
5131
    int is_file;
5132
    int is_writable;
5133
    int64_t base_offset;
5134
    int64_t buf_offset; /* start of buffer when writing, end of buffer
5135
                           when reading */
5136
    int buf_index;
5137
    int buf_size; /* 0 when writing */
5138
    uint8_t buf[IO_BUF_SIZE];
5139
};
5140

    
5141
QEMUFile *qemu_fopen(const char *filename, const char *mode)
5142
{
5143
    QEMUFile *f;
5144

    
5145
    f = qemu_mallocz(sizeof(QEMUFile));
5146
    if (!f)
5147
        return NULL;
5148
    if (!strcmp(mode, "wb")) {
5149
        f->is_writable = 1;
5150
    } else if (!strcmp(mode, "rb")) {
5151
        f->is_writable = 0;
5152
    } else {
5153
        goto fail;
5154
    }
5155
    f->outfile = fopen(filename, mode);
5156
    if (!f->outfile)
5157
        goto fail;
5158
    f->is_file = 1;
5159
    return f;
5160
 fail:
5161
    if (f->outfile)
5162
        fclose(f->outfile);
5163
    qemu_free(f);
5164
    return NULL;
5165
}
5166

    
5167
static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5168
{
5169
    QEMUFile *f;
5170

    
5171
    f = qemu_mallocz(sizeof(QEMUFile));
5172
    if (!f)
5173
        return NULL;
5174
    f->is_file = 0;
5175
    f->bs = bs;
5176
    f->is_writable = is_writable;
5177
    f->base_offset = offset;
5178
    return f;
5179
}
5180

    
5181
void qemu_fflush(QEMUFile *f)
5182
{
5183
    if (!f->is_writable)
5184
        return;
5185
    if (f->buf_index > 0) {
5186
        if (f->is_file) {
5187
            fseek(f->outfile, f->buf_offset, SEEK_SET);
5188
            fwrite(f->buf, 1, f->buf_index, f->outfile);
5189
        } else {
5190
            bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
5191
                        f->buf, f->buf_index);
5192
        }
5193
        f->buf_offset += f->buf_index;
5194
        f->buf_index = 0;
5195
    }
5196
}
5197

    
5198
static void qemu_fill_buffer(QEMUFile *f)
5199
{
5200
    int len;
5201

    
5202
    if (f->is_writable)
5203
        return;
5204
    if (f->is_file) {
5205
        fseek(f->outfile, f->buf_offset, SEEK_SET);
5206
        len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
5207
        if (len < 0)
5208
            len = 0;
5209
    } else {
5210
        len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
5211
                         f->buf, IO_BUF_SIZE);
5212
        if (len < 0)
5213
            len = 0;
5214
    }
5215
    f->buf_index = 0;
5216
    f->buf_size = len;
5217
    f->buf_offset += len;
5218
}
5219

    
5220
void qemu_fclose(QEMUFile *f)
5221
{
5222
    if (f->is_writable)
5223
        qemu_fflush(f);
5224
    if (f->is_file) {
5225
        fclose(f->outfile);
5226
    }
5227
    qemu_free(f);
5228
}
5229

    
5230
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5231
{
5232
    int l;
5233
    while (size > 0) {
5234
        l = IO_BUF_SIZE - f->buf_index;
5235
        if (l > size)
5236
            l = size;
5237
        memcpy(f->buf + f->buf_index, buf, l);
5238
        f->buf_index += l;
5239
        buf += l;
5240
        size -= l;
5241
        if (f->buf_index >= IO_BUF_SIZE)
5242
            qemu_fflush(f);
5243
    }
5244
}
5245

    
5246
void qemu_put_byte(QEMUFile *f, int v)
5247
{
5248
    f->buf[f->buf_index++] = v;
5249
    if (f->buf_index >= IO_BUF_SIZE)
5250
        qemu_fflush(f);
5251
}
5252

    
5253
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5254
{
5255
    int size, l;
5256

    
5257
    size = size1;
5258
    while (size > 0) {
5259
        l = f->buf_size - f->buf_index;
5260
        if (l == 0) {
5261
            qemu_fill_buffer(f);
5262
            l = f->buf_size - f->buf_index;
5263
            if (l == 0)
5264
                break;
5265
        }
5266
        if (l > size)
5267
            l = size;
5268
        memcpy(buf, f->buf + f->buf_index, l);
5269
        f->buf_index += l;
5270
        buf += l;
5271
        size -= l;
5272
    }
5273
    return size1 - size;
5274
}
5275

    
5276
int qemu_get_byte(QEMUFile *f)
5277
{
5278
    if (f->buf_index >= f->buf_size) {
5279
        qemu_fill_buffer(f);
5280
        if (f->buf_index >= f->buf_size)
5281
            return 0;
5282
    }
5283
    return f->buf[f->buf_index++];
5284
}
5285

    
5286
int64_t qemu_ftell(QEMUFile *f)
5287
{
5288
    return f->buf_offset - f->buf_size + f->buf_index;
5289
}
5290

    
5291
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
5292
{
5293
    if (whence == SEEK_SET) {
5294
        /* nothing to do */
5295
    } else if (whence == SEEK_CUR) {
5296
        pos += qemu_ftell(f);
5297
    } else {
5298
        /* SEEK_END not supported */
5299
        return -1;
5300
    }
5301
    if (f->is_writable) {
5302
        qemu_fflush(f);
5303
        f->buf_offset = pos;
5304
    } else {
5305
        f->buf_offset = pos;
5306
        f->buf_index = 0;
5307
        f->buf_size = 0;
5308
    }
5309
    return pos;
5310
}
5311

    
5312
void qemu_put_be16(QEMUFile *f, unsigned int v)
5313
{
5314
    qemu_put_byte(f, v >> 8);
5315
    qemu_put_byte(f, v);
5316
}
5317

    
5318
void qemu_put_be32(QEMUFile *f, unsigned int v)
5319
{
5320
    qemu_put_byte(f, v >> 24);
5321
    qemu_put_byte(f, v >> 16);
5322
    qemu_put_byte(f, v >> 8);
5323
    qemu_put_byte(f, v);
5324
}
5325

    
5326
void qemu_put_be64(QEMUFile *f, uint64_t v)
5327
{
5328
    qemu_put_be32(f, v >> 32);
5329
    qemu_put_be32(f, v);
5330
}
5331

    
5332
unsigned int qemu_get_be16(QEMUFile *f)
5333
{
5334
    unsigned int v;
5335
    v = qemu_get_byte(f) << 8;
5336
    v |= qemu_get_byte(f);
5337
    return v;
5338
}
5339

    
5340
unsigned int qemu_get_be32(QEMUFile *f)
5341
{
5342
    unsigned int v;
5343
    v = qemu_get_byte(f) << 24;
5344
    v |= qemu_get_byte(f) << 16;
5345
    v |= qemu_get_byte(f) << 8;
5346
    v |= qemu_get_byte(f);
5347
    return v;
5348
}
5349

    
5350
uint64_t qemu_get_be64(QEMUFile *f)
5351
{
5352
    uint64_t v;
5353
    v = (uint64_t)qemu_get_be32(f) << 32;
5354
    v |= qemu_get_be32(f);
5355
    return v;
5356
}
5357

    
5358
typedef struct SaveStateEntry {
5359
    char idstr[256];
5360
    int instance_id;
5361
    int version_id;
5362
    SaveStateHandler *save_state;
5363
    LoadStateHandler *load_state;
5364
    void *opaque;
5365
    struct SaveStateEntry *next;
5366
} SaveStateEntry;
5367

    
5368
static SaveStateEntry *first_se;
5369

    
5370
int register_savevm(const char *idstr,
5371
                    int instance_id,
5372
                    int version_id,
5373
                    SaveStateHandler *save_state,
5374
                    LoadStateHandler *load_state,
5375
                    void *opaque)
5376
{
5377
    SaveStateEntry *se, **pse;
5378

    
5379
    se = qemu_malloc(sizeof(SaveStateEntry));
5380
    if (!se)
5381
        return -1;
5382
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
5383
    se->instance_id = instance_id;
5384
    se->version_id = version_id;
5385
    se->save_state = save_state;
5386
    se->load_state = load_state;
5387
    se->opaque = opaque;
5388
    se->next = NULL;
5389

    
5390
    /* add at the end of list */
5391
    pse = &first_se;
5392
    while (*pse != NULL)
5393
        pse = &(*pse)->next;
5394
    *pse = se;
5395
    return 0;
5396
}
5397

    
5398
#define QEMU_VM_FILE_MAGIC   0x5145564d
5399
#define QEMU_VM_FILE_VERSION 0x00000002
5400

    
5401
static int qemu_savevm_state(QEMUFile *f)
5402
{
5403
    SaveStateEntry *se;
5404
    int len, ret;
5405
    int64_t cur_pos, len_pos, total_len_pos;
5406

    
5407
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
5408
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
5409
    total_len_pos = qemu_ftell(f);
5410
    qemu_put_be64(f, 0); /* total size */
5411

    
5412
    for(se = first_se; se != NULL; se = se->next) {
5413
        /* ID string */
5414
        len = strlen(se->idstr);
5415
        qemu_put_byte(f, len);
5416
        qemu_put_buffer(f, se->idstr, len);
5417

    
5418
        qemu_put_be32(f, se->instance_id);
5419
        qemu_put_be32(f, se->version_id);
5420

    
5421
        /* record size: filled later */
5422
        len_pos = qemu_ftell(f);
5423
        qemu_put_be32(f, 0);
5424
        se->save_state(f, se->opaque);
5425

    
5426
        /* fill record size */
5427
        cur_pos = qemu_ftell(f);
5428
        len = cur_pos - len_pos - 4;
5429
        qemu_fseek(f, len_pos, SEEK_SET);
5430
        qemu_put_be32(f, len);
5431
        qemu_fseek(f, cur_pos, SEEK_SET);
5432
    }
5433
    cur_pos = qemu_ftell(f);
5434
    qemu_fseek(f, total_len_pos, SEEK_SET);
5435
    qemu_put_be64(f, cur_pos - total_len_pos - 8);
5436
    qemu_fseek(f, cur_pos, SEEK_SET);
5437

    
5438
    ret = 0;
5439
    return ret;
5440
}
5441

    
5442
static SaveStateEntry *find_se(const char *idstr, int instance_id)
5443
{
5444
    SaveStateEntry *se;
5445

    
5446
    for(se = first_se; se != NULL; se = se->next) {
5447
        if (!strcmp(se->idstr, idstr) &&
5448
            instance_id == se->instance_id)
5449
            return se;
5450
    }
5451
    return NULL;
5452
}
5453

    
5454
static int qemu_loadvm_state(QEMUFile *f)
5455
{
5456
    SaveStateEntry *se;
5457
    int len, ret, instance_id, record_len, version_id;
5458
    int64_t total_len, end_pos, cur_pos;
5459
    unsigned int v;
5460
    char idstr[256];
5461

    
5462
    v = qemu_get_be32(f);
5463
    if (v != QEMU_VM_FILE_MAGIC)
5464
        goto fail;
5465
    v = qemu_get_be32(f);
5466
    if (v != QEMU_VM_FILE_VERSION) {
5467
    fail:
5468
        ret = -1;
5469
        goto the_end;
5470
    }
5471
    total_len = qemu_get_be64(f);
5472
    end_pos = total_len + qemu_ftell(f);
5473
    for(;;) {
5474
        if (qemu_ftell(f) >= end_pos)
5475
            break;
5476
        len = qemu_get_byte(f);
5477
        qemu_get_buffer(f, idstr, len);
5478
        idstr[len] = '\0';
5479
        instance_id = qemu_get_be32(f);
5480
        version_id = qemu_get_be32(f);
5481
        record_len = qemu_get_be32(f);
5482
#if 0
5483
        printf("idstr=%s instance=0x%x version=%d len=%d\n",
5484
               idstr, instance_id, version_id, record_len);
5485
#endif
5486
        cur_pos = qemu_ftell(f);
5487
        se = find_se(idstr, instance_id);
5488
        if (!se) {
5489
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
5490
                    instance_id, idstr);
5491
        } else {
5492
            ret = se->load_state(f, se->opaque, version_id);
5493
            if (ret < 0) {
5494
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
5495
                        instance_id, idstr);
5496
            }
5497
        }
5498
        /* always seek to exact end of record */
5499
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5500
    }
5501
    ret = 0;
5502
 the_end:
5503
    return ret;
5504
}
5505

    
5506
/* device can contain snapshots */
5507
static int bdrv_can_snapshot(BlockDriverState *bs)
5508
{
5509
    return (bs &&
5510
            !bdrv_is_removable(bs) &&
5511
            !bdrv_is_read_only(bs));
5512
}
5513

    
5514
/* device must be snapshots in order to have a reliable snapshot */
5515
static int bdrv_has_snapshot(BlockDriverState *bs)
5516
{
5517
    return (bs &&
5518
            !bdrv_is_removable(bs) &&
5519
            !bdrv_is_read_only(bs));
5520
}
5521

    
5522
static BlockDriverState *get_bs_snapshots(void)
5523
{
5524
    BlockDriverState *bs;
5525
    int i;
5526

    
5527
    if (bs_snapshots)
5528
        return bs_snapshots;
5529
    for(i = 0; i <= MAX_DISKS; i++) {
5530
        bs = bs_table[i];
5531
        if (bdrv_can_snapshot(bs))
5532
            goto ok;
5533
    }
5534
    return NULL;
5535
 ok:
5536
    bs_snapshots = bs;
5537
    return bs;
5538
}
5539

    
5540
static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5541
                              const char *name)
5542
{
5543
    QEMUSnapshotInfo *sn_tab, *sn;
5544
    int nb_sns, i, ret;
5545

    
5546
    ret = -ENOENT;
5547
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5548
    if (nb_sns < 0)
5549
        return ret;
5550
    for(i = 0; i < nb_sns; i++) {
5551
        sn = &sn_tab[i];
5552
        if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5553
            *sn_info = *sn;
5554
            ret = 0;
5555
            break;
5556
        }
5557
    }
5558
    qemu_free(sn_tab);
5559
    return ret;
5560
}
5561

    
5562
void do_savevm(const char *name)
5563
{
5564
    BlockDriverState *bs, *bs1;
5565
    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5566
    int must_delete, ret, i;
5567
    BlockDriverInfo bdi1, *bdi = &bdi1;
5568
    QEMUFile *f;
5569
    int saved_vm_running;
5570
#ifdef _WIN32
5571
    struct _timeb tb;
5572
#else
5573
    struct timeval tv;
5574
#endif
5575

    
5576
    bs = get_bs_snapshots();
5577
    if (!bs) {
5578
        term_printf("No block device can accept snapshots\n");
5579
        return;
5580
    }
5581

    
5582
    /* ??? Should this occur after vm_stop?  */
5583
    qemu_aio_flush();
5584

    
5585
    saved_vm_running = vm_running;
5586
    vm_stop(0);
5587

    
5588
    must_delete = 0;
5589
    if (name) {
5590
        ret = bdrv_snapshot_find(bs, old_sn, name);
5591
        if (ret >= 0) {
5592
            must_delete = 1;
5593
        }
5594
    }
5595
    memset(sn, 0, sizeof(*sn));
5596
    if (must_delete) {
5597
        pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5598
        pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5599
    } else {
5600
        if (name)
5601
            pstrcpy(sn->name, sizeof(sn->name), name);
5602
    }
5603

    
5604
    /* fill auxiliary fields */
5605
#ifdef _WIN32
5606
    _ftime(&tb);
5607
    sn->date_sec = tb.time;
5608
    sn->date_nsec = tb.millitm * 1000000;
5609
#else
5610
    gettimeofday(&tv, NULL);
5611
    sn->date_sec = tv.tv_sec;
5612
    sn->date_nsec = tv.tv_usec * 1000;
5613
#endif
5614
    sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5615

    
5616
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5617
        term_printf("Device %s does not support VM state snapshots\n",
5618
                    bdrv_get_device_name(bs));
5619
        goto the_end;
5620
    }
5621

    
5622
    /* save the VM state */
5623
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5624
    if (!f) {
5625
        term_printf("Could not open VM state file\n");
5626
        goto the_end;
5627
    }
5628
    ret = qemu_savevm_state(f);
5629
    sn->vm_state_size = qemu_ftell(f);
5630
    qemu_fclose(f);
5631
    if (ret < 0) {
5632
        term_printf("Error %d while writing VM\n", ret);
5633
        goto the_end;
5634
    }
5635

    
5636
    /* create the snapshots */
5637

    
5638
    for(i = 0; i < MAX_DISKS; i++) {
5639
        bs1 = bs_table[i];
5640
        if (bdrv_has_snapshot(bs1)) {
5641
            if (must_delete) {
5642
                ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5643
                if (ret < 0) {
5644
                    term_printf("Error while deleting snapshot on '%s'\n",
5645
                                bdrv_get_device_name(bs1));
5646
                }
5647
            }
5648
            ret = bdrv_snapshot_create(bs1, sn);
5649
            if (ret < 0) {
5650
                term_printf("Error while creating snapshot on '%s'\n",
5651
                            bdrv_get_device_name(bs1));
5652
            }
5653
        }
5654
    }
5655

    
5656
 the_end:
5657
    if (saved_vm_running)
5658
        vm_start();
5659
}
5660

    
5661
void do_loadvm(const char *name)
5662
{
5663
    BlockDriverState *bs, *bs1;
5664
    BlockDriverInfo bdi1, *bdi = &bdi1;
5665
    QEMUFile *f;
5666
    int i, ret;
5667
    int saved_vm_running;
5668

    
5669
    bs = get_bs_snapshots();
5670
    if (!bs) {
5671
        term_printf("No block device supports snapshots\n");
5672
        return;
5673
    }
5674

    
5675
    /* Flush all IO requests so they don't interfere with the new state.  */
5676
    qemu_aio_flush();
5677

    
5678
    saved_vm_running = vm_running;
5679
    vm_stop(0);
5680

    
5681
    for(i = 0; i <= MAX_DISKS; i++) {
5682
        bs1 = bs_table[i];
5683
        if (bdrv_has_snapshot(bs1)) {
5684
            ret = bdrv_snapshot_goto(bs1, name);
5685
            if (ret < 0) {
5686
                if (bs != bs1)
5687
                    term_printf("Warning: ");
5688
                switch(ret) {
5689
                case -ENOTSUP:
5690
                    term_printf("Snapshots not supported on device '%s'\n",
5691
                                bdrv_get_device_name(bs1));
5692
                    break;
5693
                case -ENOENT:
5694
                    term_printf("Could not find snapshot '%s' on device '%s'\n",
5695
                                name, bdrv_get_device_name(bs1));
5696
                    break;
5697
                default:
5698
                    term_printf("Error %d while activating snapshot on '%s'\n",
5699
                                ret, bdrv_get_device_name(bs1));
5700
                    break;
5701
                }
5702
                /* fatal on snapshot block device */
5703
                if (bs == bs1)
5704
                    goto the_end;
5705
            }
5706
        }
5707
    }
5708

    
5709
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5710
        term_printf("Device %s does not support VM state snapshots\n",
5711
                    bdrv_get_device_name(bs));
5712
        return;
5713
    }
5714

    
5715
    /* restore the VM state */
5716
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5717
    if (!f) {
5718
        term_printf("Could not open VM state file\n");
5719
        goto the_end;
5720
    }
5721
    ret = qemu_loadvm_state(f);
5722
    qemu_fclose(f);
5723
    if (ret < 0) {
5724
        term_printf("Error %d while loading VM state\n", ret);
5725
    }
5726
 the_end:
5727
    if (saved_vm_running)
5728
        vm_start();
5729
}
5730

    
5731
void do_delvm(const char *name)
5732
{
5733
    BlockDriverState *bs, *bs1;
5734
    int i, ret;
5735

    
5736
    bs = get_bs_snapshots();
5737
    if (!bs) {
5738
        term_printf("No block device supports snapshots\n");
5739
        return;
5740
    }
5741

    
5742
    for(i = 0; i <= MAX_DISKS; i++) {
5743
        bs1 = bs_table[i];
5744
        if (bdrv_has_snapshot(bs1)) {
5745
            ret = bdrv_snapshot_delete(bs1, name);
5746
            if (ret < 0) {
5747
                if (ret == -ENOTSUP)
5748
                    term_printf("Snapshots not supported on device '%s'\n",
5749
                                bdrv_get_device_name(bs1));
5750
                else
5751
                    term_printf("Error %d while deleting snapshot on '%s'\n",
5752
                                ret, bdrv_get_device_name(bs1));
5753
            }
5754
        }
5755
    }
5756
}
5757

    
5758
void do_info_snapshots(void)
5759
{
5760
    BlockDriverState *bs, *bs1;
5761
    QEMUSnapshotInfo *sn_tab, *sn;
5762
    int nb_sns, i;
5763
    char buf[256];
5764

    
5765
    bs = get_bs_snapshots();
5766
    if (!bs) {
5767
        term_printf("No available block device supports snapshots\n");
5768
        return;
5769
    }
5770
    term_printf("Snapshot devices:");
5771
    for(i = 0; i <= MAX_DISKS; i++) {
5772
        bs1 = bs_table[i];
5773
        if (bdrv_has_snapshot(bs1)) {
5774
            if (bs == bs1)
5775
                term_printf(" %s", bdrv_get_device_name(bs1));
5776
        }
5777
    }
5778
    term_printf("\n");
5779

    
5780
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5781
    if (nb_sns < 0) {
5782
        term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5783
        return;
5784
    }
5785
    term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5786
    term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5787
    for(i = 0; i < nb_sns; i++) {
5788
        sn = &sn_tab[i];
5789
        term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5790
    }
5791
    qemu_free(sn_tab);
5792
}
5793

    
5794
/***********************************************************/
5795
/* cpu save/restore */
5796

    
5797
#if defined(TARGET_I386)
5798

    
5799
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5800
{
5801
    qemu_put_be32(f, dt->selector);
5802
    qemu_put_betl(f, dt->base);
5803
    qemu_put_be32(f, dt->limit);
5804
    qemu_put_be32(f, dt->flags);
5805
}
5806

    
5807
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5808
{
5809
    dt->selector = qemu_get_be32(f);
5810
    dt->base = qemu_get_betl(f);
5811
    dt->limit = qemu_get_be32(f);
5812
    dt->flags = qemu_get_be32(f);
5813
}
5814

    
5815
void cpu_save(QEMUFile *f, void *opaque)
5816
{
5817
    CPUState *env = opaque;
5818
    uint16_t fptag, fpus, fpuc, fpregs_format;
5819
    uint32_t hflags;
5820
    int i;
5821

    
5822
    for(i = 0; i < CPU_NB_REGS; i++)
5823
        qemu_put_betls(f, &env->regs[i]);
5824
    qemu_put_betls(f, &env->eip);
5825
    qemu_put_betls(f, &env->eflags);
5826
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5827
    qemu_put_be32s(f, &hflags);
5828

    
5829
    /* FPU */
5830
    fpuc = env->fpuc;
5831
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5832
    fptag = 0;
5833
    for(i = 0; i < 8; i++) {
5834
        fptag |= ((!env->fptags[i]) << i);
5835
    }
5836

    
5837
    qemu_put_be16s(f, &fpuc);
5838
    qemu_put_be16s(f, &fpus);
5839
    qemu_put_be16s(f, &fptag);
5840

    
5841
#ifdef USE_X86LDOUBLE
5842
    fpregs_format = 0;
5843
#else
5844
    fpregs_format = 1;
5845
#endif
5846
    qemu_put_be16s(f, &fpregs_format);
5847

    
5848
    for(i = 0; i < 8; i++) {
5849
#ifdef USE_X86LDOUBLE
5850
        {
5851
            uint64_t mant;
5852
            uint16_t exp;
5853
            /* we save the real CPU data (in case of MMX usage only 'mant'
5854
               contains the MMX register */
5855
            cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5856
            qemu_put_be64(f, mant);
5857
            qemu_put_be16(f, exp);
5858
        }
5859
#else
5860
        /* if we use doubles for float emulation, we save the doubles to
5861
           avoid losing information in case of MMX usage. It can give
5862
           problems if the image is restored on a CPU where long
5863
           doubles are used instead. */
5864
        qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5865
#endif
5866
    }
5867

    
5868
    for(i = 0; i < 6; i++)
5869
        cpu_put_seg(f, &env->segs[i]);
5870
    cpu_put_seg(f, &env->ldt);
5871
    cpu_put_seg(f, &env->tr);
5872
    cpu_put_seg(f, &env->gdt);
5873
    cpu_put_seg(f, &env->idt);
5874

    
5875
    qemu_put_be32s(f, &env->sysenter_cs);
5876
    qemu_put_be32s(f, &env->sysenter_esp);
5877
    qemu_put_be32s(f, &env->sysenter_eip);
5878

    
5879
    qemu_put_betls(f, &env->cr[0]);
5880
    qemu_put_betls(f, &env->cr[2]);
5881
    qemu_put_betls(f, &env->cr[3]);
5882
    qemu_put_betls(f, &env->cr[4]);
5883

    
5884
    for(i = 0; i < 8; i++)
5885
        qemu_put_betls(f, &env->dr[i]);
5886

    
5887
    /* MMU */
5888
    qemu_put_be32s(f, &env->a20_mask);
5889

    
5890
    /* XMM */
5891
    qemu_put_be32s(f, &env->mxcsr);
5892
    for(i = 0; i < CPU_NB_REGS; i++) {
5893
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5894
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5895
    }
5896

    
5897
#ifdef TARGET_X86_64
5898
    qemu_put_be64s(f, &env->efer);
5899
    qemu_put_be64s(f, &env->star);
5900
    qemu_put_be64s(f, &env->lstar);
5901
    qemu_put_be64s(f, &env->cstar);
5902
    qemu_put_be64s(f, &env->fmask);
5903
    qemu_put_be64s(f, &env->kernelgsbase);
5904
#endif
5905
    qemu_put_be32s(f, &env->smbase);
5906
}
5907

    
5908
#ifdef USE_X86LDOUBLE
5909
/* XXX: add that in a FPU generic layer */
5910
union x86_longdouble {
5911
    uint64_t mant;
5912
    uint16_t exp;
5913
};
5914

    
5915
#define MANTD1(fp)        (fp & ((1LL << 52) - 1))
5916
#define EXPBIAS1 1023
5917
#define EXPD1(fp)        ((fp >> 52) & 0x7FF)
5918
#define SIGND1(fp)        ((fp >> 32) & 0x80000000)
5919

    
5920
static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5921
{
5922
    int e;
5923
    /* mantissa */
5924
    p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5925
    /* exponent + sign */
5926
    e = EXPD1(temp) - EXPBIAS1 + 16383;
5927
    e |= SIGND1(temp) >> 16;
5928
    p->exp = e;
5929
}
5930
#endif
5931

    
5932
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5933
{
5934
    CPUState *env = opaque;
5935
    int i, guess_mmx;
5936
    uint32_t hflags;
5937
    uint16_t fpus, fpuc, fptag, fpregs_format;
5938

    
5939
    if (version_id != 3 && version_id != 4)
5940
        return -EINVAL;
5941
    for(i = 0; i < CPU_NB_REGS; i++)
5942
        qemu_get_betls(f, &env->regs[i]);
5943
    qemu_get_betls(f, &env->eip);
5944
    qemu_get_betls(f, &env->eflags);
5945
    qemu_get_be32s(f, &hflags);
5946

    
5947
    qemu_get_be16s(f, &fpuc);
5948
    qemu_get_be16s(f, &fpus);
5949
    qemu_get_be16s(f, &fptag);
5950
    qemu_get_be16s(f, &fpregs_format);
5951

    
5952
    /* NOTE: we cannot always restore the FPU state if the image come
5953
       from a host with a different 'USE_X86LDOUBLE' define. We guess
5954
       if we are in an MMX state to restore correctly in that case. */
5955
    guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5956
    for(i = 0; i < 8; i++) {
5957
        uint64_t mant;
5958
        uint16_t exp;
5959

    
5960
        switch(fpregs_format) {
5961
        case 0:
5962
            mant = qemu_get_be64(f);
5963
            exp = qemu_get_be16(f);
5964
#ifdef USE_X86LDOUBLE
5965
            env->fpregs[i].d = cpu_set_fp80(mant, exp);
5966
#else
5967
            /* difficult case */
5968
            if (guess_mmx)
5969
                env->fpregs[i].mmx.MMX_Q(0) = mant;
5970
            else
5971
                env->fpregs[i].d = cpu_set_fp80(mant, exp);
5972
#endif
5973
            break;
5974
        case 1:
5975
            mant = qemu_get_be64(f);
5976
#ifdef USE_X86LDOUBLE
5977
            {
5978
                union x86_longdouble *p;
5979
                /* difficult case */
5980
                p = (void *)&env->fpregs[i];
5981
                if (guess_mmx) {
5982
                    p->mant = mant;
5983
                    p->exp = 0xffff;
5984
                } else {
5985
                    fp64_to_fp80(p, mant);
5986
                }
5987
            }
5988
#else
5989
            env->fpregs[i].mmx.MMX_Q(0) = mant;
5990
#endif
5991
            break;
5992
        default:
5993
            return -EINVAL;
5994
        }
5995
    }
5996

    
5997
    env->fpuc = fpuc;
5998
    /* XXX: restore FPU round state */
5999
    env->fpstt = (fpus >> 11) & 7;
6000
    env->fpus = fpus & ~0x3800;
6001
    fptag ^= 0xff;
6002
    for(i = 0; i < 8; i++) {
6003
        env->fptags[i] = (fptag >> i) & 1;
6004
    }
6005

    
6006
    for(i = 0; i < 6; i++)
6007
        cpu_get_seg(f, &env->segs[i]);
6008
    cpu_get_seg(f, &env->ldt);
6009
    cpu_get_seg(f, &env->tr);
6010
    cpu_get_seg(f, &env->gdt);
6011
    cpu_get_seg(f, &env->idt);
6012

    
6013
    qemu_get_be32s(f, &env->sysenter_cs);
6014
    qemu_get_be32s(f, &env->sysenter_esp);
6015
    qemu_get_be32s(f, &env->sysenter_eip);
6016

    
6017
    qemu_get_betls(f, &env->cr[0]);
6018
    qemu_get_betls(f, &env->cr[2]);
6019
    qemu_get_betls(f, &env->cr[3]);
6020
    qemu_get_betls(f, &env->cr[4]);
6021

    
6022
    for(i = 0; i < 8; i++)
6023
        qemu_get_betls(f, &env->dr[i]);
6024

    
6025
    /* MMU */
6026
    qemu_get_be32s(f, &env->a20_mask);
6027

    
6028
    qemu_get_be32s(f, &env->mxcsr);
6029
    for(i = 0; i < CPU_NB_REGS; i++) {
6030
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
6031
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
6032
    }
6033

    
6034
#ifdef TARGET_X86_64
6035
    qemu_get_be64s(f, &env->efer);
6036
    qemu_get_be64s(f, &env->star);
6037
    qemu_get_be64s(f, &env->lstar);
6038
    qemu_get_be64s(f, &env->cstar);
6039
    qemu_get_be64s(f, &env->fmask);
6040
    qemu_get_be64s(f, &env->kernelgsbase);
6041
#endif
6042
    if (version_id >= 4)
6043
        qemu_get_be32s(f, &env->smbase);
6044

    
6045
    /* XXX: compute hflags from scratch, except for CPL and IIF */
6046
    env->hflags = hflags;
6047
    tlb_flush(env, 1);
6048
    return 0;
6049
}
6050

    
6051
#elif defined(TARGET_PPC)
6052
void cpu_save(QEMUFile *f, void *opaque)
6053
{
6054
}
6055

    
6056
int cpu_load(QEMUFile *f, void *opaque, int version_id)
6057
{
6058
    return 0;
6059
}
6060

    
6061
#elif defined(TARGET_MIPS)
6062
void cpu_save(QEMUFile *f, void *opaque)
6063
{
6064
}
6065

    
6066
int cpu_load(QEMUFile *f, void *opaque, int version_id)
6067
{
6068
    return 0;
6069
}
6070

    
6071
#elif defined(TARGET_SPARC)
6072
void cpu_save(QEMUFile *f, void *opaque)
6073
{
6074
    CPUState *env = opaque;
6075
    int i;
6076
    uint32_t tmp;
6077

    
6078
    for(i = 0; i < 8; i++)
6079
        qemu_put_betls(f, &env->gregs[i]);
6080
    for(i = 0; i < NWINDOWS * 16; i++)
6081
        qemu_put_betls(f, &env->regbase[i]);
6082

    
6083
    /* FPU */
6084
    for(i = 0; i < TARGET_FPREGS; i++) {
6085
        union {
6086
            float32 f;
6087
            uint32_t i;
6088
        } u;
6089
        u.f = env->fpr[i];
6090
        qemu_put_be32(f, u.i);
6091
    }
6092

    
6093
    qemu_put_betls(f, &env->pc);
6094
    qemu_put_betls(f, &env->npc);
6095
    qemu_put_betls(f, &env->y);
6096
    tmp = GET_PSR(env);
6097
    qemu_put_be32(f, tmp);
6098
    qemu_put_betls(f, &env->fsr);
6099
    qemu_put_betls(f, &env->tbr);
6100
#ifndef TARGET_SPARC64
6101
    qemu_put_be32s(f, &env->wim);
6102
    /* MMU */
6103
    for(i = 0; i < 16; i++)
6104
        qemu_put_be32s(f, &env->mmuregs[i]);
6105
#endif
6106
}
6107

    
6108
int cpu_load(QEMUFile *f, void *opaque, int version_id)
6109
{
6110
    CPUState *env = opaque;
6111
    int i;
6112
    uint32_t tmp;
6113

    
6114
    for(i = 0; i < 8; i++)
6115
        qemu_get_betls(f, &env->gregs[i]);
6116
    for(i = 0; i < NWINDOWS * 16; i++)
6117
        qemu_get_betls(f, &env->regbase[i]);
6118

    
6119
    /* FPU */
6120
    for(i = 0; i < TARGET_FPREGS; i++) {
6121
        union {
6122
            float32 f;
6123
            uint32_t i;
6124
        } u;
6125
        u.i = qemu_get_be32(f);
6126
        env->fpr[i] = u.f;
6127
    }
6128

    
6129
    qemu_get_betls(f, &env->pc);
6130
    qemu_get_betls(f, &env->npc);
6131
    qemu_get_betls(f, &env->y);
6132
    tmp = qemu_get_be32(f);
6133
    env->cwp = 0; /* needed to ensure that the wrapping registers are
6134
                     correctly updated */
6135
    PUT_PSR(env, tmp);
6136
    qemu_get_betls(f, &env->fsr);
6137
    qemu_get_betls(f, &env->tbr);
6138
#ifndef TARGET_SPARC64
6139
    qemu_get_be32s(f, &env->wim);
6140
    /* MMU */
6141
    for(i = 0; i < 16; i++)
6142
        qemu_get_be32s(f, &env->mmuregs[i]);
6143
#endif
6144
    tlb_flush(env, 1);
6145
    return 0;
6146
}
6147

    
6148
#elif defined(TARGET_ARM)
6149

    
6150
void cpu_save(QEMUFile *f, void *opaque)
6151
{
6152
    int i;
6153
    CPUARMState *env = (CPUARMState *)opaque;
6154

    
6155
    for (i = 0; i < 16; i++) {
6156
        qemu_put_be32(f, env->regs[i]);
6157
    }
6158
    qemu_put_be32(f, cpsr_read(env));
6159
    qemu_put_be32(f, env->spsr);
6160
    for (i = 0; i < 6; i++) {
6161
        qemu_put_be32(f, env->banked_spsr[i]);
6162
        qemu_put_be32(f, env->banked_r13[i]);
6163
        qemu_put_be32(f, env->banked_r14[i]);
6164
    }
6165
    for (i = 0; i < 5; i++) {
6166
        qemu_put_be32(f, env->usr_regs[i]);
6167
        qemu_put_be32(f, env->fiq_regs[i]);
6168
    }
6169
    qemu_put_be32(f, env->cp15.c0_cpuid);
6170
    qemu_put_be32(f, env->cp15.c0_cachetype);
6171
    qemu_put_be32(f, env->cp15.c1_sys);
6172
    qemu_put_be32(f, env->cp15.c1_coproc);
6173
    qemu_put_be32(f, env->cp15.c1_xscaleauxcr);
6174
    qemu_put_be32(f, env->cp15.c2_base0);
6175
    qemu_put_be32(f, env->cp15.c2_base1);
6176
    qemu_put_be32(f, env->cp15.c2_mask);
6177
    qemu_put_be32(f, env->cp15.c2_data);
6178
    qemu_put_be32(f, env->cp15.c2_insn);
6179
    qemu_put_be32(f, env->cp15.c3);
6180
    qemu_put_be32(f, env->cp15.c5_insn);
6181
    qemu_put_be32(f, env->cp15.c5_data);
6182
    for (i = 0; i < 8; i++) {
6183
        qemu_put_be32(f, env->cp15.c6_region[i]);
6184
    }
6185
    qemu_put_be32(f, env->cp15.c6_insn);
6186
    qemu_put_be32(f, env->cp15.c6_data);
6187
    qemu_put_be32(f, env->cp15.c9_insn);
6188
    qemu_put_be32(f, env->cp15.c9_data);
6189
    qemu_put_be32(f, env->cp15.c13_fcse);
6190
    qemu_put_be32(f, env->cp15.c13_context);
6191
    qemu_put_be32(f, env->cp15.c13_tls1);
6192
    qemu_put_be32(f, env->cp15.c13_tls2);
6193
    qemu_put_be32(f, env->cp15.c13_tls3);
6194
    qemu_put_be32(f, env->cp15.c15_cpar);
6195

    
6196
    qemu_put_be32(f, env->features);
6197

    
6198
    if (arm_feature(env, ARM_FEATURE_VFP)) {
6199
        for (i = 0;  i < 16; i++) {
6200
            CPU_DoubleU u;
6201
            u.d = env->vfp.regs[i];
6202
            qemu_put_be32(f, u.l.upper);
6203
            qemu_put_be32(f, u.l.lower);
6204
        }
6205
        for (i = 0; i < 16; i++) {
6206
            qemu_put_be32(f, env->vfp.xregs[i]);
6207
        }
6208

    
6209
        /* TODO: Should use proper FPSCR access functions.  */
6210
        qemu_put_be32(f, env->vfp.vec_len);
6211
        qemu_put_be32(f, env->vfp.vec_stride);
6212

    
6213
        if (arm_feature(env, ARM_FEATURE_VFP3)) {
6214
            for (i = 16;  i < 32; i++) {
6215
                CPU_DoubleU u;
6216
                u.d = env->vfp.regs[i];
6217
                qemu_put_be32(f, u.l.upper);
6218
                qemu_put_be32(f, u.l.lower);
6219
            }
6220
        }
6221
    }
6222

    
6223
    if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6224
        for (i = 0; i < 16; i++) {
6225
            qemu_put_be64(f, env->iwmmxt.regs[i]);
6226
        }
6227
        for (i = 0; i < 16; i++) {
6228
            qemu_put_be32(f, env->iwmmxt.cregs[i]);
6229
        }
6230
    }
6231

    
6232
    if (arm_feature(env, ARM_FEATURE_M)) {
6233
        qemu_put_be32(f, env->v7m.other_sp);
6234
        qemu_put_be32(f, env->v7m.vecbase);
6235
        qemu_put_be32(f, env->v7m.basepri);
6236
        qemu_put_be32(f, env->v7m.control);
6237
        qemu_put_be32(f, env->v7m.current_sp);
6238
        qemu_put_be32(f, env->v7m.exception);
6239
    }
6240
}
6241

    
6242
int cpu_load(QEMUFile *f, void *opaque, int version_id)
6243
{
6244
    CPUARMState *env = (CPUARMState *)opaque;
6245
    int i;
6246

    
6247
    if (version_id != ARM_CPU_SAVE_VERSION)
6248
        return -EINVAL;
6249

    
6250
    for (i = 0; i < 16; i++) {
6251
        env->regs[i] = qemu_get_be32(f);
6252
    }
6253
    cpsr_write(env, qemu_get_be32(f), 0xffffffff);
6254
    env->spsr = qemu_get_be32(f);
6255
    for (i = 0; i < 6; i++) {
6256
        env->banked_spsr[i] = qemu_get_be32(f);
6257
        env->banked_r13[i] = qemu_get_be32(f);
6258
        env->banked_r14[i] = qemu_get_be32(f);
6259
    }
6260
    for (i = 0; i < 5; i++) {
6261
        env->usr_regs[i] = qemu_get_be32(f);
6262
        env->fiq_regs[i] = qemu_get_be32(f);
6263
    }
6264
    env->cp15.c0_cpuid = qemu_get_be32(f);
6265
    env->cp15.c0_cachetype = qemu_get_be32(f);
6266
    env->cp15.c1_sys = qemu_get_be32(f);
6267
    env->cp15.c1_coproc = qemu_get_be32(f);
6268
    env->cp15.c1_xscaleauxcr = qemu_get_be32(f);
6269
    env->cp15.c2_base0 = qemu_get_be32(f);
6270
    env->cp15.c2_base1 = qemu_get_be32(f);
6271
    env->cp15.c2_mask = qemu_get_be32(f);
6272
    env->cp15.c2_data = qemu_get_be32(f);
6273
    env->cp15.c2_insn = qemu_get_be32(f);
6274
    env->cp15.c3 = qemu_get_be32(f);
6275
    env->cp15.c5_insn = qemu_get_be32(f);
6276
    env->cp15.c5_data = qemu_get_be32(f);
6277
    for (i = 0; i < 8; i++) {
6278
        env->cp15.c6_region[i] = qemu_get_be32(f);
6279
    }
6280
    env->cp15.c6_insn = qemu_get_be32(f);
6281
    env->cp15.c6_data = qemu_get_be32(f);
6282
    env->cp15.c9_insn = qemu_get_be32(f);
6283
    env->cp15.c9_data = qemu_get_be32(f);
6284
    env->cp15.c13_fcse = qemu_get_be32(f);
6285
    env->cp15.c13_context = qemu_get_be32(f);
6286
    env->cp15.c13_tls1 = qemu_get_be32(f);
6287
    env->cp15.c13_tls2 = qemu_get_be32(f);
6288
    env->cp15.c13_tls3 = qemu_get_be32(f);
6289
    env->cp15.c15_cpar = qemu_get_be32(f);
6290

    
6291
    env->features = qemu_get_be32(f);
6292

    
6293
    if (arm_feature(env, ARM_FEATURE_VFP)) {
6294
        for (i = 0;  i < 16; i++) {
6295
            CPU_DoubleU u;
6296
            u.l.upper = qemu_get_be32(f);
6297
            u.l.lower = qemu_get_be32(f);
6298
            env->vfp.regs[i] = u.d;
6299
        }
6300
        for (i = 0; i < 16; i++) {
6301
            env->vfp.xregs[i] = qemu_get_be32(f);
6302
        }
6303

    
6304
        /* TODO: Should use proper FPSCR access functions.  */
6305
        env->vfp.vec_len = qemu_get_be32(f);
6306
        env->vfp.vec_stride = qemu_get_be32(f);
6307

    
6308
        if (arm_feature(env, ARM_FEATURE_VFP3)) {
6309
            for (i = 0;  i < 16; i++) {
6310
                CPU_DoubleU u;
6311
                u.l.upper = qemu_get_be32(f);
6312
                u.l.lower = qemu_get_be32(f);
6313
                env->vfp.regs[i] = u.d;
6314
            }
6315
        }
6316
    }
6317

    
6318
    if (arm_feature(env, ARM_FEATURE_IWMMXT)) {
6319
        for (i = 0; i < 16; i++) {
6320
            env->iwmmxt.regs[i] = qemu_get_be64(f);
6321
        }
6322
        for (i = 0; i < 16; i++) {
6323
            env->iwmmxt.cregs[i] = qemu_get_be32(f);
6324
        }
6325
    }
6326

    
6327
    if (arm_feature(env, ARM_FEATURE_M)) {
6328
        env->v7m.other_sp = qemu_get_be32(f);
6329
        env->v7m.vecbase = qemu_get_be32(f);
6330
        env->v7m.basepri = qemu_get_be32(f);
6331
        env->v7m.control = qemu_get_be32(f);
6332
        env->v7m.current_sp = qemu_get_be32(f);
6333
        env->v7m.exception = qemu_get_be32(f);
6334
    }
6335

    
6336
    return 0;
6337
}
6338

    
6339
#else
6340

    
6341
//#warning No CPU save/restore functions
6342

    
6343
#endif
6344

    
6345
/***********************************************************/
6346
/* ram save/restore */
6347

    
6348
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6349
{
6350
    int v;
6351

    
6352
    v = qemu_get_byte(f);
6353
    switch(v) {
6354
    case 0:
6355
        if (qemu_get_buffer(f, buf, len) != len)
6356
            return -EIO;
6357
        break;
6358
    case 1:
6359
        v = qemu_get_byte(f);
6360
        memset(buf, v, len);
6361
        break;
6362
    default:
6363
        return -EINVAL;
6364
    }
6365
    return 0;
6366
}
6367

    
6368
static int ram_load_v1(QEMUFile *f, void *opaque)
6369
{
6370
    int i, ret;
6371

    
6372
    if (qemu_get_be32(f) != phys_ram_size)
6373
        return -EINVAL;
6374
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6375
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6376
        if (ret)
6377
            return ret;
6378
    }
6379
    return 0;
6380
}
6381

    
6382
#define BDRV_HASH_BLOCK_SIZE 1024
6383
#define IOBUF_SIZE 4096
6384
#define RAM_CBLOCK_MAGIC 0xfabe
6385

    
6386
typedef struct RamCompressState {
6387
    z_stream zstream;
6388
    QEMUFile *f;
6389
    uint8_t buf[IOBUF_SIZE];
6390
} RamCompressState;
6391

    
6392
static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6393
{
6394
    int ret;
6395
    memset(s, 0, sizeof(*s));
6396
    s->f = f;
6397
    ret = deflateInit2(&s->zstream, 1,
6398
                       Z_DEFLATED, 15,
6399
                       9, Z_DEFAULT_STRATEGY);
6400
    if (ret != Z_OK)
6401
        return -1;
6402
    s->zstream.avail_out = IOBUF_SIZE;
6403
    s->zstream.next_out = s->buf;
6404
    return 0;
6405
}
6406

    
6407
static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6408
{
6409
    qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6410
    qemu_put_be16(s->f, len);
6411
    qemu_put_buffer(s->f, buf, len);
6412
}
6413

    
6414
static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6415
{
6416
    int ret;
6417

    
6418
    s->zstream.avail_in = len;
6419
    s->zstream.next_in = (uint8_t *)buf;
6420
    while (s->zstream.avail_in > 0) {
6421
        ret = deflate(&s->zstream, Z_NO_FLUSH);
6422
        if (ret != Z_OK)
6423
            return -1;
6424
        if (s->zstream.avail_out == 0) {
6425
            ram_put_cblock(s, s->buf, IOBUF_SIZE);
6426
            s->zstream.avail_out = IOBUF_SIZE;
6427
            s->zstream.next_out = s->buf;
6428
        }
6429
    }
6430
    return 0;
6431
}
6432

    
6433
static void ram_compress_close(RamCompressState *s)
6434
{
6435
    int len, ret;
6436

    
6437
    /* compress last bytes */
6438
    for(;;) {
6439
        ret = deflate(&s->zstream, Z_FINISH);
6440
        if (ret == Z_OK || ret == Z_STREAM_END) {
6441
            len = IOBUF_SIZE - s->zstream.avail_out;
6442
            if (len > 0) {
6443
                ram_put_cblock(s, s->buf, len);
6444
            }
6445
            s->zstream.avail_out = IOBUF_SIZE;
6446
            s->zstream.next_out = s->buf;
6447
            if (ret == Z_STREAM_END)
6448
                break;
6449
        } else {
6450
            goto fail;
6451
        }
6452
    }
6453
fail:
6454
    deflateEnd(&s->zstream);
6455
}
6456

    
6457
typedef struct RamDecompressState {
6458
    z_stream zstream;
6459
    QEMUFile *f;
6460
    uint8_t buf[IOBUF_SIZE];
6461
} RamDecompressState;
6462

    
6463
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6464
{
6465
    int ret;
6466
    memset(s, 0, sizeof(*s));
6467
    s->f = f;
6468
    ret = inflateInit(&s->zstream);
6469
    if (ret != Z_OK)
6470
        return -1;
6471
    return 0;
6472
}
6473

    
6474
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6475
{
6476
    int ret, clen;
6477

    
6478
    s->zstream.avail_out = len;
6479
    s->zstream.next_out = buf;
6480
    while (s->zstream.avail_out > 0) {
6481
        if (s->zstream.avail_in == 0) {
6482
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6483
                return -1;
6484
            clen = qemu_get_be16(s->f);
6485
            if (clen > IOBUF_SIZE)
6486
                return -1;
6487
            qemu_get_buffer(s->f, s->buf, clen);
6488
            s->zstream.avail_in = clen;
6489
            s->zstream.next_in = s->buf;
6490
        }
6491
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6492
        if (ret != Z_OK && ret != Z_STREAM_END) {
6493
            return -1;
6494
        }
6495
    }
6496
    return 0;
6497
}
6498

    
6499
static void ram_decompress_close(RamDecompressState *s)
6500
{
6501
    inflateEnd(&s->zstream);
6502
}
6503

    
6504
static void ram_save(QEMUFile *f, void *opaque)
6505
{
6506
    int i;
6507
    RamCompressState s1, *s = &s1;
6508
    uint8_t buf[10];
6509

    
6510
    qemu_put_be32(f, phys_ram_size);
6511
    if (ram_compress_open(s, f) < 0)
6512
        return;
6513
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6514
#if 0
6515
        if (tight_savevm_enabled) {
6516
            int64_t sector_num;
6517
            int j;
6518

6519
            /* find if the memory block is available on a virtual
6520
               block device */
6521
            sector_num = -1;
6522
            for(j = 0; j < MAX_DISKS; j++) {
6523
                if (bs_table[j]) {
6524
                    sector_num = bdrv_hash_find(bs_table[j],
6525
                                                phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6526
                    if (sector_num >= 0)
6527
                        break;
6528
                }
6529
            }
6530
            if (j == MAX_DISKS)
6531
                goto normal_compress;
6532
            buf[0] = 1;
6533
            buf[1] = j;
6534
            cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6535
            ram_compress_buf(s, buf, 10);
6536
        } else
6537
#endif
6538
        {
6539
            //        normal_compress:
6540
            buf[0] = 0;
6541
            ram_compress_buf(s, buf, 1);
6542
            ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6543
        }
6544
    }
6545
    ram_compress_close(s);
6546
}
6547

    
6548
static int ram_load(QEMUFile *f, void *opaque, int version_id)
6549
{
6550
    RamDecompressState s1, *s = &s1;
6551
    uint8_t buf[10];
6552
    int i;
6553

    
6554
    if (version_id == 1)
6555
        return ram_load_v1(f, opaque);
6556
    if (version_id != 2)
6557
        return -EINVAL;
6558
    if (qemu_get_be32(f) != phys_ram_size)
6559
        return -EINVAL;
6560
    if (ram_decompress_open(s, f) < 0)
6561
        return -EINVAL;
6562
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6563
        if (ram_decompress_buf(s, buf, 1) < 0) {
6564
            fprintf(stderr, "Error while reading ram block header\n");
6565
            goto error;
6566
        }
6567
        if (buf[0] == 0) {
6568
            if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6569
                fprintf(stderr, "Error while reading ram block address=0x%08x", i);
6570
                goto error;
6571
            }
6572
        } else
6573
#if 0
6574
        if (buf[0] == 1) {
6575
            int bs_index;
6576
            int64_t sector_num;
6577

6578
            ram_decompress_buf(s, buf + 1, 9);
6579
            bs_index = buf[1];
6580
            sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6581
            if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
6582
                fprintf(stderr, "Invalid block device index %d\n", bs_index);
6583
                goto error;
6584
            }
6585
            if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i,
6586
                          BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6587
                fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6588
                        bs_index, sector_num);
6589
                goto error;
6590
            }
6591
        } else
6592
#endif
6593
        {
6594
        error:
6595
            printf("Error block header\n");
6596
            return -EINVAL;
6597
        }
6598
    }
6599
    ram_decompress_close(s);
6600
    return 0;
6601
}
6602

    
6603
/***********************************************************/
6604
/* bottom halves (can be seen as timers which expire ASAP) */
6605

    
6606
struct QEMUBH {
6607
    QEMUBHFunc *cb;
6608
    void *opaque;
6609
    int scheduled;
6610
    QEMUBH *next;
6611
};
6612

    
6613
static QEMUBH *first_bh = NULL;
6614

    
6615
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6616
{
6617
    QEMUBH *bh;
6618
    bh = qemu_mallocz(sizeof(QEMUBH));
6619
    if (!bh)
6620
        return NULL;
6621
    bh->cb = cb;
6622
    bh->opaque = opaque;
6623
    return bh;
6624
}
6625

    
6626
int qemu_bh_poll(void)
6627
{
6628
    QEMUBH *bh, **pbh;
6629
    int ret;
6630

    
6631
    ret = 0;
6632
    for(;;) {
6633
        pbh = &first_bh;
6634
        bh = *pbh;
6635
        if (!bh)
6636
            break;
6637
        ret = 1;
6638
        *pbh = bh->next;
6639
        bh->scheduled = 0;
6640
        bh->cb(bh->opaque);
6641
    }
6642
    return ret;
6643
}
6644

    
6645
void qemu_bh_schedule(QEMUBH *bh)
6646
{
6647
    CPUState *env = cpu_single_env;
6648
    if (bh->scheduled)
6649
        return;
6650
    bh->scheduled = 1;
6651
    bh->next = first_bh;
6652
    first_bh = bh;
6653

    
6654
    /* stop the currently executing CPU to execute the BH ASAP */
6655
    if (env) {
6656
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6657
    }
6658
}
6659

    
6660
void qemu_bh_cancel(QEMUBH *bh)
6661
{
6662
    QEMUBH **pbh;
6663
    if (bh->scheduled) {
6664
        pbh = &first_bh;
6665
        while (*pbh != bh)
6666
            pbh = &(*pbh)->next;
6667
        *pbh = bh->next;
6668
        bh->scheduled = 0;
6669
    }
6670
}
6671

    
6672
void qemu_bh_delete(QEMUBH *bh)
6673
{
6674
    qemu_bh_cancel(bh);
6675
    qemu_free(bh);
6676
}
6677

    
6678
/***********************************************************/
6679
/* machine registration */
6680

    
6681
QEMUMachine *first_machine = NULL;
6682

    
6683
int qemu_register_machine(QEMUMachine *m)
6684
{
6685
    QEMUMachine **pm;
6686
    pm = &first_machine;
6687
    while (*pm != NULL)
6688
        pm = &(*pm)->next;
6689
    m->next = NULL;
6690
    *pm = m;
6691
    return 0;
6692
}
6693

    
6694
static QEMUMachine *find_machine(const char *name)
6695
{
6696
    QEMUMachine *m;
6697

    
6698
    for(m = first_machine; m != NULL; m = m->next) {
6699
        if (!strcmp(m->name, name))
6700
            return m;
6701
    }
6702
    return NULL;
6703
}
6704

    
6705
/***********************************************************/
6706
/* main execution loop */
6707

    
6708
static void gui_update(void *opaque)
6709
{
6710
    DisplayState *ds = opaque;
6711
    ds->dpy_refresh(ds);
6712
    qemu_mod_timer(ds->gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6713
}
6714

    
6715
struct vm_change_state_entry {
6716
    VMChangeStateHandler *cb;
6717
    void *opaque;
6718
    LIST_ENTRY (vm_change_state_entry) entries;
6719
};
6720

    
6721
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6722

    
6723
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6724
                                                     void *opaque)
6725
{
6726
    VMChangeStateEntry *e;
6727

    
6728
    e = qemu_mallocz(sizeof (*e));
6729
    if (!e)
6730
        return NULL;
6731

    
6732
    e->cb = cb;
6733
    e->opaque = opaque;
6734
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6735
    return e;
6736
}
6737

    
6738
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6739
{
6740
    LIST_REMOVE (e, entries);
6741
    qemu_free (e);
6742
}
6743

    
6744
static void vm_state_notify(int running)
6745
{
6746
    VMChangeStateEntry *e;
6747

    
6748
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6749
        e->cb(e->opaque, running);
6750
    }
6751
}
6752

    
6753
/* XXX: support several handlers */
6754
static VMStopHandler *vm_stop_cb;
6755
static void *vm_stop_opaque;
6756

    
6757
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6758
{
6759
    vm_stop_cb = cb;
6760
    vm_stop_opaque = opaque;
6761
    return 0;
6762
}
6763

    
6764
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6765
{
6766
    vm_stop_cb = NULL;
6767
}
6768

    
6769
void vm_start(void)
6770
{
6771
    if (!vm_running) {
6772
        cpu_enable_ticks();
6773
        vm_running = 1;
6774
        vm_state_notify(1);
6775
        qemu_rearm_alarm_timer(alarm_timer);
6776
    }
6777
}
6778

    
6779
void vm_stop(int reason)
6780
{
6781
    if (vm_running) {
6782
        cpu_disable_ticks();
6783
        vm_running = 0;
6784
        if (reason != 0) {
6785
            if (vm_stop_cb) {
6786
                vm_stop_cb(vm_stop_opaque, reason);
6787
            }
6788
        }
6789
        vm_state_notify(0);
6790
    }
6791
}
6792

    
6793
/* reset/shutdown handler */
6794

    
6795
typedef struct QEMUResetEntry {
6796
    QEMUResetHandler *func;
6797
    void *opaque;
6798
    struct QEMUResetEntry *next;
6799
} QEMUResetEntry;
6800

    
6801
static QEMUResetEntry *first_reset_entry;
6802
static int reset_requested;
6803
static int shutdown_requested;
6804
static int powerdown_requested;
6805

    
6806
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6807
{
6808
    QEMUResetEntry **pre, *re;
6809

    
6810
    pre = &first_reset_entry;
6811
    while (*pre != NULL)
6812
        pre = &(*pre)->next;
6813
    re = qemu_mallocz(sizeof(QEMUResetEntry));
6814
    re->func = func;
6815
    re->opaque = opaque;
6816
    re->next = NULL;
6817
    *pre = re;
6818
}
6819

    
6820
static void qemu_system_reset(void)
6821
{
6822
    QEMUResetEntry *re;
6823

    
6824
    /* reset all devices */
6825
    for(re = first_reset_entry; re != NULL; re = re->next) {
6826
        re->func(re->opaque);
6827
    }
6828
}
6829

    
6830
void qemu_system_reset_request(void)
6831
{
6832
    if (no_reboot) {
6833
        shutdown_requested = 1;
6834
    } else {
6835
        reset_requested = 1;
6836
    }
6837
    if (cpu_single_env)
6838
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6839
}
6840

    
6841
void qemu_system_shutdown_request(void)
6842
{
6843
    shutdown_requested = 1;
6844
    if (cpu_single_env)
6845
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6846
}
6847

    
6848
void qemu_system_powerdown_request(void)
6849
{
6850
    powerdown_requested = 1;
6851
    if (cpu_single_env)
6852
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6853
}
6854

    
6855
void main_loop_wait(int timeout)
6856
{
6857
    IOHandlerRecord *ioh;
6858
    fd_set rfds, wfds, xfds;
6859
    int ret, nfds;
6860
#ifdef _WIN32
6861
    int ret2, i;
6862
#endif
6863
    struct timeval tv;
6864
    PollingEntry *pe;
6865

    
6866

    
6867
    /* XXX: need to suppress polling by better using win32 events */
6868
    ret = 0;
6869
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6870
        ret |= pe->func(pe->opaque);
6871
    }
6872
#ifdef _WIN32
6873
    if (ret == 0) {
6874
        int err;
6875
        WaitObjects *w = &wait_objects;
6876

    
6877
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6878
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6879
            if (w->func[ret - WAIT_OBJECT_0])
6880
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6881

    
6882
            /* Check for additional signaled events */
6883
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6884

    
6885
                /* Check if event is signaled */
6886
                ret2 = WaitForSingleObject(w->events[i], 0);
6887
                if(ret2 == WAIT_OBJECT_0) {
6888
                    if (w->func[i])
6889
                        w->func[i](w->opaque[i]);
6890
                } else if (ret2 == WAIT_TIMEOUT) {
6891
                } else {
6892
                    err = GetLastError();
6893
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6894
                }
6895
            }
6896
        } else if (ret == WAIT_TIMEOUT) {
6897
        } else {
6898
            err = GetLastError();
6899
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6900
        }
6901
    }
6902
#endif
6903
    /* poll any events */
6904
    /* XXX: separate device handlers from system ones */
6905
    nfds = -1;
6906
    FD_ZERO(&rfds);
6907
    FD_ZERO(&wfds);
6908
    FD_ZERO(&xfds);
6909
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6910
        if (ioh->deleted)
6911
            continue;
6912
        if (ioh->fd_read &&
6913
            (!ioh->fd_read_poll ||
6914
             ioh->fd_read_poll(ioh->opaque) != 0)) {
6915
            FD_SET(ioh->fd, &rfds);
6916
            if (ioh->fd > nfds)
6917
                nfds = ioh->fd;
6918
        }
6919
        if (ioh->fd_write) {
6920
            FD_SET(ioh->fd, &wfds);
6921
            if (ioh->fd > nfds)
6922
                nfds = ioh->fd;
6923
        }
6924
    }
6925

    
6926
    tv.tv_sec = 0;
6927
#ifdef _WIN32
6928
    tv.tv_usec = 0;
6929
#else
6930
    tv.tv_usec = timeout * 1000;
6931
#endif
6932
#if defined(CONFIG_SLIRP)
6933
    if (slirp_inited) {
6934
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6935
    }
6936
#endif
6937
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6938
    if (ret > 0) {
6939
        IOHandlerRecord **pioh;
6940

    
6941
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6942
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
6943
                ioh->fd_read(ioh->opaque);
6944
            }
6945
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
6946
                ioh->fd_write(ioh->opaque);
6947
            }
6948
        }
6949

    
6950
        /* remove deleted IO handlers */
6951
        pioh = &first_io_handler;
6952
        while (*pioh) {
6953
            ioh = *pioh;
6954
            if (ioh->deleted) {
6955
                *pioh = ioh->next;
6956
                qemu_free(ioh);
6957
            } else
6958
                pioh = &ioh->next;
6959
        }
6960
    }
6961
#if defined(CONFIG_SLIRP)
6962
    if (slirp_inited) {
6963
        if (ret < 0) {
6964
            FD_ZERO(&rfds);
6965
            FD_ZERO(&wfds);
6966
            FD_ZERO(&xfds);
6967
        }
6968
        slirp_select_poll(&rfds, &wfds, &xfds);
6969
    }
6970
#endif
6971
    qemu_aio_poll();
6972

    
6973
    if (vm_running) {
6974
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
6975
                        qemu_get_clock(vm_clock));
6976
        /* run dma transfers, if any */
6977
        DMA_run();
6978
    }
6979

    
6980
    /* real time timers */
6981
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
6982
                    qemu_get_clock(rt_clock));
6983

    
6984
    /* Check bottom-halves last in case any of the earlier events triggered
6985
       them.  */
6986
    qemu_bh_poll();
6987

    
6988
}
6989

    
6990
static CPUState *cur_cpu;
6991

    
6992
static int main_loop(void)
6993
{
6994
    int ret, timeout;
6995
#ifdef CONFIG_PROFILER
6996
    int64_t ti;
6997
#endif
6998
    CPUState *env;
6999

    
7000
    cur_cpu = first_cpu;
7001
    for(;;) {
7002
        if (vm_running) {
7003

    
7004
            env = cur_cpu;
7005
            for(;;) {
7006
                /* get next cpu */
7007
                env = env->next_cpu;
7008
                if (!env)
7009
                    env = first_cpu;
7010
#ifdef CONFIG_PROFILER
7011
                ti = profile_getclock();
7012
#endif
7013
                ret = cpu_exec(env);
7014
#ifdef CONFIG_PROFILER
7015
                qemu_time += profile_getclock() - ti;
7016
#endif
7017
                if (ret == EXCP_HLT) {
7018
                    /* Give the next CPU a chance to run.  */
7019
                    cur_cpu = env;
7020
                    continue;
7021
                }
7022
                if (ret != EXCP_HALTED)
7023
                    break;
7024
                /* all CPUs are halted ? */
7025
                if (env == cur_cpu)
7026
                    break;
7027
            }
7028
            cur_cpu = env;
7029

    
7030
            if (shutdown_requested) {
7031
                ret = EXCP_INTERRUPT;
7032
                break;
7033
            }
7034
            if (reset_requested) {
7035
                reset_requested = 0;
7036
                qemu_system_reset();
7037
                ret = EXCP_INTERRUPT;
7038
            }
7039
            if (powerdown_requested) {
7040
                powerdown_requested = 0;
7041
                qemu_system_powerdown();
7042
                ret = EXCP_INTERRUPT;
7043
            }
7044
            if (ret == EXCP_DEBUG) {
7045
                vm_stop(EXCP_DEBUG);
7046
            }
7047
            /* If all cpus are halted then wait until the next IRQ */
7048
            /* XXX: use timeout computed from timers */
7049
            if (ret == EXCP_HALTED)
7050
                timeout = 10;
7051
            else
7052
                timeout = 0;
7053
        } else {
7054
            timeout = 10;
7055
        }
7056
#ifdef CONFIG_PROFILER
7057
        ti = profile_getclock();
7058
#endif
7059
        main_loop_wait(timeout);
7060
#ifdef CONFIG_PROFILER
7061
        dev_time += profile_getclock() - ti;
7062
#endif
7063
    }
7064
    cpu_disable_ticks();
7065
    return ret;
7066
}
7067

    
7068
static void help(int exitcode)
7069
{
7070
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
7071
           "usage: %s [options] [disk_image]\n"
7072
           "\n"
7073
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7074
           "\n"
7075
           "Standard options:\n"
7076
           "-M machine      select emulated machine (-M ? for list)\n"
7077
           "-cpu cpu        select CPU (-cpu ? for list)\n"
7078
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
7079
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
7080
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
7081
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7082
           "-mtdblock file  use 'file' as on-board Flash memory image\n"
7083
           "-sd file        use 'file' as SecureDigital card image\n"
7084
           "-pflash file    use 'file' as a parallel flash image\n"
7085
           "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7086
           "-snapshot       write to temporary files instead of disk image files\n"
7087
#ifdef CONFIG_SDL
7088
           "-no-frame       open SDL window without a frame and window decorations\n"
7089
           "-alt-grab       use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7090
           "-no-quit        disable SDL window close capability\n"
7091
#endif
7092
#ifdef TARGET_I386
7093
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
7094
#endif
7095
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
7096
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
7097
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
7098
           "-portrait       rotate graphical output 90 deg left (only PXA LCD)\n"
7099
#ifndef _WIN32
7100
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
7101
#endif
7102
#ifdef HAS_AUDIO
7103
           "-audio-help     print list of audio drivers and their options\n"
7104
           "-soundhw c1,... enable audio support\n"
7105
           "                and only specified sound cards (comma separated list)\n"
7106
           "                use -soundhw ? to get the list of supported cards\n"
7107
           "                use -soundhw all to enable all of them\n"
7108
#endif
7109
           "-localtime      set the real time clock to local time [default=utc]\n"
7110
           "-full-screen    start in full screen\n"
7111
#ifdef TARGET_I386
7112
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
7113
#endif
7114
           "-usb            enable the USB driver (will be the default soon)\n"
7115
           "-usbdevice name add the host or guest USB device 'name'\n"
7116
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7117
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
7118
#endif
7119
           "-name string    set the name of the guest\n"
7120
           "\n"
7121
           "Network options:\n"
7122
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7123
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
7124
#ifdef CONFIG_SLIRP
7125
           "-net user[,vlan=n][,hostname=host]\n"
7126
           "                connect the user mode network stack to VLAN 'n' and send\n"
7127
           "                hostname 'host' to DHCP clients\n"
7128
#endif
7129
#ifdef _WIN32
7130
           "-net tap[,vlan=n],ifname=name\n"
7131
           "                connect the host TAP network interface to VLAN 'n'\n"
7132
#else
7133
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7134
           "                connect the host TAP network interface to VLAN 'n' and use the\n"
7135
           "                network scripts 'file' (default=%s)\n"
7136
           "                and 'dfile' (default=%s);\n"
7137
           "                use '[down]script=no' to disable script execution;\n"
7138
           "                use 'fd=h' to connect to an already opened TAP interface\n"
7139
#endif
7140
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7141
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
7142
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7143
           "                connect the vlan 'n' to multicast maddr and port\n"
7144
           "-net none       use it alone to have zero network devices; if no -net option\n"
7145
           "                is provided, the default is '-net nic -net user'\n"
7146
           "\n"
7147
#ifdef CONFIG_SLIRP
7148
           "-tftp dir       allow tftp access to files in dir [-net user]\n"
7149
           "-bootp file     advertise file in BOOTP replies\n"
7150
#ifndef _WIN32
7151
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
7152
#endif
7153
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7154
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
7155
#endif
7156
           "\n"
7157
           "Linux boot specific:\n"
7158
           "-kernel bzImage use 'bzImage' as kernel image\n"
7159
           "-append cmdline use 'cmdline' as kernel command line\n"
7160
           "-initrd file    use 'file' as initial ram disk\n"
7161
           "\n"
7162
           "Debug/Expert options:\n"
7163
           "-monitor dev    redirect the monitor to char device 'dev'\n"
7164
           "-serial dev     redirect the serial port to char device 'dev'\n"
7165
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
7166
           "-pidfile file   Write PID to 'file'\n"
7167
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
7168
           "-s              wait gdb connection to port\n"
7169
           "-p port         set gdb connection port [default=%s]\n"
7170
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
7171
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
7172
           "                translation (t=none or lba) (usually qemu can guess them)\n"
7173
           "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
7174
#ifdef USE_KQEMU
7175
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
7176
           "-no-kqemu       disable KQEMU kernel module usage\n"
7177
#endif
7178
#ifdef TARGET_I386
7179
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
7180
           "                (default is CL-GD5446 PCI VGA)\n"
7181
           "-no-acpi        disable ACPI\n"
7182
#endif
7183
           "-no-reboot      exit instead of rebooting\n"
7184
           "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
7185
           "-vnc display    start a VNC server on display\n"
7186
#ifndef _WIN32
7187
           "-daemonize      daemonize QEMU after initializing\n"
7188
#endif
7189
           "-option-rom rom load a file, rom, into the option ROM space\n"
7190
#ifdef TARGET_SPARC
7191
           "-prom-env variable=value  set OpenBIOS nvram variables\n"
7192
#endif
7193
           "-clock          force the use of the given methods for timer alarm.\n"
7194
           "                To see what timers are available use -clock help\n"
7195
           "\n"
7196
           "During emulation, the following keys are useful:\n"
7197
           "ctrl-alt-f      toggle full screen\n"
7198
           "ctrl-alt-n      switch to virtual console 'n'\n"
7199
           "ctrl-alt        toggle mouse and keyboard grab\n"
7200
           "\n"
7201
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
7202
           ,
7203
           "qemu",
7204
           DEFAULT_RAM_SIZE,
7205
#ifndef _WIN32
7206
           DEFAULT_NETWORK_SCRIPT,
7207
           DEFAULT_NETWORK_DOWN_SCRIPT,
7208
#endif
7209
           DEFAULT_GDBSTUB_PORT,
7210
           "/tmp/qemu.log");
7211
    exit(exitcode);
7212
}
7213

    
7214
#define HAS_ARG 0x0001
7215

    
7216
enum {
7217
    QEMU_OPTION_h,
7218

    
7219
    QEMU_OPTION_M,
7220
    QEMU_OPTION_cpu,
7221
    QEMU_OPTION_fda,
7222
    QEMU_OPTION_fdb,
7223
    QEMU_OPTION_hda,
7224
    QEMU_OPTION_hdb,
7225
    QEMU_OPTION_hdc,
7226
    QEMU_OPTION_hdd,
7227
    QEMU_OPTION_cdrom,
7228
    QEMU_OPTION_mtdblock,
7229
    QEMU_OPTION_sd,
7230
    QEMU_OPTION_pflash,
7231
    QEMU_OPTION_boot,
7232
    QEMU_OPTION_snapshot,
7233
#ifdef TARGET_I386
7234
    QEMU_OPTION_no_fd_bootchk,
7235
#endif
7236
    QEMU_OPTION_m,
7237
    QEMU_OPTION_nographic,
7238
    QEMU_OPTION_portrait,
7239
#ifdef HAS_AUDIO
7240
    QEMU_OPTION_audio_help,
7241
    QEMU_OPTION_soundhw,
7242
#endif
7243

    
7244
    QEMU_OPTION_net,
7245
    QEMU_OPTION_tftp,
7246
    QEMU_OPTION_bootp,
7247
    QEMU_OPTION_smb,
7248
    QEMU_OPTION_redir,
7249

    
7250
    QEMU_OPTION_kernel,
7251
    QEMU_OPTION_append,
7252
    QEMU_OPTION_initrd,
7253

    
7254
    QEMU_OPTION_S,
7255
    QEMU_OPTION_s,
7256
    QEMU_OPTION_p,
7257
    QEMU_OPTION_d,
7258
    QEMU_OPTION_hdachs,
7259
    QEMU_OPTION_L,
7260
    QEMU_OPTION_bios,
7261
    QEMU_OPTION_no_code_copy,
7262
    QEMU_OPTION_k,
7263
    QEMU_OPTION_localtime,
7264
    QEMU_OPTION_cirrusvga,
7265
    QEMU_OPTION_vmsvga,
7266
    QEMU_OPTION_g,
7267
    QEMU_OPTION_std_vga,
7268
    QEMU_OPTION_echr,
7269
    QEMU_OPTION_monitor,
7270
    QEMU_OPTION_serial,
7271
    QEMU_OPTION_parallel,
7272
    QEMU_OPTION_loadvm,
7273
    QEMU_OPTION_full_screen,
7274
    QEMU_OPTION_no_frame,
7275
    QEMU_OPTION_alt_grab,
7276
    QEMU_OPTION_no_quit,
7277
    QEMU_OPTION_pidfile,
7278
    QEMU_OPTION_no_kqemu,
7279
    QEMU_OPTION_kernel_kqemu,
7280
    QEMU_OPTION_win2k_hack,
7281
    QEMU_OPTION_usb,
7282
    QEMU_OPTION_usbdevice,
7283
    QEMU_OPTION_smp,
7284
    QEMU_OPTION_vnc,
7285
    QEMU_OPTION_no_acpi,
7286
    QEMU_OPTION_no_reboot,
7287
    QEMU_OPTION_show_cursor,
7288
    QEMU_OPTION_daemonize,
7289
    QEMU_OPTION_option_rom,
7290
    QEMU_OPTION_semihosting,
7291
    QEMU_OPTION_name,
7292
    QEMU_OPTION_prom_env,
7293
    QEMU_OPTION_old_param,
7294
    QEMU_OPTION_clock,
7295
    QEMU_OPTION_startdate,
7296
};
7297

    
7298
typedef struct QEMUOption {
7299
    const char *name;
7300
    int flags;
7301
    int index;
7302
} QEMUOption;
7303

    
7304
const QEMUOption qemu_options[] = {
7305
    { "h", 0, QEMU_OPTION_h },
7306
    { "help", 0, QEMU_OPTION_h },
7307

    
7308
    { "M", HAS_ARG, QEMU_OPTION_M },
7309
    { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7310
    { "fda", HAS_ARG, QEMU_OPTION_fda },
7311
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7312
    { "hda", HAS_ARG, QEMU_OPTION_hda },
7313
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7314
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7315
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7316
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7317
    { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7318
    { "sd", HAS_ARG, QEMU_OPTION_sd },
7319
    { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7320
    { "boot", HAS_ARG, QEMU_OPTION_boot },
7321
    { "snapshot", 0, QEMU_OPTION_snapshot },
7322
#ifdef TARGET_I386
7323
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7324
#endif
7325
    { "m", HAS_ARG, QEMU_OPTION_m },
7326
    { "nographic", 0, QEMU_OPTION_nographic },
7327
    { "portrait", 0, QEMU_OPTION_portrait },
7328
    { "k", HAS_ARG, QEMU_OPTION_k },
7329
#ifdef HAS_AUDIO
7330
    { "audio-help", 0, QEMU_OPTION_audio_help },
7331
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7332
#endif
7333

    
7334
    { "net", HAS_ARG, QEMU_OPTION_net},
7335
#ifdef CONFIG_SLIRP
7336
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7337
    { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7338
#ifndef _WIN32
7339
    { "smb", HAS_ARG, QEMU_OPTION_smb },
7340
#endif
7341
    { "redir", HAS_ARG, QEMU_OPTION_redir },
7342
#endif
7343

    
7344
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7345
    { "append", HAS_ARG, QEMU_OPTION_append },
7346
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7347

    
7348
    { "S", 0, QEMU_OPTION_S },
7349
    { "s", 0, QEMU_OPTION_s },
7350
    { "p", HAS_ARG, QEMU_OPTION_p },
7351
    { "d", HAS_ARG, QEMU_OPTION_d },
7352
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7353
    { "L", HAS_ARG, QEMU_OPTION_L },
7354
    { "bios", HAS_ARG, QEMU_OPTION_bios },
7355
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
7356
#ifdef USE_KQEMU
7357
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7358
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7359
#endif
7360
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7361
    { "g", 1, QEMU_OPTION_g },
7362
#endif
7363
    { "localtime", 0, QEMU_OPTION_localtime },
7364
    { "std-vga", 0, QEMU_OPTION_std_vga },
7365
    { "echr", HAS_ARG, QEMU_OPTION_echr },
7366
    { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7367
    { "serial", HAS_ARG, QEMU_OPTION_serial },
7368
    { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7369
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7370
    { "full-screen", 0, QEMU_OPTION_full_screen },
7371
#ifdef CONFIG_SDL
7372
    { "no-frame", 0, QEMU_OPTION_no_frame },
7373
    { "alt-grab", 0, QEMU_OPTION_alt_grab },
7374
    { "no-quit", 0, QEMU_OPTION_no_quit },
7375
#endif
7376
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7377
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7378
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7379
    { "smp", HAS_ARG, QEMU_OPTION_smp },
7380
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7381

    
7382
    /* temporary options */
7383
    { "usb", 0, QEMU_OPTION_usb },
7384
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7385
    { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7386
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
7387
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
7388
    { "show-cursor", 0, QEMU_OPTION_show_cursor },
7389
    { "daemonize", 0, QEMU_OPTION_daemonize },
7390
    { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7391
#if defined(TARGET_ARM) || defined(TARGET_M68K)
7392
    { "semihosting", 0, QEMU_OPTION_semihosting },
7393
#endif
7394
    { "name", HAS_ARG, QEMU_OPTION_name },
7395
#if defined(TARGET_SPARC)
7396
    { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7397
#endif
7398
#if defined(TARGET_ARM)
7399
    { "old-param", 0, QEMU_OPTION_old_param },
7400
#endif
7401
    { "clock", HAS_ARG, QEMU_OPTION_clock },
7402
    { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7403
    { NULL },
7404
};
7405

    
7406
/* password input */
7407

    
7408
int qemu_key_check(BlockDriverState *bs, const char *name)
7409
{
7410
    char password[256];
7411
    int i;
7412

    
7413
    if (!bdrv_is_encrypted(bs))
7414
        return 0;
7415

    
7416
    term_printf("%s is encrypted.\n", name);
7417
    for(i = 0; i < 3; i++) {
7418
        monitor_readline("Password: ", 1, password, sizeof(password));
7419
        if (bdrv_set_key(bs, password) == 0)
7420
            return 0;
7421
        term_printf("invalid password\n");
7422
    }
7423
    return -EPERM;
7424
}
7425

    
7426
static BlockDriverState *get_bdrv(int index)
7427
{
7428
    BlockDriverState *bs;
7429

    
7430
    if (index < 4) {
7431
        bs = bs_table[index];
7432
    } else if (index < 6) {
7433
        bs = fd_table[index - 4];
7434
    } else {
7435
        bs = NULL;
7436
    }
7437
    return bs;
7438
}
7439

    
7440
static void read_passwords(void)
7441
{
7442
    BlockDriverState *bs;
7443
    int i;
7444

    
7445
    for(i = 0; i < 6; i++) {
7446
        bs = get_bdrv(i);
7447
        if (bs)
7448
            qemu_key_check(bs, bdrv_get_device_name(bs));
7449
    }
7450
}
7451

    
7452
/* XXX: currently we cannot use simultaneously different CPUs */
7453
static void register_machines(void)
7454
{
7455
#if defined(TARGET_I386)
7456
    qemu_register_machine(&pc_machine);
7457
    qemu_register_machine(&isapc_machine);
7458
#elif defined(TARGET_PPC)
7459
    qemu_register_machine(&heathrow_machine);
7460
    qemu_register_machine(&core99_machine);
7461
    qemu_register_machine(&prep_machine);
7462
    qemu_register_machine(&ref405ep_machine);
7463
    qemu_register_machine(&taihu_machine);
7464
#elif defined(TARGET_MIPS)
7465
    qemu_register_machine(&mips_machine);
7466
    qemu_register_machine(&mips_malta_machine);
7467
    qemu_register_machine(&mips_pica61_machine);
7468
    qemu_register_machine(&mips_mipssim_machine);
7469
#elif defined(TARGET_SPARC)
7470
#ifdef TARGET_SPARC64
7471
    qemu_register_machine(&sun4u_machine);
7472
#else
7473
    qemu_register_machine(&ss5_machine);
7474
    qemu_register_machine(&ss10_machine);
7475
    qemu_register_machine(&ss600mp_machine);
7476
#endif
7477
#elif defined(TARGET_ARM)
7478
    qemu_register_machine(&integratorcp_machine);
7479
    qemu_register_machine(&versatilepb_machine);
7480
    qemu_register_machine(&versatileab_machine);
7481
    qemu_register_machine(&realview_machine);
7482
    qemu_register_machine(&akitapda_machine);
7483
    qemu_register_machine(&spitzpda_machine);
7484
    qemu_register_machine(&borzoipda_machine);
7485
    qemu_register_machine(&terrierpda_machine);
7486
    qemu_register_machine(&palmte_machine);
7487
    qemu_register_machine(&lm3s811evb_machine);
7488
    qemu_register_machine(&lm3s6965evb_machine);
7489
    qemu_register_machine(&connex_machine);
7490
    qemu_register_machine(&verdex_machine);
7491
#elif defined(TARGET_SH4)
7492
    qemu_register_machine(&shix_machine);
7493
    qemu_register_machine(&r2d_machine);
7494
#elif defined(TARGET_ALPHA)
7495
    /* XXX: TODO */
7496
#elif defined(TARGET_M68K)
7497
    qemu_register_machine(&mcf5208evb_machine);
7498
    qemu_register_machine(&an5206_machine);
7499
    qemu_register_machine(&dummy_m68k_machine);
7500
#elif defined(TARGET_CRIS)
7501
    qemu_register_machine(&bareetraxfs_machine);
7502
#else
7503
#error unsupported CPU
7504
#endif
7505
}
7506

    
7507
#ifdef HAS_AUDIO
7508
struct soundhw soundhw[] = {
7509
#ifdef HAS_AUDIO_CHOICE
7510
#ifdef TARGET_I386
7511
    {
7512
        "pcspk",
7513
        "PC speaker",
7514
        0,
7515
        1,
7516
        { .init_isa = pcspk_audio_init }
7517
    },
7518
#endif
7519
    {
7520
        "sb16",
7521
        "Creative Sound Blaster 16",
7522
        0,
7523
        1,
7524
        { .init_isa = SB16_init }
7525
    },
7526

    
7527
#ifdef CONFIG_ADLIB
7528
    {
7529
        "adlib",
7530
#ifdef HAS_YMF262
7531
        "Yamaha YMF262 (OPL3)",
7532
#else
7533
        "Yamaha YM3812 (OPL2)",
7534
#endif
7535
        0,
7536
        1,
7537
        { .init_isa = Adlib_init }
7538
    },
7539
#endif
7540

    
7541
#ifdef CONFIG_GUS
7542
    {
7543
        "gus",
7544
        "Gravis Ultrasound GF1",
7545
        0,
7546
        1,
7547
        { .init_isa = GUS_init }
7548
    },
7549
#endif
7550

    
7551
    {
7552
        "es1370",
7553
        "ENSONIQ AudioPCI ES1370",
7554
        0,
7555
        0,
7556
        { .init_pci = es1370_init }
7557
    },
7558
#endif
7559

    
7560
    { NULL, NULL, 0, 0, { NULL } }
7561
};
7562

    
7563
static void select_soundhw (const char *optarg)
7564
{
7565
    struct soundhw *c;
7566

    
7567
    if (*optarg == '?') {
7568
    show_valid_cards:
7569

    
7570
        printf ("Valid sound card names (comma separated):\n");
7571
        for (c = soundhw; c->name; ++c) {
7572
            printf ("%-11s %s\n", c->name, c->descr);
7573
        }
7574
        printf ("\n-soundhw all will enable all of the above\n");
7575
        exit (*optarg != '?');
7576
    }
7577
    else {
7578
        size_t l;
7579
        const char *p;
7580
        char *e;
7581
        int bad_card = 0;
7582

    
7583
        if (!strcmp (optarg, "all")) {
7584
            for (c = soundhw; c->name; ++c) {
7585
                c->enabled = 1;
7586
            }
7587
            return;
7588
        }
7589

    
7590
        p = optarg;
7591
        while (*p) {
7592
            e = strchr (p, ',');
7593
            l = !e ? strlen (p) : (size_t) (e - p);
7594

    
7595
            for (c = soundhw; c->name; ++c) {
7596
                if (!strncmp (c->name, p, l)) {
7597
                    c->enabled = 1;
7598
                    break;
7599
                }
7600
            }
7601

    
7602
            if (!c->name) {
7603
                if (l > 80) {
7604
                    fprintf (stderr,
7605
                             "Unknown sound card name (too big to show)\n");
7606
                }
7607
                else {
7608
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
7609
                             (int) l, p);
7610
                }
7611
                bad_card = 1;
7612
            }
7613
            p += l + (e != NULL);
7614
        }
7615

    
7616
        if (bad_card)
7617
            goto show_valid_cards;
7618
    }
7619
}
7620
#endif
7621

    
7622
#ifdef _WIN32
7623
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7624
{
7625
    exit(STATUS_CONTROL_C_EXIT);
7626
    return TRUE;
7627
}
7628
#endif
7629

    
7630
#define MAX_NET_CLIENTS 32
7631

    
7632
int main(int argc, char **argv)
7633
{
7634
#ifdef CONFIG_GDBSTUB
7635
    int use_gdbstub;
7636
    const char *gdbstub_port;
7637
#endif
7638
    uint32_t boot_devices_bitmap = 0;
7639
    int i, cdrom_index, pflash_index;
7640
    int snapshot, linux_boot, net_boot;
7641
    const char *initrd_filename;
7642
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
7643
    const char *pflash_filename[MAX_PFLASH];
7644
    const char *sd_filename;
7645
    const char *mtd_filename;
7646
    const char *kernel_filename, *kernel_cmdline;
7647
    const char *boot_devices = "";
7648
    DisplayState *ds = &display_state;
7649
    int cyls, heads, secs, translation;
7650
    char net_clients[MAX_NET_CLIENTS][256];
7651
    int nb_net_clients;
7652
    int optind;
7653
    const char *r, *optarg;
7654
    CharDriverState *monitor_hd;
7655
    char monitor_device[128];
7656
    char serial_devices[MAX_SERIAL_PORTS][128];
7657
    int serial_device_index;
7658
    char parallel_devices[MAX_PARALLEL_PORTS][128];
7659
    int parallel_device_index;
7660
    const char *loadvm = NULL;
7661
    QEMUMachine *machine;
7662
    const char *cpu_model;
7663
    char usb_devices[MAX_USB_CMDLINE][128];
7664
    int usb_devices_index;
7665
    int fds[2];
7666
    const char *pid_file = NULL;
7667
    VLANState *vlan;
7668

    
7669
    LIST_INIT (&vm_change_state_head);
7670
#ifndef _WIN32
7671
    {
7672
        struct sigaction act;
7673
        sigfillset(&act.sa_mask);
7674
        act.sa_flags = 0;
7675
        act.sa_handler = SIG_IGN;
7676
        sigaction(SIGPIPE, &act, NULL);
7677
    }
7678
#else
7679
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7680
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
7681
       QEMU to run on a single CPU */
7682
    {
7683
        HANDLE h;
7684
        DWORD mask, smask;
7685
        int i;
7686
        h = GetCurrentProcess();
7687
        if (GetProcessAffinityMask(h, &mask, &smask)) {
7688
            for(i = 0; i < 32; i++) {
7689
                if (mask & (1 << i))
7690
                    break;
7691
            }
7692
            if (i != 32) {
7693
                mask = 1 << i;
7694
                SetProcessAffinityMask(h, mask);
7695
            }
7696
        }
7697
    }
7698
#endif
7699

    
7700
    register_machines();
7701
    machine = first_machine;
7702
    cpu_model = NULL;
7703
    initrd_filename = NULL;
7704
    for(i = 0; i < MAX_FD; i++)
7705
        fd_filename[i] = NULL;
7706
    for(i = 0; i < MAX_DISKS; i++)
7707
        hd_filename[i] = NULL;
7708
    for(i = 0; i < MAX_PFLASH; i++)
7709
        pflash_filename[i] = NULL;
7710
    pflash_index = 0;
7711
    sd_filename = NULL;
7712
    mtd_filename = NULL;
7713
    ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7714
    vga_ram_size = VGA_RAM_SIZE;
7715
#ifdef CONFIG_GDBSTUB
7716
    use_gdbstub = 0;
7717
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
7718
#endif
7719
    snapshot = 0;
7720
    nographic = 0;
7721
    kernel_filename = NULL;
7722
    kernel_cmdline = "";
7723
#ifdef TARGET_PPC
7724
    cdrom_index = 1;
7725
#else
7726
    cdrom_index = 2;
7727
#endif
7728
    cyls = heads = secs = 0;
7729
    translation = BIOS_ATA_TRANSLATION_AUTO;
7730
    pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7731

    
7732
    pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7733
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
7734
        serial_devices[i][0] = '\0';
7735
    serial_device_index = 0;
7736

    
7737
    pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7738
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7739
        parallel_devices[i][0] = '\0';
7740
    parallel_device_index = 0;
7741

    
7742
    usb_devices_index = 0;
7743

    
7744
    nb_net_clients = 0;
7745

    
7746
    nb_nics = 0;
7747
    /* default mac address of the first network interface */
7748

    
7749
    optind = 1;
7750
    for(;;) {
7751
        if (optind >= argc)
7752
            break;
7753
        r = argv[optind];
7754
        if (r[0] != '-') {
7755
            hd_filename[0] = argv[optind++];
7756
        } else {
7757
            const QEMUOption *popt;
7758

    
7759
            optind++;
7760
            /* Treat --foo the same as -foo.  */
7761
            if (r[1] == '-')
7762
                r++;
7763
            popt = qemu_options;
7764
            for(;;) {
7765
                if (!popt->name) {
7766
                    fprintf(stderr, "%s: invalid option -- '%s'\n",
7767
                            argv[0], r);
7768
                    exit(1);
7769
                }
7770
                if (!strcmp(popt->name, r + 1))
7771
                    break;
7772
                popt++;
7773
            }
7774
            if (popt->flags & HAS_ARG) {
7775
                if (optind >= argc) {
7776
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
7777
                            argv[0], r);
7778
                    exit(1);
7779
                }
7780
                optarg = argv[optind++];
7781
            } else {
7782
                optarg = NULL;
7783
            }
7784

    
7785
            switch(popt->index) {
7786
            case QEMU_OPTION_M:
7787
                machine = find_machine(optarg);
7788
                if (!machine) {
7789
                    QEMUMachine *m;
7790
                    printf("Supported machines are:\n");
7791
                    for(m = first_machine; m != NULL; m = m->next) {
7792
                        printf("%-10s %s%s\n",
7793
                               m->name, m->desc,
7794
                               m == first_machine ? " (default)" : "");
7795
                    }
7796
                    exit(*optarg != '?');
7797
                }
7798
                break;
7799
            case QEMU_OPTION_cpu:
7800
                /* hw initialization will check this */
7801
                if (*optarg == '?') {
7802
/* XXX: implement xxx_cpu_list for targets that still miss it */
7803
#if defined(cpu_list)
7804
                    cpu_list(stdout, &fprintf);
7805
#endif
7806
                    exit(0);
7807
                } else {
7808
                    cpu_model = optarg;
7809
                }
7810
                break;
7811
            case QEMU_OPTION_initrd:
7812
                initrd_filename = optarg;
7813
                break;
7814
            case QEMU_OPTION_hda:
7815
            case QEMU_OPTION_hdb:
7816
            case QEMU_OPTION_hdc:
7817
            case QEMU_OPTION_hdd:
7818
                {
7819
                    int hd_index;
7820
                    hd_index = popt->index - QEMU_OPTION_hda;
7821
                    hd_filename[hd_index] = optarg;
7822
                    if (hd_index == cdrom_index)
7823
                        cdrom_index = -1;
7824
                }
7825
                break;
7826
            case QEMU_OPTION_mtdblock:
7827
                mtd_filename = optarg;
7828
                break;
7829
            case QEMU_OPTION_sd:
7830
                sd_filename = optarg;
7831
                break;
7832
            case QEMU_OPTION_pflash:
7833
                if (pflash_index >= MAX_PFLASH) {
7834
                    fprintf(stderr, "qemu: too many parallel flash images\n");
7835
                    exit(1);
7836
                }
7837
                pflash_filename[pflash_index++] = optarg;
7838
                break;
7839
            case QEMU_OPTION_snapshot:
7840
                snapshot = 1;
7841
                break;
7842
            case QEMU_OPTION_hdachs:
7843
                {
7844
                    const char *p;
7845
                    p = optarg;
7846
                    cyls = strtol(p, (char **)&p, 0);
7847
                    if (cyls < 1 || cyls > 16383)
7848
                        goto chs_fail;
7849
                    if (*p != ',')
7850
                        goto chs_fail;
7851
                    p++;
7852
                    heads = strtol(p, (char **)&p, 0);
7853
                    if (heads < 1 || heads > 16)
7854
                        goto chs_fail;
7855
                    if (*p != ',')
7856
                        goto chs_fail;
7857
                    p++;
7858
                    secs = strtol(p, (char **)&p, 0);
7859
                    if (secs < 1 || secs > 63)
7860
                        goto chs_fail;
7861
                    if (*p == ',') {
7862
                        p++;
7863
                        if (!strcmp(p, "none"))
7864
                            translation = BIOS_ATA_TRANSLATION_NONE;
7865
                        else if (!strcmp(p, "lba"))
7866
                            translation = BIOS_ATA_TRANSLATION_LBA;
7867
                        else if (!strcmp(p, "auto"))
7868
                            translation = BIOS_ATA_TRANSLATION_AUTO;
7869
                        else
7870
                            goto chs_fail;
7871
                    } else if (*p != '\0') {
7872
                    chs_fail:
7873
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
7874
                        exit(1);
7875
                    }
7876
                }
7877
                break;
7878
            case QEMU_OPTION_nographic:
7879
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7880
                pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7881
                pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7882
                nographic = 1;
7883
                break;
7884
            case QEMU_OPTION_portrait:
7885
                graphic_rotate = 1;
7886
                break;
7887
            case QEMU_OPTION_kernel:
7888
                kernel_filename = optarg;
7889
                break;
7890
            case QEMU_OPTION_append:
7891
                kernel_cmdline = optarg;
7892
                break;
7893
            case QEMU_OPTION_cdrom:
7894
                if (cdrom_index >= 0) {
7895
                    hd_filename[cdrom_index] = optarg;
7896
                }
7897
                break;
7898
            case QEMU_OPTION_boot:
7899
                boot_devices = optarg;
7900
                /* We just do some generic consistency checks */
7901
                {
7902
                    /* Could easily be extended to 64 devices if needed */
7903
                    const unsigned char *p;
7904
                    
7905
                    boot_devices_bitmap = 0;
7906
                    for (p = boot_devices; *p != '\0'; p++) {
7907
                        /* Allowed boot devices are:
7908
                         * a b     : floppy disk drives
7909
                         * c ... f : IDE disk drives
7910
                         * g ... m : machine implementation dependant drives
7911
                         * n ... p : network devices
7912
                         * It's up to each machine implementation to check
7913
                         * if the given boot devices match the actual hardware
7914
                         * implementation and firmware features.
7915
                         */
7916
                        if (*p < 'a' || *p > 'q') {
7917
                            fprintf(stderr, "Invalid boot device '%c'\n", *p);
7918
                            exit(1);
7919
                        }
7920
                        if (boot_devices_bitmap & (1 << (*p - 'a'))) {
7921
                            fprintf(stderr,
7922
                                    "Boot device '%c' was given twice\n",*p);
7923
                            exit(1);
7924
                        }
7925
                        boot_devices_bitmap |= 1 << (*p - 'a');
7926
                    }
7927
                }
7928
                break;
7929
            case QEMU_OPTION_fda:
7930
                fd_filename[0] = optarg;
7931
                break;
7932
            case QEMU_OPTION_fdb:
7933
                fd_filename[1] = optarg;
7934
                break;
7935
#ifdef TARGET_I386
7936
            case QEMU_OPTION_no_fd_bootchk:
7937
                fd_bootchk = 0;
7938
                break;
7939
#endif
7940
            case QEMU_OPTION_no_code_copy:
7941
                code_copy_enabled = 0;
7942
                break;
7943
            case QEMU_OPTION_net:
7944
                if (nb_net_clients >= MAX_NET_CLIENTS) {
7945
                    fprintf(stderr, "qemu: too many network clients\n");
7946
                    exit(1);
7947
                }
7948
                pstrcpy(net_clients[nb_net_clients],
7949
                        sizeof(net_clients[0]),
7950
                        optarg);
7951
                nb_net_clients++;
7952
                break;
7953
#ifdef CONFIG_SLIRP
7954
            case QEMU_OPTION_tftp:
7955
                tftp_prefix = optarg;
7956
                break;
7957
            case QEMU_OPTION_bootp:
7958
                bootp_filename = optarg;
7959
                break;
7960
#ifndef _WIN32
7961
            case QEMU_OPTION_smb:
7962
                net_slirp_smb(optarg);
7963
                break;
7964
#endif
7965
            case QEMU_OPTION_redir:
7966
                net_slirp_redir(optarg);
7967
                break;
7968
#endif
7969
#ifdef HAS_AUDIO
7970
            case QEMU_OPTION_audio_help:
7971
                AUD_help ();
7972
                exit (0);
7973
                break;
7974
            case QEMU_OPTION_soundhw:
7975
                select_soundhw (optarg);
7976
                break;
7977
#endif
7978
            case QEMU_OPTION_h:
7979
                help(0);
7980
                break;
7981
            case QEMU_OPTION_m:
7982
                ram_size = atoi(optarg) * 1024 * 1024;
7983
                if (ram_size <= 0)
7984
                    help(1);
7985
                if (ram_size > PHYS_RAM_MAX_SIZE) {
7986
                    fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7987
                            PHYS_RAM_MAX_SIZE / (1024 * 1024));
7988
                    exit(1);
7989
                }
7990
                break;
7991
            case QEMU_OPTION_d:
7992
                {
7993
                    int mask;
7994
                    CPULogItem *item;
7995

    
7996
                    mask = cpu_str_to_log_mask(optarg);
7997
                    if (!mask) {
7998
                        printf("Log items (comma separated):\n");
7999
                    for(item = cpu_log_items; item->mask != 0; item++) {
8000
                        printf("%-10s %s\n", item->name, item->help);
8001
                    }
8002
                    exit(1);
8003
                    }
8004
                    cpu_set_log(mask);
8005
                }
8006
                break;
8007
#ifdef CONFIG_GDBSTUB
8008
            case QEMU_OPTION_s:
8009
                use_gdbstub = 1;
8010
                break;
8011
            case QEMU_OPTION_p:
8012
                gdbstub_port = optarg;
8013
                break;
8014
#endif
8015
            case QEMU_OPTION_L:
8016
                bios_dir = optarg;
8017
                break;
8018
            case QEMU_OPTION_bios:
8019
                bios_name = optarg;
8020
                break;
8021
            case QEMU_OPTION_S:
8022
                autostart = 0;
8023
                break;
8024
            case QEMU_OPTION_k:
8025
                keyboard_layout = optarg;
8026
                break;
8027
            case QEMU_OPTION_localtime:
8028
                rtc_utc = 0;
8029
                break;
8030
            case QEMU_OPTION_cirrusvga:
8031
                cirrus_vga_enabled = 1;
8032
                vmsvga_enabled = 0;
8033
                break;
8034
            case QEMU_OPTION_vmsvga:
8035
                cirrus_vga_enabled = 0;
8036
                vmsvga_enabled = 1;
8037
                break;
8038
            case QEMU_OPTION_std_vga:
8039
                cirrus_vga_enabled = 0;
8040
                vmsvga_enabled = 0;
8041
                break;
8042
            case QEMU_OPTION_g:
8043
                {
8044
                    const char *p;
8045
                    int w, h, depth;
8046
                    p = optarg;
8047
                    w = strtol(p, (char **)&p, 10);
8048
                    if (w <= 0) {
8049
                    graphic_error:
8050
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
8051
                        exit(1);
8052
                    }
8053
                    if (*p != 'x')
8054
                        goto graphic_error;
8055
                    p++;
8056
                    h = strtol(p, (char **)&p, 10);
8057
                    if (h <= 0)
8058
                        goto graphic_error;
8059
                    if (*p == 'x') {
8060
                        p++;
8061
                        depth = strtol(p, (char **)&p, 10);
8062
                        if (depth != 8 && depth != 15 && depth != 16 &&
8063
                            depth != 24 && depth != 32)
8064
                            goto graphic_error;
8065
                    } else if (*p == '\0') {
8066
                        depth = graphic_depth;
8067
                    } else {
8068
                        goto graphic_error;
8069
                    }
8070

    
8071
                    graphic_width = w;
8072
                    graphic_height = h;
8073
                    graphic_depth = depth;
8074
                }
8075
                break;
8076
            case QEMU_OPTION_echr:
8077
                {
8078
                    char *r;
8079
                    term_escape_char = strtol(optarg, &r, 0);
8080
                    if (r == optarg)
8081
                        printf("Bad argument to echr\n");
8082
                    break;
8083
                }
8084
            case QEMU_OPTION_monitor:
8085
                pstrcpy(monitor_device, sizeof(monitor_device), optarg);
8086
                break;
8087
            case QEMU_OPTION_serial:
8088
                if (serial_device_index >= MAX_SERIAL_PORTS) {
8089
                    fprintf(stderr, "qemu: too many serial ports\n");
8090
                    exit(1);
8091
                }
8092
                pstrcpy(serial_devices[serial_device_index],
8093
                        sizeof(serial_devices[0]), optarg);
8094
                serial_device_index++;
8095
                break;
8096
            case QEMU_OPTION_parallel:
8097
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8098
                    fprintf(stderr, "qemu: too many parallel ports\n");
8099
                    exit(1);
8100
                }
8101
                pstrcpy(parallel_devices[parallel_device_index],
8102
                        sizeof(parallel_devices[0]), optarg);
8103
                parallel_device_index++;
8104
                break;
8105
            case QEMU_OPTION_loadvm:
8106
                loadvm = optarg;
8107
                break;
8108
            case QEMU_OPTION_full_screen:
8109
                full_screen = 1;
8110
                break;
8111
#ifdef CONFIG_SDL
8112
            case QEMU_OPTION_no_frame:
8113
                no_frame = 1;
8114
                break;
8115
            case QEMU_OPTION_alt_grab:
8116
                alt_grab = 1;
8117
                break;
8118
            case QEMU_OPTION_no_quit:
8119
                no_quit = 1;
8120
                break;
8121
#endif
8122
            case QEMU_OPTION_pidfile:
8123
                pid_file = optarg;
8124
                break;
8125
#ifdef TARGET_I386
8126
            case QEMU_OPTION_win2k_hack:
8127
                win2k_install_hack = 1;
8128
                break;
8129
#endif
8130
#ifdef USE_KQEMU
8131
            case QEMU_OPTION_no_kqemu:
8132
                kqemu_allowed = 0;
8133
                break;
8134
            case QEMU_OPTION_kernel_kqemu:
8135
                kqemu_allowed = 2;
8136
                break;
8137
#endif
8138
            case QEMU_OPTION_usb:
8139
                usb_enabled = 1;
8140
                break;
8141
            case QEMU_OPTION_usbdevice:
8142
                usb_enabled = 1;
8143
                if (usb_devices_index >= MAX_USB_CMDLINE) {
8144
                    fprintf(stderr, "Too many USB devices\n");
8145
                    exit(1);
8146
                }
8147
                pstrcpy(usb_devices[usb_devices_index],
8148
                        sizeof(usb_devices[usb_devices_index]),
8149
                        optarg);
8150
                usb_devices_index++;
8151
                break;
8152
            case QEMU_OPTION_smp:
8153
                smp_cpus = atoi(optarg);
8154
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8155
                    fprintf(stderr, "Invalid number of CPUs\n");
8156
                    exit(1);
8157
                }
8158
                break;
8159
            case QEMU_OPTION_vnc:
8160
                vnc_display = optarg;
8161
                break;
8162
            case QEMU_OPTION_no_acpi:
8163
                acpi_enabled = 0;
8164
                break;
8165
            case QEMU_OPTION_no_reboot:
8166
                no_reboot = 1;
8167
                break;
8168
            case QEMU_OPTION_show_cursor:
8169
                cursor_hide = 0;
8170
                break;
8171
            case QEMU_OPTION_daemonize:
8172
                daemonize = 1;
8173
                break;
8174
            case QEMU_OPTION_option_rom:
8175
                if (nb_option_roms >= MAX_OPTION_ROMS) {
8176
                    fprintf(stderr, "Too many option ROMs\n");
8177
                    exit(1);
8178
                }
8179
                option_rom[nb_option_roms] = optarg;
8180
                nb_option_roms++;
8181
                break;
8182
            case QEMU_OPTION_semihosting:
8183
                semihosting_enabled = 1;
8184
                break;
8185
            case QEMU_OPTION_name:
8186
                qemu_name = optarg;
8187
                break;
8188
#ifdef TARGET_SPARC
8189
            case QEMU_OPTION_prom_env:
8190
                if (nb_prom_envs >= MAX_PROM_ENVS) {
8191
                    fprintf(stderr, "Too many prom variables\n");
8192
                    exit(1);
8193
                }
8194
                prom_envs[nb_prom_envs] = optarg;
8195
                nb_prom_envs++;
8196
                break;
8197
#endif
8198
#ifdef TARGET_ARM
8199
            case QEMU_OPTION_old_param:
8200
                old_param = 1;
8201
#endif
8202
            case QEMU_OPTION_clock:
8203
                configure_alarms(optarg);
8204
                break;
8205
            case QEMU_OPTION_startdate:
8206
                {
8207
                    struct tm tm;
8208
                    if (!strcmp(optarg, "now")) {
8209
                        rtc_start_date = -1;
8210
                    } else {
8211
                        if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8212
                               &tm.tm_year,
8213
                               &tm.tm_mon,
8214
                               &tm.tm_mday,
8215
                               &tm.tm_hour,
8216
                               &tm.tm_min,
8217
                               &tm.tm_sec) == 6) {
8218
                            /* OK */
8219
                        } else if (sscanf(optarg, "%d-%d-%d",
8220
                                          &tm.tm_year,
8221
                                          &tm.tm_mon,
8222
                                          &tm.tm_mday) == 3) {
8223
                            tm.tm_hour = 0;
8224
                            tm.tm_min = 0;
8225
                            tm.tm_sec = 0;
8226
                        } else {
8227
                            goto date_fail;
8228
                        }
8229
                        tm.tm_year -= 1900;
8230
                        tm.tm_mon--;
8231
                        rtc_start_date = mktimegm(&tm);
8232
                        if (rtc_start_date == -1) {
8233
                        date_fail:
8234
                            fprintf(stderr, "Invalid date format. Valid format are:\n"
8235
                                    "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8236
                            exit(1);
8237
                        }
8238
                    }
8239
                }
8240
                break;
8241
            }
8242
        }
8243
    }
8244

    
8245
#ifndef _WIN32
8246
    if (daemonize && !nographic && vnc_display == NULL) {
8247
        fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8248
        daemonize = 0;
8249
    }
8250

    
8251
    if (daemonize) {
8252
        pid_t pid;
8253

    
8254
        if (pipe(fds) == -1)
8255
            exit(1);
8256

    
8257
        pid = fork();
8258
        if (pid > 0) {
8259
            uint8_t status;
8260
            ssize_t len;
8261

    
8262
            close(fds[1]);
8263

    
8264
        again:
8265
            len = read(fds[0], &status, 1);
8266
            if (len == -1 && (errno == EINTR))
8267
                goto again;
8268

    
8269
            if (len != 1)
8270
                exit(1);
8271
            else if (status == 1) {
8272
                fprintf(stderr, "Could not acquire pidfile\n");
8273
                exit(1);
8274
            } else
8275
                exit(0);
8276
        } else if (pid < 0)
8277
            exit(1);
8278

    
8279
        setsid();
8280

    
8281
        pid = fork();
8282
        if (pid > 0)
8283
            exit(0);
8284
        else if (pid < 0)
8285
            exit(1);
8286

    
8287
        umask(027);
8288
        chdir("/");
8289

    
8290
        signal(SIGTSTP, SIG_IGN);
8291
        signal(SIGTTOU, SIG_IGN);
8292
        signal(SIGTTIN, SIG_IGN);
8293
    }
8294
#endif
8295

    
8296
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8297
        if (daemonize) {
8298
            uint8_t status = 1;
8299
            write(fds[1], &status, 1);
8300
        } else
8301
            fprintf(stderr, "Could not acquire pid file\n");
8302
        exit(1);
8303
    }
8304

    
8305
#ifdef USE_KQEMU
8306
    if (smp_cpus > 1)
8307
        kqemu_allowed = 0;
8308
#endif
8309
    linux_boot = (kernel_filename != NULL);
8310
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8311

    
8312
    /* XXX: this should not be: some embedded targets just have flash */
8313
    if (!linux_boot && net_boot == 0 &&
8314
        hd_filename[0] == NULL &&
8315
        (cdrom_index >= 0 && hd_filename[cdrom_index] == NULL) &&
8316
        fd_filename[0] == NULL &&
8317
        pflash_filename[0] == NULL)
8318
        help(1);
8319

    
8320
    /* boot to floppy or the default cd if no hard disk defined yet */
8321
    if (!boot_devices[0]) {
8322
        if (hd_filename[0] != NULL)
8323
            boot_devices = "c";
8324
        else if (fd_filename[0] != NULL)
8325
            boot_devices = "a";
8326
        else
8327
            boot_devices = "d";
8328
    }
8329
    setvbuf(stdout, NULL, _IOLBF, 0);
8330

    
8331
    init_timers();
8332
    init_timer_alarm();
8333
    qemu_aio_init();
8334

    
8335
#ifdef _WIN32
8336
    socket_init();
8337
#endif
8338

    
8339
    /* init network clients */
8340
    if (nb_net_clients == 0) {
8341
        /* if no clients, we use a default config */
8342
        pstrcpy(net_clients[0], sizeof(net_clients[0]),
8343
                "nic");
8344
        pstrcpy(net_clients[1], sizeof(net_clients[0]),
8345
                "user");
8346
        nb_net_clients = 2;
8347
    }
8348

    
8349
    for(i = 0;i < nb_net_clients; i++) {
8350
        if (net_client_init(net_clients[i]) < 0)
8351
            exit(1);
8352
    }
8353
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8354
        if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8355
            continue;
8356
        if (vlan->nb_guest_devs == 0) {
8357
            fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8358
            exit(1);
8359
        }
8360
        if (vlan->nb_host_devs == 0)
8361
            fprintf(stderr,
8362
                    "Warning: vlan %d is not connected to host network\n",
8363
                    vlan->id);
8364
    }
8365

    
8366
#ifdef TARGET_I386
8367
    /* XXX: this should be moved in the PC machine instanciation code */
8368
    if (net_boot != 0) {
8369
        int netroms = 0;
8370
        for (i = 0; i < nb_nics && i < 4; i++) {
8371
            const char *model = nd_table[i].model;
8372
            char buf[1024];
8373
            if (net_boot & (1 << i)) {
8374
                if (model == NULL)
8375
                    model = "ne2k_pci";
8376
                snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8377
                if (get_image_size(buf) > 0) {
8378
                    if (nb_option_roms >= MAX_OPTION_ROMS) {
8379
                        fprintf(stderr, "Too many option ROMs\n");
8380
                        exit(1);
8381
                    }
8382
                    option_rom[nb_option_roms] = strdup(buf);
8383
                    nb_option_roms++;
8384
                    netroms++;
8385
                }
8386
            }
8387
        }
8388
        if (netroms == 0) {
8389
            fprintf(stderr, "No valid PXE rom found for network device\n");
8390
            exit(1);
8391
        }
8392
    }
8393
#endif
8394

    
8395
    /* init the memory */
8396
    phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
8397

    
8398
    phys_ram_base = qemu_vmalloc(phys_ram_size);
8399
    if (!phys_ram_base) {
8400
        fprintf(stderr, "Could not allocate physical memory\n");
8401
        exit(1);
8402
    }
8403

    
8404
    /* we always create the cdrom drive, even if no disk is there */
8405
    bdrv_init();
8406
    if (cdrom_index >= 0) {
8407
        bs_table[cdrom_index] = bdrv_new("cdrom");
8408
        bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
8409
    }
8410

    
8411
    /* open the virtual block devices */
8412
    for(i = 0; i < MAX_DISKS; i++) {
8413
        if (hd_filename[i]) {
8414
            if (!bs_table[i]) {
8415
                char buf[64];
8416
                snprintf(buf, sizeof(buf), "hd%c", i + 'a');
8417
                bs_table[i] = bdrv_new(buf);
8418
            }
8419
            if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8420
                fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
8421
                        hd_filename[i]);
8422
                exit(1);
8423
            }
8424
            if (i == 0 && cyls != 0) {
8425
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
8426
                bdrv_set_translation_hint(bs_table[i], translation);
8427
            }
8428
        }
8429
    }
8430

    
8431
    /* we always create at least one floppy disk */
8432
    fd_table[0] = bdrv_new("fda");
8433
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
8434

    
8435
    for(i = 0; i < MAX_FD; i++) {
8436
        if (fd_filename[i]) {
8437
            if (!fd_table[i]) {
8438
                char buf[64];
8439
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
8440
                fd_table[i] = bdrv_new(buf);
8441
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
8442
            }
8443
            if (fd_filename[i][0] != '\0') {
8444
                if (bdrv_open(fd_table[i], fd_filename[i],
8445
                              snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8446
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
8447
                            fd_filename[i]);
8448
                    exit(1);
8449
                }
8450
            }
8451
        }
8452
    }
8453

    
8454
    /* Open the virtual parallel flash block devices */
8455
    for(i = 0; i < MAX_PFLASH; i++) {
8456
        if (pflash_filename[i]) {
8457
            if (!pflash_table[i]) {
8458
                char buf[64];
8459
                snprintf(buf, sizeof(buf), "fl%c", i + 'a');
8460
                pflash_table[i] = bdrv_new(buf);
8461
            }
8462
            if (bdrv_open(pflash_table[i], pflash_filename[i],
8463
                          snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8464
                fprintf(stderr, "qemu: could not open flash image '%s'\n",
8465
                        pflash_filename[i]);
8466
                exit(1);
8467
            }
8468
        }
8469
    }
8470

    
8471
    sd_bdrv = bdrv_new ("sd");
8472
    /* FIXME: This isn't really a floppy, but it's a reasonable
8473
       approximation.  */
8474
    bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
8475
    if (sd_filename) {
8476
        if (bdrv_open(sd_bdrv, sd_filename,
8477
                      snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
8478
            fprintf(stderr, "qemu: could not open SD card image %s\n",
8479
                    sd_filename);
8480
        } else
8481
            qemu_key_check(sd_bdrv, sd_filename);
8482
    }
8483

    
8484
    if (mtd_filename) {
8485
        mtd_bdrv = bdrv_new ("mtd");
8486
        if (bdrv_open(mtd_bdrv, mtd_filename,
8487
                      snapshot ? BDRV_O_SNAPSHOT : 0) < 0 ||
8488
            qemu_key_check(mtd_bdrv, mtd_filename)) {
8489
            fprintf(stderr, "qemu: could not open Flash image %s\n",
8490
                    mtd_filename);
8491
            bdrv_delete(mtd_bdrv);
8492
            mtd_bdrv = 0;
8493
        }
8494
    }
8495

    
8496
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8497
    register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8498

    
8499
    init_ioports();
8500

    
8501
    /* terminal init */
8502
    memset(&display_state, 0, sizeof(display_state));
8503
    if (nographic) {
8504
        /* nearly nothing to do */
8505
        dumb_display_init(ds);
8506
    } else if (vnc_display != NULL) {
8507
        vnc_display_init(ds);
8508
        if (vnc_display_open(ds, vnc_display) < 0)
8509
            exit(1);
8510
    } else {
8511
#if defined(CONFIG_SDL)
8512
        sdl_display_init(ds, full_screen, no_frame);
8513
#elif defined(CONFIG_COCOA)
8514
        cocoa_display_init(ds, full_screen);
8515
#else
8516
        dumb_display_init(ds);
8517
#endif
8518
    }
8519

    
8520
    /* Maintain compatibility with multiple stdio monitors */
8521
    if (!strcmp(monitor_device,"stdio")) {
8522
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8523
            if (!strcmp(serial_devices[i],"mon:stdio")) {
8524
                monitor_device[0] = '\0';
8525
                break;
8526
            } else if (!strcmp(serial_devices[i],"stdio")) {
8527
                monitor_device[0] = '\0';
8528
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
8529
                break;
8530
            }
8531
        }
8532
    }
8533
    if (monitor_device[0] != '\0') {
8534
        monitor_hd = qemu_chr_open(monitor_device);
8535
        if (!monitor_hd) {
8536
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8537
            exit(1);
8538
        }
8539
        monitor_init(monitor_hd, !nographic);
8540
    }
8541

    
8542
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8543
        const char *devname = serial_devices[i];
8544
        if (devname[0] != '\0' && strcmp(devname, "none")) {
8545
            serial_hds[i] = qemu_chr_open(devname);
8546
            if (!serial_hds[i]) {
8547
                fprintf(stderr, "qemu: could not open serial device '%s'\n",
8548
                        devname);
8549
                exit(1);
8550
            }
8551
            if (strstart(devname, "vc", 0))
8552
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8553
        }
8554
    }
8555

    
8556
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8557
        const char *devname = parallel_devices[i];
8558
        if (devname[0] != '\0' && strcmp(devname, "none")) {
8559
            parallel_hds[i] = qemu_chr_open(devname);
8560
            if (!parallel_hds[i]) {
8561
                fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8562
                        devname);
8563
                exit(1);
8564
            }
8565
            if (strstart(devname, "vc", 0))
8566
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8567
        }
8568
    }
8569

    
8570
    machine->init(ram_size, vga_ram_size, boot_devices, ds,
8571
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8572

    
8573
    /* init USB devices */
8574
    if (usb_enabled) {
8575
        for(i = 0; i < usb_devices_index; i++) {
8576
            if (usb_device_add(usb_devices[i]) < 0) {
8577
                fprintf(stderr, "Warning: could not add USB device %s\n",
8578
                        usb_devices[i]);
8579
            }
8580
        }
8581
    }
8582

    
8583
    if (display_state.dpy_refresh) {
8584
        display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8585
        qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8586
    }
8587

    
8588
#ifdef CONFIG_GDBSTUB
8589
    if (use_gdbstub) {
8590
        /* XXX: use standard host:port notation and modify options
8591
           accordingly. */
8592
        if (gdbserver_start(gdbstub_port) < 0) {
8593
            fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8594
                    gdbstub_port);
8595
            exit(1);
8596
        }
8597
    }
8598
#endif
8599

    
8600
    if (loadvm)
8601
        do_loadvm(loadvm);
8602

    
8603
    {
8604
        /* XXX: simplify init */
8605
        read_passwords();
8606
        if (autostart) {
8607
            vm_start();
8608
        }
8609
    }
8610

    
8611
    if (daemonize) {
8612
        uint8_t status = 0;
8613
        ssize_t len;
8614
        int fd;
8615

    
8616
    again1:
8617
        len = write(fds[1], &status, 1);
8618
        if (len == -1 && (errno == EINTR))
8619
            goto again1;
8620

    
8621
        if (len != 1)
8622
            exit(1);
8623

    
8624
        TFR(fd = open("/dev/null", O_RDWR));
8625
        if (fd == -1)
8626
            exit(1);
8627

    
8628
        dup2(fd, 0);
8629
        dup2(fd, 1);
8630
        dup2(fd, 2);
8631

    
8632
        close(fd);
8633
    }
8634

    
8635
    main_loop();
8636
    quit_timers();
8637

    
8638
#if !defined(_WIN32)
8639
    /* close network clients */
8640
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8641
        VLANClientState *vc;
8642

    
8643
        for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
8644
            if (vc->fd_read == tap_receive) {
8645
                char ifname[64];
8646
                TAPState *s = vc->opaque;
8647

    
8648
                if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
8649
                    s->down_script[0])
8650
                    launch_script(s->down_script, ifname, s->fd);
8651
            }
8652
    }
8653
    }
8654
#endif
8655
    return 0;
8656
}