Statistics
| Branch: | Revision:

root / vl.c @ 18fdb1c5

History | View | Annotate | Download (230.8 kB)

1
/*
2
 * QEMU System Emulator
3
 *
4
 * Copyright (c) 2003-2008 Fabrice Bellard
5
 *
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in
14
 * all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
 * THE SOFTWARE.
23
 */
24
#include "hw/hw.h"
25
#include "hw/boards.h"
26
#include "hw/usb.h"
27
#include "hw/pcmcia.h"
28
#include "hw/pc.h"
29
#include "hw/audiodev.h"
30
#include "hw/isa.h"
31
#include "hw/baum.h"
32
#include "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 <mmsystem.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
#ifdef TARGET_PPC
146
#define DEFAULT_RAM_SIZE 144
147
#else
148
#define DEFAULT_RAM_SIZE 128
149
#endif
150
/* in ms */
151
#define GUI_REFRESH_INTERVAL 30
152

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

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

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

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

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

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

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

    
259
static uint32_t default_ioport_readb(void *opaque, uint32_t address)
260
{
261
#ifdef DEBUG_UNUSED_IOPORT
262
    fprintf(stderr, "unused inb: port=0x%04x\n", address);
263
#endif
264
    return 0xff;
265
}
266

    
267
static void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
268
{
269
#ifdef DEBUG_UNUSED_IOPORT
270
    fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
271
#endif
272
}
273

    
274
/* default is to make two byte accesses */
275
static uint32_t default_ioport_readw(void *opaque, uint32_t address)
276
{
277
    uint32_t data;
278
    data = ioport_read_table[0][address](ioport_opaque[address], address);
279
    address = (address + 1) & (MAX_IOPORTS - 1);
280
    data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
281
    return data;
282
}
283

    
284
static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
285
{
286
    ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
287
    address = (address + 1) & (MAX_IOPORTS - 1);
288
    ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
289
}
290

    
291
static uint32_t default_ioport_readl(void *opaque, uint32_t address)
292
{
293
#ifdef DEBUG_UNUSED_IOPORT
294
    fprintf(stderr, "unused inl: port=0x%04x\n", address);
295
#endif
296
    return 0xffffffff;
297
}
298

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

    
306
static void init_ioports(void)
307
{
308
    int i;
309

    
310
    for(i = 0; i < MAX_IOPORTS; i++) {
311
        ioport_read_table[0][i] = default_ioport_readb;
312
        ioport_write_table[0][i] = default_ioport_writeb;
313
        ioport_read_table[1][i] = default_ioport_readw;
314
        ioport_write_table[1][i] = default_ioport_writew;
315
        ioport_read_table[2][i] = default_ioport_readl;
316
        ioport_write_table[2][i] = default_ioport_writel;
317
    }
318
}
319

    
320
/* size is the word size in byte */
321
int register_ioport_read(int start, int length, int size,
322
                         IOPortReadFunc *func, void *opaque)
323
{
324
    int i, bsize;
325

    
326
    if (size == 1) {
327
        bsize = 0;
328
    } else if (size == 2) {
329
        bsize = 1;
330
    } else if (size == 4) {
331
        bsize = 2;
332
    } else {
333
        hw_error("register_ioport_read: invalid size");
334
        return -1;
335
    }
336
    for(i = start; i < start + length; i += size) {
337
        ioport_read_table[bsize][i] = func;
338
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
339
            hw_error("register_ioport_read: invalid opaque");
340
        ioport_opaque[i] = opaque;
341
    }
342
    return 0;
343
}
344

    
345
/* size is the word size in byte */
346
int register_ioport_write(int start, int length, int size,
347
                          IOPortWriteFunc *func, void *opaque)
348
{
349
    int i, bsize;
350

    
351
    if (size == 1) {
352
        bsize = 0;
353
    } else if (size == 2) {
354
        bsize = 1;
355
    } else if (size == 4) {
356
        bsize = 2;
357
    } else {
358
        hw_error("register_ioport_write: invalid size");
359
        return -1;
360
    }
361
    for(i = start; i < start + length; i += size) {
362
        ioport_write_table[bsize][i] = func;
363
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
364
            hw_error("register_ioport_write: invalid opaque");
365
        ioport_opaque[i] = opaque;
366
    }
367
    return 0;
368
}
369

    
370
void isa_unassign_ioport(int start, int length)
371
{
372
    int i;
373

    
374
    for(i = start; i < start + length; i++) {
375
        ioport_read_table[0][i] = default_ioport_readb;
376
        ioport_read_table[1][i] = default_ioport_readw;
377
        ioport_read_table[2][i] = default_ioport_readl;
378

    
379
        ioport_write_table[0][i] = default_ioport_writeb;
380
        ioport_write_table[1][i] = default_ioport_writew;
381
        ioport_write_table[2][i] = default_ioport_writel;
382
    }
383
}
384

    
385
/***********************************************************/
386

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

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

    
413
void cpu_outl(CPUState *env, int addr, int val)
414
{
415
#ifdef DEBUG_IOPORT
416
    if (loglevel & CPU_LOG_IOPORT)
417
        fprintf(logfile, "outl: %04x %08x\n", addr, val);
418
#endif
419
    ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
420
#ifdef USE_KQEMU
421
    if (env)
422
        env->last_io_time = cpu_get_time_fast();
423
#endif
424
}
425

    
426
int cpu_inb(CPUState *env, int addr)
427
{
428
    int val;
429
    val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
430
#ifdef DEBUG_IOPORT
431
    if (loglevel & CPU_LOG_IOPORT)
432
        fprintf(logfile, "inb : %04x %02x\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_inw(CPUState *env, int addr)
442
{
443
    int val;
444
    val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
445
#ifdef DEBUG_IOPORT
446
    if (loglevel & CPU_LOG_IOPORT)
447
        fprintf(logfile, "inw : %04x %04x\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
int cpu_inl(CPUState *env, int addr)
457
{
458
    int val;
459
    val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
460
#ifdef DEBUG_IOPORT
461
    if (loglevel & CPU_LOG_IOPORT)
462
        fprintf(logfile, "inl : %04x %08x\n", addr, val);
463
#endif
464
#ifdef USE_KQEMU
465
    if (env)
466
        env->last_io_time = cpu_get_time_fast();
467
#endif
468
    return val;
469
}
470

    
471
/***********************************************************/
472
void hw_error(const char *fmt, ...)
473
{
474
    va_list ap;
475
    CPUState *env;
476

    
477
    va_start(ap, fmt);
478
    fprintf(stderr, "qemu: hardware error: ");
479
    vfprintf(stderr, fmt, ap);
480
    fprintf(stderr, "\n");
481
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
482
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
483
#ifdef TARGET_I386
484
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
485
#else
486
        cpu_dump_state(env, stderr, fprintf, 0);
487
#endif
488
    }
489
    va_end(ap);
490
    abort();
491
}
492

    
493
/***********************************************************/
494
/* keyboard/mouse */
495

    
496
static QEMUPutKBDEvent *qemu_put_kbd_event;
497
static void *qemu_put_kbd_event_opaque;
498
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
499
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
500

    
501
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
502
{
503
    qemu_put_kbd_event_opaque = opaque;
504
    qemu_put_kbd_event = func;
505
}
506

    
507
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
508
                                                void *opaque, int absolute,
509
                                                const char *name)
510
{
511
    QEMUPutMouseEntry *s, *cursor;
512

    
513
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
514
    if (!s)
515
        return NULL;
516

    
517
    s->qemu_put_mouse_event = func;
518
    s->qemu_put_mouse_event_opaque = opaque;
519
    s->qemu_put_mouse_event_absolute = absolute;
520
    s->qemu_put_mouse_event_name = qemu_strdup(name);
521
    s->next = NULL;
522

    
523
    if (!qemu_put_mouse_event_head) {
524
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
525
        return s;
526
    }
527

    
528
    cursor = qemu_put_mouse_event_head;
529
    while (cursor->next != NULL)
530
        cursor = cursor->next;
531

    
532
    cursor->next = s;
533
    qemu_put_mouse_event_current = s;
534

    
535
    return s;
536
}
537

    
538
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
539
{
540
    QEMUPutMouseEntry *prev = NULL, *cursor;
541

    
542
    if (!qemu_put_mouse_event_head || entry == NULL)
543
        return;
544

    
545
    cursor = qemu_put_mouse_event_head;
546
    while (cursor != NULL && cursor != entry) {
547
        prev = cursor;
548
        cursor = cursor->next;
549
    }
550

    
551
    if (cursor == NULL) // does not exist or list empty
552
        return;
553
    else if (prev == NULL) { // entry is head
554
        qemu_put_mouse_event_head = cursor->next;
555
        if (qemu_put_mouse_event_current == entry)
556
            qemu_put_mouse_event_current = cursor->next;
557
        qemu_free(entry->qemu_put_mouse_event_name);
558
        qemu_free(entry);
559
        return;
560
    }
561

    
562
    prev->next = entry->next;
563

    
564
    if (qemu_put_mouse_event_current == entry)
565
        qemu_put_mouse_event_current = prev;
566

    
567
    qemu_free(entry->qemu_put_mouse_event_name);
568
    qemu_free(entry);
569
}
570

    
571
void kbd_put_keycode(int keycode)
572
{
573
    if (qemu_put_kbd_event) {
574
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
575
    }
576
}
577

    
578
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
579
{
580
    QEMUPutMouseEvent *mouse_event;
581
    void *mouse_event_opaque;
582
    int width;
583

    
584
    if (!qemu_put_mouse_event_current) {
585
        return;
586
    }
587

    
588
    mouse_event =
589
        qemu_put_mouse_event_current->qemu_put_mouse_event;
590
    mouse_event_opaque =
591
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
592

    
593
    if (mouse_event) {
594
        if (graphic_rotate) {
595
            if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
596
                width = 0x7fff;
597
            else
598
                width = graphic_width - 1;
599
            mouse_event(mouse_event_opaque,
600
                                 width - dy, dx, dz, buttons_state);
601
        } else
602
            mouse_event(mouse_event_opaque,
603
                                 dx, dy, dz, buttons_state);
604
    }
605
}
606

    
607
int kbd_mouse_is_absolute(void)
608
{
609
    if (!qemu_put_mouse_event_current)
610
        return 0;
611

    
612
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
613
}
614

    
615
void do_info_mice(void)
616
{
617
    QEMUPutMouseEntry *cursor;
618
    int index = 0;
619

    
620
    if (!qemu_put_mouse_event_head) {
621
        term_printf("No mouse devices connected\n");
622
        return;
623
    }
624

    
625
    term_printf("Mouse devices available:\n");
626
    cursor = qemu_put_mouse_event_head;
627
    while (cursor != NULL) {
628
        term_printf("%c Mouse #%d: %s\n",
629
                    (cursor == qemu_put_mouse_event_current ? '*' : ' '),
630
                    index, cursor->qemu_put_mouse_event_name);
631
        index++;
632
        cursor = cursor->next;
633
    }
634
}
635

    
636
void do_mouse_set(int index)
637
{
638
    QEMUPutMouseEntry *cursor;
639
    int i = 0;
640

    
641
    if (!qemu_put_mouse_event_head) {
642
        term_printf("No mouse devices connected\n");
643
        return;
644
    }
645

    
646
    cursor = qemu_put_mouse_event_head;
647
    while (cursor != NULL && index != i) {
648
        i++;
649
        cursor = cursor->next;
650
    }
651

    
652
    if (cursor != NULL)
653
        qemu_put_mouse_event_current = cursor;
654
    else
655
        term_printf("Mouse at given index not found\n");
656
}
657

    
658
/* compute with 96 bit intermediate result: (a*b)/c */
659
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
660
{
661
    union {
662
        uint64_t ll;
663
        struct {
664
#ifdef WORDS_BIGENDIAN
665
            uint32_t high, low;
666
#else
667
            uint32_t low, high;
668
#endif
669
        } l;
670
    } u, res;
671
    uint64_t rl, rh;
672

    
673
    u.ll = a;
674
    rl = (uint64_t)u.l.low * (uint64_t)b;
675
    rh = (uint64_t)u.l.high * (uint64_t)b;
676
    rh += (rl >> 32);
677
    res.l.high = rh / c;
678
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
679
    return res.ll;
680
}
681

    
682
/***********************************************************/
683
/* real time host monotonic timer */
684

    
685
#define QEMU_TIMER_BASE 1000000000LL
686

    
687
#ifdef WIN32
688

    
689
static int64_t clock_freq;
690

    
691
static void init_get_clock(void)
692
{
693
    LARGE_INTEGER freq;
694
    int ret;
695
    ret = QueryPerformanceFrequency(&freq);
696
    if (ret == 0) {
697
        fprintf(stderr, "Could not calibrate ticks\n");
698
        exit(1);
699
    }
700
    clock_freq = freq.QuadPart;
701
}
702

    
703
static int64_t get_clock(void)
704
{
705
    LARGE_INTEGER ti;
706
    QueryPerformanceCounter(&ti);
707
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
708
}
709

    
710
#else
711

    
712
static int use_rt_clock;
713

    
714
static void init_get_clock(void)
715
{
716
    use_rt_clock = 0;
717
#if defined(__linux__)
718
    {
719
        struct timespec ts;
720
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
721
            use_rt_clock = 1;
722
        }
723
    }
724
#endif
725
}
726

    
727
static int64_t get_clock(void)
728
{
729
#if defined(__linux__)
730
    if (use_rt_clock) {
731
        struct timespec ts;
732
        clock_gettime(CLOCK_MONOTONIC, &ts);
733
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
734
    } else
735
#endif
736
    {
737
        /* XXX: using gettimeofday leads to problems if the date
738
           changes, so it should be avoided. */
739
        struct timeval tv;
740
        gettimeofday(&tv, NULL);
741
        return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
742
    }
743
}
744
#endif
745

    
746
/* Return the virtual CPU time, based on the instruction counter.  */
747
static int64_t cpu_get_icount(void)
748
{
749
    int64_t icount;
750
    CPUState *env = cpu_single_env;;
751
    icount = qemu_icount;
752
    if (env) {
753
        if (!can_do_io(env))
754
            fprintf(stderr, "Bad clock read\n");
755
        icount -= (env->icount_decr.u16.low + env->icount_extra);
756
    }
757
    return qemu_icount_bias + (icount << icount_time_shift);
758
}
759

    
760
/***********************************************************/
761
/* guest cycle counter */
762

    
763
static int64_t cpu_ticks_prev;
764
static int64_t cpu_ticks_offset;
765
static int64_t cpu_clock_offset;
766
static int cpu_ticks_enabled;
767

    
768
/* return the host CPU cycle counter and handle stop/restart */
769
int64_t cpu_get_ticks(void)
770
{
771
    if (use_icount) {
772
        return cpu_get_icount();
773
    }
774
    if (!cpu_ticks_enabled) {
775
        return cpu_ticks_offset;
776
    } else {
777
        int64_t ticks;
778
        ticks = cpu_get_real_ticks();
779
        if (cpu_ticks_prev > ticks) {
780
            /* Note: non increasing ticks may happen if the host uses
781
               software suspend */
782
            cpu_ticks_offset += cpu_ticks_prev - ticks;
783
        }
784
        cpu_ticks_prev = ticks;
785
        return ticks + cpu_ticks_offset;
786
    }
787
}
788

    
789
/* return the host CPU monotonic timer and handle stop/restart */
790
static int64_t cpu_get_clock(void)
791
{
792
    int64_t ti;
793
    if (!cpu_ticks_enabled) {
794
        return cpu_clock_offset;
795
    } else {
796
        ti = get_clock();
797
        return ti + cpu_clock_offset;
798
    }
799
}
800

    
801
/* enable cpu_get_ticks() */
802
void cpu_enable_ticks(void)
803
{
804
    if (!cpu_ticks_enabled) {
805
        cpu_ticks_offset -= cpu_get_real_ticks();
806
        cpu_clock_offset -= get_clock();
807
        cpu_ticks_enabled = 1;
808
    }
809
}
810

    
811
/* disable cpu_get_ticks() : the clock is stopped. You must not call
812
   cpu_get_ticks() after that.  */
813
void cpu_disable_ticks(void)
814
{
815
    if (cpu_ticks_enabled) {
816
        cpu_ticks_offset = cpu_get_ticks();
817
        cpu_clock_offset = cpu_get_clock();
818
        cpu_ticks_enabled = 0;
819
    }
820
}
821

    
822
/***********************************************************/
823
/* timers */
824

    
825
#define QEMU_TIMER_REALTIME 0
826
#define QEMU_TIMER_VIRTUAL  1
827

    
828
struct QEMUClock {
829
    int type;
830
    /* XXX: add frequency */
831
};
832

    
833
struct QEMUTimer {
834
    QEMUClock *clock;
835
    int64_t expire_time;
836
    QEMUTimerCB *cb;
837
    void *opaque;
838
    struct QEMUTimer *next;
839
};
840

    
841
struct qemu_alarm_timer {
842
    char const *name;
843
    unsigned int flags;
844

    
845
    int (*start)(struct qemu_alarm_timer *t);
846
    void (*stop)(struct qemu_alarm_timer *t);
847
    void (*rearm)(struct qemu_alarm_timer *t);
848
    void *priv;
849
};
850

    
851
#define ALARM_FLAG_DYNTICKS  0x1
852
#define ALARM_FLAG_EXPIRED   0x2
853

    
854
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
855
{
856
    return t->flags & ALARM_FLAG_DYNTICKS;
857
}
858

    
859
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
860
{
861
    if (!alarm_has_dynticks(t))
862
        return;
863

    
864
    t->rearm(t);
865
}
866

    
867
/* TODO: MIN_TIMER_REARM_US should be optimized */
868
#define MIN_TIMER_REARM_US 250
869

    
870
static struct qemu_alarm_timer *alarm_timer;
871

    
872
#ifdef _WIN32
873

    
874
struct qemu_alarm_win32 {
875
    MMRESULT timerId;
876
    HANDLE host_alarm;
877
    unsigned int period;
878
} alarm_win32_data = {0, NULL, -1};
879

    
880
static int win32_start_timer(struct qemu_alarm_timer *t);
881
static void win32_stop_timer(struct qemu_alarm_timer *t);
882
static void win32_rearm_timer(struct qemu_alarm_timer *t);
883

    
884
#else
885

    
886
static int unix_start_timer(struct qemu_alarm_timer *t);
887
static void unix_stop_timer(struct qemu_alarm_timer *t);
888

    
889
#ifdef __linux__
890

    
891
static int dynticks_start_timer(struct qemu_alarm_timer *t);
892
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
893
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
894

    
895
static int hpet_start_timer(struct qemu_alarm_timer *t);
896
static void hpet_stop_timer(struct qemu_alarm_timer *t);
897

    
898
static int rtc_start_timer(struct qemu_alarm_timer *t);
899
static void rtc_stop_timer(struct qemu_alarm_timer *t);
900

    
901
#endif /* __linux__ */
902

    
903
#endif /* _WIN32 */
904

    
905
/* Correlation between real and virtual time is always going to be
906
   fairly approximate, so ignore small variation.
907
   When the guest is idle real and virtual time will be aligned in
908
   the IO wait loop.  */
909
#define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
910

    
911
static void icount_adjust(void)
912
{
913
    int64_t cur_time;
914
    int64_t cur_icount;
915
    int64_t delta;
916
    static int64_t last_delta;
917
    /* If the VM is not running, then do nothing.  */
918
    if (!vm_running)
919
        return;
920

    
921
    cur_time = cpu_get_clock();
922
    cur_icount = qemu_get_clock(vm_clock);
923
    delta = cur_icount - cur_time;
924
    /* FIXME: This is a very crude algorithm, somewhat prone to oscillation.  */
925
    if (delta > 0
926
        && last_delta + ICOUNT_WOBBLE < delta * 2
927
        && icount_time_shift > 0) {
928
        /* The guest is getting too far ahead.  Slow time down.  */
929
        icount_time_shift--;
930
    }
931
    if (delta < 0
932
        && last_delta - ICOUNT_WOBBLE > delta * 2
933
        && icount_time_shift < MAX_ICOUNT_SHIFT) {
934
        /* The guest is getting too far behind.  Speed time up.  */
935
        icount_time_shift++;
936
    }
937
    last_delta = delta;
938
    qemu_icount_bias = cur_icount - (qemu_icount << icount_time_shift);
939
}
940

    
941
static void icount_adjust_rt(void * opaque)
942
{
943
    qemu_mod_timer(icount_rt_timer,
944
                   qemu_get_clock(rt_clock) + 1000);
945
    icount_adjust();
946
}
947

    
948
static void icount_adjust_vm(void * opaque)
949
{
950
    qemu_mod_timer(icount_vm_timer,
951
                   qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
952
    icount_adjust();
953
}
954

    
955
static void init_icount_adjust(void)
956
{
957
    /* Have both realtime and virtual time triggers for speed adjustment.
958
       The realtime trigger catches emulated time passing too slowly,
959
       the virtual time trigger catches emulated time passing too fast.
960
       Realtime triggers occur even when idle, so use them less frequently
961
       than VM triggers.  */
962
    icount_rt_timer = qemu_new_timer(rt_clock, icount_adjust_rt, NULL);
963
    qemu_mod_timer(icount_rt_timer,
964
                   qemu_get_clock(rt_clock) + 1000);
965
    icount_vm_timer = qemu_new_timer(vm_clock, icount_adjust_vm, NULL);
966
    qemu_mod_timer(icount_vm_timer,
967
                   qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
968
}
969

    
970
static struct qemu_alarm_timer alarm_timers[] = {
971
#ifndef _WIN32
972
#ifdef __linux__
973
    {"dynticks", ALARM_FLAG_DYNTICKS, dynticks_start_timer,
974
     dynticks_stop_timer, dynticks_rearm_timer, NULL},
975
    /* HPET - if available - is preferred */
976
    {"hpet", 0, hpet_start_timer, hpet_stop_timer, NULL, NULL},
977
    /* ...otherwise try RTC */
978
    {"rtc", 0, rtc_start_timer, rtc_stop_timer, NULL, NULL},
979
#endif
980
    {"unix", 0, unix_start_timer, unix_stop_timer, NULL, NULL},
981
#else
982
    {"dynticks", ALARM_FLAG_DYNTICKS, win32_start_timer,
983
     win32_stop_timer, win32_rearm_timer, &alarm_win32_data},
984
    {"win32", 0, win32_start_timer,
985
     win32_stop_timer, NULL, &alarm_win32_data},
986
#endif
987
    {NULL, }
988
};
989

    
990
static void show_available_alarms(void)
991
{
992
    int i;
993

    
994
    printf("Available alarm timers, in order of precedence:\n");
995
    for (i = 0; alarm_timers[i].name; i++)
996
        printf("%s\n", alarm_timers[i].name);
997
}
998

    
999
static void configure_alarms(char const *opt)
1000
{
1001
    int i;
1002
    int cur = 0;
1003
    int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1004
    char *arg;
1005
    char *name;
1006
    struct qemu_alarm_timer tmp;
1007

    
1008
    if (!strcmp(opt, "?")) {
1009
        show_available_alarms();
1010
        exit(0);
1011
    }
1012

    
1013
    arg = strdup(opt);
1014

    
1015
    /* Reorder the array */
1016
    name = strtok(arg, ",");
1017
    while (name) {
1018
        for (i = 0; i < count && alarm_timers[i].name; i++) {
1019
            if (!strcmp(alarm_timers[i].name, name))
1020
                break;
1021
        }
1022

    
1023
        if (i == count) {
1024
            fprintf(stderr, "Unknown clock %s\n", name);
1025
            goto next;
1026
        }
1027

    
1028
        if (i < cur)
1029
            /* Ignore */
1030
            goto next;
1031

    
1032
        /* Swap */
1033
        tmp = alarm_timers[i];
1034
        alarm_timers[i] = alarm_timers[cur];
1035
        alarm_timers[cur] = tmp;
1036

    
1037
        cur++;
1038
next:
1039
        name = strtok(NULL, ",");
1040
    }
1041

    
1042
    free(arg);
1043

    
1044
    if (cur) {
1045
        /* Disable remaining timers */
1046
        for (i = cur; i < count; i++)
1047
            alarm_timers[i].name = NULL;
1048
    } else {
1049
        show_available_alarms();
1050
        exit(1);
1051
    }
1052
}
1053

    
1054
QEMUClock *rt_clock;
1055
QEMUClock *vm_clock;
1056

    
1057
static QEMUTimer *active_timers[2];
1058

    
1059
static QEMUClock *qemu_new_clock(int type)
1060
{
1061
    QEMUClock *clock;
1062
    clock = qemu_mallocz(sizeof(QEMUClock));
1063
    if (!clock)
1064
        return NULL;
1065
    clock->type = type;
1066
    return clock;
1067
}
1068

    
1069
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1070
{
1071
    QEMUTimer *ts;
1072

    
1073
    ts = qemu_mallocz(sizeof(QEMUTimer));
1074
    ts->clock = clock;
1075
    ts->cb = cb;
1076
    ts->opaque = opaque;
1077
    return ts;
1078
}
1079

    
1080
void qemu_free_timer(QEMUTimer *ts)
1081
{
1082
    qemu_free(ts);
1083
}
1084

    
1085
/* stop a timer, but do not dealloc it */
1086
void qemu_del_timer(QEMUTimer *ts)
1087
{
1088
    QEMUTimer **pt, *t;
1089

    
1090
    /* NOTE: this code must be signal safe because
1091
       qemu_timer_expired() can be called from a signal. */
1092
    pt = &active_timers[ts->clock->type];
1093
    for(;;) {
1094
        t = *pt;
1095
        if (!t)
1096
            break;
1097
        if (t == ts) {
1098
            *pt = t->next;
1099
            break;
1100
        }
1101
        pt = &t->next;
1102
    }
1103
}
1104

    
1105
/* modify the current timer so that it will be fired when current_time
1106
   >= expire_time. The corresponding callback will be called. */
1107
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1108
{
1109
    QEMUTimer **pt, *t;
1110

    
1111
    qemu_del_timer(ts);
1112

    
1113
    /* add the timer in the sorted list */
1114
    /* NOTE: this code must be signal safe because
1115
       qemu_timer_expired() can be called from a signal. */
1116
    pt = &active_timers[ts->clock->type];
1117
    for(;;) {
1118
        t = *pt;
1119
        if (!t)
1120
            break;
1121
        if (t->expire_time > expire_time)
1122
            break;
1123
        pt = &t->next;
1124
    }
1125
    ts->expire_time = expire_time;
1126
    ts->next = *pt;
1127
    *pt = ts;
1128

    
1129
    /* Rearm if necessary  */
1130
    if (pt == &active_timers[ts->clock->type]) {
1131
        if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1132
            qemu_rearm_alarm_timer(alarm_timer);
1133
        }
1134
        /* Interrupt execution to force deadline recalculation.  */
1135
        if (use_icount && cpu_single_env) {
1136
            cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1137
        }
1138
    }
1139
}
1140

    
1141
int qemu_timer_pending(QEMUTimer *ts)
1142
{
1143
    QEMUTimer *t;
1144
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1145
        if (t == ts)
1146
            return 1;
1147
    }
1148
    return 0;
1149
}
1150

    
1151
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1152
{
1153
    if (!timer_head)
1154
        return 0;
1155
    return (timer_head->expire_time <= current_time);
1156
}
1157

    
1158
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1159
{
1160
    QEMUTimer *ts;
1161

    
1162
    for(;;) {
1163
        ts = *ptimer_head;
1164
        if (!ts || ts->expire_time > current_time)
1165
            break;
1166
        /* remove timer from the list before calling the callback */
1167
        *ptimer_head = ts->next;
1168
        ts->next = NULL;
1169

    
1170
        /* run the callback (the timer list can be modified) */
1171
        ts->cb(ts->opaque);
1172
    }
1173
}
1174

    
1175
int64_t qemu_get_clock(QEMUClock *clock)
1176
{
1177
    switch(clock->type) {
1178
    case QEMU_TIMER_REALTIME:
1179
        return get_clock() / 1000000;
1180
    default:
1181
    case QEMU_TIMER_VIRTUAL:
1182
        if (use_icount) {
1183
            return cpu_get_icount();
1184
        } else {
1185
            return cpu_get_clock();
1186
        }
1187
    }
1188
}
1189

    
1190
static void init_timers(void)
1191
{
1192
    init_get_clock();
1193
    ticks_per_sec = QEMU_TIMER_BASE;
1194
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1195
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1196
}
1197

    
1198
/* save a timer */
1199
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1200
{
1201
    uint64_t expire_time;
1202

    
1203
    if (qemu_timer_pending(ts)) {
1204
        expire_time = ts->expire_time;
1205
    } else {
1206
        expire_time = -1;
1207
    }
1208
    qemu_put_be64(f, expire_time);
1209
}
1210

    
1211
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1212
{
1213
    uint64_t expire_time;
1214

    
1215
    expire_time = qemu_get_be64(f);
1216
    if (expire_time != -1) {
1217
        qemu_mod_timer(ts, expire_time);
1218
    } else {
1219
        qemu_del_timer(ts);
1220
    }
1221
}
1222

    
1223
static void timer_save(QEMUFile *f, void *opaque)
1224
{
1225
    if (cpu_ticks_enabled) {
1226
        hw_error("cannot save state if virtual timers are running");
1227
    }
1228
    qemu_put_be64(f, cpu_ticks_offset);
1229
    qemu_put_be64(f, ticks_per_sec);
1230
    qemu_put_be64(f, cpu_clock_offset);
1231
}
1232

    
1233
static int timer_load(QEMUFile *f, void *opaque, int version_id)
1234
{
1235
    if (version_id != 1 && version_id != 2)
1236
        return -EINVAL;
1237
    if (cpu_ticks_enabled) {
1238
        return -EINVAL;
1239
    }
1240
    cpu_ticks_offset=qemu_get_be64(f);
1241
    ticks_per_sec=qemu_get_be64(f);
1242
    if (version_id == 2) {
1243
        cpu_clock_offset=qemu_get_be64(f);
1244
    }
1245
    return 0;
1246
}
1247

    
1248
#ifdef _WIN32
1249
void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg,
1250
                                 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
1251
#else
1252
static void host_alarm_handler(int host_signum)
1253
#endif
1254
{
1255
#if 0
1256
#define DISP_FREQ 1000
1257
    {
1258
        static int64_t delta_min = INT64_MAX;
1259
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
1260
        static int count;
1261
        ti = qemu_get_clock(vm_clock);
1262
        if (last_clock != 0) {
1263
            delta = ti - last_clock;
1264
            if (delta < delta_min)
1265
                delta_min = delta;
1266
            if (delta > delta_max)
1267
                delta_max = delta;
1268
            delta_cum += delta;
1269
            if (++count == DISP_FREQ) {
1270
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
1271
                       muldiv64(delta_min, 1000000, ticks_per_sec),
1272
                       muldiv64(delta_max, 1000000, ticks_per_sec),
1273
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
1274
                       (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
1275
                count = 0;
1276
                delta_min = INT64_MAX;
1277
                delta_max = 0;
1278
                delta_cum = 0;
1279
            }
1280
        }
1281
        last_clock = ti;
1282
    }
1283
#endif
1284
    if (alarm_has_dynticks(alarm_timer) ||
1285
        (!use_icount &&
1286
            qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
1287
                               qemu_get_clock(vm_clock))) ||
1288
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
1289
                           qemu_get_clock(rt_clock))) {
1290
#ifdef _WIN32
1291
        struct qemu_alarm_win32 *data = ((struct qemu_alarm_timer*)dwUser)->priv;
1292
        SetEvent(data->host_alarm);
1293
#endif
1294
        CPUState *env = next_cpu;
1295

    
1296
        alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1297

    
1298
        if (env) {
1299
            /* stop the currently executing cpu because a timer occured */
1300
            cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1301
#ifdef USE_KQEMU
1302
            if (env->kqemu_enabled) {
1303
                kqemu_cpu_interrupt(env);
1304
            }
1305
#endif
1306
        }
1307
        event_pending = 1;
1308
    }
1309
}
1310

    
1311
static int64_t qemu_next_deadline(void)
1312
{
1313
    int64_t delta;
1314

    
1315
    if (active_timers[QEMU_TIMER_VIRTUAL]) {
1316
        delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1317
                     qemu_get_clock(vm_clock);
1318
    } else {
1319
        /* To avoid problems with overflow limit this to 2^32.  */
1320
        delta = INT32_MAX;
1321
    }
1322

    
1323
    if (delta < 0)
1324
        delta = 0;
1325

    
1326
    return delta;
1327
}
1328

    
1329
static uint64_t qemu_next_deadline_dyntick(void)
1330
{
1331
    int64_t delta;
1332
    int64_t rtdelta;
1333

    
1334
    if (use_icount)
1335
        delta = INT32_MAX;
1336
    else
1337
        delta = (qemu_next_deadline() + 999) / 1000;
1338

    
1339
    if (active_timers[QEMU_TIMER_REALTIME]) {
1340
        rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1341
                 qemu_get_clock(rt_clock))*1000;
1342
        if (rtdelta < delta)
1343
            delta = rtdelta;
1344
    }
1345

    
1346
    if (delta < MIN_TIMER_REARM_US)
1347
        delta = MIN_TIMER_REARM_US;
1348

    
1349
    return delta;
1350
}
1351

    
1352
#ifndef _WIN32
1353

    
1354
#if defined(__linux__)
1355

    
1356
#define RTC_FREQ 1024
1357

    
1358
static void enable_sigio_timer(int fd)
1359
{
1360
    struct sigaction act;
1361

    
1362
    /* timer signal */
1363
    sigfillset(&act.sa_mask);
1364
    act.sa_flags = 0;
1365
    act.sa_handler = host_alarm_handler;
1366

    
1367
    sigaction(SIGIO, &act, NULL);
1368
    fcntl(fd, F_SETFL, O_ASYNC);
1369
    fcntl(fd, F_SETOWN, getpid());
1370
}
1371

    
1372
static int hpet_start_timer(struct qemu_alarm_timer *t)
1373
{
1374
    struct hpet_info info;
1375
    int r, fd;
1376

    
1377
    fd = open("/dev/hpet", O_RDONLY);
1378
    if (fd < 0)
1379
        return -1;
1380

    
1381
    /* Set frequency */
1382
    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1383
    if (r < 0) {
1384
        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1385
                "error, but for better emulation accuracy type:\n"
1386
                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1387
        goto fail;
1388
    }
1389

    
1390
    /* Check capabilities */
1391
    r = ioctl(fd, HPET_INFO, &info);
1392
    if (r < 0)
1393
        goto fail;
1394

    
1395
    /* Enable periodic mode */
1396
    r = ioctl(fd, HPET_EPI, 0);
1397
    if (info.hi_flags && (r < 0))
1398
        goto fail;
1399

    
1400
    /* Enable interrupt */
1401
    r = ioctl(fd, HPET_IE_ON, 0);
1402
    if (r < 0)
1403
        goto fail;
1404

    
1405
    enable_sigio_timer(fd);
1406
    t->priv = (void *)(long)fd;
1407

    
1408
    return 0;
1409
fail:
1410
    close(fd);
1411
    return -1;
1412
}
1413

    
1414
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1415
{
1416
    int fd = (long)t->priv;
1417

    
1418
    close(fd);
1419
}
1420

    
1421
static int rtc_start_timer(struct qemu_alarm_timer *t)
1422
{
1423
    int rtc_fd;
1424
    unsigned long current_rtc_freq = 0;
1425

    
1426
    TFR(rtc_fd = open("/dev/rtc", O_RDONLY));
1427
    if (rtc_fd < 0)
1428
        return -1;
1429
    ioctl(rtc_fd, RTC_IRQP_READ, &current_rtc_freq);
1430
    if (current_rtc_freq != RTC_FREQ &&
1431
        ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1432
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1433
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1434
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1435
        goto fail;
1436
    }
1437
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1438
    fail:
1439
        close(rtc_fd);
1440
        return -1;
1441
    }
1442

    
1443
    enable_sigio_timer(rtc_fd);
1444

    
1445
    t->priv = (void *)(long)rtc_fd;
1446

    
1447
    return 0;
1448
}
1449

    
1450
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1451
{
1452
    int rtc_fd = (long)t->priv;
1453

    
1454
    close(rtc_fd);
1455
}
1456

    
1457
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1458
{
1459
    struct sigevent ev;
1460
    timer_t host_timer;
1461
    struct sigaction act;
1462

    
1463
    sigfillset(&act.sa_mask);
1464
    act.sa_flags = 0;
1465
    act.sa_handler = host_alarm_handler;
1466

    
1467
    sigaction(SIGALRM, &act, NULL);
1468

    
1469
    ev.sigev_value.sival_int = 0;
1470
    ev.sigev_notify = SIGEV_SIGNAL;
1471
    ev.sigev_signo = SIGALRM;
1472

    
1473
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1474
        perror("timer_create");
1475

    
1476
        /* disable dynticks */
1477
        fprintf(stderr, "Dynamic Ticks disabled\n");
1478

    
1479
        return -1;
1480
    }
1481

    
1482
    t->priv = (void *)host_timer;
1483

    
1484
    return 0;
1485
}
1486

    
1487
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1488
{
1489
    timer_t host_timer = (timer_t)t->priv;
1490

    
1491
    timer_delete(host_timer);
1492
}
1493

    
1494
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1495
{
1496
    timer_t host_timer = (timer_t)t->priv;
1497
    struct itimerspec timeout;
1498
    int64_t nearest_delta_us = INT64_MAX;
1499
    int64_t current_us;
1500

    
1501
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1502
                !active_timers[QEMU_TIMER_VIRTUAL])
1503
        return;
1504

    
1505
    nearest_delta_us = qemu_next_deadline_dyntick();
1506

    
1507
    /* check whether a timer is already running */
1508
    if (timer_gettime(host_timer, &timeout)) {
1509
        perror("gettime");
1510
        fprintf(stderr, "Internal timer error: aborting\n");
1511
        exit(1);
1512
    }
1513
    current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1514
    if (current_us && current_us <= nearest_delta_us)
1515
        return;
1516

    
1517
    timeout.it_interval.tv_sec = 0;
1518
    timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1519
    timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
1520
    timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1521
    if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1522
        perror("settime");
1523
        fprintf(stderr, "Internal timer error: aborting\n");
1524
        exit(1);
1525
    }
1526
}
1527

    
1528
#endif /* defined(__linux__) */
1529

    
1530
static int unix_start_timer(struct qemu_alarm_timer *t)
1531
{
1532
    struct sigaction act;
1533
    struct itimerval itv;
1534
    int err;
1535

    
1536
    /* timer signal */
1537
    sigfillset(&act.sa_mask);
1538
    act.sa_flags = 0;
1539
    act.sa_handler = host_alarm_handler;
1540

    
1541
    sigaction(SIGALRM, &act, NULL);
1542

    
1543
    itv.it_interval.tv_sec = 0;
1544
    /* for i386 kernel 2.6 to get 1 ms */
1545
    itv.it_interval.tv_usec = 999;
1546
    itv.it_value.tv_sec = 0;
1547
    itv.it_value.tv_usec = 10 * 1000;
1548

    
1549
    err = setitimer(ITIMER_REAL, &itv, NULL);
1550
    if (err)
1551
        return -1;
1552

    
1553
    return 0;
1554
}
1555

    
1556
static void unix_stop_timer(struct qemu_alarm_timer *t)
1557
{
1558
    struct itimerval itv;
1559

    
1560
    memset(&itv, 0, sizeof(itv));
1561
    setitimer(ITIMER_REAL, &itv, NULL);
1562
}
1563

    
1564
#endif /* !defined(_WIN32) */
1565

    
1566
#ifdef _WIN32
1567

    
1568
static int win32_start_timer(struct qemu_alarm_timer *t)
1569
{
1570
    TIMECAPS tc;
1571
    struct qemu_alarm_win32 *data = t->priv;
1572
    UINT flags;
1573

    
1574
    data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1575
    if (!data->host_alarm) {
1576
        perror("Failed CreateEvent");
1577
        return -1;
1578
    }
1579

    
1580
    memset(&tc, 0, sizeof(tc));
1581
    timeGetDevCaps(&tc, sizeof(tc));
1582

    
1583
    if (data->period < tc.wPeriodMin)
1584
        data->period = tc.wPeriodMin;
1585

    
1586
    timeBeginPeriod(data->period);
1587

    
1588
    flags = TIME_CALLBACK_FUNCTION;
1589
    if (alarm_has_dynticks(t))
1590
        flags |= TIME_ONESHOT;
1591
    else
1592
        flags |= TIME_PERIODIC;
1593

    
1594
    data->timerId = timeSetEvent(1,         // interval (ms)
1595
                        data->period,       // resolution
1596
                        host_alarm_handler, // function
1597
                        (DWORD)t,           // parameter
1598
                        flags);
1599

    
1600
    if (!data->timerId) {
1601
        perror("Failed to initialize win32 alarm timer");
1602

    
1603
        timeEndPeriod(data->period);
1604
        CloseHandle(data->host_alarm);
1605
        return -1;
1606
    }
1607

    
1608
    qemu_add_wait_object(data->host_alarm, NULL, NULL);
1609

    
1610
    return 0;
1611
}
1612

    
1613
static void win32_stop_timer(struct qemu_alarm_timer *t)
1614
{
1615
    struct qemu_alarm_win32 *data = t->priv;
1616

    
1617
    timeKillEvent(data->timerId);
1618
    timeEndPeriod(data->period);
1619

    
1620
    CloseHandle(data->host_alarm);
1621
}
1622

    
1623
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1624
{
1625
    struct qemu_alarm_win32 *data = t->priv;
1626
    uint64_t nearest_delta_us;
1627

    
1628
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1629
                !active_timers[QEMU_TIMER_VIRTUAL])
1630
        return;
1631

    
1632
    nearest_delta_us = qemu_next_deadline_dyntick();
1633
    nearest_delta_us /= 1000;
1634

    
1635
    timeKillEvent(data->timerId);
1636

    
1637
    data->timerId = timeSetEvent(1,
1638
                        data->period,
1639
                        host_alarm_handler,
1640
                        (DWORD)t,
1641
                        TIME_ONESHOT | TIME_PERIODIC);
1642

    
1643
    if (!data->timerId) {
1644
        perror("Failed to re-arm win32 alarm timer");
1645

    
1646
        timeEndPeriod(data->period);
1647
        CloseHandle(data->host_alarm);
1648
        exit(1);
1649
    }
1650
}
1651

    
1652
#endif /* _WIN32 */
1653

    
1654
static void init_timer_alarm(void)
1655
{
1656
    struct qemu_alarm_timer *t;
1657
    int i, err = -1;
1658

    
1659
    for (i = 0; alarm_timers[i].name; i++) {
1660
        t = &alarm_timers[i];
1661

    
1662
        err = t->start(t);
1663
        if (!err)
1664
            break;
1665
    }
1666

    
1667
    if (err) {
1668
        fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1669
        fprintf(stderr, "Terminating\n");
1670
        exit(1);
1671
    }
1672

    
1673
    alarm_timer = t;
1674
}
1675

    
1676
static void quit_timers(void)
1677
{
1678
    alarm_timer->stop(alarm_timer);
1679
    alarm_timer = NULL;
1680
}
1681

    
1682
/***********************************************************/
1683
/* host time/date access */
1684
void qemu_get_timedate(struct tm *tm, int offset)
1685
{
1686
    time_t ti;
1687
    struct tm *ret;
1688

    
1689
    time(&ti);
1690
    ti += offset;
1691
    if (rtc_date_offset == -1) {
1692
        if (rtc_utc)
1693
            ret = gmtime(&ti);
1694
        else
1695
            ret = localtime(&ti);
1696
    } else {
1697
        ti -= rtc_date_offset;
1698
        ret = gmtime(&ti);
1699
    }
1700

    
1701
    memcpy(tm, ret, sizeof(struct tm));
1702
}
1703

    
1704
int qemu_timedate_diff(struct tm *tm)
1705
{
1706
    time_t seconds;
1707

    
1708
    if (rtc_date_offset == -1)
1709
        if (rtc_utc)
1710
            seconds = mktimegm(tm);
1711
        else
1712
            seconds = mktime(tm);
1713
    else
1714
        seconds = mktimegm(tm) + rtc_date_offset;
1715

    
1716
    return seconds - time(NULL);
1717
}
1718

    
1719
/***********************************************************/
1720
/* character device */
1721

    
1722
static void qemu_chr_event(CharDriverState *s, int event)
1723
{
1724
    if (!s->chr_event)
1725
        return;
1726
    s->chr_event(s->handler_opaque, event);
1727
}
1728

    
1729
static void qemu_chr_reset_bh(void *opaque)
1730
{
1731
    CharDriverState *s = opaque;
1732
    qemu_chr_event(s, CHR_EVENT_RESET);
1733
    qemu_bh_delete(s->bh);
1734
    s->bh = NULL;
1735
}
1736

    
1737
void qemu_chr_reset(CharDriverState *s)
1738
{
1739
    if (s->bh == NULL) {
1740
        s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1741
        qemu_bh_schedule(s->bh);
1742
    }
1743
}
1744

    
1745
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1746
{
1747
    return s->chr_write(s, buf, len);
1748
}
1749

    
1750
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1751
{
1752
    if (!s->chr_ioctl)
1753
        return -ENOTSUP;
1754
    return s->chr_ioctl(s, cmd, arg);
1755
}
1756

    
1757
int qemu_chr_can_read(CharDriverState *s)
1758
{
1759
    if (!s->chr_can_read)
1760
        return 0;
1761
    return s->chr_can_read(s->handler_opaque);
1762
}
1763

    
1764
void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1765
{
1766
    s->chr_read(s->handler_opaque, buf, len);
1767
}
1768

    
1769
void qemu_chr_accept_input(CharDriverState *s)
1770
{
1771
    if (s->chr_accept_input)
1772
        s->chr_accept_input(s);
1773
}
1774

    
1775
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1776
{
1777
    char buf[4096];
1778
    va_list ap;
1779
    va_start(ap, fmt);
1780
    vsnprintf(buf, sizeof(buf), fmt, ap);
1781
    qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1782
    va_end(ap);
1783
}
1784

    
1785
void qemu_chr_send_event(CharDriverState *s, int event)
1786
{
1787
    if (s->chr_send_event)
1788
        s->chr_send_event(s, event);
1789
}
1790

    
1791
void qemu_chr_add_handlers(CharDriverState *s,
1792
                           IOCanRWHandler *fd_can_read,
1793
                           IOReadHandler *fd_read,
1794
                           IOEventHandler *fd_event,
1795
                           void *opaque)
1796
{
1797
    s->chr_can_read = fd_can_read;
1798
    s->chr_read = fd_read;
1799
    s->chr_event = fd_event;
1800
    s->handler_opaque = opaque;
1801
    if (s->chr_update_read_handler)
1802
        s->chr_update_read_handler(s);
1803
}
1804

    
1805
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1806
{
1807
    return len;
1808
}
1809

    
1810
static CharDriverState *qemu_chr_open_null(void)
1811
{
1812
    CharDriverState *chr;
1813

    
1814
    chr = qemu_mallocz(sizeof(CharDriverState));
1815
    if (!chr)
1816
        return NULL;
1817
    chr->chr_write = null_chr_write;
1818
    return chr;
1819
}
1820

    
1821
/* MUX driver for serial I/O splitting */
1822
static int term_timestamps;
1823
static int64_t term_timestamps_start;
1824
#define MAX_MUX 4
1825
#define MUX_BUFFER_SIZE 32        /* Must be a power of 2.  */
1826
#define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1827
typedef struct {
1828
    IOCanRWHandler *chr_can_read[MAX_MUX];
1829
    IOReadHandler *chr_read[MAX_MUX];
1830
    IOEventHandler *chr_event[MAX_MUX];
1831
    void *ext_opaque[MAX_MUX];
1832
    CharDriverState *drv;
1833
    unsigned char buffer[MUX_BUFFER_SIZE];
1834
    int prod;
1835
    int cons;
1836
    int mux_cnt;
1837
    int term_got_escape;
1838
    int max_size;
1839
} MuxDriver;
1840

    
1841

    
1842
static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1843
{
1844
    MuxDriver *d = chr->opaque;
1845
    int ret;
1846
    if (!term_timestamps) {
1847
        ret = d->drv->chr_write(d->drv, buf, len);
1848
    } else {
1849
        int i;
1850

    
1851
        ret = 0;
1852
        for(i = 0; i < len; i++) {
1853
            ret += d->drv->chr_write(d->drv, buf+i, 1);
1854
            if (buf[i] == '\n') {
1855
                char buf1[64];
1856
                int64_t ti;
1857
                int secs;
1858

    
1859
                ti = get_clock();
1860
                if (term_timestamps_start == -1)
1861
                    term_timestamps_start = ti;
1862
                ti -= term_timestamps_start;
1863
                secs = ti / 1000000000;
1864
                snprintf(buf1, sizeof(buf1),
1865
                         "[%02d:%02d:%02d.%03d] ",
1866
                         secs / 3600,
1867
                         (secs / 60) % 60,
1868
                         secs % 60,
1869
                         (int)((ti / 1000000) % 1000));
1870
                d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1871
            }
1872
        }
1873
    }
1874
    return ret;
1875
}
1876

    
1877
static char *mux_help[] = {
1878
    "% h    print this help\n\r",
1879
    "% x    exit emulator\n\r",
1880
    "% s    save disk data back to file (if -snapshot)\n\r",
1881
    "% t    toggle console timestamps\n\r"
1882
    "% b    send break (magic sysrq)\n\r",
1883
    "% c    switch between console and monitor\n\r",
1884
    "% %  sends %\n\r",
1885
    NULL
1886
};
1887

    
1888
static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1889
static void mux_print_help(CharDriverState *chr)
1890
{
1891
    int i, j;
1892
    char ebuf[15] = "Escape-Char";
1893
    char cbuf[50] = "\n\r";
1894

    
1895
    if (term_escape_char > 0 && term_escape_char < 26) {
1896
        sprintf(cbuf,"\n\r");
1897
        sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1898
    } else {
1899
        sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1900
            term_escape_char);
1901
    }
1902
    chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1903
    for (i = 0; mux_help[i] != NULL; i++) {
1904
        for (j=0; mux_help[i][j] != '\0'; j++) {
1905
            if (mux_help[i][j] == '%')
1906
                chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1907
            else
1908
                chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1909
        }
1910
    }
1911
}
1912

    
1913
static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1914
{
1915
    if (d->term_got_escape) {
1916
        d->term_got_escape = 0;
1917
        if (ch == term_escape_char)
1918
            goto send_char;
1919
        switch(ch) {
1920
        case '?':
1921
        case 'h':
1922
            mux_print_help(chr);
1923
            break;
1924
        case 'x':
1925
            {
1926
                 char *term =  "QEMU: Terminated\n\r";
1927
                 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1928
                 exit(0);
1929
                 break;
1930
            }
1931
        case 's':
1932
            {
1933
                int i;
1934
                for (i = 0; i < nb_drives; i++) {
1935
                        bdrv_commit(drives_table[i].bdrv);
1936
                }
1937
            }
1938
            break;
1939
        case 'b':
1940
            qemu_chr_event(chr, CHR_EVENT_BREAK);
1941
            break;
1942
        case 'c':
1943
            /* Switch to the next registered device */
1944
            chr->focus++;
1945
            if (chr->focus >= d->mux_cnt)
1946
                chr->focus = 0;
1947
            break;
1948
       case 't':
1949
           term_timestamps = !term_timestamps;
1950
           term_timestamps_start = -1;
1951
           break;
1952
        }
1953
    } else if (ch == term_escape_char) {
1954
        d->term_got_escape = 1;
1955
    } else {
1956
    send_char:
1957
        return 1;
1958
    }
1959
    return 0;
1960
}
1961

    
1962
static void mux_chr_accept_input(CharDriverState *chr)
1963
{
1964
    int m = chr->focus;
1965
    MuxDriver *d = chr->opaque;
1966

    
1967
    while (d->prod != d->cons &&
1968
           d->chr_can_read[m] &&
1969
           d->chr_can_read[m](d->ext_opaque[m])) {
1970
        d->chr_read[m](d->ext_opaque[m],
1971
                       &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1972
    }
1973
}
1974

    
1975
static int mux_chr_can_read(void *opaque)
1976
{
1977
    CharDriverState *chr = opaque;
1978
    MuxDriver *d = chr->opaque;
1979

    
1980
    if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
1981
        return 1;
1982
    if (d->chr_can_read[chr->focus])
1983
        return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1984
    return 0;
1985
}
1986

    
1987
static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1988
{
1989
    CharDriverState *chr = opaque;
1990
    MuxDriver *d = chr->opaque;
1991
    int m = chr->focus;
1992
    int i;
1993

    
1994
    mux_chr_accept_input (opaque);
1995

    
1996
    for(i = 0; i < size; i++)
1997
        if (mux_proc_byte(chr, d, buf[i])) {
1998
            if (d->prod == d->cons &&
1999
                d->chr_can_read[m] &&
2000
                d->chr_can_read[m](d->ext_opaque[m]))
2001
                d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
2002
            else
2003
                d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
2004
        }
2005
}
2006

    
2007
static void mux_chr_event(void *opaque, int event)
2008
{
2009
    CharDriverState *chr = opaque;
2010
    MuxDriver *d = chr->opaque;
2011
    int i;
2012

    
2013
    /* Send the event to all registered listeners */
2014
    for (i = 0; i < d->mux_cnt; i++)
2015
        if (d->chr_event[i])
2016
            d->chr_event[i](d->ext_opaque[i], event);
2017
}
2018

    
2019
static void mux_chr_update_read_handler(CharDriverState *chr)
2020
{
2021
    MuxDriver *d = chr->opaque;
2022

    
2023
    if (d->mux_cnt >= MAX_MUX) {
2024
        fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
2025
        return;
2026
    }
2027
    d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
2028
    d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
2029
    d->chr_read[d->mux_cnt] = chr->chr_read;
2030
    d->chr_event[d->mux_cnt] = chr->chr_event;
2031
    /* Fix up the real driver with mux routines */
2032
    if (d->mux_cnt == 0) {
2033
        qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
2034
                              mux_chr_event, chr);
2035
    }
2036
    chr->focus = d->mux_cnt;
2037
    d->mux_cnt++;
2038
}
2039

    
2040
static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
2041
{
2042
    CharDriverState *chr;
2043
    MuxDriver *d;
2044

    
2045
    chr = qemu_mallocz(sizeof(CharDriverState));
2046
    if (!chr)
2047
        return NULL;
2048
    d = qemu_mallocz(sizeof(MuxDriver));
2049
    if (!d) {
2050
        free(chr);
2051
        return NULL;
2052
    }
2053

    
2054
    chr->opaque = d;
2055
    d->drv = drv;
2056
    chr->focus = -1;
2057
    chr->chr_write = mux_chr_write;
2058
    chr->chr_update_read_handler = mux_chr_update_read_handler;
2059
    chr->chr_accept_input = mux_chr_accept_input;
2060
    return chr;
2061
}
2062

    
2063

    
2064
#ifdef _WIN32
2065

    
2066
static void socket_cleanup(void)
2067
{
2068
    WSACleanup();
2069
}
2070

    
2071
static int socket_init(void)
2072
{
2073
    WSADATA Data;
2074
    int ret, err;
2075

    
2076
    ret = WSAStartup(MAKEWORD(2,2), &Data);
2077
    if (ret != 0) {
2078
        err = WSAGetLastError();
2079
        fprintf(stderr, "WSAStartup: %d\n", err);
2080
        return -1;
2081
    }
2082
    atexit(socket_cleanup);
2083
    return 0;
2084
}
2085

    
2086
static int send_all(int fd, const uint8_t *buf, int len1)
2087
{
2088
    int ret, len;
2089

    
2090
    len = len1;
2091
    while (len > 0) {
2092
        ret = send(fd, buf, len, 0);
2093
        if (ret < 0) {
2094
            int errno;
2095
            errno = WSAGetLastError();
2096
            if (errno != WSAEWOULDBLOCK) {
2097
                return -1;
2098
            }
2099
        } else if (ret == 0) {
2100
            break;
2101
        } else {
2102
            buf += ret;
2103
            len -= ret;
2104
        }
2105
    }
2106
    return len1 - len;
2107
}
2108

    
2109
void socket_set_nonblock(int fd)
2110
{
2111
    unsigned long opt = 1;
2112
    ioctlsocket(fd, FIONBIO, &opt);
2113
}
2114

    
2115
#else
2116

    
2117
static int unix_write(int fd, const uint8_t *buf, int len1)
2118
{
2119
    int ret, len;
2120

    
2121
    len = len1;
2122
    while (len > 0) {
2123
        ret = write(fd, buf, len);
2124
        if (ret < 0) {
2125
            if (errno != EINTR && errno != EAGAIN)
2126
                return -1;
2127
        } else if (ret == 0) {
2128
            break;
2129
        } else {
2130
            buf += ret;
2131
            len -= ret;
2132
        }
2133
    }
2134
    return len1 - len;
2135
}
2136

    
2137
static inline int send_all(int fd, const uint8_t *buf, int len1)
2138
{
2139
    return unix_write(fd, buf, len1);
2140
}
2141

    
2142
void socket_set_nonblock(int fd)
2143
{
2144
    int f;
2145
    f = fcntl(fd, F_GETFL);
2146
    fcntl(fd, F_SETFL, f | O_NONBLOCK);
2147
}
2148
#endif /* !_WIN32 */
2149

    
2150
#ifndef _WIN32
2151

    
2152
typedef struct {
2153
    int fd_in, fd_out;
2154
    int max_size;
2155
} FDCharDriver;
2156

    
2157
#define STDIO_MAX_CLIENTS 1
2158
static int stdio_nb_clients = 0;
2159

    
2160
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2161
{
2162
    FDCharDriver *s = chr->opaque;
2163
    return unix_write(s->fd_out, buf, len);
2164
}
2165

    
2166
static int fd_chr_read_poll(void *opaque)
2167
{
2168
    CharDriverState *chr = opaque;
2169
    FDCharDriver *s = chr->opaque;
2170

    
2171
    s->max_size = qemu_chr_can_read(chr);
2172
    return s->max_size;
2173
}
2174

    
2175
static void fd_chr_read(void *opaque)
2176
{
2177
    CharDriverState *chr = opaque;
2178
    FDCharDriver *s = chr->opaque;
2179
    int size, len;
2180
    uint8_t buf[1024];
2181

    
2182
    len = sizeof(buf);
2183
    if (len > s->max_size)
2184
        len = s->max_size;
2185
    if (len == 0)
2186
        return;
2187
    size = read(s->fd_in, buf, len);
2188
    if (size == 0) {
2189
        /* FD has been closed. Remove it from the active list.  */
2190
        qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2191
        return;
2192
    }
2193
    if (size > 0) {
2194
        qemu_chr_read(chr, buf, size);
2195
    }
2196
}
2197

    
2198
static void fd_chr_update_read_handler(CharDriverState *chr)
2199
{
2200
    FDCharDriver *s = chr->opaque;
2201

    
2202
    if (s->fd_in >= 0) {
2203
        if (nographic && s->fd_in == 0) {
2204
        } else {
2205
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2206
                                 fd_chr_read, NULL, chr);
2207
        }
2208
    }
2209
}
2210

    
2211
static void fd_chr_close(struct CharDriverState *chr)
2212
{
2213
    FDCharDriver *s = chr->opaque;
2214

    
2215
    if (s->fd_in >= 0) {
2216
        if (nographic && s->fd_in == 0) {
2217
        } else {
2218
            qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2219
        }
2220
    }
2221

    
2222
    qemu_free(s);
2223
}
2224

    
2225
/* open a character device to a unix fd */
2226
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2227
{
2228
    CharDriverState *chr;
2229
    FDCharDriver *s;
2230

    
2231
    chr = qemu_mallocz(sizeof(CharDriverState));
2232
    if (!chr)
2233
        return NULL;
2234
    s = qemu_mallocz(sizeof(FDCharDriver));
2235
    if (!s) {
2236
        free(chr);
2237
        return NULL;
2238
    }
2239
    s->fd_in = fd_in;
2240
    s->fd_out = fd_out;
2241
    chr->opaque = s;
2242
    chr->chr_write = fd_chr_write;
2243
    chr->chr_update_read_handler = fd_chr_update_read_handler;
2244
    chr->chr_close = fd_chr_close;
2245

    
2246
    qemu_chr_reset(chr);
2247

    
2248
    return chr;
2249
}
2250

    
2251
static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2252
{
2253
    int fd_out;
2254

    
2255
    TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2256
    if (fd_out < 0)
2257
        return NULL;
2258
    return qemu_chr_open_fd(-1, fd_out);
2259
}
2260

    
2261
static CharDriverState *qemu_chr_open_pipe(const char *filename)
2262
{
2263
    int fd_in, fd_out;
2264
    char filename_in[256], filename_out[256];
2265

    
2266
    snprintf(filename_in, 256, "%s.in", filename);
2267
    snprintf(filename_out, 256, "%s.out", filename);
2268
    TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2269
    TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2270
    if (fd_in < 0 || fd_out < 0) {
2271
        if (fd_in >= 0)
2272
            close(fd_in);
2273
        if (fd_out >= 0)
2274
            close(fd_out);
2275
        TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2276
        if (fd_in < 0)
2277
            return NULL;
2278
    }
2279
    return qemu_chr_open_fd(fd_in, fd_out);
2280
}
2281

    
2282

    
2283
/* for STDIO, we handle the case where several clients use it
2284
   (nographic mode) */
2285

    
2286
#define TERM_FIFO_MAX_SIZE 1
2287

    
2288
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2289
static int term_fifo_size;
2290

    
2291
static int stdio_read_poll(void *opaque)
2292
{
2293
    CharDriverState *chr = opaque;
2294

    
2295
    /* try to flush the queue if needed */
2296
    if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2297
        qemu_chr_read(chr, term_fifo, 1);
2298
        term_fifo_size = 0;
2299
    }
2300
    /* see if we can absorb more chars */
2301
    if (term_fifo_size == 0)
2302
        return 1;
2303
    else
2304
        return 0;
2305
}
2306

    
2307
static void stdio_read(void *opaque)
2308
{
2309
    int size;
2310
    uint8_t buf[1];
2311
    CharDriverState *chr = opaque;
2312

    
2313
    size = read(0, buf, 1);
2314
    if (size == 0) {
2315
        /* stdin has been closed. Remove it from the active list.  */
2316
        qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2317
        return;
2318
    }
2319
    if (size > 0) {
2320
        if (qemu_chr_can_read(chr) > 0) {
2321
            qemu_chr_read(chr, buf, 1);
2322
        } else if (term_fifo_size == 0) {
2323
            term_fifo[term_fifo_size++] = buf[0];
2324
        }
2325
    }
2326
}
2327

    
2328
/* init terminal so that we can grab keys */
2329
static struct termios oldtty;
2330
static int old_fd0_flags;
2331
static int term_atexit_done;
2332

    
2333
static void term_exit(void)
2334
{
2335
    tcsetattr (0, TCSANOW, &oldtty);
2336
    fcntl(0, F_SETFL, old_fd0_flags);
2337
}
2338

    
2339
static void term_init(void)
2340
{
2341
    struct termios tty;
2342

    
2343
    tcgetattr (0, &tty);
2344
    oldtty = tty;
2345
    old_fd0_flags = fcntl(0, F_GETFL);
2346

    
2347
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2348
                          |INLCR|IGNCR|ICRNL|IXON);
2349
    tty.c_oflag |= OPOST;
2350
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2351
    /* if graphical mode, we allow Ctrl-C handling */
2352
    if (nographic)
2353
        tty.c_lflag &= ~ISIG;
2354
    tty.c_cflag &= ~(CSIZE|PARENB);
2355
    tty.c_cflag |= CS8;
2356
    tty.c_cc[VMIN] = 1;
2357
    tty.c_cc[VTIME] = 0;
2358

    
2359
    tcsetattr (0, TCSANOW, &tty);
2360

    
2361
    if (!term_atexit_done++)
2362
        atexit(term_exit);
2363

    
2364
    fcntl(0, F_SETFL, O_NONBLOCK);
2365
}
2366

    
2367
static void qemu_chr_close_stdio(struct CharDriverState *chr)
2368
{
2369
    term_exit();
2370
    stdio_nb_clients--;
2371
    qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2372
    fd_chr_close(chr);
2373
}
2374

    
2375
static CharDriverState *qemu_chr_open_stdio(void)
2376
{
2377
    CharDriverState *chr;
2378

    
2379
    if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2380
        return NULL;
2381
    chr = qemu_chr_open_fd(0, 1);
2382
    chr->chr_close = qemu_chr_close_stdio;
2383
    qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2384
    stdio_nb_clients++;
2385
    term_init();
2386

    
2387
    return chr;
2388
}
2389

    
2390
#ifdef __sun__
2391
/* Once Solaris has openpty(), this is going to be removed. */
2392
int openpty(int *amaster, int *aslave, char *name,
2393
            struct termios *termp, struct winsize *winp)
2394
{
2395
        const char *slave;
2396
        int mfd = -1, sfd = -1;
2397

    
2398
        *amaster = *aslave = -1;
2399

    
2400
        mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
2401
        if (mfd < 0)
2402
                goto err;
2403

    
2404
        if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
2405
                goto err;
2406

    
2407
        if ((slave = ptsname(mfd)) == NULL)
2408
                goto err;
2409

    
2410
        if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
2411
                goto err;
2412

    
2413
        if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
2414
            (termp != NULL && tcgetattr(sfd, termp) < 0))
2415
                goto err;
2416

    
2417
        if (amaster)
2418
                *amaster = mfd;
2419
        if (aslave)
2420
                *aslave = sfd;
2421
        if (winp)
2422
                ioctl(sfd, TIOCSWINSZ, winp);
2423

    
2424
        return 0;
2425

    
2426
err:
2427
        if (sfd != -1)
2428
                close(sfd);
2429
        close(mfd);
2430
        return -1;
2431
}
2432

    
2433
void cfmakeraw (struct termios *termios_p)
2434
{
2435
        termios_p->c_iflag &=
2436
                ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2437
        termios_p->c_oflag &= ~OPOST;
2438
        termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2439
        termios_p->c_cflag &= ~(CSIZE|PARENB);
2440
        termios_p->c_cflag |= CS8;
2441

    
2442
        termios_p->c_cc[VMIN] = 0;
2443
        termios_p->c_cc[VTIME] = 0;
2444
}
2445
#endif
2446

    
2447
#if defined(__linux__) || defined(__sun__)
2448
static CharDriverState *qemu_chr_open_pty(void)
2449
{
2450
    struct termios tty;
2451
    int master_fd, slave_fd;
2452

    
2453
    if (openpty(&master_fd, &slave_fd, NULL, NULL, NULL) < 0) {
2454
        return NULL;
2455
    }
2456

    
2457
    /* Set raw attributes on the pty. */
2458
    cfmakeraw(&tty);
2459
    tcsetattr(slave_fd, TCSAFLUSH, &tty);
2460

    
2461
    fprintf(stderr, "char device redirected to %s\n", ptsname(master_fd));
2462
    return qemu_chr_open_fd(master_fd, master_fd);
2463
}
2464

    
2465
static void tty_serial_init(int fd, int speed,
2466
                            int parity, int data_bits, int stop_bits)
2467
{
2468
    struct termios tty;
2469
    speed_t spd;
2470

    
2471
#if 0
2472
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2473
           speed, parity, data_bits, stop_bits);
2474
#endif
2475
    tcgetattr (fd, &tty);
2476

    
2477
#define MARGIN 1.1
2478
    if (speed <= 50 * MARGIN)
2479
        spd = B50;
2480
    else if (speed <= 75 * MARGIN)
2481
        spd = B75;
2482
    else if (speed <= 300 * MARGIN)
2483
        spd = B300;
2484
    else if (speed <= 600 * MARGIN)
2485
        spd = B600;
2486
    else if (speed <= 1200 * MARGIN)
2487
        spd = B1200;
2488
    else if (speed <= 2400 * MARGIN)
2489
        spd = B2400;
2490
    else if (speed <= 4800 * MARGIN)
2491
        spd = B4800;
2492
    else if (speed <= 9600 * MARGIN)
2493
        spd = B9600;
2494
    else if (speed <= 19200 * MARGIN)
2495
        spd = B19200;
2496
    else if (speed <= 38400 * MARGIN)
2497
        spd = B38400;
2498
    else if (speed <= 57600 * MARGIN)
2499
        spd = B57600;
2500
    else if (speed <= 115200 * MARGIN)
2501
        spd = B115200;
2502
    else
2503
        spd = B115200;
2504

    
2505
    cfsetispeed(&tty, spd);
2506
    cfsetospeed(&tty, spd);
2507

    
2508
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2509
                          |INLCR|IGNCR|ICRNL|IXON);
2510
    tty.c_oflag |= OPOST;
2511
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2512
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2513
    switch(data_bits) {
2514
    default:
2515
    case 8:
2516
        tty.c_cflag |= CS8;
2517
        break;
2518
    case 7:
2519
        tty.c_cflag |= CS7;
2520
        break;
2521
    case 6:
2522
        tty.c_cflag |= CS6;
2523
        break;
2524
    case 5:
2525
        tty.c_cflag |= CS5;
2526
        break;
2527
    }
2528
    switch(parity) {
2529
    default:
2530
    case 'N':
2531
        break;
2532
    case 'E':
2533
        tty.c_cflag |= PARENB;
2534
        break;
2535
    case 'O':
2536
        tty.c_cflag |= PARENB | PARODD;
2537
        break;
2538
    }
2539
    if (stop_bits == 2)
2540
        tty.c_cflag |= CSTOPB;
2541

    
2542
    tcsetattr (fd, TCSANOW, &tty);
2543
}
2544

    
2545
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2546
{
2547
    FDCharDriver *s = chr->opaque;
2548

    
2549
    switch(cmd) {
2550
    case CHR_IOCTL_SERIAL_SET_PARAMS:
2551
        {
2552
            QEMUSerialSetParams *ssp = arg;
2553
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2554
                            ssp->data_bits, ssp->stop_bits);
2555
        }
2556
        break;
2557
    case CHR_IOCTL_SERIAL_SET_BREAK:
2558
        {
2559
            int enable = *(int *)arg;
2560
            if (enable)
2561
                tcsendbreak(s->fd_in, 1);
2562
        }
2563
        break;
2564
    default:
2565
        return -ENOTSUP;
2566
    }
2567
    return 0;
2568
}
2569

    
2570
static CharDriverState *qemu_chr_open_tty(const char *filename)
2571
{
2572
    CharDriverState *chr;
2573
    int fd;
2574

    
2575
    TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2576
    tty_serial_init(fd, 115200, 'N', 8, 1);
2577
    chr = qemu_chr_open_fd(fd, fd);
2578
    if (!chr) {
2579
        close(fd);
2580
        return NULL;
2581
    }
2582
    chr->chr_ioctl = tty_serial_ioctl;
2583
    qemu_chr_reset(chr);
2584
    return chr;
2585
}
2586
#else  /* ! __linux__ && ! __sun__ */
2587
static CharDriverState *qemu_chr_open_pty(void)
2588
{
2589
    return NULL;
2590
}
2591
#endif /* __linux__ || __sun__ */
2592

    
2593
#if defined(__linux__)
2594
typedef struct {
2595
    int fd;
2596
    int mode;
2597
} ParallelCharDriver;
2598

    
2599
static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2600
{
2601
    if (s->mode != mode) {
2602
        int m = mode;
2603
        if (ioctl(s->fd, PPSETMODE, &m) < 0)
2604
            return 0;
2605
        s->mode = mode;
2606
    }
2607
    return 1;
2608
}
2609

    
2610
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2611
{
2612
    ParallelCharDriver *drv = chr->opaque;
2613
    int fd = drv->fd;
2614
    uint8_t b;
2615

    
2616
    switch(cmd) {
2617
    case CHR_IOCTL_PP_READ_DATA:
2618
        if (ioctl(fd, PPRDATA, &b) < 0)
2619
            return -ENOTSUP;
2620
        *(uint8_t *)arg = b;
2621
        break;
2622
    case CHR_IOCTL_PP_WRITE_DATA:
2623
        b = *(uint8_t *)arg;
2624
        if (ioctl(fd, PPWDATA, &b) < 0)
2625
            return -ENOTSUP;
2626
        break;
2627
    case CHR_IOCTL_PP_READ_CONTROL:
2628
        if (ioctl(fd, PPRCONTROL, &b) < 0)
2629
            return -ENOTSUP;
2630
        /* Linux gives only the lowest bits, and no way to know data
2631
           direction! For better compatibility set the fixed upper
2632
           bits. */
2633
        *(uint8_t *)arg = b | 0xc0;
2634
        break;
2635
    case CHR_IOCTL_PP_WRITE_CONTROL:
2636
        b = *(uint8_t *)arg;
2637
        if (ioctl(fd, PPWCONTROL, &b) < 0)
2638
            return -ENOTSUP;
2639
        break;
2640
    case CHR_IOCTL_PP_READ_STATUS:
2641
        if (ioctl(fd, PPRSTATUS, &b) < 0)
2642
            return -ENOTSUP;
2643
        *(uint8_t *)arg = b;
2644
        break;
2645
    case CHR_IOCTL_PP_EPP_READ_ADDR:
2646
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2647
            struct ParallelIOArg *parg = arg;
2648
            int n = read(fd, parg->buffer, parg->count);
2649
            if (n != parg->count) {
2650
                return -EIO;
2651
            }
2652
        }
2653
        break;
2654
    case CHR_IOCTL_PP_EPP_READ:
2655
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2656
            struct ParallelIOArg *parg = arg;
2657
            int n = read(fd, parg->buffer, parg->count);
2658
            if (n != parg->count) {
2659
                return -EIO;
2660
            }
2661
        }
2662
        break;
2663
    case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2664
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2665
            struct ParallelIOArg *parg = arg;
2666
            int n = write(fd, parg->buffer, parg->count);
2667
            if (n != parg->count) {
2668
                return -EIO;
2669
            }
2670
        }
2671
        break;
2672
    case CHR_IOCTL_PP_EPP_WRITE:
2673
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2674
            struct ParallelIOArg *parg = arg;
2675
            int n = write(fd, parg->buffer, parg->count);
2676
            if (n != parg->count) {
2677
                return -EIO;
2678
            }
2679
        }
2680
        break;
2681
    default:
2682
        return -ENOTSUP;
2683
    }
2684
    return 0;
2685
}
2686

    
2687
static void pp_close(CharDriverState *chr)
2688
{
2689
    ParallelCharDriver *drv = chr->opaque;
2690
    int fd = drv->fd;
2691

    
2692
    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2693
    ioctl(fd, PPRELEASE);
2694
    close(fd);
2695
    qemu_free(drv);
2696
}
2697

    
2698
static CharDriverState *qemu_chr_open_pp(const char *filename)
2699
{
2700
    CharDriverState *chr;
2701
    ParallelCharDriver *drv;
2702
    int fd;
2703

    
2704
    TFR(fd = open(filename, O_RDWR));
2705
    if (fd < 0)
2706
        return NULL;
2707

    
2708
    if (ioctl(fd, PPCLAIM) < 0) {
2709
        close(fd);
2710
        return NULL;
2711
    }
2712

    
2713
    drv = qemu_mallocz(sizeof(ParallelCharDriver));
2714
    if (!drv) {
2715
        close(fd);
2716
        return NULL;
2717
    }
2718
    drv->fd = fd;
2719
    drv->mode = IEEE1284_MODE_COMPAT;
2720

    
2721
    chr = qemu_mallocz(sizeof(CharDriverState));
2722
    if (!chr) {
2723
        qemu_free(drv);
2724
        close(fd);
2725
        return NULL;
2726
    }
2727
    chr->chr_write = null_chr_write;
2728
    chr->chr_ioctl = pp_ioctl;
2729
    chr->chr_close = pp_close;
2730
    chr->opaque = drv;
2731

    
2732
    qemu_chr_reset(chr);
2733

    
2734
    return chr;
2735
}
2736
#endif /* __linux__ */
2737

    
2738
#else /* _WIN32 */
2739

    
2740
typedef struct {
2741
    int max_size;
2742
    HANDLE hcom, hrecv, hsend;
2743
    OVERLAPPED orecv, osend;
2744
    BOOL fpipe;
2745
    DWORD len;
2746
} WinCharState;
2747

    
2748
#define NSENDBUF 2048
2749
#define NRECVBUF 2048
2750
#define MAXCONNECT 1
2751
#define NTIMEOUT 5000
2752

    
2753
static int win_chr_poll(void *opaque);
2754
static int win_chr_pipe_poll(void *opaque);
2755

    
2756
static void win_chr_close(CharDriverState *chr)
2757
{
2758
    WinCharState *s = chr->opaque;
2759

    
2760
    if (s->hsend) {
2761
        CloseHandle(s->hsend);
2762
        s->hsend = NULL;
2763
    }
2764
    if (s->hrecv) {
2765
        CloseHandle(s->hrecv);
2766
        s->hrecv = NULL;
2767
    }
2768
    if (s->hcom) {
2769
        CloseHandle(s->hcom);
2770
        s->hcom = NULL;
2771
    }
2772
    if (s->fpipe)
2773
        qemu_del_polling_cb(win_chr_pipe_poll, chr);
2774
    else
2775
        qemu_del_polling_cb(win_chr_poll, chr);
2776
}
2777

    
2778
static int win_chr_init(CharDriverState *chr, const char *filename)
2779
{
2780
    WinCharState *s = chr->opaque;
2781
    COMMCONFIG comcfg;
2782
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2783
    COMSTAT comstat;
2784
    DWORD size;
2785
    DWORD err;
2786

    
2787
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2788
    if (!s->hsend) {
2789
        fprintf(stderr, "Failed CreateEvent\n");
2790
        goto fail;
2791
    }
2792
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2793
    if (!s->hrecv) {
2794
        fprintf(stderr, "Failed CreateEvent\n");
2795
        goto fail;
2796
    }
2797

    
2798
    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2799
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2800
    if (s->hcom == INVALID_HANDLE_VALUE) {
2801
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2802
        s->hcom = NULL;
2803
        goto fail;
2804
    }
2805

    
2806
    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2807
        fprintf(stderr, "Failed SetupComm\n");
2808
        goto fail;
2809
    }
2810

    
2811
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2812
    size = sizeof(COMMCONFIG);
2813
    GetDefaultCommConfig(filename, &comcfg, &size);
2814
    comcfg.dcb.DCBlength = sizeof(DCB);
2815
    CommConfigDialog(filename, NULL, &comcfg);
2816

    
2817
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
2818
        fprintf(stderr, "Failed SetCommState\n");
2819
        goto fail;
2820
    }
2821

    
2822
    if (!SetCommMask(s->hcom, EV_ERR)) {
2823
        fprintf(stderr, "Failed SetCommMask\n");
2824
        goto fail;
2825
    }
2826

    
2827
    cto.ReadIntervalTimeout = MAXDWORD;
2828
    if (!SetCommTimeouts(s->hcom, &cto)) {
2829
        fprintf(stderr, "Failed SetCommTimeouts\n");
2830
        goto fail;
2831
    }
2832

    
2833
    if (!ClearCommError(s->hcom, &err, &comstat)) {
2834
        fprintf(stderr, "Failed ClearCommError\n");
2835
        goto fail;
2836
    }
2837
    qemu_add_polling_cb(win_chr_poll, chr);
2838
    return 0;
2839

    
2840
 fail:
2841
    win_chr_close(chr);
2842
    return -1;
2843
}
2844

    
2845
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2846
{
2847
    WinCharState *s = chr->opaque;
2848
    DWORD len, ret, size, err;
2849

    
2850
    len = len1;
2851
    ZeroMemory(&s->osend, sizeof(s->osend));
2852
    s->osend.hEvent = s->hsend;
2853
    while (len > 0) {
2854
        if (s->hsend)
2855
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2856
        else
2857
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
2858
        if (!ret) {
2859
            err = GetLastError();
2860
            if (err == ERROR_IO_PENDING) {
2861
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2862
                if (ret) {
2863
                    buf += size;
2864
                    len -= size;
2865
                } else {
2866
                    break;
2867
                }
2868
            } else {
2869
                break;
2870
            }
2871
        } else {
2872
            buf += size;
2873
            len -= size;
2874
        }
2875
    }
2876
    return len1 - len;
2877
}
2878

    
2879
static int win_chr_read_poll(CharDriverState *chr)
2880
{
2881
    WinCharState *s = chr->opaque;
2882

    
2883
    s->max_size = qemu_chr_can_read(chr);
2884
    return s->max_size;
2885
}
2886

    
2887
static void win_chr_readfile(CharDriverState *chr)
2888
{
2889
    WinCharState *s = chr->opaque;
2890
    int ret, err;
2891
    uint8_t buf[1024];
2892
    DWORD size;
2893

    
2894
    ZeroMemory(&s->orecv, sizeof(s->orecv));
2895
    s->orecv.hEvent = s->hrecv;
2896
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2897
    if (!ret) {
2898
        err = GetLastError();
2899
        if (err == ERROR_IO_PENDING) {
2900
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2901
        }
2902
    }
2903

    
2904
    if (size > 0) {
2905
        qemu_chr_read(chr, buf, size);
2906
    }
2907
}
2908

    
2909
static void win_chr_read(CharDriverState *chr)
2910
{
2911
    WinCharState *s = chr->opaque;
2912

    
2913
    if (s->len > s->max_size)
2914
        s->len = s->max_size;
2915
    if (s->len == 0)
2916
        return;
2917

    
2918
    win_chr_readfile(chr);
2919
}
2920

    
2921
static int win_chr_poll(void *opaque)
2922
{
2923
    CharDriverState *chr = opaque;
2924
    WinCharState *s = chr->opaque;
2925
    COMSTAT status;
2926
    DWORD comerr;
2927

    
2928
    ClearCommError(s->hcom, &comerr, &status);
2929
    if (status.cbInQue > 0) {
2930
        s->len = status.cbInQue;
2931
        win_chr_read_poll(chr);
2932
        win_chr_read(chr);
2933
        return 1;
2934
    }
2935
    return 0;
2936
}
2937

    
2938
static CharDriverState *qemu_chr_open_win(const char *filename)
2939
{
2940
    CharDriverState *chr;
2941
    WinCharState *s;
2942

    
2943
    chr = qemu_mallocz(sizeof(CharDriverState));
2944
    if (!chr)
2945
        return NULL;
2946
    s = qemu_mallocz(sizeof(WinCharState));
2947
    if (!s) {
2948
        free(chr);
2949
        return NULL;
2950
    }
2951
    chr->opaque = s;
2952
    chr->chr_write = win_chr_write;
2953
    chr->chr_close = win_chr_close;
2954

    
2955
    if (win_chr_init(chr, filename) < 0) {
2956
        free(s);
2957
        free(chr);
2958
        return NULL;
2959
    }
2960
    qemu_chr_reset(chr);
2961
    return chr;
2962
}
2963

    
2964
static int win_chr_pipe_poll(void *opaque)
2965
{
2966
    CharDriverState *chr = opaque;
2967
    WinCharState *s = chr->opaque;
2968
    DWORD size;
2969

    
2970
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2971
    if (size > 0) {
2972
        s->len = size;
2973
        win_chr_read_poll(chr);
2974
        win_chr_read(chr);
2975
        return 1;
2976
    }
2977
    return 0;
2978
}
2979

    
2980
static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2981
{
2982
    WinCharState *s = chr->opaque;
2983
    OVERLAPPED ov;
2984
    int ret;
2985
    DWORD size;
2986
    char openname[256];
2987

    
2988
    s->fpipe = TRUE;
2989

    
2990
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2991
    if (!s->hsend) {
2992
        fprintf(stderr, "Failed CreateEvent\n");
2993
        goto fail;
2994
    }
2995
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2996
    if (!s->hrecv) {
2997
        fprintf(stderr, "Failed CreateEvent\n");
2998
        goto fail;
2999
    }
3000

    
3001
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
3002
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
3003
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
3004
                              PIPE_WAIT,
3005
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
3006
    if (s->hcom == INVALID_HANDLE_VALUE) {
3007
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3008
        s->hcom = NULL;
3009
        goto fail;
3010
    }
3011

    
3012
    ZeroMemory(&ov, sizeof(ov));
3013
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3014
    ret = ConnectNamedPipe(s->hcom, &ov);
3015
    if (ret) {
3016
        fprintf(stderr, "Failed ConnectNamedPipe\n");
3017
        goto fail;
3018
    }
3019

    
3020
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
3021
    if (!ret) {
3022
        fprintf(stderr, "Failed GetOverlappedResult\n");
3023
        if (ov.hEvent) {
3024
            CloseHandle(ov.hEvent);
3025
            ov.hEvent = NULL;
3026
        }
3027
        goto fail;
3028
    }
3029

    
3030
    if (ov.hEvent) {
3031
        CloseHandle(ov.hEvent);
3032
        ov.hEvent = NULL;
3033
    }
3034
    qemu_add_polling_cb(win_chr_pipe_poll, chr);
3035
    return 0;
3036

    
3037
 fail:
3038
    win_chr_close(chr);
3039
    return -1;
3040
}
3041

    
3042

    
3043
static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
3044
{
3045
    CharDriverState *chr;
3046
    WinCharState *s;
3047

    
3048
    chr = qemu_mallocz(sizeof(CharDriverState));
3049
    if (!chr)
3050
        return NULL;
3051
    s = qemu_mallocz(sizeof(WinCharState));
3052
    if (!s) {
3053
        free(chr);
3054
        return NULL;
3055
    }
3056
    chr->opaque = s;
3057
    chr->chr_write = win_chr_write;
3058
    chr->chr_close = win_chr_close;
3059

    
3060
    if (win_chr_pipe_init(chr, filename) < 0) {
3061
        free(s);
3062
        free(chr);
3063
        return NULL;
3064
    }
3065
    qemu_chr_reset(chr);
3066
    return chr;
3067
}
3068

    
3069
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
3070
{
3071
    CharDriverState *chr;
3072
    WinCharState *s;
3073

    
3074
    chr = qemu_mallocz(sizeof(CharDriverState));
3075
    if (!chr)
3076
        return NULL;
3077
    s = qemu_mallocz(sizeof(WinCharState));
3078
    if (!s) {
3079
        free(chr);
3080
        return NULL;
3081
    }
3082
    s->hcom = fd_out;
3083
    chr->opaque = s;
3084
    chr->chr_write = win_chr_write;
3085
    qemu_chr_reset(chr);
3086
    return chr;
3087
}
3088

    
3089
static CharDriverState *qemu_chr_open_win_con(const char *filename)
3090
{
3091
    return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
3092
}
3093

    
3094
static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
3095
{
3096
    HANDLE fd_out;
3097

    
3098
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3099
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3100
    if (fd_out == INVALID_HANDLE_VALUE)
3101
        return NULL;
3102

    
3103
    return qemu_chr_open_win_file(fd_out);
3104
}
3105
#endif /* !_WIN32 */
3106

    
3107
/***********************************************************/
3108
/* UDP Net console */
3109

    
3110
typedef struct {
3111
    int fd;
3112
    struct sockaddr_in daddr;
3113
    uint8_t buf[1024];
3114
    int bufcnt;
3115
    int bufptr;
3116
    int max_size;
3117
} NetCharDriver;
3118

    
3119
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3120
{
3121
    NetCharDriver *s = chr->opaque;
3122

    
3123
    return sendto(s->fd, buf, len, 0,
3124
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
3125
}
3126

    
3127
static int udp_chr_read_poll(void *opaque)
3128
{
3129
    CharDriverState *chr = opaque;
3130
    NetCharDriver *s = chr->opaque;
3131

    
3132
    s->max_size = qemu_chr_can_read(chr);
3133

    
3134
    /* If there were any stray characters in the queue process them
3135
     * first
3136
     */
3137
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3138
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3139
        s->bufptr++;
3140
        s->max_size = qemu_chr_can_read(chr);
3141
    }
3142
    return s->max_size;
3143
}
3144

    
3145
static void udp_chr_read(void *opaque)
3146
{
3147
    CharDriverState *chr = opaque;
3148
    NetCharDriver *s = chr->opaque;
3149

    
3150
    if (s->max_size == 0)
3151
        return;
3152
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3153
    s->bufptr = s->bufcnt;
3154
    if (s->bufcnt <= 0)
3155
        return;
3156

    
3157
    s->bufptr = 0;
3158
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3159
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3160
        s->bufptr++;
3161
        s->max_size = qemu_chr_can_read(chr);
3162
    }
3163
}
3164

    
3165
static void udp_chr_update_read_handler(CharDriverState *chr)
3166
{
3167
    NetCharDriver *s = chr->opaque;
3168

    
3169
    if (s->fd >= 0) {
3170
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3171
                             udp_chr_read, NULL, chr);
3172
    }
3173
}
3174

    
3175
int parse_host_port(struct sockaddr_in *saddr, const char *str);
3176
#ifndef _WIN32
3177
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3178
#endif
3179
int parse_host_src_port(struct sockaddr_in *haddr,
3180
                        struct sockaddr_in *saddr,
3181
                        const char *str);
3182

    
3183
static CharDriverState *qemu_chr_open_udp(const char *def)
3184
{
3185
    CharDriverState *chr = NULL;
3186
    NetCharDriver *s = NULL;
3187
    int fd = -1;
3188
    struct sockaddr_in saddr;
3189

    
3190
    chr = qemu_mallocz(sizeof(CharDriverState));
3191
    if (!chr)
3192
        goto return_err;
3193
    s = qemu_mallocz(sizeof(NetCharDriver));
3194
    if (!s)
3195
        goto return_err;
3196

    
3197
    fd = socket(PF_INET, SOCK_DGRAM, 0);
3198
    if (fd < 0) {
3199
        perror("socket(PF_INET, SOCK_DGRAM)");
3200
        goto return_err;
3201
    }
3202

    
3203
    if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3204
        printf("Could not parse: %s\n", def);
3205
        goto return_err;
3206
    }
3207

    
3208
    if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3209
    {
3210
        perror("bind");
3211
        goto return_err;
3212
    }
3213

    
3214
    s->fd = fd;
3215
    s->bufcnt = 0;
3216
    s->bufptr = 0;
3217
    chr->opaque = s;
3218
    chr->chr_write = udp_chr_write;
3219
    chr->chr_update_read_handler = udp_chr_update_read_handler;
3220
    return chr;
3221

    
3222
return_err:
3223
    if (chr)
3224
        free(chr);
3225
    if (s)
3226
        free(s);
3227
    if (fd >= 0)
3228
        closesocket(fd);
3229
    return NULL;
3230
}
3231

    
3232
/***********************************************************/
3233
/* TCP Net console */
3234

    
3235
typedef struct {
3236
    int fd, listen_fd;
3237
    int connected;
3238
    int max_size;
3239
    int do_telnetopt;
3240
    int do_nodelay;
3241
    int is_unix;
3242
} TCPCharDriver;
3243

    
3244
static void tcp_chr_accept(void *opaque);
3245

    
3246
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3247
{
3248
    TCPCharDriver *s = chr->opaque;
3249
    if (s->connected) {
3250
        return send_all(s->fd, buf, len);
3251
    } else {
3252
        /* XXX: indicate an error ? */
3253
        return len;
3254
    }
3255
}
3256

    
3257
static int tcp_chr_read_poll(void *opaque)
3258
{
3259
    CharDriverState *chr = opaque;
3260
    TCPCharDriver *s = chr->opaque;
3261
    if (!s->connected)
3262
        return 0;
3263
    s->max_size = qemu_chr_can_read(chr);
3264
    return s->max_size;
3265
}
3266

    
3267
#define IAC 255
3268
#define IAC_BREAK 243
3269
static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3270
                                      TCPCharDriver *s,
3271
                                      uint8_t *buf, int *size)
3272
{
3273
    /* Handle any telnet client's basic IAC options to satisfy char by
3274
     * char mode with no echo.  All IAC options will be removed from
3275
     * the buf and the do_telnetopt variable will be used to track the
3276
     * state of the width of the IAC information.
3277
     *
3278
     * IAC commands come in sets of 3 bytes with the exception of the
3279
     * "IAC BREAK" command and the double IAC.
3280
     */
3281

    
3282
    int i;
3283
    int j = 0;
3284

    
3285
    for (i = 0; i < *size; i++) {
3286
        if (s->do_telnetopt > 1) {
3287
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3288
                /* Double IAC means send an IAC */
3289
                if (j != i)
3290
                    buf[j] = buf[i];
3291
                j++;
3292
                s->do_telnetopt = 1;
3293
            } else {
3294
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3295
                    /* Handle IAC break commands by sending a serial break */
3296
                    qemu_chr_event(chr, CHR_EVENT_BREAK);
3297
                    s->do_telnetopt++;
3298
                }
3299
                s->do_telnetopt++;
3300
            }
3301
            if (s->do_telnetopt >= 4) {
3302
                s->do_telnetopt = 1;
3303
            }
3304
        } else {
3305
            if ((unsigned char)buf[i] == IAC) {
3306
                s->do_telnetopt = 2;
3307
            } else {
3308
                if (j != i)
3309
                    buf[j] = buf[i];
3310
                j++;
3311
            }
3312
        }
3313
    }
3314
    *size = j;
3315
}
3316

    
3317
static void tcp_chr_read(void *opaque)
3318
{
3319
    CharDriverState *chr = opaque;
3320
    TCPCharDriver *s = chr->opaque;
3321
    uint8_t buf[1024];
3322
    int len, size;
3323

    
3324
    if (!s->connected || s->max_size <= 0)
3325
        return;
3326
    len = sizeof(buf);
3327
    if (len > s->max_size)
3328
        len = s->max_size;
3329
    size = recv(s->fd, buf, len, 0);
3330
    if (size == 0) {
3331
        /* connection closed */
3332
        s->connected = 0;
3333
        if (s->listen_fd >= 0) {
3334
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3335
        }
3336
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3337
        closesocket(s->fd);
3338
        s->fd = -1;
3339
    } else if (size > 0) {
3340
        if (s->do_telnetopt)
3341
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3342
        if (size > 0)
3343
            qemu_chr_read(chr, buf, size);
3344
    }
3345
}
3346

    
3347
static void tcp_chr_connect(void *opaque)
3348
{
3349
    CharDriverState *chr = opaque;
3350
    TCPCharDriver *s = chr->opaque;
3351

    
3352
    s->connected = 1;
3353
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3354
                         tcp_chr_read, NULL, chr);
3355
    qemu_chr_reset(chr);
3356
}
3357

    
3358
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3359
static void tcp_chr_telnet_init(int fd)
3360
{
3361
    char buf[3];
3362
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3363
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
3364
    send(fd, (char *)buf, 3, 0);
3365
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
3366
    send(fd, (char *)buf, 3, 0);
3367
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
3368
    send(fd, (char *)buf, 3, 0);
3369
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
3370
    send(fd, (char *)buf, 3, 0);
3371
}
3372

    
3373
static void socket_set_nodelay(int fd)
3374
{
3375
    int val = 1;
3376
    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3377
}
3378

    
3379
static void tcp_chr_accept(void *opaque)
3380
{
3381
    CharDriverState *chr = opaque;
3382
    TCPCharDriver *s = chr->opaque;
3383
    struct sockaddr_in saddr;
3384
#ifndef _WIN32
3385
    struct sockaddr_un uaddr;
3386
#endif
3387
    struct sockaddr *addr;
3388
    socklen_t len;
3389
    int fd;
3390

    
3391
    for(;;) {
3392
#ifndef _WIN32
3393
        if (s->is_unix) {
3394
            len = sizeof(uaddr);
3395
            addr = (struct sockaddr *)&uaddr;
3396
        } else
3397
#endif
3398
        {
3399
            len = sizeof(saddr);
3400
            addr = (struct sockaddr *)&saddr;
3401
        }
3402
        fd = accept(s->listen_fd, addr, &len);
3403
        if (fd < 0 && errno != EINTR) {
3404
            return;
3405
        } else if (fd >= 0) {
3406
            if (s->do_telnetopt)
3407
                tcp_chr_telnet_init(fd);
3408
            break;
3409
        }
3410
    }
3411
    socket_set_nonblock(fd);
3412
    if (s->do_nodelay)
3413
        socket_set_nodelay(fd);
3414
    s->fd = fd;
3415
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3416
    tcp_chr_connect(chr);
3417
}
3418

    
3419
static void tcp_chr_close(CharDriverState *chr)
3420
{
3421
    TCPCharDriver *s = chr->opaque;
3422
    if (s->fd >= 0)
3423
        closesocket(s->fd);
3424
    if (s->listen_fd >= 0)
3425
        closesocket(s->listen_fd);
3426
    qemu_free(s);
3427
}
3428

    
3429
static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3430
                                          int is_telnet,
3431
                                          int is_unix)
3432
{
3433
    CharDriverState *chr = NULL;
3434
    TCPCharDriver *s = NULL;
3435
    int fd = -1, ret, err, val;
3436
    int is_listen = 0;
3437
    int is_waitconnect = 1;
3438
    int do_nodelay = 0;
3439
    const char *ptr;
3440
    struct sockaddr_in saddr;
3441
#ifndef _WIN32
3442
    struct sockaddr_un uaddr;
3443
#endif
3444
    struct sockaddr *addr;
3445
    socklen_t addrlen;
3446

    
3447
#ifndef _WIN32
3448
    if (is_unix) {
3449
        addr = (struct sockaddr *)&uaddr;
3450
        addrlen = sizeof(uaddr);
3451
        if (parse_unix_path(&uaddr, host_str) < 0)
3452
            goto fail;
3453
    } else
3454
#endif
3455
    {
3456
        addr = (struct sockaddr *)&saddr;
3457
        addrlen = sizeof(saddr);
3458
        if (parse_host_port(&saddr, host_str) < 0)
3459
            goto fail;
3460
    }
3461

    
3462
    ptr = host_str;
3463
    while((ptr = strchr(ptr,','))) {
3464
        ptr++;
3465
        if (!strncmp(ptr,"server",6)) {
3466
            is_listen = 1;
3467
        } else if (!strncmp(ptr,"nowait",6)) {
3468
            is_waitconnect = 0;
3469
        } else if (!strncmp(ptr,"nodelay",6)) {
3470
            do_nodelay = 1;
3471
        } else {
3472
            printf("Unknown option: %s\n", ptr);
3473
            goto fail;
3474
        }
3475
    }
3476
    if (!is_listen)
3477
        is_waitconnect = 0;
3478

    
3479
    chr = qemu_mallocz(sizeof(CharDriverState));
3480
    if (!chr)
3481
        goto fail;
3482
    s = qemu_mallocz(sizeof(TCPCharDriver));
3483
    if (!s)
3484
        goto fail;
3485

    
3486
#ifndef _WIN32
3487
    if (is_unix)
3488
        fd = socket(PF_UNIX, SOCK_STREAM, 0);
3489
    else
3490
#endif
3491
        fd = socket(PF_INET, SOCK_STREAM, 0);
3492

    
3493
    if (fd < 0)
3494
        goto fail;
3495

    
3496
    if (!is_waitconnect)
3497
        socket_set_nonblock(fd);
3498

    
3499
    s->connected = 0;
3500
    s->fd = -1;
3501
    s->listen_fd = -1;
3502
    s->is_unix = is_unix;
3503
    s->do_nodelay = do_nodelay && !is_unix;
3504

    
3505
    chr->opaque = s;
3506
    chr->chr_write = tcp_chr_write;
3507
    chr->chr_close = tcp_chr_close;
3508

    
3509
    if (is_listen) {
3510
        /* allow fast reuse */
3511
#ifndef _WIN32
3512
        if (is_unix) {
3513
            char path[109];
3514
            pstrcpy(path, sizeof(path), uaddr.sun_path);
3515
            unlink(path);
3516
        } else
3517
#endif
3518
        {
3519
            val = 1;
3520
            setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3521
        }
3522

    
3523
        ret = bind(fd, addr, addrlen);
3524
        if (ret < 0)
3525
            goto fail;
3526

    
3527
        ret = listen(fd, 0);
3528
        if (ret < 0)
3529
            goto fail;
3530

    
3531
        s->listen_fd = fd;
3532
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3533
        if (is_telnet)
3534
            s->do_telnetopt = 1;
3535
    } else {
3536
        for(;;) {
3537
            ret = connect(fd, addr, addrlen);
3538
            if (ret < 0) {
3539
                err = socket_error();
3540
                if (err == EINTR || err == EWOULDBLOCK) {
3541
                } else if (err == EINPROGRESS) {
3542
                    break;
3543
#ifdef _WIN32
3544
                } else if (err == WSAEALREADY) {
3545
                    break;
3546
#endif
3547
                } else {
3548
                    goto fail;
3549
                }
3550
            } else {
3551
                s->connected = 1;
3552
                break;
3553
            }
3554
        }
3555
        s->fd = fd;
3556
        socket_set_nodelay(fd);
3557
        if (s->connected)
3558
            tcp_chr_connect(chr);
3559
        else
3560
            qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3561
    }
3562

    
3563
    if (is_listen && is_waitconnect) {
3564
        printf("QEMU waiting for connection on: %s\n", host_str);
3565
        tcp_chr_accept(chr);
3566
        socket_set_nonblock(s->listen_fd);
3567
    }
3568

    
3569
    return chr;
3570
 fail:
3571
    if (fd >= 0)
3572
        closesocket(fd);
3573
    qemu_free(s);
3574
    qemu_free(chr);
3575
    return NULL;
3576
}
3577

    
3578
CharDriverState *qemu_chr_open(const char *filename)
3579
{
3580
    const char *p;
3581

    
3582
    if (!strcmp(filename, "vc")) {
3583
        return text_console_init(&display_state, 0);
3584
    } else if (strstart(filename, "vc:", &p)) {
3585
        return text_console_init(&display_state, p);
3586
    } else if (!strcmp(filename, "null")) {
3587
        return qemu_chr_open_null();
3588
    } else
3589
    if (strstart(filename, "tcp:", &p)) {
3590
        return qemu_chr_open_tcp(p, 0, 0);
3591
    } else
3592
    if (strstart(filename, "telnet:", &p)) {
3593
        return qemu_chr_open_tcp(p, 1, 0);
3594
    } else
3595
    if (strstart(filename, "udp:", &p)) {
3596
        return qemu_chr_open_udp(p);
3597
    } else
3598
    if (strstart(filename, "mon:", &p)) {
3599
        CharDriverState *drv = qemu_chr_open(p);
3600
        if (drv) {
3601
            drv = qemu_chr_open_mux(drv);
3602
            monitor_init(drv, !nographic);
3603
            return drv;
3604
        }
3605
        printf("Unable to open driver: %s\n", p);
3606
        return 0;
3607
    } else
3608
#ifndef _WIN32
3609
    if (strstart(filename, "unix:", &p)) {
3610
        return qemu_chr_open_tcp(p, 0, 1);
3611
    } else if (strstart(filename, "file:", &p)) {
3612
        return qemu_chr_open_file_out(p);
3613
    } else if (strstart(filename, "pipe:", &p)) {
3614
        return qemu_chr_open_pipe(p);
3615
    } else if (!strcmp(filename, "pty")) {
3616
        return qemu_chr_open_pty();
3617
    } else if (!strcmp(filename, "stdio")) {
3618
        return qemu_chr_open_stdio();
3619
    } else
3620
#if defined(__linux__)
3621
    if (strstart(filename, "/dev/parport", NULL)) {
3622
        return qemu_chr_open_pp(filename);
3623
    } else
3624
#endif
3625
#if defined(__linux__) || defined(__sun__)
3626
    if (strstart(filename, "/dev/", NULL)) {
3627
        return qemu_chr_open_tty(filename);
3628
    } else
3629
#endif
3630
#else /* !_WIN32 */
3631
    if (strstart(filename, "COM", NULL)) {
3632
        return qemu_chr_open_win(filename);
3633
    } else
3634
    if (strstart(filename, "pipe:", &p)) {
3635
        return qemu_chr_open_win_pipe(p);
3636
    } else
3637
    if (strstart(filename, "con:", NULL)) {
3638
        return qemu_chr_open_win_con(filename);
3639
    } else
3640
    if (strstart(filename, "file:", &p)) {
3641
        return qemu_chr_open_win_file_out(p);
3642
    } else
3643
#endif
3644
#ifdef CONFIG_BRLAPI
3645
    if (!strcmp(filename, "braille")) {
3646
        return chr_baum_init();
3647
    } else
3648
#endif
3649
    {
3650
        return NULL;
3651
    }
3652
}
3653

    
3654
void qemu_chr_close(CharDriverState *chr)
3655
{
3656
    if (chr->chr_close)
3657
        chr->chr_close(chr);
3658
    qemu_free(chr);
3659
}
3660

    
3661
/***********************************************************/
3662
/* network device redirectors */
3663

    
3664
__attribute__ (( unused ))
3665
static void hex_dump(FILE *f, const uint8_t *buf, int size)
3666
{
3667
    int len, i, j, c;
3668

    
3669
    for(i=0;i<size;i+=16) {
3670
        len = size - i;
3671
        if (len > 16)
3672
            len = 16;
3673
        fprintf(f, "%08x ", i);
3674
        for(j=0;j<16;j++) {
3675
            if (j < len)
3676
                fprintf(f, " %02x", buf[i+j]);
3677
            else
3678
                fprintf(f, "   ");
3679
        }
3680
        fprintf(f, " ");
3681
        for(j=0;j<len;j++) {
3682
            c = buf[i+j];
3683
            if (c < ' ' || c > '~')
3684
                c = '.';
3685
            fprintf(f, "%c", c);
3686
        }
3687
        fprintf(f, "\n");
3688
    }
3689
}
3690

    
3691
static int parse_macaddr(uint8_t *macaddr, const char *p)
3692
{
3693
    int i;
3694
    char *last_char;
3695
    long int offset;
3696

    
3697
    errno = 0;
3698
    offset = strtol(p, &last_char, 0);    
3699
    if (0 == errno && '\0' == *last_char &&
3700
            offset >= 0 && offset <= 0xFFFFFF) {
3701
        macaddr[3] = (offset & 0xFF0000) >> 16;
3702
        macaddr[4] = (offset & 0xFF00) >> 8;
3703
        macaddr[5] = offset & 0xFF;
3704
        return 0;
3705
    } else {
3706
        for(i = 0; i < 6; i++) {
3707
            macaddr[i] = strtol(p, (char **)&p, 16);
3708
            if (i == 5) {
3709
                if (*p != '\0')
3710
                    return -1;
3711
            } else {
3712
                if (*p != ':' && *p != '-')
3713
                    return -1;
3714
                p++;
3715
            }
3716
        }
3717
        return 0;    
3718
    }
3719

    
3720
    return -1;
3721
}
3722

    
3723
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3724
{
3725
    const char *p, *p1;
3726
    int len;
3727
    p = *pp;
3728
    p1 = strchr(p, sep);
3729
    if (!p1)
3730
        return -1;
3731
    len = p1 - p;
3732
    p1++;
3733
    if (buf_size > 0) {
3734
        if (len > buf_size - 1)
3735
            len = buf_size - 1;
3736
        memcpy(buf, p, len);
3737
        buf[len] = '\0';
3738
    }
3739
    *pp = p1;
3740
    return 0;
3741
}
3742

    
3743
int parse_host_src_port(struct sockaddr_in *haddr,
3744
                        struct sockaddr_in *saddr,
3745
                        const char *input_str)
3746
{
3747
    char *str = strdup(input_str);
3748
    char *host_str = str;
3749
    char *src_str;
3750
    char *ptr;
3751

    
3752
    /*
3753
     * Chop off any extra arguments at the end of the string which
3754
     * would start with a comma, then fill in the src port information
3755
     * if it was provided else use the "any address" and "any port".
3756
     */
3757
    if ((ptr = strchr(str,',')))
3758
        *ptr = '\0';
3759

    
3760
    if ((src_str = strchr(input_str,'@'))) {
3761
        *src_str = '\0';
3762
        src_str++;
3763
    }
3764

    
3765
    if (parse_host_port(haddr, host_str) < 0)
3766
        goto fail;
3767

    
3768
    if (!src_str || *src_str == '\0')
3769
        src_str = ":0";
3770

    
3771
    if (parse_host_port(saddr, src_str) < 0)
3772
        goto fail;
3773

    
3774
    free(str);
3775
    return(0);
3776

    
3777
fail:
3778
    free(str);
3779
    return -1;
3780
}
3781

    
3782
int parse_host_port(struct sockaddr_in *saddr, const char *str)
3783
{
3784
    char buf[512];
3785
    struct hostent *he;
3786
    const char *p, *r;
3787
    int port;
3788

    
3789
    p = str;
3790
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3791
        return -1;
3792
    saddr->sin_family = AF_INET;
3793
    if (buf[0] == '\0') {
3794
        saddr->sin_addr.s_addr = 0;
3795
    } else {
3796
        if (isdigit(buf[0])) {
3797
            if (!inet_aton(buf, &saddr->sin_addr))
3798
                return -1;
3799
        } else {
3800
            if ((he = gethostbyname(buf)) == NULL)
3801
                return - 1;
3802
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
3803
        }
3804
    }
3805
    port = strtol(p, (char **)&r, 0);
3806
    if (r == p)
3807
        return -1;
3808
    saddr->sin_port = htons(port);
3809
    return 0;
3810
}
3811

    
3812
#ifndef _WIN32
3813
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3814
{
3815
    const char *p;
3816
    int len;
3817

    
3818
    len = MIN(108, strlen(str));
3819
    p = strchr(str, ',');
3820
    if (p)
3821
        len = MIN(len, p - str);
3822

    
3823
    memset(uaddr, 0, sizeof(*uaddr));
3824

    
3825
    uaddr->sun_family = AF_UNIX;
3826
    memcpy(uaddr->sun_path, str, len);
3827

    
3828
    return 0;
3829
}
3830
#endif
3831

    
3832
/* find or alloc a new VLAN */
3833
VLANState *qemu_find_vlan(int id)
3834
{
3835
    VLANState **pvlan, *vlan;
3836
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3837
        if (vlan->id == id)
3838
            return vlan;
3839
    }
3840
    vlan = qemu_mallocz(sizeof(VLANState));
3841
    if (!vlan)
3842
        return NULL;
3843
    vlan->id = id;
3844
    vlan->next = NULL;
3845
    pvlan = &first_vlan;
3846
    while (*pvlan != NULL)
3847
        pvlan = &(*pvlan)->next;
3848
    *pvlan = vlan;
3849
    return vlan;
3850
}
3851

    
3852
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3853
                                      IOReadHandler *fd_read,
3854
                                      IOCanRWHandler *fd_can_read,
3855
                                      void *opaque)
3856
{
3857
    VLANClientState *vc, **pvc;
3858
    vc = qemu_mallocz(sizeof(VLANClientState));
3859
    if (!vc)
3860
        return NULL;
3861
    vc->fd_read = fd_read;
3862
    vc->fd_can_read = fd_can_read;
3863
    vc->opaque = opaque;
3864
    vc->vlan = vlan;
3865

    
3866
    vc->next = NULL;
3867
    pvc = &vlan->first_client;
3868
    while (*pvc != NULL)
3869
        pvc = &(*pvc)->next;
3870
    *pvc = vc;
3871
    return vc;
3872
}
3873

    
3874
void qemu_del_vlan_client(VLANClientState *vc)
3875
{
3876
    VLANClientState **pvc = &vc->vlan->first_client;
3877

    
3878
    while (*pvc != NULL)
3879
        if (*pvc == vc) {
3880
            *pvc = vc->next;
3881
            free(vc);
3882
            break;
3883
        } else
3884
            pvc = &(*pvc)->next;
3885
}
3886

    
3887
int qemu_can_send_packet(VLANClientState *vc1)
3888
{
3889
    VLANState *vlan = vc1->vlan;
3890
    VLANClientState *vc;
3891

    
3892
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3893
        if (vc != vc1) {
3894
            if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
3895
                return 1;
3896
        }
3897
    }
3898
    return 0;
3899
}
3900

    
3901
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3902
{
3903
    VLANState *vlan = vc1->vlan;
3904
    VLANClientState *vc;
3905

    
3906
#if 0
3907
    printf("vlan %d send:\n", vlan->id);
3908
    hex_dump(stdout, buf, size);
3909
#endif
3910
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3911
        if (vc != vc1) {
3912
            vc->fd_read(vc->opaque, buf, size);
3913
        }
3914
    }
3915
}
3916

    
3917
#if defined(CONFIG_SLIRP)
3918

    
3919
/* slirp network adapter */
3920

    
3921
static int slirp_inited;
3922
static VLANClientState *slirp_vc;
3923

    
3924
int slirp_can_output(void)
3925
{
3926
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
3927
}
3928

    
3929
void slirp_output(const uint8_t *pkt, int pkt_len)
3930
{
3931
#if 0
3932
    printf("slirp output:\n");
3933
    hex_dump(stdout, pkt, pkt_len);
3934
#endif
3935
    if (!slirp_vc)
3936
        return;
3937
    qemu_send_packet(slirp_vc, pkt, pkt_len);
3938
}
3939

    
3940
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3941
{
3942
#if 0
3943
    printf("slirp input:\n");
3944
    hex_dump(stdout, buf, size);
3945
#endif
3946
    slirp_input(buf, size);
3947
}
3948

    
3949
static int net_slirp_init(VLANState *vlan)
3950
{
3951
    if (!slirp_inited) {
3952
        slirp_inited = 1;
3953
        slirp_init();
3954
    }
3955
    slirp_vc = qemu_new_vlan_client(vlan,
3956
                                    slirp_receive, NULL, NULL);
3957
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3958
    return 0;
3959
}
3960

    
3961
static void net_slirp_redir(const char *redir_str)
3962
{
3963
    int is_udp;
3964
    char buf[256], *r;
3965
    const char *p;
3966
    struct in_addr guest_addr;
3967
    int host_port, guest_port;
3968

    
3969
    if (!slirp_inited) {
3970
        slirp_inited = 1;
3971
        slirp_init();
3972
    }
3973

    
3974
    p = redir_str;
3975
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3976
        goto fail;
3977
    if (!strcmp(buf, "tcp")) {
3978
        is_udp = 0;
3979
    } else if (!strcmp(buf, "udp")) {
3980
        is_udp = 1;
3981
    } else {
3982
        goto fail;
3983
    }
3984

    
3985
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3986
        goto fail;
3987
    host_port = strtol(buf, &r, 0);
3988
    if (r == buf)
3989
        goto fail;
3990

    
3991
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3992
        goto fail;
3993
    if (buf[0] == '\0') {
3994
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
3995
    }
3996
    if (!inet_aton(buf, &guest_addr))
3997
        goto fail;
3998

    
3999
    guest_port = strtol(p, &r, 0);
4000
    if (r == p)
4001
        goto fail;
4002

    
4003
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
4004
        fprintf(stderr, "qemu: could not set up redirection\n");
4005
        exit(1);
4006
    }
4007
    return;
4008
 fail:
4009
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4010
    exit(1);
4011
}
4012

    
4013
#ifndef _WIN32
4014

    
4015
char smb_dir[1024];
4016

    
4017
static void erase_dir(char *dir_name)
4018
{
4019
    DIR *d;
4020
    struct dirent *de;
4021
    char filename[1024];
4022

    
4023
    /* erase all the files in the directory */
4024
    if ((d = opendir(dir_name)) != 0) {
4025
        for(;;) {
4026
            de = readdir(d);
4027
            if (!de)
4028
                break;
4029
            if (strcmp(de->d_name, ".") != 0 &&
4030
                strcmp(de->d_name, "..") != 0) {
4031
                snprintf(filename, sizeof(filename), "%s/%s",
4032
                         smb_dir, de->d_name);
4033
                if (unlink(filename) != 0)  /* is it a directory? */
4034
                    erase_dir(filename);
4035
            }
4036
        }
4037
        closedir(d);
4038
        rmdir(dir_name);
4039
    }
4040
}
4041

    
4042
/* automatic user mode samba server configuration */
4043
static void smb_exit(void)
4044
{
4045
    erase_dir(smb_dir);
4046
}
4047

    
4048
/* automatic user mode samba server configuration */
4049
static void net_slirp_smb(const char *exported_dir)
4050
{
4051
    char smb_conf[1024];
4052
    char smb_cmdline[1024];
4053
    FILE *f;
4054

    
4055
    if (!slirp_inited) {
4056
        slirp_inited = 1;
4057
        slirp_init();
4058
    }
4059

    
4060
    /* XXX: better tmp dir construction */
4061
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
4062
    if (mkdir(smb_dir, 0700) < 0) {
4063
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
4064
        exit(1);
4065
    }
4066
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
4067

    
4068
    f = fopen(smb_conf, "w");
4069
    if (!f) {
4070
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
4071
        exit(1);
4072
    }
4073
    fprintf(f,
4074
            "[global]\n"
4075
            "private dir=%s\n"
4076
            "smb ports=0\n"
4077
            "socket address=127.0.0.1\n"
4078
            "pid directory=%s\n"
4079
            "lock directory=%s\n"
4080
            "log file=%s/log.smbd\n"
4081
            "smb passwd file=%s/smbpasswd\n"
4082
            "security = share\n"
4083
            "[qemu]\n"
4084
            "path=%s\n"
4085
            "read only=no\n"
4086
            "guest ok=yes\n",
4087
            smb_dir,
4088
            smb_dir,
4089
            smb_dir,
4090
            smb_dir,
4091
            smb_dir,
4092
            exported_dir
4093
            );
4094
    fclose(f);
4095
    atexit(smb_exit);
4096

    
4097
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
4098
             SMBD_COMMAND, smb_conf);
4099

    
4100
    slirp_add_exec(0, smb_cmdline, 4, 139);
4101
}
4102

    
4103
#endif /* !defined(_WIN32) */
4104
void do_info_slirp(void)
4105
{
4106
    slirp_stats();
4107
}
4108

    
4109
#endif /* CONFIG_SLIRP */
4110

    
4111
#if !defined(_WIN32)
4112

    
4113
typedef struct TAPState {
4114
    VLANClientState *vc;
4115
    int fd;
4116
    char down_script[1024];
4117
} TAPState;
4118

    
4119
static void tap_receive(void *opaque, const uint8_t *buf, int size)
4120
{
4121
    TAPState *s = opaque;
4122
    int ret;
4123
    for(;;) {
4124
        ret = write(s->fd, buf, size);
4125
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
4126
        } else {
4127
            break;
4128
        }
4129
    }
4130
}
4131

    
4132
static void tap_send(void *opaque)
4133
{
4134
    TAPState *s = opaque;
4135
    uint8_t buf[4096];
4136
    int size;
4137

    
4138
#ifdef __sun__
4139
    struct strbuf sbuf;
4140
    int f = 0;
4141
    sbuf.maxlen = sizeof(buf);
4142
    sbuf.buf = buf;
4143
    size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
4144
#else
4145
    size = read(s->fd, buf, sizeof(buf));
4146
#endif
4147
    if (size > 0) {
4148
        qemu_send_packet(s->vc, buf, size);
4149
    }
4150
}
4151

    
4152
/* fd support */
4153

    
4154
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
4155
{
4156
    TAPState *s;
4157

    
4158
    s = qemu_mallocz(sizeof(TAPState));
4159
    if (!s)
4160
        return NULL;
4161
    s->fd = fd;
4162
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
4163
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
4164
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4165
    return s;
4166
}
4167

    
4168
#if defined (_BSD) || defined (__FreeBSD_kernel__)
4169
static int tap_open(char *ifname, int ifname_size)
4170
{
4171
    int fd;
4172
    char *dev;
4173
    struct stat s;
4174

    
4175
    TFR(fd = open("/dev/tap", O_RDWR));
4176
    if (fd < 0) {
4177
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4178
        return -1;
4179
    }
4180

    
4181
    fstat(fd, &s);
4182
    dev = devname(s.st_rdev, S_IFCHR);
4183
    pstrcpy(ifname, ifname_size, dev);
4184

    
4185
    fcntl(fd, F_SETFL, O_NONBLOCK);
4186
    return fd;
4187
}
4188
#elif defined(__sun__)
4189
#define TUNNEWPPA       (('T'<<16) | 0x0001)
4190
/*
4191
 * Allocate TAP device, returns opened fd.
4192
 * Stores dev name in the first arg(must be large enough).
4193
 */
4194
int tap_alloc(char *dev)
4195
{
4196
    int tap_fd, if_fd, ppa = -1;
4197
    static int ip_fd = 0;
4198
    char *ptr;
4199

    
4200
    static int arp_fd = 0;
4201
    int ip_muxid, arp_muxid;
4202
    struct strioctl  strioc_if, strioc_ppa;
4203
    int link_type = I_PLINK;;
4204
    struct lifreq ifr;
4205
    char actual_name[32] = "";
4206

    
4207
    memset(&ifr, 0x0, sizeof(ifr));
4208

    
4209
    if( *dev ){
4210
       ptr = dev;
4211
       while( *ptr && !isdigit((int)*ptr) ) ptr++;
4212
       ppa = atoi(ptr);
4213
    }
4214

    
4215
    /* Check if IP device was opened */
4216
    if( ip_fd )
4217
       close(ip_fd);
4218

    
4219
    TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4220
    if (ip_fd < 0) {
4221
       syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4222
       return -1;
4223
    }
4224

    
4225
    TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4226
    if (tap_fd < 0) {
4227
       syslog(LOG_ERR, "Can't open /dev/tap");
4228
       return -1;
4229
    }
4230

    
4231
    /* Assign a new PPA and get its unit number. */
4232
    strioc_ppa.ic_cmd = TUNNEWPPA;
4233
    strioc_ppa.ic_timout = 0;
4234
    strioc_ppa.ic_len = sizeof(ppa);
4235
    strioc_ppa.ic_dp = (char *)&ppa;
4236
    if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4237
       syslog (LOG_ERR, "Can't assign new interface");
4238

    
4239
    TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4240
    if (if_fd < 0) {
4241
       syslog(LOG_ERR, "Can't open /dev/tap (2)");
4242
       return -1;
4243
    }
4244
    if(ioctl(if_fd, I_PUSH, "ip") < 0){
4245
       syslog(LOG_ERR, "Can't push IP module");
4246
       return -1;
4247
    }
4248

    
4249
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4250
        syslog(LOG_ERR, "Can't get flags\n");
4251

    
4252
    snprintf (actual_name, 32, "tap%d", ppa);
4253
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4254

    
4255
    ifr.lifr_ppa = ppa;
4256
    /* Assign ppa according to the unit number returned by tun device */
4257

    
4258
    if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4259
        syslog (LOG_ERR, "Can't set PPA %d", ppa);
4260
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4261
        syslog (LOG_ERR, "Can't get flags\n");
4262
    /* Push arp module to if_fd */
4263
    if (ioctl (if_fd, I_PUSH, "arp") < 0)
4264
        syslog (LOG_ERR, "Can't push ARP module (2)");
4265

    
4266
    /* Push arp module to ip_fd */
4267
    if (ioctl (ip_fd, I_POP, NULL) < 0)
4268
        syslog (LOG_ERR, "I_POP failed\n");
4269
    if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4270
        syslog (LOG_ERR, "Can't push ARP module (3)\n");
4271
    /* Open arp_fd */
4272
    TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4273
    if (arp_fd < 0)
4274
       syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4275

    
4276
    /* Set ifname to arp */
4277
    strioc_if.ic_cmd = SIOCSLIFNAME;
4278
    strioc_if.ic_timout = 0;
4279
    strioc_if.ic_len = sizeof(ifr);
4280
    strioc_if.ic_dp = (char *)&ifr;
4281
    if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4282
        syslog (LOG_ERR, "Can't set ifname to arp\n");
4283
    }
4284

    
4285
    if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4286
       syslog(LOG_ERR, "Can't link TAP device to IP");
4287
       return -1;
4288
    }
4289

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

    
4293
    close (if_fd);
4294

    
4295
    memset(&ifr, 0x0, sizeof(ifr));
4296
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4297
    ifr.lifr_ip_muxid  = ip_muxid;
4298
    ifr.lifr_arp_muxid = arp_muxid;
4299

    
4300
    if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4301
    {
4302
      ioctl (ip_fd, I_PUNLINK , arp_muxid);
4303
      ioctl (ip_fd, I_PUNLINK, ip_muxid);
4304
      syslog (LOG_ERR, "Can't set multiplexor id");
4305
    }
4306

    
4307
    sprintf(dev, "tap%d", ppa);
4308
    return tap_fd;
4309
}
4310

    
4311
static int tap_open(char *ifname, int ifname_size)
4312
{
4313
    char  dev[10]="";
4314
    int fd;
4315
    if( (fd = tap_alloc(dev)) < 0 ){
4316
       fprintf(stderr, "Cannot allocate TAP device\n");
4317
       return -1;
4318
    }
4319
    pstrcpy(ifname, ifname_size, dev);
4320
    fcntl(fd, F_SETFL, O_NONBLOCK);
4321
    return fd;
4322
}
4323
#else
4324
static int tap_open(char *ifname, int ifname_size)
4325
{
4326
    struct ifreq ifr;
4327
    int fd, ret;
4328

    
4329
    TFR(fd = open("/dev/net/tun", O_RDWR));
4330
    if (fd < 0) {
4331
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4332
        return -1;
4333
    }
4334
    memset(&ifr, 0, sizeof(ifr));
4335
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4336
    if (ifname[0] != '\0')
4337
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4338
    else
4339
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4340
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4341
    if (ret != 0) {
4342
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4343
        close(fd);
4344
        return -1;
4345
    }
4346
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
4347
    fcntl(fd, F_SETFL, O_NONBLOCK);
4348
    return fd;
4349
}
4350
#endif
4351

    
4352
static int launch_script(const char *setup_script, const char *ifname, int fd)
4353
{
4354
    int pid, status;
4355
    char *args[3];
4356
    char **parg;
4357

    
4358
        /* try to launch network script */
4359
        pid = fork();
4360
        if (pid >= 0) {
4361
            if (pid == 0) {
4362
                int open_max = sysconf (_SC_OPEN_MAX), i;
4363
                for (i = 0; i < open_max; i++)
4364
                    if (i != STDIN_FILENO &&
4365
                        i != STDOUT_FILENO &&
4366
                        i != STDERR_FILENO &&
4367
                        i != fd)
4368
                        close(i);
4369

    
4370
                parg = args;
4371
                *parg++ = (char *)setup_script;
4372
                *parg++ = (char *)ifname;
4373
                *parg++ = NULL;
4374
                execv(setup_script, args);
4375
                _exit(1);
4376
            }
4377
            while (waitpid(pid, &status, 0) != pid);
4378
            if (!WIFEXITED(status) ||
4379
                WEXITSTATUS(status) != 0) {
4380
                fprintf(stderr, "%s: could not launch network script\n",
4381
                        setup_script);
4382
                return -1;
4383
            }
4384
        }
4385
    return 0;
4386
}
4387

    
4388
static int net_tap_init(VLANState *vlan, const char *ifname1,
4389
                        const char *setup_script, const char *down_script)
4390
{
4391
    TAPState *s;
4392
    int fd;
4393
    char ifname[128];
4394

    
4395
    if (ifname1 != NULL)
4396
        pstrcpy(ifname, sizeof(ifname), ifname1);
4397
    else
4398
        ifname[0] = '\0';
4399
    TFR(fd = tap_open(ifname, sizeof(ifname)));
4400
    if (fd < 0)
4401
        return -1;
4402

    
4403
    if (!setup_script || !strcmp(setup_script, "no"))
4404
        setup_script = "";
4405
    if (setup_script[0] != '\0') {
4406
        if (launch_script(setup_script, ifname, fd))
4407
            return -1;
4408
    }
4409
    s = net_tap_fd_init(vlan, fd);
4410
    if (!s)
4411
        return -1;
4412
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4413
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
4414
    if (down_script && strcmp(down_script, "no"))
4415
        snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4416
    return 0;
4417
}
4418

    
4419
#endif /* !_WIN32 */
4420

    
4421
/* network connection */
4422
typedef struct NetSocketState {
4423
    VLANClientState *vc;
4424
    int fd;
4425
    int state; /* 0 = getting length, 1 = getting data */
4426
    int index;
4427
    int packet_len;
4428
    uint8_t buf[4096];
4429
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4430
} NetSocketState;
4431

    
4432
typedef struct NetSocketListenState {
4433
    VLANState *vlan;
4434
    int fd;
4435
} NetSocketListenState;
4436

    
4437
/* XXX: we consider we can send the whole packet without blocking */
4438
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4439
{
4440
    NetSocketState *s = opaque;
4441
    uint32_t len;
4442
    len = htonl(size);
4443

    
4444
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4445
    send_all(s->fd, buf, size);
4446
}
4447

    
4448
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4449
{
4450
    NetSocketState *s = opaque;
4451
    sendto(s->fd, buf, size, 0,
4452
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4453
}
4454

    
4455
static void net_socket_send(void *opaque)
4456
{
4457
    NetSocketState *s = opaque;
4458
    int l, size, err;
4459
    uint8_t buf1[4096];
4460
    const uint8_t *buf;
4461

    
4462
    size = recv(s->fd, buf1, sizeof(buf1), 0);
4463
    if (size < 0) {
4464
        err = socket_error();
4465
        if (err != EWOULDBLOCK)
4466
            goto eoc;
4467
    } else if (size == 0) {
4468
        /* end of connection */
4469
    eoc:
4470
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4471
        closesocket(s->fd);
4472
        return;
4473
    }
4474
    buf = buf1;
4475
    while (size > 0) {
4476
        /* reassemble a packet from the network */
4477
        switch(s->state) {
4478
        case 0:
4479
            l = 4 - s->index;
4480
            if (l > size)
4481
                l = size;
4482
            memcpy(s->buf + s->index, buf, l);
4483
            buf += l;
4484
            size -= l;
4485
            s->index += l;
4486
            if (s->index == 4) {
4487
                /* got length */
4488
                s->packet_len = ntohl(*(uint32_t *)s->buf);
4489
                s->index = 0;
4490
                s->state = 1;
4491
            }
4492
            break;
4493
        case 1:
4494
            l = s->packet_len - s->index;
4495
            if (l > size)
4496
                l = size;
4497
            memcpy(s->buf + s->index, buf, l);
4498
            s->index += l;
4499
            buf += l;
4500
            size -= l;
4501
            if (s->index >= s->packet_len) {
4502
                qemu_send_packet(s->vc, s->buf, s->packet_len);
4503
                s->index = 0;
4504
                s->state = 0;
4505
            }
4506
            break;
4507
        }
4508
    }
4509
}
4510

    
4511
static void net_socket_send_dgram(void *opaque)
4512
{
4513
    NetSocketState *s = opaque;
4514
    int size;
4515

    
4516
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4517
    if (size < 0)
4518
        return;
4519
    if (size == 0) {
4520
        /* end of connection */
4521
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4522
        return;
4523
    }
4524
    qemu_send_packet(s->vc, s->buf, size);
4525
}
4526

    
4527
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4528
{
4529
    struct ip_mreq imr;
4530
    int fd;
4531
    int val, ret;
4532
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4533
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4534
                inet_ntoa(mcastaddr->sin_addr),
4535
                (int)ntohl(mcastaddr->sin_addr.s_addr));
4536
        return -1;
4537

    
4538
    }
4539
    fd = socket(PF_INET, SOCK_DGRAM, 0);
4540
    if (fd < 0) {
4541
        perror("socket(PF_INET, SOCK_DGRAM)");
4542
        return -1;
4543
    }
4544

    
4545
    val = 1;
4546
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4547
                   (const char *)&val, sizeof(val));
4548
    if (ret < 0) {
4549
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4550
        goto fail;
4551
    }
4552

    
4553
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4554
    if (ret < 0) {
4555
        perror("bind");
4556
        goto fail;
4557
    }
4558

    
4559
    /* Add host to multicast group */
4560
    imr.imr_multiaddr = mcastaddr->sin_addr;
4561
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
4562

    
4563
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4564
                     (const char *)&imr, sizeof(struct ip_mreq));
4565
    if (ret < 0) {
4566
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
4567
        goto fail;
4568
    }
4569

    
4570
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4571
    val = 1;
4572
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4573
                   (const char *)&val, sizeof(val));
4574
    if (ret < 0) {
4575
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4576
        goto fail;
4577
    }
4578

    
4579
    socket_set_nonblock(fd);
4580
    return fd;
4581
fail:
4582
    if (fd >= 0)
4583
        closesocket(fd);
4584
    return -1;
4585
}
4586

    
4587
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4588
                                          int is_connected)
4589
{
4590
    struct sockaddr_in saddr;
4591
    int newfd;
4592
    socklen_t saddr_len;
4593
    NetSocketState *s;
4594

    
4595
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4596
     * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4597
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
4598
     */
4599

    
4600
    if (is_connected) {
4601
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4602
            /* must be bound */
4603
            if (saddr.sin_addr.s_addr==0) {
4604
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4605
                        fd);
4606
                return NULL;
4607
            }
4608
            /* clone dgram socket */
4609
            newfd = net_socket_mcast_create(&saddr);
4610
            if (newfd < 0) {
4611
                /* error already reported by net_socket_mcast_create() */
4612
                close(fd);
4613
                return NULL;
4614
            }
4615
            /* clone newfd to fd, close newfd */
4616
            dup2(newfd, fd);
4617
            close(newfd);
4618

    
4619
        } else {
4620
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4621
                    fd, strerror(errno));
4622
            return NULL;
4623
        }
4624
    }
4625

    
4626
    s = qemu_mallocz(sizeof(NetSocketState));
4627
    if (!s)
4628
        return NULL;
4629
    s->fd = fd;
4630

    
4631
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4632
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4633

    
4634
    /* mcast: save bound address as dst */
4635
    if (is_connected) s->dgram_dst=saddr;
4636

    
4637
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4638
            "socket: fd=%d (%s mcast=%s:%d)",
4639
            fd, is_connected? "cloned" : "",
4640
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4641
    return s;
4642
}
4643

    
4644
static void net_socket_connect(void *opaque)
4645
{
4646
    NetSocketState *s = opaque;
4647
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4648
}
4649

    
4650
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4651
                                          int is_connected)
4652
{
4653
    NetSocketState *s;
4654
    s = qemu_mallocz(sizeof(NetSocketState));
4655
    if (!s)
4656
        return NULL;
4657
    s->fd = fd;
4658
    s->vc = qemu_new_vlan_client(vlan,
4659
                                 net_socket_receive, NULL, s);
4660
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4661
             "socket: fd=%d", fd);
4662
    if (is_connected) {
4663
        net_socket_connect(s);
4664
    } else {
4665
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4666
    }
4667
    return s;
4668
}
4669

    
4670
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4671
                                          int is_connected)
4672
{
4673
    int so_type=-1, optlen=sizeof(so_type);
4674

    
4675
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4676
        (socklen_t *)&optlen)< 0) {
4677
        fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4678
        return NULL;
4679
    }
4680
    switch(so_type) {
4681
    case SOCK_DGRAM:
4682
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
4683
    case SOCK_STREAM:
4684
        return net_socket_fd_init_stream(vlan, fd, is_connected);
4685
    default:
4686
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4687
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4688
        return net_socket_fd_init_stream(vlan, fd, is_connected);
4689
    }
4690
    return NULL;
4691
}
4692

    
4693
static void net_socket_accept(void *opaque)
4694
{
4695
    NetSocketListenState *s = opaque;
4696
    NetSocketState *s1;
4697
    struct sockaddr_in saddr;
4698
    socklen_t len;
4699
    int fd;
4700

    
4701
    for(;;) {
4702
        len = sizeof(saddr);
4703
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4704
        if (fd < 0 && errno != EINTR) {
4705
            return;
4706
        } else if (fd >= 0) {
4707
            break;
4708
        }
4709
    }
4710
    s1 = net_socket_fd_init(s->vlan, fd, 1);
4711
    if (!s1) {
4712
        closesocket(fd);
4713
    } else {
4714
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4715
                 "socket: connection from %s:%d",
4716
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4717
    }
4718
}
4719

    
4720
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4721
{
4722
    NetSocketListenState *s;
4723
    int fd, val, ret;
4724
    struct sockaddr_in saddr;
4725

    
4726
    if (parse_host_port(&saddr, host_str) < 0)
4727
        return -1;
4728

    
4729
    s = qemu_mallocz(sizeof(NetSocketListenState));
4730
    if (!s)
4731
        return -1;
4732

    
4733
    fd = socket(PF_INET, SOCK_STREAM, 0);
4734
    if (fd < 0) {
4735
        perror("socket");
4736
        return -1;
4737
    }
4738
    socket_set_nonblock(fd);
4739

    
4740
    /* allow fast reuse */
4741
    val = 1;
4742
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4743

    
4744
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4745
    if (ret < 0) {
4746
        perror("bind");
4747
        return -1;
4748
    }
4749
    ret = listen(fd, 0);
4750
    if (ret < 0) {
4751
        perror("listen");
4752
        return -1;
4753
    }
4754
    s->vlan = vlan;
4755
    s->fd = fd;
4756
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4757
    return 0;
4758
}
4759

    
4760
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4761
{
4762
    NetSocketState *s;
4763
    int fd, connected, ret, err;
4764
    struct sockaddr_in saddr;
4765

    
4766
    if (parse_host_port(&saddr, host_str) < 0)
4767
        return -1;
4768

    
4769
    fd = socket(PF_INET, SOCK_STREAM, 0);
4770
    if (fd < 0) {
4771
        perror("socket");
4772
        return -1;
4773
    }
4774
    socket_set_nonblock(fd);
4775

    
4776
    connected = 0;
4777
    for(;;) {
4778
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4779
        if (ret < 0) {
4780
            err = socket_error();
4781
            if (err == EINTR || err == EWOULDBLOCK) {
4782
            } else if (err == EINPROGRESS) {
4783
                break;
4784
#ifdef _WIN32
4785
            } else if (err == WSAEALREADY) {
4786
                break;
4787
#endif
4788
            } else {
4789
                perror("connect");
4790
                closesocket(fd);
4791
                return -1;
4792
            }
4793
        } else {
4794
            connected = 1;
4795
            break;
4796
        }
4797
    }
4798
    s = net_socket_fd_init(vlan, fd, connected);
4799
    if (!s)
4800
        return -1;
4801
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4802
             "socket: connect to %s:%d",
4803
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4804
    return 0;
4805
}
4806

    
4807
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4808
{
4809
    NetSocketState *s;
4810
    int fd;
4811
    struct sockaddr_in saddr;
4812

    
4813
    if (parse_host_port(&saddr, host_str) < 0)
4814
        return -1;
4815

    
4816

    
4817
    fd = net_socket_mcast_create(&saddr);
4818
    if (fd < 0)
4819
        return -1;
4820

    
4821
    s = net_socket_fd_init(vlan, fd, 0);
4822
    if (!s)
4823
        return -1;
4824

    
4825
    s->dgram_dst = saddr;
4826

    
4827
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4828
             "socket: mcast=%s:%d",
4829
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4830
    return 0;
4831

    
4832
}
4833

    
4834
static const char *get_opt_name(char *buf, int buf_size, const char *p)
4835
{
4836
    char *q;
4837

    
4838
    q = buf;
4839
    while (*p != '\0' && *p != '=') {
4840
        if (q && (q - buf) < buf_size - 1)
4841
            *q++ = *p;
4842
        p++;
4843
    }
4844
    if (q)
4845
        *q = '\0';
4846

    
4847
    return p;
4848
}
4849

    
4850
static const char *get_opt_value(char *buf, int buf_size, const char *p)
4851
{
4852
    char *q;
4853

    
4854
    q = buf;
4855
    while (*p != '\0') {
4856
        if (*p == ',') {
4857
            if (*(p + 1) != ',')
4858
                break;
4859
            p++;
4860
        }
4861
        if (q && (q - buf) < buf_size - 1)
4862
            *q++ = *p;
4863
        p++;
4864
    }
4865
    if (q)
4866
        *q = '\0';
4867

    
4868
    return p;
4869
}
4870

    
4871
static int get_param_value(char *buf, int buf_size,
4872
                           const char *tag, const char *str)
4873
{
4874
    const char *p;
4875
    char option[128];
4876

    
4877
    p = str;
4878
    for(;;) {
4879
        p = get_opt_name(option, sizeof(option), p);
4880
        if (*p != '=')
4881
            break;
4882
        p++;
4883
        if (!strcmp(tag, option)) {
4884
            (void)get_opt_value(buf, buf_size, p);
4885
            return strlen(buf);
4886
        } else {
4887
            p = get_opt_value(NULL, 0, p);
4888
        }
4889
        if (*p != ',')
4890
            break;
4891
        p++;
4892
    }
4893
    return 0;
4894
}
4895

    
4896
static int check_params(char *buf, int buf_size,
4897
                        char **params, const char *str)
4898
{
4899
    const char *p;
4900
    int i;
4901

    
4902
    p = str;
4903
    for(;;) {
4904
        p = get_opt_name(buf, buf_size, p);
4905
        if (*p != '=')
4906
            return -1;
4907
        p++;
4908
        for(i = 0; params[i] != NULL; i++)
4909
            if (!strcmp(params[i], buf))
4910
                break;
4911
        if (params[i] == NULL)
4912
            return -1;
4913
        p = get_opt_value(NULL, 0, p);
4914
        if (*p != ',')
4915
            break;
4916
        p++;
4917
    }
4918
    return 0;
4919
}
4920

    
4921

    
4922
static int net_client_init(const char *str)
4923
{
4924
    const char *p;
4925
    char *q;
4926
    char device[64];
4927
    char buf[1024];
4928
    int vlan_id, ret;
4929
    VLANState *vlan;
4930

    
4931
    p = str;
4932
    q = device;
4933
    while (*p != '\0' && *p != ',') {
4934
        if ((q - device) < sizeof(device) - 1)
4935
            *q++ = *p;
4936
        p++;
4937
    }
4938
    *q = '\0';
4939
    if (*p == ',')
4940
        p++;
4941
    vlan_id = 0;
4942
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4943
        vlan_id = strtol(buf, NULL, 0);
4944
    }
4945
    vlan = qemu_find_vlan(vlan_id);
4946
    if (!vlan) {
4947
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4948
        return -1;
4949
    }
4950
    if (!strcmp(device, "nic")) {
4951
        NICInfo *nd;
4952
        uint8_t *macaddr;
4953

    
4954
        if (nb_nics >= MAX_NICS) {
4955
            fprintf(stderr, "Too Many NICs\n");
4956
            return -1;
4957
        }
4958
        nd = &nd_table[nb_nics];
4959
        macaddr = nd->macaddr;
4960
        macaddr[0] = 0x52;
4961
        macaddr[1] = 0x54;
4962
        macaddr[2] = 0x00;
4963
        macaddr[3] = 0x12;
4964
        macaddr[4] = 0x34;
4965
        macaddr[5] = 0x56 + nb_nics;
4966

    
4967
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4968
            if (parse_macaddr(macaddr, buf) < 0) {
4969
                fprintf(stderr, "invalid syntax for ethernet address\n");
4970
                return -1;
4971
            }
4972
        }
4973
        if (get_param_value(buf, sizeof(buf), "model", p)) {
4974
            nd->model = strdup(buf);
4975
        }
4976
        nd->vlan = vlan;
4977
        nb_nics++;
4978
        vlan->nb_guest_devs++;
4979
        ret = 0;
4980
    } else
4981
    if (!strcmp(device, "none")) {
4982
        /* does nothing. It is needed to signal that no network cards
4983
           are wanted */
4984
        ret = 0;
4985
    } else
4986
#ifdef CONFIG_SLIRP
4987
    if (!strcmp(device, "user")) {
4988
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4989
            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4990
        }
4991
        vlan->nb_host_devs++;
4992
        ret = net_slirp_init(vlan);
4993
    } else
4994
#endif
4995
#ifdef _WIN32
4996
    if (!strcmp(device, "tap")) {
4997
        char ifname[64];
4998
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4999
            fprintf(stderr, "tap: no interface name\n");
5000
            return -1;
5001
        }
5002
        vlan->nb_host_devs++;
5003
        ret = tap_win32_init(vlan, ifname);
5004
    } else
5005
#else
5006
    if (!strcmp(device, "tap")) {
5007
        char ifname[64];
5008
        char setup_script[1024], down_script[1024];
5009
        int fd;
5010
        vlan->nb_host_devs++;
5011
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5012
            fd = strtol(buf, NULL, 0);
5013
            fcntl(fd, F_SETFL, O_NONBLOCK);
5014
            ret = -1;
5015
            if (net_tap_fd_init(vlan, fd))
5016
                ret = 0;
5017
        } else {
5018
            if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5019
                ifname[0] = '\0';
5020
            }
5021
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
5022
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
5023
            }
5024
            if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
5025
                pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
5026
            }
5027
            ret = net_tap_init(vlan, ifname, setup_script, down_script);
5028
        }
5029
    } else
5030
#endif
5031
    if (!strcmp(device, "socket")) {
5032
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5033
            int fd;
5034
            fd = strtol(buf, NULL, 0);
5035
            ret = -1;
5036
            if (net_socket_fd_init(vlan, fd, 1))
5037
                ret = 0;
5038
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
5039
            ret = net_socket_listen_init(vlan, buf);
5040
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
5041
            ret = net_socket_connect_init(vlan, buf);
5042
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
5043
            ret = net_socket_mcast_init(vlan, buf);
5044
        } else {
5045
            fprintf(stderr, "Unknown socket options: %s\n", p);
5046
            return -1;
5047
        }
5048
        vlan->nb_host_devs++;
5049
    } else
5050
    {
5051
        fprintf(stderr, "Unknown network device: %s\n", device);
5052
        return -1;
5053
    }
5054
    if (ret < 0) {
5055
        fprintf(stderr, "Could not initialize device '%s'\n", device);
5056
    }
5057

    
5058
    return ret;
5059
}
5060

    
5061
void do_info_network(void)
5062
{
5063
    VLANState *vlan;
5064
    VLANClientState *vc;
5065

    
5066
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
5067
        term_printf("VLAN %d devices:\n", vlan->id);
5068
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
5069
            term_printf("  %s\n", vc->info_str);
5070
    }
5071
}
5072

    
5073
#define HD_ALIAS "index=%d,media=disk"
5074
#ifdef TARGET_PPC
5075
#define CDROM_ALIAS "index=1,media=cdrom"
5076
#else
5077
#define CDROM_ALIAS "index=2,media=cdrom"
5078
#endif
5079
#define FD_ALIAS "index=%d,if=floppy"
5080
#define PFLASH_ALIAS "if=pflash"
5081
#define MTD_ALIAS "if=mtd"
5082
#define SD_ALIAS "index=0,if=sd"
5083

    
5084
static int drive_add(const char *file, const char *fmt, ...)
5085
{
5086
    va_list ap;
5087

    
5088
    if (nb_drives_opt >= MAX_DRIVES) {
5089
        fprintf(stderr, "qemu: too many drives\n");
5090
        exit(1);
5091
    }
5092

    
5093
    drives_opt[nb_drives_opt].file = file;
5094
    va_start(ap, fmt);
5095
    vsnprintf(drives_opt[nb_drives_opt].opt,
5096
              sizeof(drives_opt[0].opt), fmt, ap);
5097
    va_end(ap);
5098

    
5099
    return nb_drives_opt++;
5100
}
5101

    
5102
int drive_get_index(BlockInterfaceType type, int bus, int unit)
5103
{
5104
    int index;
5105

    
5106
    /* seek interface, bus and unit */
5107

    
5108
    for (index = 0; index < nb_drives; index++)
5109
        if (drives_table[index].type == type &&
5110
            drives_table[index].bus == bus &&
5111
            drives_table[index].unit == unit)
5112
        return index;
5113

    
5114
    return -1;
5115
}
5116

    
5117
int drive_get_max_bus(BlockInterfaceType type)
5118
{
5119
    int max_bus;
5120
    int index;
5121

    
5122
    max_bus = -1;
5123
    for (index = 0; index < nb_drives; index++) {
5124
        if(drives_table[index].type == type &&
5125
           drives_table[index].bus > max_bus)
5126
            max_bus = drives_table[index].bus;
5127
    }
5128
    return max_bus;
5129
}
5130

    
5131
static void bdrv_format_print(void *opaque, const char *name)
5132
{
5133
    fprintf(stderr, " %s", name);
5134
}
5135

    
5136
static int drive_init(struct drive_opt *arg, int snapshot,
5137
                      QEMUMachine *machine)
5138
{
5139
    char buf[128];
5140
    char file[1024];
5141
    char devname[128];
5142
    const char *mediastr = "";
5143
    BlockInterfaceType type;
5144
    enum { MEDIA_DISK, MEDIA_CDROM } media;
5145
    int bus_id, unit_id;
5146
    int cyls, heads, secs, translation;
5147
    BlockDriverState *bdrv;
5148
    BlockDriver *drv = NULL;
5149
    int max_devs;
5150
    int index;
5151
    int cache;
5152
    int bdrv_flags;
5153
    char *str = arg->opt;
5154
    char *params[] = { "bus", "unit", "if", "index", "cyls", "heads",
5155
                       "secs", "trans", "media", "snapshot", "file",
5156
                       "cache", "format", NULL };
5157

    
5158
    if (check_params(buf, sizeof(buf), params, str) < 0) {
5159
         fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
5160
                         buf, str);
5161
         return -1;
5162
    }
5163

    
5164
    file[0] = 0;
5165
    cyls = heads = secs = 0;
5166
    bus_id = 0;
5167
    unit_id = -1;
5168
    translation = BIOS_ATA_TRANSLATION_AUTO;
5169
    index = -1;
5170
    cache = 1;
5171

    
5172
    if (!strcmp(machine->name, "realview") ||
5173
        !strcmp(machine->name, "SS-5") ||
5174
        !strcmp(machine->name, "SS-10") ||
5175
        !strcmp(machine->name, "SS-600MP") ||
5176
        !strcmp(machine->name, "versatilepb") ||
5177
        !strcmp(machine->name, "versatileab")) {
5178
        type = IF_SCSI;
5179
        max_devs = MAX_SCSI_DEVS;
5180
        strcpy(devname, "scsi");
5181
    } else {
5182
        type = IF_IDE;
5183
        max_devs = MAX_IDE_DEVS;
5184
        strcpy(devname, "ide");
5185
    }
5186
    media = MEDIA_DISK;
5187

    
5188
    /* extract parameters */
5189

    
5190
    if (get_param_value(buf, sizeof(buf), "bus", str)) {
5191
        bus_id = strtol(buf, NULL, 0);
5192
        if (bus_id < 0) {
5193
            fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5194
            return -1;
5195
        }
5196
    }
5197

    
5198
    if (get_param_value(buf, sizeof(buf), "unit", str)) {
5199
        unit_id = strtol(buf, NULL, 0);
5200
        if (unit_id < 0) {
5201
            fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5202
            return -1;
5203
        }
5204
    }
5205

    
5206
    if (get_param_value(buf, sizeof(buf), "if", str)) {
5207
        pstrcpy(devname, sizeof(devname), buf);
5208
        if (!strcmp(buf, "ide")) {
5209
            type = IF_IDE;
5210
            max_devs = MAX_IDE_DEVS;
5211
        } else if (!strcmp(buf, "scsi")) {
5212
            type = IF_SCSI;
5213
            max_devs = MAX_SCSI_DEVS;
5214
        } else if (!strcmp(buf, "floppy")) {
5215
            type = IF_FLOPPY;
5216
            max_devs = 0;
5217
        } else if (!strcmp(buf, "pflash")) {
5218
            type = IF_PFLASH;
5219
            max_devs = 0;
5220
        } else if (!strcmp(buf, "mtd")) {
5221
            type = IF_MTD;
5222
            max_devs = 0;
5223
        } else if (!strcmp(buf, "sd")) {
5224
            type = IF_SD;
5225
            max_devs = 0;
5226
        } else {
5227
            fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5228
            return -1;
5229
        }
5230
    }
5231

    
5232
    if (get_param_value(buf, sizeof(buf), "index", str)) {
5233
        index = strtol(buf, NULL, 0);
5234
        if (index < 0) {
5235
            fprintf(stderr, "qemu: '%s' invalid index\n", str);
5236
            return -1;
5237
        }
5238
    }
5239

    
5240
    if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5241
        cyls = strtol(buf, NULL, 0);
5242
    }
5243

    
5244
    if (get_param_value(buf, sizeof(buf), "heads", str)) {
5245
        heads = strtol(buf, NULL, 0);
5246
    }
5247

    
5248
    if (get_param_value(buf, sizeof(buf), "secs", str)) {
5249
        secs = strtol(buf, NULL, 0);
5250
    }
5251

    
5252
    if (cyls || heads || secs) {
5253
        if (cyls < 1 || cyls > 16383) {
5254
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5255
            return -1;
5256
        }
5257
        if (heads < 1 || heads > 16) {
5258
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5259
            return -1;
5260
        }
5261
        if (secs < 1 || secs > 63) {
5262
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5263
            return -1;
5264
        }
5265
    }
5266

    
5267
    if (get_param_value(buf, sizeof(buf), "trans", str)) {
5268
        if (!cyls) {
5269
            fprintf(stderr,
5270
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
5271
                    str);
5272
            return -1;
5273
        }
5274
        if (!strcmp(buf, "none"))
5275
            translation = BIOS_ATA_TRANSLATION_NONE;
5276
        else if (!strcmp(buf, "lba"))
5277
            translation = BIOS_ATA_TRANSLATION_LBA;
5278
        else if (!strcmp(buf, "auto"))
5279
            translation = BIOS_ATA_TRANSLATION_AUTO;
5280
        else {
5281
            fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5282
            return -1;
5283
        }
5284
    }
5285

    
5286
    if (get_param_value(buf, sizeof(buf), "media", str)) {
5287
        if (!strcmp(buf, "disk")) {
5288
            media = MEDIA_DISK;
5289
        } else if (!strcmp(buf, "cdrom")) {
5290
            if (cyls || secs || heads) {
5291
                fprintf(stderr,
5292
                        "qemu: '%s' invalid physical CHS format\n", str);
5293
                return -1;
5294
            }
5295
            media = MEDIA_CDROM;
5296
        } else {
5297
            fprintf(stderr, "qemu: '%s' invalid media\n", str);
5298
            return -1;
5299
        }
5300
    }
5301

    
5302
    if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5303
        if (!strcmp(buf, "on"))
5304
            snapshot = 1;
5305
        else if (!strcmp(buf, "off"))
5306
            snapshot = 0;
5307
        else {
5308
            fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5309
            return -1;
5310
        }
5311
    }
5312

    
5313
    if (get_param_value(buf, sizeof(buf), "cache", str)) {
5314
        if (!strcmp(buf, "off"))
5315
            cache = 0;
5316
        else if (!strcmp(buf, "on"))
5317
            cache = 1;
5318
        else {
5319
           fprintf(stderr, "qemu: invalid cache option\n");
5320
           return -1;
5321
        }
5322
    }
5323

    
5324
    if (get_param_value(buf, sizeof(buf), "format", str)) {
5325
       if (strcmp(buf, "?") == 0) {
5326
            fprintf(stderr, "qemu: Supported formats:");
5327
            bdrv_iterate_format(bdrv_format_print, NULL);
5328
            fprintf(stderr, "\n");
5329
            return -1;
5330
        }
5331
        drv = bdrv_find_format(buf);
5332
        if (!drv) {
5333
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
5334
            return -1;
5335
        }
5336
    }
5337

    
5338
    if (arg->file == NULL)
5339
        get_param_value(file, sizeof(file), "file", str);
5340
    else
5341
        pstrcpy(file, sizeof(file), arg->file);
5342

    
5343
    /* compute bus and unit according index */
5344

    
5345
    if (index != -1) {
5346
        if (bus_id != 0 || unit_id != -1) {
5347
            fprintf(stderr,
5348
                    "qemu: '%s' index cannot be used with bus and unit\n", str);
5349
            return -1;
5350
        }
5351
        if (max_devs == 0)
5352
        {
5353
            unit_id = index;
5354
            bus_id = 0;
5355
        } else {
5356
            unit_id = index % max_devs;
5357
            bus_id = index / max_devs;
5358
        }
5359
    }
5360

    
5361
    /* if user doesn't specify a unit_id,
5362
     * try to find the first free
5363
     */
5364

    
5365
    if (unit_id == -1) {
5366
       unit_id = 0;
5367
       while (drive_get_index(type, bus_id, unit_id) != -1) {
5368
           unit_id++;
5369
           if (max_devs && unit_id >= max_devs) {
5370
               unit_id -= max_devs;
5371
               bus_id++;
5372
           }
5373
       }
5374
    }
5375

    
5376
    /* check unit id */
5377

    
5378
    if (max_devs && unit_id >= max_devs) {
5379
        fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5380
                        str, unit_id, max_devs - 1);
5381
        return -1;
5382
    }
5383

    
5384
    /*
5385
     * ignore multiple definitions
5386
     */
5387

    
5388
    if (drive_get_index(type, bus_id, unit_id) != -1)
5389
        return 0;
5390

    
5391
    /* init */
5392

    
5393
    if (type == IF_IDE || type == IF_SCSI)
5394
        mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5395
    if (max_devs)
5396
        snprintf(buf, sizeof(buf), "%s%i%s%i",
5397
                 devname, bus_id, mediastr, unit_id);
5398
    else
5399
        snprintf(buf, sizeof(buf), "%s%s%i",
5400
                 devname, mediastr, unit_id);
5401
    bdrv = bdrv_new(buf);
5402
    drives_table[nb_drives].bdrv = bdrv;
5403
    drives_table[nb_drives].type = type;
5404
    drives_table[nb_drives].bus = bus_id;
5405
    drives_table[nb_drives].unit = unit_id;
5406
    nb_drives++;
5407

    
5408
    switch(type) {
5409
    case IF_IDE:
5410
    case IF_SCSI:
5411
        switch(media) {
5412
        case MEDIA_DISK:
5413
            if (cyls != 0) {
5414
                bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5415
                bdrv_set_translation_hint(bdrv, translation);
5416
            }
5417
            break;
5418
        case MEDIA_CDROM:
5419
            bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5420
            break;
5421
        }
5422
        break;
5423
    case IF_SD:
5424
        /* FIXME: This isn't really a floppy, but it's a reasonable
5425
           approximation.  */
5426
    case IF_FLOPPY:
5427
        bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5428
        break;
5429
    case IF_PFLASH:
5430
    case IF_MTD:
5431
        break;
5432
    }
5433
    if (!file[0])
5434
        return 0;
5435
    bdrv_flags = 0;
5436
    if (snapshot)
5437
        bdrv_flags |= BDRV_O_SNAPSHOT;
5438
    if (!cache)
5439
        bdrv_flags |= BDRV_O_DIRECT;
5440
    if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
5441
        fprintf(stderr, "qemu: could not open disk image %s\n",
5442
                        file);
5443
        return -1;
5444
    }
5445
    return 0;
5446
}
5447

    
5448
/***********************************************************/
5449
/* USB devices */
5450

    
5451
static USBPort *used_usb_ports;
5452
static USBPort *free_usb_ports;
5453

    
5454
/* ??? Maybe change this to register a hub to keep track of the topology.  */
5455
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5456
                            usb_attachfn attach)
5457
{
5458
    port->opaque = opaque;
5459
    port->index = index;
5460
    port->attach = attach;
5461
    port->next = free_usb_ports;
5462
    free_usb_ports = port;
5463
}
5464

    
5465
static int usb_device_add(const char *devname)
5466
{
5467
    const char *p;
5468
    USBDevice *dev;
5469
    USBPort *port;
5470

    
5471
    if (!free_usb_ports)
5472
        return -1;
5473

    
5474
    if (strstart(devname, "host:", &p)) {
5475
        dev = usb_host_device_open(p);
5476
    } else if (!strcmp(devname, "mouse")) {
5477
        dev = usb_mouse_init();
5478
    } else if (!strcmp(devname, "tablet")) {
5479
        dev = usb_tablet_init();
5480
    } else if (!strcmp(devname, "keyboard")) {
5481
        dev = usb_keyboard_init();
5482
    } else if (strstart(devname, "disk:", &p)) {
5483
        dev = usb_msd_init(p);
5484
    } else if (!strcmp(devname, "wacom-tablet")) {
5485
        dev = usb_wacom_init();
5486
    } else if (strstart(devname, "serial:", &p)) {
5487
        dev = usb_serial_init(p);
5488
#ifdef CONFIG_BRLAPI
5489
    } else if (!strcmp(devname, "braille")) {
5490
        dev = usb_baum_init();
5491
#endif
5492
    } else if (strstart(devname, "net:", &p)) {
5493
        int nicidx = strtoul(p, NULL, 0);
5494

    
5495
        if (nicidx >= nb_nics || strcmp(nd_table[nicidx].model, "usb"))
5496
            return -1;
5497
        dev = usb_net_init(&nd_table[nicidx]);
5498
    } else {
5499
        return -1;
5500
    }
5501
    if (!dev)
5502
        return -1;
5503

    
5504
    /* Find a USB port to add the device to.  */
5505
    port = free_usb_ports;
5506
    if (!port->next) {
5507
        USBDevice *hub;
5508

    
5509
        /* Create a new hub and chain it on.  */
5510
        free_usb_ports = NULL;
5511
        port->next = used_usb_ports;
5512
        used_usb_ports = port;
5513

    
5514
        hub = usb_hub_init(VM_USB_HUB_SIZE);
5515
        usb_attach(port, hub);
5516
        port = free_usb_ports;
5517
    }
5518

    
5519
    free_usb_ports = port->next;
5520
    port->next = used_usb_ports;
5521
    used_usb_ports = port;
5522
    usb_attach(port, dev);
5523
    return 0;
5524
}
5525

    
5526
static int usb_device_del(const char *devname)
5527
{
5528
    USBPort *port;
5529
    USBPort **lastp;
5530
    USBDevice *dev;
5531
    int bus_num, addr;
5532
    const char *p;
5533

    
5534
    if (!used_usb_ports)
5535
        return -1;
5536

    
5537
    p = strchr(devname, '.');
5538
    if (!p)
5539
        return -1;
5540
    bus_num = strtoul(devname, NULL, 0);
5541
    addr = strtoul(p + 1, NULL, 0);
5542
    if (bus_num != 0)
5543
        return -1;
5544

    
5545
    lastp = &used_usb_ports;
5546
    port = used_usb_ports;
5547
    while (port && port->dev->addr != addr) {
5548
        lastp = &port->next;
5549
        port = port->next;
5550
    }
5551

    
5552
    if (!port)
5553
        return -1;
5554

    
5555
    dev = port->dev;
5556
    *lastp = port->next;
5557
    usb_attach(port, NULL);
5558
    dev->handle_destroy(dev);
5559
    port->next = free_usb_ports;
5560
    free_usb_ports = port;
5561
    return 0;
5562
}
5563

    
5564
void do_usb_add(const char *devname)
5565
{
5566
    int ret;
5567
    ret = usb_device_add(devname);
5568
    if (ret < 0)
5569
        term_printf("Could not add USB device '%s'\n", devname);
5570
}
5571

    
5572
void do_usb_del(const char *devname)
5573
{
5574
    int ret;
5575
    ret = usb_device_del(devname);
5576
    if (ret < 0)
5577
        term_printf("Could not remove USB device '%s'\n", devname);
5578
}
5579

    
5580
void usb_info(void)
5581
{
5582
    USBDevice *dev;
5583
    USBPort *port;
5584
    const char *speed_str;
5585

    
5586
    if (!usb_enabled) {
5587
        term_printf("USB support not enabled\n");
5588
        return;
5589
    }
5590

    
5591
    for (port = used_usb_ports; port; port = port->next) {
5592
        dev = port->dev;
5593
        if (!dev)
5594
            continue;
5595
        switch(dev->speed) {
5596
        case USB_SPEED_LOW:
5597
            speed_str = "1.5";
5598
            break;
5599
        case USB_SPEED_FULL:
5600
            speed_str = "12";
5601
            break;
5602
        case USB_SPEED_HIGH:
5603
            speed_str = "480";
5604
            break;
5605
        default:
5606
            speed_str = "?";
5607
            break;
5608
        }
5609
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n",
5610
                    0, dev->addr, speed_str, dev->devname);
5611
    }
5612
}
5613

    
5614
/***********************************************************/
5615
/* PCMCIA/Cardbus */
5616

    
5617
static struct pcmcia_socket_entry_s {
5618
    struct pcmcia_socket_s *socket;
5619
    struct pcmcia_socket_entry_s *next;
5620
} *pcmcia_sockets = 0;
5621

    
5622
void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5623
{
5624
    struct pcmcia_socket_entry_s *entry;
5625

    
5626
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5627
    entry->socket = socket;
5628
    entry->next = pcmcia_sockets;
5629
    pcmcia_sockets = entry;
5630
}
5631

    
5632
void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5633
{
5634
    struct pcmcia_socket_entry_s *entry, **ptr;
5635

    
5636
    ptr = &pcmcia_sockets;
5637
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5638
        if (entry->socket == socket) {
5639
            *ptr = entry->next;
5640
            qemu_free(entry);
5641
        }
5642
}
5643

    
5644
void pcmcia_info(void)
5645
{
5646
    struct pcmcia_socket_entry_s *iter;
5647
    if (!pcmcia_sockets)
5648
        term_printf("No PCMCIA sockets\n");
5649

    
5650
    for (iter = pcmcia_sockets; iter; iter = iter->next)
5651
        term_printf("%s: %s\n", iter->socket->slot_string,
5652
                    iter->socket->attached ? iter->socket->card_string :
5653
                    "Empty");
5654
}
5655

    
5656
/***********************************************************/
5657
/* dumb display */
5658

    
5659
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5660
{
5661
}
5662

    
5663
static void dumb_resize(DisplayState *ds, int w, int h)
5664
{
5665
}
5666

    
5667
static void dumb_refresh(DisplayState *ds)
5668
{
5669
#if defined(CONFIG_SDL)
5670
    vga_hw_update();
5671
#endif
5672
}
5673

    
5674
static void dumb_display_init(DisplayState *ds)
5675
{
5676
    ds->data = NULL;
5677
    ds->linesize = 0;
5678
    ds->depth = 0;
5679
    ds->dpy_update = dumb_update;
5680
    ds->dpy_resize = dumb_resize;
5681
    ds->dpy_refresh = dumb_refresh;
5682
}
5683

    
5684
/***********************************************************/
5685
/* I/O handling */
5686

    
5687
#define MAX_IO_HANDLERS 64
5688

    
5689
typedef struct IOHandlerRecord {
5690
    int fd;
5691
    IOCanRWHandler *fd_read_poll;
5692
    IOHandler *fd_read;
5693
    IOHandler *fd_write;
5694
    int deleted;
5695
    void *opaque;
5696
    /* temporary data */
5697
    struct pollfd *ufd;
5698
    struct IOHandlerRecord *next;
5699
} IOHandlerRecord;
5700

    
5701
static IOHandlerRecord *first_io_handler;
5702

    
5703
/* XXX: fd_read_poll should be suppressed, but an API change is
5704
   necessary in the character devices to suppress fd_can_read(). */
5705
int qemu_set_fd_handler2(int fd,
5706
                         IOCanRWHandler *fd_read_poll,
5707
                         IOHandler *fd_read,
5708
                         IOHandler *fd_write,
5709
                         void *opaque)
5710
{
5711
    IOHandlerRecord **pioh, *ioh;
5712

    
5713
    if (!fd_read && !fd_write) {
5714
        pioh = &first_io_handler;
5715
        for(;;) {
5716
            ioh = *pioh;
5717
            if (ioh == NULL)
5718
                break;
5719
            if (ioh->fd == fd) {
5720
                ioh->deleted = 1;
5721
                break;
5722
            }
5723
            pioh = &ioh->next;
5724
        }
5725
    } else {
5726
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
5727
            if (ioh->fd == fd)
5728
                goto found;
5729
        }
5730
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
5731
        if (!ioh)
5732
            return -1;
5733
        ioh->next = first_io_handler;
5734
        first_io_handler = ioh;
5735
    found:
5736
        ioh->fd = fd;
5737
        ioh->fd_read_poll = fd_read_poll;
5738
        ioh->fd_read = fd_read;
5739
        ioh->fd_write = fd_write;
5740
        ioh->opaque = opaque;
5741
        ioh->deleted = 0;
5742
    }
5743
    return 0;
5744
}
5745

    
5746
int qemu_set_fd_handler(int fd,
5747
                        IOHandler *fd_read,
5748
                        IOHandler *fd_write,
5749
                        void *opaque)
5750
{
5751
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
5752
}
5753

    
5754
/***********************************************************/
5755
/* Polling handling */
5756

    
5757
typedef struct PollingEntry {
5758
    PollingFunc *func;
5759
    void *opaque;
5760
    struct PollingEntry *next;
5761
} PollingEntry;
5762

    
5763
static PollingEntry *first_polling_entry;
5764

    
5765
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
5766
{
5767
    PollingEntry **ppe, *pe;
5768
    pe = qemu_mallocz(sizeof(PollingEntry));
5769
    if (!pe)
5770
        return -1;
5771
    pe->func = func;
5772
    pe->opaque = opaque;
5773
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
5774
    *ppe = pe;
5775
    return 0;
5776
}
5777

    
5778
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
5779
{
5780
    PollingEntry **ppe, *pe;
5781
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
5782
        pe = *ppe;
5783
        if (pe->func == func && pe->opaque == opaque) {
5784
            *ppe = pe->next;
5785
            qemu_free(pe);
5786
            break;
5787
        }
5788
    }
5789
}
5790

    
5791
#ifdef _WIN32
5792
/***********************************************************/
5793
/* Wait objects support */
5794
typedef struct WaitObjects {
5795
    int num;
5796
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
5797
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
5798
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
5799
} WaitObjects;
5800

    
5801
static WaitObjects wait_objects = {0};
5802

    
5803
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5804
{
5805
    WaitObjects *w = &wait_objects;
5806

    
5807
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
5808
        return -1;
5809
    w->events[w->num] = handle;
5810
    w->func[w->num] = func;
5811
    w->opaque[w->num] = opaque;
5812
    w->num++;
5813
    return 0;
5814
}
5815

    
5816
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
5817
{
5818
    int i, found;
5819
    WaitObjects *w = &wait_objects;
5820

    
5821
    found = 0;
5822
    for (i = 0; i < w->num; i++) {
5823
        if (w->events[i] == handle)
5824
            found = 1;
5825
        if (found) {
5826
            w->events[i] = w->events[i + 1];
5827
            w->func[i] = w->func[i + 1];
5828
            w->opaque[i] = w->opaque[i + 1];
5829
        }
5830
    }
5831
    if (found)
5832
        w->num--;
5833
}
5834
#endif
5835

    
5836
/***********************************************************/
5837
/* savevm/loadvm support */
5838

    
5839
#define IO_BUF_SIZE 32768
5840

    
5841
struct QEMUFile {
5842
    FILE *outfile;
5843
    BlockDriverState *bs;
5844
    int is_file;
5845
    int is_writable;
5846
    int64_t base_offset;
5847
    int64_t buf_offset; /* start of buffer when writing, end of buffer
5848
                           when reading */
5849
    int buf_index;
5850
    int buf_size; /* 0 when writing */
5851
    uint8_t buf[IO_BUF_SIZE];
5852
};
5853

    
5854
QEMUFile *qemu_fopen(const char *filename, const char *mode)
5855
{
5856
    QEMUFile *f;
5857

    
5858
    f = qemu_mallocz(sizeof(QEMUFile));
5859
    if (!f)
5860
        return NULL;
5861
    if (!strcmp(mode, "wb")) {
5862
        f->is_writable = 1;
5863
    } else if (!strcmp(mode, "rb")) {
5864
        f->is_writable = 0;
5865
    } else {
5866
        goto fail;
5867
    }
5868
    f->outfile = fopen(filename, mode);
5869
    if (!f->outfile)
5870
        goto fail;
5871
    f->is_file = 1;
5872
    return f;
5873
 fail:
5874
    if (f->outfile)
5875
        fclose(f->outfile);
5876
    qemu_free(f);
5877
    return NULL;
5878
}
5879

    
5880
static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
5881
{
5882
    QEMUFile *f;
5883

    
5884
    f = qemu_mallocz(sizeof(QEMUFile));
5885
    if (!f)
5886
        return NULL;
5887
    f->is_file = 0;
5888
    f->bs = bs;
5889
    f->is_writable = is_writable;
5890
    f->base_offset = offset;
5891
    return f;
5892
}
5893

    
5894
void qemu_fflush(QEMUFile *f)
5895
{
5896
    if (!f->is_writable)
5897
        return;
5898
    if (f->buf_index > 0) {
5899
        if (f->is_file) {
5900
            fseek(f->outfile, f->buf_offset, SEEK_SET);
5901
            fwrite(f->buf, 1, f->buf_index, f->outfile);
5902
        } else {
5903
            bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
5904
                        f->buf, f->buf_index);
5905
        }
5906
        f->buf_offset += f->buf_index;
5907
        f->buf_index = 0;
5908
    }
5909
}
5910

    
5911
static void qemu_fill_buffer(QEMUFile *f)
5912
{
5913
    int len;
5914

    
5915
    if (f->is_writable)
5916
        return;
5917
    if (f->is_file) {
5918
        fseek(f->outfile, f->buf_offset, SEEK_SET);
5919
        len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
5920
        if (len < 0)
5921
            len = 0;
5922
    } else {
5923
        len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
5924
                         f->buf, IO_BUF_SIZE);
5925
        if (len < 0)
5926
            len = 0;
5927
    }
5928
    f->buf_index = 0;
5929
    f->buf_size = len;
5930
    f->buf_offset += len;
5931
}
5932

    
5933
void qemu_fclose(QEMUFile *f)
5934
{
5935
    if (f->is_writable)
5936
        qemu_fflush(f);
5937
    if (f->is_file) {
5938
        fclose(f->outfile);
5939
    }
5940
    qemu_free(f);
5941
}
5942

    
5943
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
5944
{
5945
    int l;
5946
    while (size > 0) {
5947
        l = IO_BUF_SIZE - f->buf_index;
5948
        if (l > size)
5949
            l = size;
5950
        memcpy(f->buf + f->buf_index, buf, l);
5951
        f->buf_index += l;
5952
        buf += l;
5953
        size -= l;
5954
        if (f->buf_index >= IO_BUF_SIZE)
5955
            qemu_fflush(f);
5956
    }
5957
}
5958

    
5959
void qemu_put_byte(QEMUFile *f, int v)
5960
{
5961
    f->buf[f->buf_index++] = v;
5962
    if (f->buf_index >= IO_BUF_SIZE)
5963
        qemu_fflush(f);
5964
}
5965

    
5966
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
5967
{
5968
    int size, l;
5969

    
5970
    size = size1;
5971
    while (size > 0) {
5972
        l = f->buf_size - f->buf_index;
5973
        if (l == 0) {
5974
            qemu_fill_buffer(f);
5975
            l = f->buf_size - f->buf_index;
5976
            if (l == 0)
5977
                break;
5978
        }
5979
        if (l > size)
5980
            l = size;
5981
        memcpy(buf, f->buf + f->buf_index, l);
5982
        f->buf_index += l;
5983
        buf += l;
5984
        size -= l;
5985
    }
5986
    return size1 - size;
5987
}
5988

    
5989
int qemu_get_byte(QEMUFile *f)
5990
{
5991
    if (f->buf_index >= f->buf_size) {
5992
        qemu_fill_buffer(f);
5993
        if (f->buf_index >= f->buf_size)
5994
            return 0;
5995
    }
5996
    return f->buf[f->buf_index++];
5997
}
5998

    
5999
int64_t qemu_ftell(QEMUFile *f)
6000
{
6001
    return f->buf_offset - f->buf_size + f->buf_index;
6002
}
6003

    
6004
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
6005
{
6006
    if (whence == SEEK_SET) {
6007
        /* nothing to do */
6008
    } else if (whence == SEEK_CUR) {
6009
        pos += qemu_ftell(f);
6010
    } else {
6011
        /* SEEK_END not supported */
6012
        return -1;
6013
    }
6014
    if (f->is_writable) {
6015
        qemu_fflush(f);
6016
        f->buf_offset = pos;
6017
    } else {
6018
        f->buf_offset = pos;
6019
        f->buf_index = 0;
6020
        f->buf_size = 0;
6021
    }
6022
    return pos;
6023
}
6024

    
6025
void qemu_put_be16(QEMUFile *f, unsigned int v)
6026
{
6027
    qemu_put_byte(f, v >> 8);
6028
    qemu_put_byte(f, v);
6029
}
6030

    
6031
void qemu_put_be32(QEMUFile *f, unsigned int v)
6032
{
6033
    qemu_put_byte(f, v >> 24);
6034
    qemu_put_byte(f, v >> 16);
6035
    qemu_put_byte(f, v >> 8);
6036
    qemu_put_byte(f, v);
6037
}
6038

    
6039
void qemu_put_be64(QEMUFile *f, uint64_t v)
6040
{
6041
    qemu_put_be32(f, v >> 32);
6042
    qemu_put_be32(f, v);
6043
}
6044

    
6045
unsigned int qemu_get_be16(QEMUFile *f)
6046
{
6047
    unsigned int v;
6048
    v = qemu_get_byte(f) << 8;
6049
    v |= qemu_get_byte(f);
6050
    return v;
6051
}
6052

    
6053
unsigned int qemu_get_be32(QEMUFile *f)
6054
{
6055
    unsigned int v;
6056
    v = qemu_get_byte(f) << 24;
6057
    v |= qemu_get_byte(f) << 16;
6058
    v |= qemu_get_byte(f) << 8;
6059
    v |= qemu_get_byte(f);
6060
    return v;
6061
}
6062

    
6063
uint64_t qemu_get_be64(QEMUFile *f)
6064
{
6065
    uint64_t v;
6066
    v = (uint64_t)qemu_get_be32(f) << 32;
6067
    v |= qemu_get_be32(f);
6068
    return v;
6069
}
6070

    
6071
typedef struct SaveStateEntry {
6072
    char idstr[256];
6073
    int instance_id;
6074
    int version_id;
6075
    SaveStateHandler *save_state;
6076
    LoadStateHandler *load_state;
6077
    void *opaque;
6078
    struct SaveStateEntry *next;
6079
} SaveStateEntry;
6080

    
6081
static SaveStateEntry *first_se;
6082

    
6083
/* TODO: Individual devices generally have very little idea about the rest
6084
   of the system, so instance_id should be removed/replaced.
6085
   Meanwhile pass -1 as instance_id if you do not already have a clearly
6086
   distinguishing id for all instances of your device class. */
6087
int register_savevm(const char *idstr,
6088
                    int instance_id,
6089
                    int version_id,
6090
                    SaveStateHandler *save_state,
6091
                    LoadStateHandler *load_state,
6092
                    void *opaque)
6093
{
6094
    SaveStateEntry *se, **pse;
6095

    
6096
    se = qemu_malloc(sizeof(SaveStateEntry));
6097
    if (!se)
6098
        return -1;
6099
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6100
    se->instance_id = (instance_id == -1) ? 0 : instance_id;
6101
    se->version_id = version_id;
6102
    se->save_state = save_state;
6103
    se->load_state = load_state;
6104
    se->opaque = opaque;
6105
    se->next = NULL;
6106

    
6107
    /* add at the end of list */
6108
    pse = &first_se;
6109
    while (*pse != NULL) {
6110
        if (instance_id == -1
6111
                && strcmp(se->idstr, (*pse)->idstr) == 0
6112
                && se->instance_id <= (*pse)->instance_id)
6113
            se->instance_id = (*pse)->instance_id + 1;
6114
        pse = &(*pse)->next;
6115
    }
6116
    *pse = se;
6117
    return 0;
6118
}
6119

    
6120
#define QEMU_VM_FILE_MAGIC   0x5145564d
6121
#define QEMU_VM_FILE_VERSION 0x00000002
6122

    
6123
static int qemu_savevm_state(QEMUFile *f)
6124
{
6125
    SaveStateEntry *se;
6126
    int len, ret;
6127
    int64_t cur_pos, len_pos, total_len_pos;
6128

    
6129
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6130
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6131
    total_len_pos = qemu_ftell(f);
6132
    qemu_put_be64(f, 0); /* total size */
6133

    
6134
    for(se = first_se; se != NULL; se = se->next) {
6135
        if (se->save_state == NULL)
6136
            /* this one has a loader only, for backwards compatibility */
6137
            continue;
6138

    
6139
        /* ID string */
6140
        len = strlen(se->idstr);
6141
        qemu_put_byte(f, len);
6142
        qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6143

    
6144
        qemu_put_be32(f, se->instance_id);
6145
        qemu_put_be32(f, se->version_id);
6146

    
6147
        /* record size: filled later */
6148
        len_pos = qemu_ftell(f);
6149
        qemu_put_be32(f, 0);
6150
        se->save_state(f, se->opaque);
6151

    
6152
        /* fill record size */
6153
        cur_pos = qemu_ftell(f);
6154
        len = cur_pos - len_pos - 4;
6155
        qemu_fseek(f, len_pos, SEEK_SET);
6156
        qemu_put_be32(f, len);
6157
        qemu_fseek(f, cur_pos, SEEK_SET);
6158
    }
6159
    cur_pos = qemu_ftell(f);
6160
    qemu_fseek(f, total_len_pos, SEEK_SET);
6161
    qemu_put_be64(f, cur_pos - total_len_pos - 8);
6162
    qemu_fseek(f, cur_pos, SEEK_SET);
6163

    
6164
    ret = 0;
6165
    return ret;
6166
}
6167

    
6168
static SaveStateEntry *find_se(const char *idstr, int instance_id)
6169
{
6170
    SaveStateEntry *se;
6171

    
6172
    for(se = first_se; se != NULL; se = se->next) {
6173
        if (!strcmp(se->idstr, idstr) &&
6174
            instance_id == se->instance_id)
6175
            return se;
6176
    }
6177
    return NULL;
6178
}
6179

    
6180
static int qemu_loadvm_state(QEMUFile *f)
6181
{
6182
    SaveStateEntry *se;
6183
    int len, ret, instance_id, record_len, version_id;
6184
    int64_t total_len, end_pos, cur_pos;
6185
    unsigned int v;
6186
    char idstr[256];
6187

    
6188
    v = qemu_get_be32(f);
6189
    if (v != QEMU_VM_FILE_MAGIC)
6190
        goto fail;
6191
    v = qemu_get_be32(f);
6192
    if (v != QEMU_VM_FILE_VERSION) {
6193
    fail:
6194
        ret = -1;
6195
        goto the_end;
6196
    }
6197
    total_len = qemu_get_be64(f);
6198
    end_pos = total_len + qemu_ftell(f);
6199
    for(;;) {
6200
        if (qemu_ftell(f) >= end_pos)
6201
            break;
6202
        len = qemu_get_byte(f);
6203
        qemu_get_buffer(f, (uint8_t *)idstr, len);
6204
        idstr[len] = '\0';
6205
        instance_id = qemu_get_be32(f);
6206
        version_id = qemu_get_be32(f);
6207
        record_len = qemu_get_be32(f);
6208
#if 0
6209
        printf("idstr=%s instance=0x%x version=%d len=%d\n",
6210
               idstr, instance_id, version_id, record_len);
6211
#endif
6212
        cur_pos = qemu_ftell(f);
6213
        se = find_se(idstr, instance_id);
6214
        if (!se) {
6215
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6216
                    instance_id, idstr);
6217
        } else {
6218
            ret = se->load_state(f, se->opaque, version_id);
6219
            if (ret < 0) {
6220
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6221
                        instance_id, idstr);
6222
            }
6223
        }
6224
        /* always seek to exact end of record */
6225
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6226
    }
6227
    ret = 0;
6228
 the_end:
6229
    return ret;
6230
}
6231

    
6232
/* device can contain snapshots */
6233
static int bdrv_can_snapshot(BlockDriverState *bs)
6234
{
6235
    return (bs &&
6236
            !bdrv_is_removable(bs) &&
6237
            !bdrv_is_read_only(bs));
6238
}
6239

    
6240
/* device must be snapshots in order to have a reliable snapshot */
6241
static int bdrv_has_snapshot(BlockDriverState *bs)
6242
{
6243
    return (bs &&
6244
            !bdrv_is_removable(bs) &&
6245
            !bdrv_is_read_only(bs));
6246
}
6247

    
6248
static BlockDriverState *get_bs_snapshots(void)
6249
{
6250
    BlockDriverState *bs;
6251
    int i;
6252

    
6253
    if (bs_snapshots)
6254
        return bs_snapshots;
6255
    for(i = 0; i <= nb_drives; i++) {
6256
        bs = drives_table[i].bdrv;
6257
        if (bdrv_can_snapshot(bs))
6258
            goto ok;
6259
    }
6260
    return NULL;
6261
 ok:
6262
    bs_snapshots = bs;
6263
    return bs;
6264
}
6265

    
6266
static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6267
                              const char *name)
6268
{
6269
    QEMUSnapshotInfo *sn_tab, *sn;
6270
    int nb_sns, i, ret;
6271

    
6272
    ret = -ENOENT;
6273
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6274
    if (nb_sns < 0)
6275
        return ret;
6276
    for(i = 0; i < nb_sns; i++) {
6277
        sn = &sn_tab[i];
6278
        if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6279
            *sn_info = *sn;
6280
            ret = 0;
6281
            break;
6282
        }
6283
    }
6284
    qemu_free(sn_tab);
6285
    return ret;
6286
}
6287

    
6288
void do_savevm(const char *name)
6289
{
6290
    BlockDriverState *bs, *bs1;
6291
    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6292
    int must_delete, ret, i;
6293
    BlockDriverInfo bdi1, *bdi = &bdi1;
6294
    QEMUFile *f;
6295
    int saved_vm_running;
6296
#ifdef _WIN32
6297
    struct _timeb tb;
6298
#else
6299
    struct timeval tv;
6300
#endif
6301

    
6302
    bs = get_bs_snapshots();
6303
    if (!bs) {
6304
        term_printf("No block device can accept snapshots\n");
6305
        return;
6306
    }
6307

    
6308
    /* ??? Should this occur after vm_stop?  */
6309
    qemu_aio_flush();
6310

    
6311
    saved_vm_running = vm_running;
6312
    vm_stop(0);
6313

    
6314
    must_delete = 0;
6315
    if (name) {
6316
        ret = bdrv_snapshot_find(bs, old_sn, name);
6317
        if (ret >= 0) {
6318
            must_delete = 1;
6319
        }
6320
    }
6321
    memset(sn, 0, sizeof(*sn));
6322
    if (must_delete) {
6323
        pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6324
        pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6325
    } else {
6326
        if (name)
6327
            pstrcpy(sn->name, sizeof(sn->name), name);
6328
    }
6329

    
6330
    /* fill auxiliary fields */
6331
#ifdef _WIN32
6332
    _ftime(&tb);
6333
    sn->date_sec = tb.time;
6334
    sn->date_nsec = tb.millitm * 1000000;
6335
#else
6336
    gettimeofday(&tv, NULL);
6337
    sn->date_sec = tv.tv_sec;
6338
    sn->date_nsec = tv.tv_usec * 1000;
6339
#endif
6340
    sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6341

    
6342
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6343
        term_printf("Device %s does not support VM state snapshots\n",
6344
                    bdrv_get_device_name(bs));
6345
        goto the_end;
6346
    }
6347

    
6348
    /* save the VM state */
6349
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6350
    if (!f) {
6351
        term_printf("Could not open VM state file\n");
6352
        goto the_end;
6353
    }
6354
    ret = qemu_savevm_state(f);
6355
    sn->vm_state_size = qemu_ftell(f);
6356
    qemu_fclose(f);
6357
    if (ret < 0) {
6358
        term_printf("Error %d while writing VM\n", ret);
6359
        goto the_end;
6360
    }
6361

    
6362
    /* create the snapshots */
6363

    
6364
    for(i = 0; i < nb_drives; i++) {
6365
        bs1 = drives_table[i].bdrv;
6366
        if (bdrv_has_snapshot(bs1)) {
6367
            if (must_delete) {
6368
                ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6369
                if (ret < 0) {
6370
                    term_printf("Error while deleting snapshot on '%s'\n",
6371
                                bdrv_get_device_name(bs1));
6372
                }
6373
            }
6374
            ret = bdrv_snapshot_create(bs1, sn);
6375
            if (ret < 0) {
6376
                term_printf("Error while creating snapshot on '%s'\n",
6377
                            bdrv_get_device_name(bs1));
6378
            }
6379
        }
6380
    }
6381

    
6382
 the_end:
6383
    if (saved_vm_running)
6384
        vm_start();
6385
}
6386

    
6387
void do_loadvm(const char *name)
6388
{
6389
    BlockDriverState *bs, *bs1;
6390
    BlockDriverInfo bdi1, *bdi = &bdi1;
6391
    QEMUFile *f;
6392
    int i, ret;
6393
    int saved_vm_running;
6394

    
6395
    bs = get_bs_snapshots();
6396
    if (!bs) {
6397
        term_printf("No block device supports snapshots\n");
6398
        return;
6399
    }
6400

    
6401
    /* Flush all IO requests so they don't interfere with the new state.  */
6402
    qemu_aio_flush();
6403

    
6404
    saved_vm_running = vm_running;
6405
    vm_stop(0);
6406

    
6407
    for(i = 0; i <= nb_drives; i++) {
6408
        bs1 = drives_table[i].bdrv;
6409
        if (bdrv_has_snapshot(bs1)) {
6410
            ret = bdrv_snapshot_goto(bs1, name);
6411
            if (ret < 0) {
6412
                if (bs != bs1)
6413
                    term_printf("Warning: ");
6414
                switch(ret) {
6415
                case -ENOTSUP:
6416
                    term_printf("Snapshots not supported on device '%s'\n",
6417
                                bdrv_get_device_name(bs1));
6418
                    break;
6419
                case -ENOENT:
6420
                    term_printf("Could not find snapshot '%s' on device '%s'\n",
6421
                                name, bdrv_get_device_name(bs1));
6422
                    break;
6423
                default:
6424
                    term_printf("Error %d while activating snapshot on '%s'\n",
6425
                                ret, bdrv_get_device_name(bs1));
6426
                    break;
6427
                }
6428
                /* fatal on snapshot block device */
6429
                if (bs == bs1)
6430
                    goto the_end;
6431
            }
6432
        }
6433
    }
6434

    
6435
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6436
        term_printf("Device %s does not support VM state snapshots\n",
6437
                    bdrv_get_device_name(bs));
6438
        return;
6439
    }
6440

    
6441
    /* restore the VM state */
6442
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6443
    if (!f) {
6444
        term_printf("Could not open VM state file\n");
6445
        goto the_end;
6446
    }
6447
    ret = qemu_loadvm_state(f);
6448
    qemu_fclose(f);
6449
    if (ret < 0) {
6450
        term_printf("Error %d while loading VM state\n", ret);
6451
    }
6452
 the_end:
6453
    if (saved_vm_running)
6454
        vm_start();
6455
}
6456

    
6457
void do_delvm(const char *name)
6458
{
6459
    BlockDriverState *bs, *bs1;
6460
    int i, ret;
6461

    
6462
    bs = get_bs_snapshots();
6463
    if (!bs) {
6464
        term_printf("No block device supports snapshots\n");
6465
        return;
6466
    }
6467

    
6468
    for(i = 0; i <= nb_drives; i++) {
6469
        bs1 = drives_table[i].bdrv;
6470
        if (bdrv_has_snapshot(bs1)) {
6471
            ret = bdrv_snapshot_delete(bs1, name);
6472
            if (ret < 0) {
6473
                if (ret == -ENOTSUP)
6474
                    term_printf("Snapshots not supported on device '%s'\n",
6475
                                bdrv_get_device_name(bs1));
6476
                else
6477
                    term_printf("Error %d while deleting snapshot on '%s'\n",
6478
                                ret, bdrv_get_device_name(bs1));
6479
            }
6480
        }
6481
    }
6482
}
6483

    
6484
void do_info_snapshots(void)
6485
{
6486
    BlockDriverState *bs, *bs1;
6487
    QEMUSnapshotInfo *sn_tab, *sn;
6488
    int nb_sns, i;
6489
    char buf[256];
6490

    
6491
    bs = get_bs_snapshots();
6492
    if (!bs) {
6493
        term_printf("No available block device supports snapshots\n");
6494
        return;
6495
    }
6496
    term_printf("Snapshot devices:");
6497
    for(i = 0; i <= nb_drives; i++) {
6498
        bs1 = drives_table[i].bdrv;
6499
        if (bdrv_has_snapshot(bs1)) {
6500
            if (bs == bs1)
6501
                term_printf(" %s", bdrv_get_device_name(bs1));
6502
        }
6503
    }
6504
    term_printf("\n");
6505

    
6506
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6507
    if (nb_sns < 0) {
6508
        term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6509
        return;
6510
    }
6511
    term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6512
    term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6513
    for(i = 0; i < nb_sns; i++) {
6514
        sn = &sn_tab[i];
6515
        term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6516
    }
6517
    qemu_free(sn_tab);
6518
}
6519

    
6520
/***********************************************************/
6521
/* ram save/restore */
6522

    
6523
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6524
{
6525
    int v;
6526

    
6527
    v = qemu_get_byte(f);
6528
    switch(v) {
6529
    case 0:
6530
        if (qemu_get_buffer(f, buf, len) != len)
6531
            return -EIO;
6532
        break;
6533
    case 1:
6534
        v = qemu_get_byte(f);
6535
        memset(buf, v, len);
6536
        break;
6537
    default:
6538
        return -EINVAL;
6539
    }
6540
    return 0;
6541
}
6542

    
6543
static int ram_load_v1(QEMUFile *f, void *opaque)
6544
{
6545
    int ret;
6546
    ram_addr_t i;
6547

    
6548
    if (qemu_get_be32(f) != phys_ram_size)
6549
        return -EINVAL;
6550
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6551
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6552
        if (ret)
6553
            return ret;
6554
    }
6555
    return 0;
6556
}
6557

    
6558
#define BDRV_HASH_BLOCK_SIZE 1024
6559
#define IOBUF_SIZE 4096
6560
#define RAM_CBLOCK_MAGIC 0xfabe
6561

    
6562
typedef struct RamCompressState {
6563
    z_stream zstream;
6564
    QEMUFile *f;
6565
    uint8_t buf[IOBUF_SIZE];
6566
} RamCompressState;
6567

    
6568
static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6569
{
6570
    int ret;
6571
    memset(s, 0, sizeof(*s));
6572
    s->f = f;
6573
    ret = deflateInit2(&s->zstream, 1,
6574
                       Z_DEFLATED, 15,
6575
                       9, Z_DEFAULT_STRATEGY);
6576
    if (ret != Z_OK)
6577
        return -1;
6578
    s->zstream.avail_out = IOBUF_SIZE;
6579
    s->zstream.next_out = s->buf;
6580
    return 0;
6581
}
6582

    
6583
static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6584
{
6585
    qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6586
    qemu_put_be16(s->f, len);
6587
    qemu_put_buffer(s->f, buf, len);
6588
}
6589

    
6590
static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6591
{
6592
    int ret;
6593

    
6594
    s->zstream.avail_in = len;
6595
    s->zstream.next_in = (uint8_t *)buf;
6596
    while (s->zstream.avail_in > 0) {
6597
        ret = deflate(&s->zstream, Z_NO_FLUSH);
6598
        if (ret != Z_OK)
6599
            return -1;
6600
        if (s->zstream.avail_out == 0) {
6601
            ram_put_cblock(s, s->buf, IOBUF_SIZE);
6602
            s->zstream.avail_out = IOBUF_SIZE;
6603
            s->zstream.next_out = s->buf;
6604
        }
6605
    }
6606
    return 0;
6607
}
6608

    
6609
static void ram_compress_close(RamCompressState *s)
6610
{
6611
    int len, ret;
6612

    
6613
    /* compress last bytes */
6614
    for(;;) {
6615
        ret = deflate(&s->zstream, Z_FINISH);
6616
        if (ret == Z_OK || ret == Z_STREAM_END) {
6617
            len = IOBUF_SIZE - s->zstream.avail_out;
6618
            if (len > 0) {
6619
                ram_put_cblock(s, s->buf, len);
6620
            }
6621
            s->zstream.avail_out = IOBUF_SIZE;
6622
            s->zstream.next_out = s->buf;
6623
            if (ret == Z_STREAM_END)
6624
                break;
6625
        } else {
6626
            goto fail;
6627
        }
6628
    }
6629
fail:
6630
    deflateEnd(&s->zstream);
6631
}
6632

    
6633
typedef struct RamDecompressState {
6634
    z_stream zstream;
6635
    QEMUFile *f;
6636
    uint8_t buf[IOBUF_SIZE];
6637
} RamDecompressState;
6638

    
6639
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6640
{
6641
    int ret;
6642
    memset(s, 0, sizeof(*s));
6643
    s->f = f;
6644
    ret = inflateInit(&s->zstream);
6645
    if (ret != Z_OK)
6646
        return -1;
6647
    return 0;
6648
}
6649

    
6650
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6651
{
6652
    int ret, clen;
6653

    
6654
    s->zstream.avail_out = len;
6655
    s->zstream.next_out = buf;
6656
    while (s->zstream.avail_out > 0) {
6657
        if (s->zstream.avail_in == 0) {
6658
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6659
                return -1;
6660
            clen = qemu_get_be16(s->f);
6661
            if (clen > IOBUF_SIZE)
6662
                return -1;
6663
            qemu_get_buffer(s->f, s->buf, clen);
6664
            s->zstream.avail_in = clen;
6665
            s->zstream.next_in = s->buf;
6666
        }
6667
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6668
        if (ret != Z_OK && ret != Z_STREAM_END) {
6669
            return -1;
6670
        }
6671
    }
6672
    return 0;
6673
}
6674

    
6675
static void ram_decompress_close(RamDecompressState *s)
6676
{
6677
    inflateEnd(&s->zstream);
6678
}
6679

    
6680
static void ram_save(QEMUFile *f, void *opaque)
6681
{
6682
    ram_addr_t i;
6683
    RamCompressState s1, *s = &s1;
6684
    uint8_t buf[10];
6685

    
6686
    qemu_put_be32(f, phys_ram_size);
6687
    if (ram_compress_open(s, f) < 0)
6688
        return;
6689
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6690
#if 0
6691
        if (tight_savevm_enabled) {
6692
            int64_t sector_num;
6693
            int j;
6694

6695
            /* find if the memory block is available on a virtual
6696
               block device */
6697
            sector_num = -1;
6698
            for(j = 0; j < nb_drives; j++) {
6699
                sector_num = bdrv_hash_find(drives_table[j].bdrv,
6700
                                            phys_ram_base + i,
6701
                                            BDRV_HASH_BLOCK_SIZE);
6702
                if (sector_num >= 0)
6703
                    break;
6704
            }
6705
            if (j == nb_drives)
6706
                goto normal_compress;
6707
            buf[0] = 1;
6708
            buf[1] = j;
6709
            cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
6710
            ram_compress_buf(s, buf, 10);
6711
        } else
6712
#endif
6713
        {
6714
            //        normal_compress:
6715
            buf[0] = 0;
6716
            ram_compress_buf(s, buf, 1);
6717
            ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
6718
        }
6719
    }
6720
    ram_compress_close(s);
6721
}
6722

    
6723
static int ram_load(QEMUFile *f, void *opaque, int version_id)
6724
{
6725
    RamDecompressState s1, *s = &s1;
6726
    uint8_t buf[10];
6727
    ram_addr_t i;
6728

    
6729
    if (version_id == 1)
6730
        return ram_load_v1(f, opaque);
6731
    if (version_id != 2)
6732
        return -EINVAL;
6733
    if (qemu_get_be32(f) != phys_ram_size)
6734
        return -EINVAL;
6735
    if (ram_decompress_open(s, f) < 0)
6736
        return -EINVAL;
6737
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
6738
        if (ram_decompress_buf(s, buf, 1) < 0) {
6739
            fprintf(stderr, "Error while reading ram block header\n");
6740
            goto error;
6741
        }
6742
        if (buf[0] == 0) {
6743
            if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
6744
                fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
6745
                goto error;
6746
            }
6747
        } else
6748
#if 0
6749
        if (buf[0] == 1) {
6750
            int bs_index;
6751
            int64_t sector_num;
6752

6753
            ram_decompress_buf(s, buf + 1, 9);
6754
            bs_index = buf[1];
6755
            sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
6756
            if (bs_index >= nb_drives) {
6757
                fprintf(stderr, "Invalid block device index %d\n", bs_index);
6758
                goto error;
6759
            }
6760
            if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
6761
                          phys_ram_base + i,
6762
                          BDRV_HASH_BLOCK_SIZE / 512) < 0) {
6763
                fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
6764
                        bs_index, sector_num);
6765
                goto error;
6766
            }
6767
        } else
6768
#endif
6769
        {
6770
        error:
6771
            printf("Error block header\n");
6772
            return -EINVAL;
6773
        }
6774
    }
6775
    ram_decompress_close(s);
6776
    return 0;
6777
}
6778

    
6779
/***********************************************************/
6780
/* bottom halves (can be seen as timers which expire ASAP) */
6781

    
6782
struct QEMUBH {
6783
    QEMUBHFunc *cb;
6784
    void *opaque;
6785
    int scheduled;
6786
    QEMUBH *next;
6787
};
6788

    
6789
static QEMUBH *first_bh = NULL;
6790

    
6791
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
6792
{
6793
    QEMUBH *bh;
6794
    bh = qemu_mallocz(sizeof(QEMUBH));
6795
    if (!bh)
6796
        return NULL;
6797
    bh->cb = cb;
6798
    bh->opaque = opaque;
6799
    return bh;
6800
}
6801

    
6802
int qemu_bh_poll(void)
6803
{
6804
    QEMUBH *bh, **pbh;
6805
    int ret;
6806

    
6807
    ret = 0;
6808
    for(;;) {
6809
        pbh = &first_bh;
6810
        bh = *pbh;
6811
        if (!bh)
6812
            break;
6813
        ret = 1;
6814
        *pbh = bh->next;
6815
        bh->scheduled = 0;
6816
        bh->cb(bh->opaque);
6817
    }
6818
    return ret;
6819
}
6820

    
6821
void qemu_bh_schedule(QEMUBH *bh)
6822
{
6823
    CPUState *env = cpu_single_env;
6824
    if (bh->scheduled)
6825
        return;
6826
    bh->scheduled = 1;
6827
    bh->next = first_bh;
6828
    first_bh = bh;
6829

    
6830
    /* stop the currently executing CPU to execute the BH ASAP */
6831
    if (env) {
6832
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6833
    }
6834
}
6835

    
6836
void qemu_bh_cancel(QEMUBH *bh)
6837
{
6838
    QEMUBH **pbh;
6839
    if (bh->scheduled) {
6840
        pbh = &first_bh;
6841
        while (*pbh != bh)
6842
            pbh = &(*pbh)->next;
6843
        *pbh = bh->next;
6844
        bh->scheduled = 0;
6845
    }
6846
}
6847

    
6848
void qemu_bh_delete(QEMUBH *bh)
6849
{
6850
    qemu_bh_cancel(bh);
6851
    qemu_free(bh);
6852
}
6853

    
6854
/***********************************************************/
6855
/* machine registration */
6856

    
6857
QEMUMachine *first_machine = NULL;
6858

    
6859
int qemu_register_machine(QEMUMachine *m)
6860
{
6861
    QEMUMachine **pm;
6862
    pm = &first_machine;
6863
    while (*pm != NULL)
6864
        pm = &(*pm)->next;
6865
    m->next = NULL;
6866
    *pm = m;
6867
    return 0;
6868
}
6869

    
6870
static QEMUMachine *find_machine(const char *name)
6871
{
6872
    QEMUMachine *m;
6873

    
6874
    for(m = first_machine; m != NULL; m = m->next) {
6875
        if (!strcmp(m->name, name))
6876
            return m;
6877
    }
6878
    return NULL;
6879
}
6880

    
6881
/***********************************************************/
6882
/* main execution loop */
6883

    
6884
static void gui_update(void *opaque)
6885
{
6886
    DisplayState *ds = opaque;
6887
    ds->dpy_refresh(ds);
6888
    qemu_mod_timer(ds->gui_timer,
6889
        (ds->gui_timer_interval ?
6890
            ds->gui_timer_interval :
6891
            GUI_REFRESH_INTERVAL)
6892
        + qemu_get_clock(rt_clock));
6893
}
6894

    
6895
struct vm_change_state_entry {
6896
    VMChangeStateHandler *cb;
6897
    void *opaque;
6898
    LIST_ENTRY (vm_change_state_entry) entries;
6899
};
6900

    
6901
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6902

    
6903
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6904
                                                     void *opaque)
6905
{
6906
    VMChangeStateEntry *e;
6907

    
6908
    e = qemu_mallocz(sizeof (*e));
6909
    if (!e)
6910
        return NULL;
6911

    
6912
    e->cb = cb;
6913
    e->opaque = opaque;
6914
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6915
    return e;
6916
}
6917

    
6918
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6919
{
6920
    LIST_REMOVE (e, entries);
6921
    qemu_free (e);
6922
}
6923

    
6924
static void vm_state_notify(int running)
6925
{
6926
    VMChangeStateEntry *e;
6927

    
6928
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6929
        e->cb(e->opaque, running);
6930
    }
6931
}
6932

    
6933
/* XXX: support several handlers */
6934
static VMStopHandler *vm_stop_cb;
6935
static void *vm_stop_opaque;
6936

    
6937
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6938
{
6939
    vm_stop_cb = cb;
6940
    vm_stop_opaque = opaque;
6941
    return 0;
6942
}
6943

    
6944
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6945
{
6946
    vm_stop_cb = NULL;
6947
}
6948

    
6949
void vm_start(void)
6950
{
6951
    if (!vm_running) {
6952
        cpu_enable_ticks();
6953
        vm_running = 1;
6954
        vm_state_notify(1);
6955
        qemu_rearm_alarm_timer(alarm_timer);
6956
    }
6957
}
6958

    
6959
void vm_stop(int reason)
6960
{
6961
    if (vm_running) {
6962
        cpu_disable_ticks();
6963
        vm_running = 0;
6964
        if (reason != 0) {
6965
            if (vm_stop_cb) {
6966
                vm_stop_cb(vm_stop_opaque, reason);
6967
            }
6968
        }
6969
        vm_state_notify(0);
6970
    }
6971
}
6972

    
6973
/* reset/shutdown handler */
6974

    
6975
typedef struct QEMUResetEntry {
6976
    QEMUResetHandler *func;
6977
    void *opaque;
6978
    struct QEMUResetEntry *next;
6979
} QEMUResetEntry;
6980

    
6981
static QEMUResetEntry *first_reset_entry;
6982
static int reset_requested;
6983
static int shutdown_requested;
6984
static int powerdown_requested;
6985

    
6986
int qemu_shutdown_requested(void)
6987
{
6988
    int r = shutdown_requested;
6989
    shutdown_requested = 0;
6990
    return r;
6991
}
6992

    
6993
int qemu_reset_requested(void)
6994
{
6995
    int r = reset_requested;
6996
    reset_requested = 0;
6997
    return r;
6998
}
6999

    
7000
int qemu_powerdown_requested(void)
7001
{
7002
    int r = powerdown_requested;
7003
    powerdown_requested = 0;
7004
    return r;
7005
}
7006

    
7007
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7008
{
7009
    QEMUResetEntry **pre, *re;
7010

    
7011
    pre = &first_reset_entry;
7012
    while (*pre != NULL)
7013
        pre = &(*pre)->next;
7014
    re = qemu_mallocz(sizeof(QEMUResetEntry));
7015
    re->func = func;
7016
    re->opaque = opaque;
7017
    re->next = NULL;
7018
    *pre = re;
7019
}
7020

    
7021
void qemu_system_reset(void)
7022
{
7023
    QEMUResetEntry *re;
7024

    
7025
    /* reset all devices */
7026
    for(re = first_reset_entry; re != NULL; re = re->next) {
7027
        re->func(re->opaque);
7028
    }
7029
}
7030

    
7031
void qemu_system_reset_request(void)
7032
{
7033
    if (no_reboot) {
7034
        shutdown_requested = 1;
7035
    } else {
7036
        reset_requested = 1;
7037
    }
7038
    if (cpu_single_env)
7039
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7040
}
7041

    
7042
void qemu_system_shutdown_request(void)
7043
{
7044
    shutdown_requested = 1;
7045
    if (cpu_single_env)
7046
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7047
}
7048

    
7049
void qemu_system_powerdown_request(void)
7050
{
7051
    powerdown_requested = 1;
7052
    if (cpu_single_env)
7053
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7054
}
7055

    
7056
void main_loop_wait(int timeout)
7057
{
7058
    IOHandlerRecord *ioh;
7059
    fd_set rfds, wfds, xfds;
7060
    int ret, nfds;
7061
#ifdef _WIN32
7062
    int ret2, i;
7063
#endif
7064
    struct timeval tv;
7065
    PollingEntry *pe;
7066

    
7067

    
7068
    /* XXX: need to suppress polling by better using win32 events */
7069
    ret = 0;
7070
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7071
        ret |= pe->func(pe->opaque);
7072
    }
7073
#ifdef _WIN32
7074
    if (ret == 0) {
7075
        int err;
7076
        WaitObjects *w = &wait_objects;
7077

    
7078
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7079
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7080
            if (w->func[ret - WAIT_OBJECT_0])
7081
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7082

    
7083
            /* Check for additional signaled events */
7084
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7085

    
7086
                /* Check if event is signaled */
7087
                ret2 = WaitForSingleObject(w->events[i], 0);
7088
                if(ret2 == WAIT_OBJECT_0) {
7089
                    if (w->func[i])
7090
                        w->func[i](w->opaque[i]);
7091
                } else if (ret2 == WAIT_TIMEOUT) {
7092
                } else {
7093
                    err = GetLastError();
7094
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7095
                }
7096
            }
7097
        } else if (ret == WAIT_TIMEOUT) {
7098
        } else {
7099
            err = GetLastError();
7100
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7101
        }
7102
    }
7103
#endif
7104
    /* poll any events */
7105
    /* XXX: separate device handlers from system ones */
7106
    nfds = -1;
7107
    FD_ZERO(&rfds);
7108
    FD_ZERO(&wfds);
7109
    FD_ZERO(&xfds);
7110
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7111
        if (ioh->deleted)
7112
            continue;
7113
        if (ioh->fd_read &&
7114
            (!ioh->fd_read_poll ||
7115
             ioh->fd_read_poll(ioh->opaque) != 0)) {
7116
            FD_SET(ioh->fd, &rfds);
7117
            if (ioh->fd > nfds)
7118
                nfds = ioh->fd;
7119
        }
7120
        if (ioh->fd_write) {
7121
            FD_SET(ioh->fd, &wfds);
7122
            if (ioh->fd > nfds)
7123
                nfds = ioh->fd;
7124
        }
7125
    }
7126

    
7127
    tv.tv_sec = 0;
7128
#ifdef _WIN32
7129
    tv.tv_usec = 0;
7130
#else
7131
    tv.tv_usec = timeout * 1000;
7132
#endif
7133
#if defined(CONFIG_SLIRP)
7134
    if (slirp_inited) {
7135
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7136
    }
7137
#endif
7138
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7139
    if (ret > 0) {
7140
        IOHandlerRecord **pioh;
7141

    
7142
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7143
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7144
                ioh->fd_read(ioh->opaque);
7145
            }
7146
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7147
                ioh->fd_write(ioh->opaque);
7148
            }
7149
        }
7150

    
7151
        /* remove deleted IO handlers */
7152
        pioh = &first_io_handler;
7153
        while (*pioh) {
7154
            ioh = *pioh;
7155
            if (ioh->deleted) {
7156
                *pioh = ioh->next;
7157
                qemu_free(ioh);
7158
            } else
7159
                pioh = &ioh->next;
7160
        }
7161
    }
7162
#if defined(CONFIG_SLIRP)
7163
    if (slirp_inited) {
7164
        if (ret < 0) {
7165
            FD_ZERO(&rfds);
7166
            FD_ZERO(&wfds);
7167
            FD_ZERO(&xfds);
7168
        }
7169
        slirp_select_poll(&rfds, &wfds, &xfds);
7170
    }
7171
#endif
7172
    qemu_aio_poll();
7173

    
7174
    if (vm_running) {
7175
        if (likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
7176
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7177
                        qemu_get_clock(vm_clock));
7178
        /* run dma transfers, if any */
7179
        DMA_run();
7180
    }
7181

    
7182
    /* real time timers */
7183
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7184
                    qemu_get_clock(rt_clock));
7185

    
7186
    if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7187
        alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7188
        qemu_rearm_alarm_timer(alarm_timer);
7189
    }
7190

    
7191
    /* Check bottom-halves last in case any of the earlier events triggered
7192
       them.  */
7193
    qemu_bh_poll();
7194

    
7195
}
7196

    
7197
static int main_loop(void)
7198
{
7199
    int ret, timeout;
7200
#ifdef CONFIG_PROFILER
7201
    int64_t ti;
7202
#endif
7203
    CPUState *env;
7204

    
7205
    cur_cpu = first_cpu;
7206
    next_cpu = cur_cpu->next_cpu ?: first_cpu;
7207
    for(;;) {
7208
        if (vm_running) {
7209

    
7210
            for(;;) {
7211
                /* get next cpu */
7212
                env = next_cpu;
7213
#ifdef CONFIG_PROFILER
7214
                ti = profile_getclock();
7215
#endif
7216
                if (use_icount) {
7217
                    int64_t count;
7218
                    int decr;
7219
                    qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
7220
                    env->icount_decr.u16.low = 0;
7221
                    env->icount_extra = 0;
7222
                    count = qemu_next_deadline();
7223
                    count = (count + (1 << icount_time_shift) - 1)
7224
                            >> icount_time_shift;
7225
                    qemu_icount += count;
7226
                    decr = (count > 0xffff) ? 0xffff : count;
7227
                    count -= decr;
7228
                    env->icount_decr.u16.low = decr;
7229
                    env->icount_extra = count;
7230
                }
7231
                ret = cpu_exec(env);
7232
#ifdef CONFIG_PROFILER
7233
                qemu_time += profile_getclock() - ti;
7234
#endif
7235
                if (use_icount) {
7236
                    /* Fold pending instructions back into the
7237
                       instruction counter, and clear the interrupt flag.  */
7238
                    qemu_icount -= (env->icount_decr.u16.low
7239
                                    + env->icount_extra);
7240
                    env->icount_decr.u32 = 0;
7241
                    env->icount_extra = 0;
7242
                }
7243
                next_cpu = env->next_cpu ?: first_cpu;
7244
                if (event_pending && likely(ret != EXCP_DEBUG)) {
7245
                    ret = EXCP_INTERRUPT;
7246
                    event_pending = 0;
7247
                    break;
7248
                }
7249
                if (ret == EXCP_HLT) {
7250
                    /* Give the next CPU a chance to run.  */
7251
                    cur_cpu = env;
7252
                    continue;
7253
                }
7254
                if (ret != EXCP_HALTED)
7255
                    break;
7256
                /* all CPUs are halted ? */
7257
                if (env == cur_cpu)
7258
                    break;
7259
            }
7260
            cur_cpu = env;
7261

    
7262
            if (shutdown_requested) {
7263
                ret = EXCP_INTERRUPT;
7264
                if (no_shutdown) {
7265
                    vm_stop(0);
7266
                    no_shutdown = 0;
7267
                }
7268
                else
7269
                    break;
7270
            }
7271
            if (reset_requested) {
7272
                reset_requested = 0;
7273
                qemu_system_reset();
7274
                ret = EXCP_INTERRUPT;
7275
            }
7276
            if (powerdown_requested) {
7277
                powerdown_requested = 0;
7278
                qemu_system_powerdown();
7279
                ret = EXCP_INTERRUPT;
7280
            }
7281
            if (unlikely(ret == EXCP_DEBUG)) {
7282
                vm_stop(EXCP_DEBUG);
7283
            }
7284
            /* If all cpus are halted then wait until the next IRQ */
7285
            /* XXX: use timeout computed from timers */
7286
            if (ret == EXCP_HALTED) {
7287
                if (use_icount) {
7288
                    int64_t add;
7289
                    int64_t delta;
7290
                    /* Advance virtual time to the next event.  */
7291
                    if (use_icount == 1) {
7292
                        /* When not using an adaptive execution frequency
7293
                           we tend to get badly out of sync with real time,
7294
                           so just delay for a reasonable amount of time.  */
7295
                        delta = 0;
7296
                    } else {
7297
                        delta = cpu_get_icount() - cpu_get_clock();
7298
                    }
7299
                    if (delta > 0) {
7300
                        /* If virtual time is ahead of real time then just
7301
                           wait for IO.  */
7302
                        timeout = (delta / 1000000) + 1;
7303
                    } else {
7304
                        /* Wait for either IO to occur or the next
7305
                           timer event.  */
7306
                        add = qemu_next_deadline();
7307
                        /* We advance the timer before checking for IO.
7308
                           Limit the amount we advance so that early IO
7309
                           activity won't get the guest too far ahead.  */
7310
                        if (add > 10000000)
7311
                            add = 10000000;
7312
                        delta += add;
7313
                        add = (add + (1 << icount_time_shift) - 1)
7314
                              >> icount_time_shift;
7315
                        qemu_icount += add;
7316
                        timeout = delta / 1000000;
7317
                        if (timeout < 0)
7318
                            timeout = 0;
7319
                    }
7320
                } else {
7321
                    timeout = 10;
7322
                }
7323
            } else {
7324
                timeout = 0;
7325
            }
7326
        } else {
7327
            timeout = 10;
7328
        }
7329
#ifdef CONFIG_PROFILER
7330
        ti = profile_getclock();
7331
#endif
7332
        main_loop_wait(timeout);
7333
#ifdef CONFIG_PROFILER
7334
        dev_time += profile_getclock() - ti;
7335
#endif
7336
    }
7337
    cpu_disable_ticks();
7338
    return ret;
7339
}
7340

    
7341
static void help(int exitcode)
7342
{
7343
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7344
           "usage: %s [options] [disk_image]\n"
7345
           "\n"
7346
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7347
           "\n"
7348
           "Standard options:\n"
7349
           "-M machine      select emulated machine (-M ? for list)\n"
7350
           "-cpu cpu        select CPU (-cpu ? for list)\n"
7351
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
7352
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
7353
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
7354
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7355
           "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7356
           "       [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7357
           "       [,cache=on|off][,format=f]\n"
7358
           "                use 'file' as a drive image\n"
7359
           "-mtdblock file  use 'file' as on-board Flash memory image\n"
7360
           "-sd file        use 'file' as SecureDigital card image\n"
7361
           "-pflash file    use 'file' as a parallel flash image\n"
7362
           "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7363
           "-snapshot       write to temporary files instead of disk image files\n"
7364
#ifdef CONFIG_SDL
7365
           "-no-frame       open SDL window without a frame and window decorations\n"
7366
           "-alt-grab       use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7367
           "-no-quit        disable SDL window close capability\n"
7368
#endif
7369
#ifdef TARGET_I386
7370
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
7371
#endif
7372
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
7373
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
7374
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
7375
           "-portrait       rotate graphical output 90 deg left (only PXA LCD)\n"
7376
#ifndef _WIN32
7377
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
7378
#endif
7379
#ifdef HAS_AUDIO
7380
           "-audio-help     print list of audio drivers and their options\n"
7381
           "-soundhw c1,... enable audio support\n"
7382
           "                and only specified sound cards (comma separated list)\n"
7383
           "                use -soundhw ? to get the list of supported cards\n"
7384
           "                use -soundhw all to enable all of them\n"
7385
#endif
7386
           "-localtime      set the real time clock to local time [default=utc]\n"
7387
           "-full-screen    start in full screen\n"
7388
#ifdef TARGET_I386
7389
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
7390
#endif
7391
           "-usb            enable the USB driver (will be the default soon)\n"
7392
           "-usbdevice name add the host or guest USB device 'name'\n"
7393
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7394
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
7395
#endif
7396
           "-name string    set the name of the guest\n"
7397
           "\n"
7398
           "Network options:\n"
7399
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7400
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
7401
#ifdef CONFIG_SLIRP
7402
           "-net user[,vlan=n][,hostname=host]\n"
7403
           "                connect the user mode network stack to VLAN 'n' and send\n"
7404
           "                hostname 'host' to DHCP clients\n"
7405
#endif
7406
#ifdef _WIN32
7407
           "-net tap[,vlan=n],ifname=name\n"
7408
           "                connect the host TAP network interface to VLAN 'n'\n"
7409
#else
7410
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7411
           "                connect the host TAP network interface to VLAN 'n' and use the\n"
7412
           "                network scripts 'file' (default=%s)\n"
7413
           "                and 'dfile' (default=%s);\n"
7414
           "                use '[down]script=no' to disable script execution;\n"
7415
           "                use 'fd=h' to connect to an already opened TAP interface\n"
7416
#endif
7417
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7418
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
7419
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7420
           "                connect the vlan 'n' to multicast maddr and port\n"
7421
           "-net none       use it alone to have zero network devices; if no -net option\n"
7422
           "                is provided, the default is '-net nic -net user'\n"
7423
           "\n"
7424
#ifdef CONFIG_SLIRP
7425
           "-tftp dir       allow tftp access to files in dir [-net user]\n"
7426
           "-bootp file     advertise file in BOOTP replies\n"
7427
#ifndef _WIN32
7428
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
7429
#endif
7430
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7431
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
7432
#endif
7433
           "\n"
7434
           "Linux boot specific:\n"
7435
           "-kernel bzImage use 'bzImage' as kernel image\n"
7436
           "-append cmdline use 'cmdline' as kernel command line\n"
7437
           "-initrd file    use 'file' as initial ram disk\n"
7438
           "\n"
7439
           "Debug/Expert options:\n"
7440
           "-monitor dev    redirect the monitor to char device 'dev'\n"
7441
           "-serial dev     redirect the serial port to char device 'dev'\n"
7442
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
7443
           "-pidfile file   Write PID to 'file'\n"
7444
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
7445
           "-s              wait gdb connection to port\n"
7446
           "-p port         set gdb connection port [default=%s]\n"
7447
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
7448
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
7449
           "                translation (t=none or lba) (usually qemu can guess them)\n"
7450
           "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
7451
#ifdef USE_KQEMU
7452
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
7453
           "-no-kqemu       disable KQEMU kernel module usage\n"
7454
#endif
7455
#ifdef TARGET_I386
7456
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
7457
           "                (default is CL-GD5446 PCI VGA)\n"
7458
           "-no-acpi        disable ACPI\n"
7459
#endif
7460
#ifdef CONFIG_CURSES
7461
           "-curses         use a curses/ncurses interface instead of SDL\n"
7462
#endif
7463
           "-no-reboot      exit instead of rebooting\n"
7464
           "-no-shutdown    stop before shutdown\n"
7465
           "-loadvm [tag|id]  start right away with a saved state (loadvm in monitor)\n"
7466
           "-vnc display    start a VNC server on display\n"
7467
#ifndef _WIN32
7468
           "-daemonize      daemonize QEMU after initializing\n"
7469
#endif
7470
           "-option-rom rom load a file, rom, into the option ROM space\n"
7471
#ifdef TARGET_SPARC
7472
           "-prom-env variable=value  set OpenBIOS nvram variables\n"
7473
#endif
7474
           "-clock          force the use of the given methods for timer alarm.\n"
7475
           "                To see what timers are available use -clock ?\n"
7476
           "-startdate      select initial date of the clock\n"
7477
           "-icount [N|auto]\n"
7478
           "                Enable virtual instruction counter with 2^N clock ticks per instruction\n"
7479
           "\n"
7480
           "During emulation, the following keys are useful:\n"
7481
           "ctrl-alt-f      toggle full screen\n"
7482
           "ctrl-alt-n      switch to virtual console 'n'\n"
7483
           "ctrl-alt        toggle mouse and keyboard grab\n"
7484
           "\n"
7485
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
7486
           ,
7487
           "qemu",
7488
           DEFAULT_RAM_SIZE,
7489
#ifndef _WIN32
7490
           DEFAULT_NETWORK_SCRIPT,
7491
           DEFAULT_NETWORK_DOWN_SCRIPT,
7492
#endif
7493
           DEFAULT_GDBSTUB_PORT,
7494
           "/tmp/qemu.log");
7495
    exit(exitcode);
7496
}
7497

    
7498
#define HAS_ARG 0x0001
7499

    
7500
enum {
7501
    QEMU_OPTION_h,
7502

    
7503
    QEMU_OPTION_M,
7504
    QEMU_OPTION_cpu,
7505
    QEMU_OPTION_fda,
7506
    QEMU_OPTION_fdb,
7507
    QEMU_OPTION_hda,
7508
    QEMU_OPTION_hdb,
7509
    QEMU_OPTION_hdc,
7510
    QEMU_OPTION_hdd,
7511
    QEMU_OPTION_drive,
7512
    QEMU_OPTION_cdrom,
7513
    QEMU_OPTION_mtdblock,
7514
    QEMU_OPTION_sd,
7515
    QEMU_OPTION_pflash,
7516
    QEMU_OPTION_boot,
7517
    QEMU_OPTION_snapshot,
7518
#ifdef TARGET_I386
7519
    QEMU_OPTION_no_fd_bootchk,
7520
#endif
7521
    QEMU_OPTION_m,
7522
    QEMU_OPTION_nographic,
7523
    QEMU_OPTION_portrait,
7524
#ifdef HAS_AUDIO
7525
    QEMU_OPTION_audio_help,
7526
    QEMU_OPTION_soundhw,
7527
#endif
7528

    
7529
    QEMU_OPTION_net,
7530
    QEMU_OPTION_tftp,
7531
    QEMU_OPTION_bootp,
7532
    QEMU_OPTION_smb,
7533
    QEMU_OPTION_redir,
7534

    
7535
    QEMU_OPTION_kernel,
7536
    QEMU_OPTION_append,
7537
    QEMU_OPTION_initrd,
7538

    
7539
    QEMU_OPTION_S,
7540
    QEMU_OPTION_s,
7541
    QEMU_OPTION_p,
7542
    QEMU_OPTION_d,
7543
    QEMU_OPTION_hdachs,
7544
    QEMU_OPTION_L,
7545
    QEMU_OPTION_bios,
7546
    QEMU_OPTION_k,
7547
    QEMU_OPTION_localtime,
7548
    QEMU_OPTION_cirrusvga,
7549
    QEMU_OPTION_vmsvga,
7550
    QEMU_OPTION_g,
7551
    QEMU_OPTION_std_vga,
7552
    QEMU_OPTION_echr,
7553
    QEMU_OPTION_monitor,
7554
    QEMU_OPTION_serial,
7555
    QEMU_OPTION_parallel,
7556
    QEMU_OPTION_loadvm,
7557
    QEMU_OPTION_full_screen,
7558
    QEMU_OPTION_no_frame,
7559
    QEMU_OPTION_alt_grab,
7560
    QEMU_OPTION_no_quit,
7561
    QEMU_OPTION_pidfile,
7562
    QEMU_OPTION_no_kqemu,
7563
    QEMU_OPTION_kernel_kqemu,
7564
    QEMU_OPTION_win2k_hack,
7565
    QEMU_OPTION_usb,
7566
    QEMU_OPTION_usbdevice,
7567
    QEMU_OPTION_smp,
7568
    QEMU_OPTION_vnc,
7569
    QEMU_OPTION_no_acpi,
7570
    QEMU_OPTION_curses,
7571
    QEMU_OPTION_no_reboot,
7572
    QEMU_OPTION_no_shutdown,
7573
    QEMU_OPTION_show_cursor,
7574
    QEMU_OPTION_daemonize,
7575
    QEMU_OPTION_option_rom,
7576
    QEMU_OPTION_semihosting,
7577
    QEMU_OPTION_name,
7578
    QEMU_OPTION_prom_env,
7579
    QEMU_OPTION_old_param,
7580
    QEMU_OPTION_clock,
7581
    QEMU_OPTION_startdate,
7582
    QEMU_OPTION_tb_size,
7583
    QEMU_OPTION_icount,
7584
};
7585

    
7586
typedef struct QEMUOption {
7587
    const char *name;
7588
    int flags;
7589
    int index;
7590
} QEMUOption;
7591

    
7592
const QEMUOption qemu_options[] = {
7593
    { "h", 0, QEMU_OPTION_h },
7594
    { "help", 0, QEMU_OPTION_h },
7595

    
7596
    { "M", HAS_ARG, QEMU_OPTION_M },
7597
    { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7598
    { "fda", HAS_ARG, QEMU_OPTION_fda },
7599
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7600
    { "hda", HAS_ARG, QEMU_OPTION_hda },
7601
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7602
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7603
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7604
    { "drive", HAS_ARG, QEMU_OPTION_drive },
7605
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7606
    { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7607
    { "sd", HAS_ARG, QEMU_OPTION_sd },
7608
    { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7609
    { "boot", HAS_ARG, QEMU_OPTION_boot },
7610
    { "snapshot", 0, QEMU_OPTION_snapshot },
7611
#ifdef TARGET_I386
7612
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7613
#endif
7614
    { "m", HAS_ARG, QEMU_OPTION_m },
7615
    { "nographic", 0, QEMU_OPTION_nographic },
7616
    { "portrait", 0, QEMU_OPTION_portrait },
7617
    { "k", HAS_ARG, QEMU_OPTION_k },
7618
#ifdef HAS_AUDIO
7619
    { "audio-help", 0, QEMU_OPTION_audio_help },
7620
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7621
#endif
7622

    
7623
    { "net", HAS_ARG, QEMU_OPTION_net},
7624
#ifdef CONFIG_SLIRP
7625
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7626
    { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7627
#ifndef _WIN32
7628
    { "smb", HAS_ARG, QEMU_OPTION_smb },
7629
#endif
7630
    { "redir", HAS_ARG, QEMU_OPTION_redir },
7631
#endif
7632

    
7633
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7634
    { "append", HAS_ARG, QEMU_OPTION_append },
7635
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7636

    
7637
    { "S", 0, QEMU_OPTION_S },
7638
    { "s", 0, QEMU_OPTION_s },
7639
    { "p", HAS_ARG, QEMU_OPTION_p },
7640
    { "d", HAS_ARG, QEMU_OPTION_d },
7641
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7642
    { "L", HAS_ARG, QEMU_OPTION_L },
7643
    { "bios", HAS_ARG, QEMU_OPTION_bios },
7644
#ifdef USE_KQEMU
7645
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7646
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7647
#endif
7648
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7649
    { "g", 1, QEMU_OPTION_g },
7650
#endif
7651
    { "localtime", 0, QEMU_OPTION_localtime },
7652
    { "std-vga", 0, QEMU_OPTION_std_vga },
7653
    { "echr", HAS_ARG, QEMU_OPTION_echr },
7654
    { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7655
    { "serial", HAS_ARG, QEMU_OPTION_serial },
7656
    { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7657
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7658
    { "full-screen", 0, QEMU_OPTION_full_screen },
7659
#ifdef CONFIG_SDL
7660
    { "no-frame", 0, QEMU_OPTION_no_frame },
7661
    { "alt-grab", 0, QEMU_OPTION_alt_grab },
7662
    { "no-quit", 0, QEMU_OPTION_no_quit },
7663
#endif
7664
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7665
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7666
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7667
    { "smp", HAS_ARG, QEMU_OPTION_smp },
7668
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7669
#ifdef CONFIG_CURSES
7670
    { "curses", 0, QEMU_OPTION_curses },
7671
#endif
7672

    
7673
    /* temporary options */
7674
    { "usb", 0, QEMU_OPTION_usb },
7675
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
7676
    { "vmwarevga", 0, QEMU_OPTION_vmsvga },
7677
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
7678
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
7679
    { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
7680
    { "show-cursor", 0, QEMU_OPTION_show_cursor },
7681
    { "daemonize", 0, QEMU_OPTION_daemonize },
7682
    { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
7683
#if defined(TARGET_ARM) || defined(TARGET_M68K)
7684
    { "semihosting", 0, QEMU_OPTION_semihosting },
7685
#endif
7686
    { "name", HAS_ARG, QEMU_OPTION_name },
7687
#if defined(TARGET_SPARC)
7688
    { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
7689
#endif
7690
#if defined(TARGET_ARM)
7691
    { "old-param", 0, QEMU_OPTION_old_param },
7692
#endif
7693
    { "clock", HAS_ARG, QEMU_OPTION_clock },
7694
    { "startdate", HAS_ARG, QEMU_OPTION_startdate },
7695
    { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
7696
    { "icount", HAS_ARG, QEMU_OPTION_icount },
7697
    { NULL },
7698
};
7699

    
7700
/* password input */
7701

    
7702
int qemu_key_check(BlockDriverState *bs, const char *name)
7703
{
7704
    char password[256];
7705
    int i;
7706

    
7707
    if (!bdrv_is_encrypted(bs))
7708
        return 0;
7709

    
7710
    term_printf("%s is encrypted.\n", name);
7711
    for(i = 0; i < 3; i++) {
7712
        monitor_readline("Password: ", 1, password, sizeof(password));
7713
        if (bdrv_set_key(bs, password) == 0)
7714
            return 0;
7715
        term_printf("invalid password\n");
7716
    }
7717
    return -EPERM;
7718
}
7719

    
7720
static BlockDriverState *get_bdrv(int index)
7721
{
7722
    if (index > nb_drives)
7723
        return NULL;
7724
    return drives_table[index].bdrv;
7725
}
7726

    
7727
static void read_passwords(void)
7728
{
7729
    BlockDriverState *bs;
7730
    int i;
7731

    
7732
    for(i = 0; i < 6; i++) {
7733
        bs = get_bdrv(i);
7734
        if (bs)
7735
            qemu_key_check(bs, bdrv_get_device_name(bs));
7736
    }
7737
}
7738

    
7739
#ifdef HAS_AUDIO
7740
struct soundhw soundhw[] = {
7741
#ifdef HAS_AUDIO_CHOICE
7742
#if defined(TARGET_I386) || defined(TARGET_MIPS)
7743
    {
7744
        "pcspk",
7745
        "PC speaker",
7746
        0,
7747
        1,
7748
        { .init_isa = pcspk_audio_init }
7749
    },
7750
#endif
7751
    {
7752
        "sb16",
7753
        "Creative Sound Blaster 16",
7754
        0,
7755
        1,
7756
        { .init_isa = SB16_init }
7757
    },
7758

    
7759
#ifdef CONFIG_CS4231A
7760
    {
7761
        "cs4231a",
7762
        "CS4231A",
7763
        0,
7764
        1,
7765
        { .init_isa = cs4231a_init }
7766
    },
7767
#endif
7768

    
7769
#ifdef CONFIG_ADLIB
7770
    {
7771
        "adlib",
7772
#ifdef HAS_YMF262
7773
        "Yamaha YMF262 (OPL3)",
7774
#else
7775
        "Yamaha YM3812 (OPL2)",
7776
#endif
7777
        0,
7778
        1,
7779
        { .init_isa = Adlib_init }
7780
    },
7781
#endif
7782

    
7783
#ifdef CONFIG_GUS
7784
    {
7785
        "gus",
7786
        "Gravis Ultrasound GF1",
7787
        0,
7788
        1,
7789
        { .init_isa = GUS_init }
7790
    },
7791
#endif
7792

    
7793
#ifdef CONFIG_AC97
7794
    {
7795
        "ac97",
7796
        "Intel 82801AA AC97 Audio",
7797
        0,
7798
        0,
7799
        { .init_pci = ac97_init }
7800
    },
7801
#endif
7802

    
7803
    {
7804
        "es1370",
7805
        "ENSONIQ AudioPCI ES1370",
7806
        0,
7807
        0,
7808
        { .init_pci = es1370_init }
7809
    },
7810
#endif
7811

    
7812
    { NULL, NULL, 0, 0, { NULL } }
7813
};
7814

    
7815
static void select_soundhw (const char *optarg)
7816
{
7817
    struct soundhw *c;
7818

    
7819
    if (*optarg == '?') {
7820
    show_valid_cards:
7821

    
7822
        printf ("Valid sound card names (comma separated):\n");
7823
        for (c = soundhw; c->name; ++c) {
7824
            printf ("%-11s %s\n", c->name, c->descr);
7825
        }
7826
        printf ("\n-soundhw all will enable all of the above\n");
7827
        exit (*optarg != '?');
7828
    }
7829
    else {
7830
        size_t l;
7831
        const char *p;
7832
        char *e;
7833
        int bad_card = 0;
7834

    
7835
        if (!strcmp (optarg, "all")) {
7836
            for (c = soundhw; c->name; ++c) {
7837
                c->enabled = 1;
7838
            }
7839
            return;
7840
        }
7841

    
7842
        p = optarg;
7843
        while (*p) {
7844
            e = strchr (p, ',');
7845
            l = !e ? strlen (p) : (size_t) (e - p);
7846

    
7847
            for (c = soundhw; c->name; ++c) {
7848
                if (!strncmp (c->name, p, l)) {
7849
                    c->enabled = 1;
7850
                    break;
7851
                }
7852
            }
7853

    
7854
            if (!c->name) {
7855
                if (l > 80) {
7856
                    fprintf (stderr,
7857
                             "Unknown sound card name (too big to show)\n");
7858
                }
7859
                else {
7860
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
7861
                             (int) l, p);
7862
                }
7863
                bad_card = 1;
7864
            }
7865
            p += l + (e != NULL);
7866
        }
7867

    
7868
        if (bad_card)
7869
            goto show_valid_cards;
7870
    }
7871
}
7872
#endif
7873

    
7874
#ifdef _WIN32
7875
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
7876
{
7877
    exit(STATUS_CONTROL_C_EXIT);
7878
    return TRUE;
7879
}
7880
#endif
7881

    
7882
#define MAX_NET_CLIENTS 32
7883

    
7884
int main(int argc, char **argv)
7885
{
7886
#ifdef CONFIG_GDBSTUB
7887
    int use_gdbstub;
7888
    const char *gdbstub_port;
7889
#endif
7890
    uint32_t boot_devices_bitmap = 0;
7891
    int i;
7892
    int snapshot, linux_boot, net_boot;
7893
    const char *initrd_filename;
7894
    const char *kernel_filename, *kernel_cmdline;
7895
    const char *boot_devices = "";
7896
    DisplayState *ds = &display_state;
7897
    int cyls, heads, secs, translation;
7898
    const char *net_clients[MAX_NET_CLIENTS];
7899
    int nb_net_clients;
7900
    int hda_index;
7901
    int optind;
7902
    const char *r, *optarg;
7903
    CharDriverState *monitor_hd;
7904
    const char *monitor_device;
7905
    const char *serial_devices[MAX_SERIAL_PORTS];
7906
    int serial_device_index;
7907
    const char *parallel_devices[MAX_PARALLEL_PORTS];
7908
    int parallel_device_index;
7909
    const char *loadvm = NULL;
7910
    QEMUMachine *machine;
7911
    const char *cpu_model;
7912
    const char *usb_devices[MAX_USB_CMDLINE];
7913
    int usb_devices_index;
7914
    int fds[2];
7915
    int tb_size;
7916
    const char *pid_file = NULL;
7917
    VLANState *vlan;
7918

    
7919
    LIST_INIT (&vm_change_state_head);
7920
#ifndef _WIN32
7921
    {
7922
        struct sigaction act;
7923
        sigfillset(&act.sa_mask);
7924
        act.sa_flags = 0;
7925
        act.sa_handler = SIG_IGN;
7926
        sigaction(SIGPIPE, &act, NULL);
7927
    }
7928
#else
7929
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
7930
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
7931
       QEMU to run on a single CPU */
7932
    {
7933
        HANDLE h;
7934
        DWORD mask, smask;
7935
        int i;
7936
        h = GetCurrentProcess();
7937
        if (GetProcessAffinityMask(h, &mask, &smask)) {
7938
            for(i = 0; i < 32; i++) {
7939
                if (mask & (1 << i))
7940
                    break;
7941
            }
7942
            if (i != 32) {
7943
                mask = 1 << i;
7944
                SetProcessAffinityMask(h, mask);
7945
            }
7946
        }
7947
    }
7948
#endif
7949

    
7950
    register_machines();
7951
    machine = first_machine;
7952
    cpu_model = NULL;
7953
    initrd_filename = NULL;
7954
    ram_size = 0;
7955
    vga_ram_size = VGA_RAM_SIZE;
7956
#ifdef CONFIG_GDBSTUB
7957
    use_gdbstub = 0;
7958
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
7959
#endif
7960
    snapshot = 0;
7961
    nographic = 0;
7962
    curses = 0;
7963
    kernel_filename = NULL;
7964
    kernel_cmdline = "";
7965
    cyls = heads = secs = 0;
7966
    translation = BIOS_ATA_TRANSLATION_AUTO;
7967
    monitor_device = "vc";
7968

    
7969
    serial_devices[0] = "vc:80Cx24C";
7970
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
7971
        serial_devices[i] = NULL;
7972
    serial_device_index = 0;
7973

    
7974
    parallel_devices[0] = "vc:640x480";
7975
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7976
        parallel_devices[i] = NULL;
7977
    parallel_device_index = 0;
7978

    
7979
    usb_devices_index = 0;
7980

    
7981
    nb_net_clients = 0;
7982
    nb_drives = 0;
7983
    nb_drives_opt = 0;
7984
    hda_index = -1;
7985

    
7986
    nb_nics = 0;
7987

    
7988
    tb_size = 0;
7989
    
7990
    optind = 1;
7991
    for(;;) {
7992
        if (optind >= argc)
7993
            break;
7994
        r = argv[optind];
7995
        if (r[0] != '-') {
7996
            hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
7997
        } else {
7998
            const QEMUOption *popt;
7999

    
8000
            optind++;
8001
            /* Treat --foo the same as -foo.  */
8002
            if (r[1] == '-')
8003
                r++;
8004
            popt = qemu_options;
8005
            for(;;) {
8006
                if (!popt->name) {
8007
                    fprintf(stderr, "%s: invalid option -- '%s'\n",
8008
                            argv[0], r);
8009
                    exit(1);
8010
                }
8011
                if (!strcmp(popt->name, r + 1))
8012
                    break;
8013
                popt++;
8014
            }
8015
            if (popt->flags & HAS_ARG) {
8016
                if (optind >= argc) {
8017
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
8018
                            argv[0], r);
8019
                    exit(1);
8020
                }
8021
                optarg = argv[optind++];
8022
            } else {
8023
                optarg = NULL;
8024
            }
8025

    
8026
            switch(popt->index) {
8027
            case QEMU_OPTION_M:
8028
                machine = find_machine(optarg);
8029
                if (!machine) {
8030
                    QEMUMachine *m;
8031
                    printf("Supported machines are:\n");
8032
                    for(m = first_machine; m != NULL; m = m->next) {
8033
                        printf("%-10s %s%s\n",
8034
                               m->name, m->desc,
8035
                               m == first_machine ? " (default)" : "");
8036
                    }
8037
                    exit(*optarg != '?');
8038
                }
8039
                break;
8040
            case QEMU_OPTION_cpu:
8041
                /* hw initialization will check this */
8042
                if (*optarg == '?') {
8043
/* XXX: implement xxx_cpu_list for targets that still miss it */
8044
#if defined(cpu_list)
8045
                    cpu_list(stdout, &fprintf);
8046
#endif
8047
                    exit(0);
8048
                } else {
8049
                    cpu_model = optarg;
8050
                }
8051
                break;
8052
            case QEMU_OPTION_initrd:
8053
                initrd_filename = optarg;
8054
                break;
8055
            case QEMU_OPTION_hda:
8056
                if (cyls == 0)
8057
                    hda_index = drive_add(optarg, HD_ALIAS, 0);
8058
                else
8059
                    hda_index = drive_add(optarg, HD_ALIAS
8060
                             ",cyls=%d,heads=%d,secs=%d%s",
8061
                             0, cyls, heads, secs,
8062
                             translation == BIOS_ATA_TRANSLATION_LBA ?
8063
                                 ",trans=lba" :
8064
                             translation == BIOS_ATA_TRANSLATION_NONE ?
8065
                                 ",trans=none" : "");
8066
                 break;
8067
            case QEMU_OPTION_hdb:
8068
            case QEMU_OPTION_hdc:
8069
            case QEMU_OPTION_hdd:
8070
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8071
                break;
8072
            case QEMU_OPTION_drive:
8073
                drive_add(NULL, "%s", optarg);
8074
                break;
8075
            case QEMU_OPTION_mtdblock:
8076
                drive_add(optarg, MTD_ALIAS);
8077
                break;
8078
            case QEMU_OPTION_sd:
8079
                drive_add(optarg, SD_ALIAS);
8080
                break;
8081
            case QEMU_OPTION_pflash:
8082
                drive_add(optarg, PFLASH_ALIAS);
8083
                break;
8084
            case QEMU_OPTION_snapshot:
8085
                snapshot = 1;
8086
                break;
8087
            case QEMU_OPTION_hdachs:
8088
                {
8089
                    const char *p;
8090
                    p = optarg;
8091
                    cyls = strtol(p, (char **)&p, 0);
8092
                    if (cyls < 1 || cyls > 16383)
8093
                        goto chs_fail;
8094
                    if (*p != ',')
8095
                        goto chs_fail;
8096
                    p++;
8097
                    heads = strtol(p, (char **)&p, 0);
8098
                    if (heads < 1 || heads > 16)
8099
                        goto chs_fail;
8100
                    if (*p != ',')
8101
                        goto chs_fail;
8102
                    p++;
8103
                    secs = strtol(p, (char **)&p, 0);
8104
                    if (secs < 1 || secs > 63)
8105
                        goto chs_fail;
8106
                    if (*p == ',') {
8107
                        p++;
8108
                        if (!strcmp(p, "none"))
8109
                            translation = BIOS_ATA_TRANSLATION_NONE;
8110
                        else if (!strcmp(p, "lba"))
8111
                            translation = BIOS_ATA_TRANSLATION_LBA;
8112
                        else if (!strcmp(p, "auto"))
8113
                            translation = BIOS_ATA_TRANSLATION_AUTO;
8114
                        else
8115
                            goto chs_fail;
8116
                    } else if (*p != '\0') {
8117
                    chs_fail:
8118
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
8119
                        exit(1);
8120
                    }
8121
                    if (hda_index != -1)
8122
                        snprintf(drives_opt[hda_index].opt,
8123
                                 sizeof(drives_opt[hda_index].opt),
8124
                                 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8125
                                 0, cyls, heads, secs,
8126
                                 translation == BIOS_ATA_TRANSLATION_LBA ?
8127
                                         ",trans=lba" :
8128
                                 translation == BIOS_ATA_TRANSLATION_NONE ?
8129
                                     ",trans=none" : "");
8130
                }
8131
                break;
8132
            case QEMU_OPTION_nographic:
8133
                serial_devices[0] = "stdio";
8134
                parallel_devices[0] = "null";
8135
                monitor_device = "stdio";
8136
                nographic = 1;
8137
                break;
8138
#ifdef CONFIG_CURSES
8139
            case QEMU_OPTION_curses:
8140
                curses = 1;
8141
                break;
8142
#endif
8143
            case QEMU_OPTION_portrait:
8144
                graphic_rotate = 1;
8145
                break;
8146
            case QEMU_OPTION_kernel:
8147
                kernel_filename = optarg;
8148
                break;
8149
            case QEMU_OPTION_append:
8150
                kernel_cmdline = optarg;
8151
                break;
8152
            case QEMU_OPTION_cdrom:
8153
                drive_add(optarg, CDROM_ALIAS);
8154
                break;
8155
            case QEMU_OPTION_boot:
8156
                boot_devices = optarg;
8157
                /* We just do some generic consistency checks */
8158
                {
8159
                    /* Could easily be extended to 64 devices if needed */
8160
                    const char *p;
8161
                    
8162
                    boot_devices_bitmap = 0;
8163
                    for (p = boot_devices; *p != '\0'; p++) {
8164
                        /* Allowed boot devices are:
8165
                         * a b     : floppy disk drives
8166
                         * c ... f : IDE disk drives
8167
                         * g ... m : machine implementation dependant drives
8168
                         * n ... p : network devices
8169
                         * It's up to each machine implementation to check
8170
                         * if the given boot devices match the actual hardware
8171
                         * implementation and firmware features.
8172
                         */
8173
                        if (*p < 'a' || *p > 'q') {
8174
                            fprintf(stderr, "Invalid boot device '%c'\n", *p);
8175
                            exit(1);
8176
                        }
8177
                        if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8178
                            fprintf(stderr,
8179
                                    "Boot device '%c' was given twice\n",*p);
8180
                            exit(1);
8181
                        }
8182
                        boot_devices_bitmap |= 1 << (*p - 'a');
8183
                    }
8184
                }
8185
                break;
8186
            case QEMU_OPTION_fda:
8187
            case QEMU_OPTION_fdb:
8188
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8189
                break;
8190
#ifdef TARGET_I386
8191
            case QEMU_OPTION_no_fd_bootchk:
8192
                fd_bootchk = 0;
8193
                break;
8194
#endif
8195
            case QEMU_OPTION_net:
8196
                if (nb_net_clients >= MAX_NET_CLIENTS) {
8197
                    fprintf(stderr, "qemu: too many network clients\n");
8198
                    exit(1);
8199
                }
8200
                net_clients[nb_net_clients] = optarg;
8201
                nb_net_clients++;
8202
                break;
8203
#ifdef CONFIG_SLIRP
8204
            case QEMU_OPTION_tftp:
8205
                tftp_prefix = optarg;
8206
                break;
8207
            case QEMU_OPTION_bootp:
8208
                bootp_filename = optarg;
8209
                break;
8210
#ifndef _WIN32
8211
            case QEMU_OPTION_smb:
8212
                net_slirp_smb(optarg);
8213
                break;
8214
#endif
8215
            case QEMU_OPTION_redir:
8216
                net_slirp_redir(optarg);
8217
                break;
8218
#endif
8219
#ifdef HAS_AUDIO
8220
            case QEMU_OPTION_audio_help:
8221
                AUD_help ();
8222
                exit (0);
8223
                break;
8224
            case QEMU_OPTION_soundhw:
8225
                select_soundhw (optarg);
8226
                break;
8227
#endif
8228
            case QEMU_OPTION_h:
8229
                help(0);
8230
                break;
8231
            case QEMU_OPTION_m: {
8232
                uint64_t value;
8233
                char *ptr;
8234

    
8235
                value = strtoul(optarg, &ptr, 10);
8236
                switch (*ptr) {
8237
                case 0: case 'M': case 'm':
8238
                    value <<= 20;
8239
                    break;
8240
                case 'G': case 'g':
8241
                    value <<= 30;
8242
                    break;
8243
                default:
8244
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
8245
                    exit(1);
8246
                }
8247

    
8248
                /* On 32-bit hosts, QEMU is limited by virtual address space */
8249
                if (value > (2047 << 20)
8250
#ifndef USE_KQEMU
8251
                    && HOST_LONG_BITS == 32
8252
#endif
8253
                    ) {
8254
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
8255
                    exit(1);
8256
                }
8257
                if (value != (uint64_t)(ram_addr_t)value) {
8258
                    fprintf(stderr, "qemu: ram size too large\n");
8259
                    exit(1);
8260
                }
8261
                ram_size = value;
8262
                break;
8263
            }
8264
            case QEMU_OPTION_d:
8265
                {
8266
                    int mask;
8267
                    CPULogItem *item;
8268

    
8269
                    mask = cpu_str_to_log_mask(optarg);
8270
                    if (!mask) {
8271
                        printf("Log items (comma separated):\n");
8272
                    for(item = cpu_log_items; item->mask != 0; item++) {
8273
                        printf("%-10s %s\n", item->name, item->help);
8274
                    }
8275
                    exit(1);
8276
                    }
8277
                    cpu_set_log(mask);
8278
                }
8279
                break;
8280
#ifdef CONFIG_GDBSTUB
8281
            case QEMU_OPTION_s:
8282
                use_gdbstub = 1;
8283
                break;
8284
            case QEMU_OPTION_p:
8285
                gdbstub_port = optarg;
8286
                break;
8287
#endif
8288
            case QEMU_OPTION_L:
8289
                bios_dir = optarg;
8290
                break;
8291
            case QEMU_OPTION_bios:
8292
                bios_name = optarg;
8293
                break;
8294
            case QEMU_OPTION_S:
8295
                autostart = 0;
8296
                break;
8297
            case QEMU_OPTION_k:
8298
                keyboard_layout = optarg;
8299
                break;
8300
            case QEMU_OPTION_localtime:
8301
                rtc_utc = 0;
8302
                break;
8303
            case QEMU_OPTION_cirrusvga:
8304
                cirrus_vga_enabled = 1;
8305
                vmsvga_enabled = 0;
8306
                break;
8307
            case QEMU_OPTION_vmsvga:
8308
                cirrus_vga_enabled = 0;
8309
                vmsvga_enabled = 1;
8310
                break;
8311
            case QEMU_OPTION_std_vga:
8312
                cirrus_vga_enabled = 0;
8313
                vmsvga_enabled = 0;
8314
                break;
8315
            case QEMU_OPTION_g:
8316
                {
8317
                    const char *p;
8318
                    int w, h, depth;
8319
                    p = optarg;
8320
                    w = strtol(p, (char **)&p, 10);
8321
                    if (w <= 0) {
8322
                    graphic_error:
8323
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
8324
                        exit(1);
8325
                    }
8326
                    if (*p != 'x')
8327
                        goto graphic_error;
8328
                    p++;
8329
                    h = strtol(p, (char **)&p, 10);
8330
                    if (h <= 0)
8331
                        goto graphic_error;
8332
                    if (*p == 'x') {
8333
                        p++;
8334
                        depth = strtol(p, (char **)&p, 10);
8335
                        if (depth != 8 && depth != 15 && depth != 16 &&
8336
                            depth != 24 && depth != 32)
8337
                            goto graphic_error;
8338
                    } else if (*p == '\0') {
8339
                        depth = graphic_depth;
8340
                    } else {
8341
                        goto graphic_error;
8342
                    }
8343

    
8344
                    graphic_width = w;
8345
                    graphic_height = h;
8346
                    graphic_depth = depth;
8347
                }
8348
                break;
8349
            case QEMU_OPTION_echr:
8350
                {
8351
                    char *r;
8352
                    term_escape_char = strtol(optarg, &r, 0);
8353
                    if (r == optarg)
8354
                        printf("Bad argument to echr\n");
8355
                    break;
8356
                }
8357
            case QEMU_OPTION_monitor:
8358
                monitor_device = optarg;
8359
                break;
8360
            case QEMU_OPTION_serial:
8361
                if (serial_device_index >= MAX_SERIAL_PORTS) {
8362
                    fprintf(stderr, "qemu: too many serial ports\n");
8363
                    exit(1);
8364
                }
8365
                serial_devices[serial_device_index] = optarg;
8366
                serial_device_index++;
8367
                break;
8368
            case QEMU_OPTION_parallel:
8369
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8370
                    fprintf(stderr, "qemu: too many parallel ports\n");
8371
                    exit(1);
8372
                }
8373
                parallel_devices[parallel_device_index] = optarg;
8374
                parallel_device_index++;
8375
                break;
8376
            case QEMU_OPTION_loadvm:
8377
                loadvm = optarg;
8378
                break;
8379
            case QEMU_OPTION_full_screen:
8380
                full_screen = 1;
8381
                break;
8382
#ifdef CONFIG_SDL
8383
            case QEMU_OPTION_no_frame:
8384
                no_frame = 1;
8385
                break;
8386
            case QEMU_OPTION_alt_grab:
8387
                alt_grab = 1;
8388
                break;
8389
            case QEMU_OPTION_no_quit:
8390
                no_quit = 1;
8391
                break;
8392
#endif
8393
            case QEMU_OPTION_pidfile:
8394
                pid_file = optarg;
8395
                break;
8396
#ifdef TARGET_I386
8397
            case QEMU_OPTION_win2k_hack:
8398
                win2k_install_hack = 1;
8399
                break;
8400
#endif
8401
#ifdef USE_KQEMU
8402
            case QEMU_OPTION_no_kqemu:
8403
                kqemu_allowed = 0;
8404
                break;
8405
            case QEMU_OPTION_kernel_kqemu:
8406
                kqemu_allowed = 2;
8407
                break;
8408
#endif
8409
            case QEMU_OPTION_usb:
8410
                usb_enabled = 1;
8411
                break;
8412
            case QEMU_OPTION_usbdevice:
8413
                usb_enabled = 1;
8414
                if (usb_devices_index >= MAX_USB_CMDLINE) {
8415
                    fprintf(stderr, "Too many USB devices\n");
8416
                    exit(1);
8417
                }
8418
                usb_devices[usb_devices_index] = optarg;
8419
                usb_devices_index++;
8420
                break;
8421
            case QEMU_OPTION_smp:
8422
                smp_cpus = atoi(optarg);
8423
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8424
                    fprintf(stderr, "Invalid number of CPUs\n");
8425
                    exit(1);
8426
                }
8427
                break;
8428
            case QEMU_OPTION_vnc:
8429
                vnc_display = optarg;
8430
                break;
8431
            case QEMU_OPTION_no_acpi:
8432
                acpi_enabled = 0;
8433
                break;
8434
            case QEMU_OPTION_no_reboot:
8435
                no_reboot = 1;
8436
                break;
8437
            case QEMU_OPTION_no_shutdown:
8438
                no_shutdown = 1;
8439
                break;
8440
            case QEMU_OPTION_show_cursor:
8441
                cursor_hide = 0;
8442
                break;
8443
            case QEMU_OPTION_daemonize:
8444
                daemonize = 1;
8445
                break;
8446
            case QEMU_OPTION_option_rom:
8447
                if (nb_option_roms >= MAX_OPTION_ROMS) {
8448
                    fprintf(stderr, "Too many option ROMs\n");
8449
                    exit(1);
8450
                }
8451
                option_rom[nb_option_roms] = optarg;
8452
                nb_option_roms++;
8453
                break;
8454
            case QEMU_OPTION_semihosting:
8455
                semihosting_enabled = 1;
8456
                break;
8457
            case QEMU_OPTION_name:
8458
                qemu_name = optarg;
8459
                break;
8460
#ifdef TARGET_SPARC
8461
            case QEMU_OPTION_prom_env:
8462
                if (nb_prom_envs >= MAX_PROM_ENVS) {
8463
                    fprintf(stderr, "Too many prom variables\n");
8464
                    exit(1);
8465
                }
8466
                prom_envs[nb_prom_envs] = optarg;
8467
                nb_prom_envs++;
8468
                break;
8469
#endif
8470
#ifdef TARGET_ARM
8471
            case QEMU_OPTION_old_param:
8472
                old_param = 1;
8473
                break;
8474
#endif
8475
            case QEMU_OPTION_clock:
8476
                configure_alarms(optarg);
8477
                break;
8478
            case QEMU_OPTION_startdate:
8479
                {
8480
                    struct tm tm;
8481
                    time_t rtc_start_date;
8482
                    if (!strcmp(optarg, "now")) {
8483
                        rtc_date_offset = -1;
8484
                    } else {
8485
                        if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8486
                               &tm.tm_year,
8487
                               &tm.tm_mon,
8488
                               &tm.tm_mday,
8489
                               &tm.tm_hour,
8490
                               &tm.tm_min,
8491
                               &tm.tm_sec) == 6) {
8492
                            /* OK */
8493
                        } else if (sscanf(optarg, "%d-%d-%d",
8494
                                          &tm.tm_year,
8495
                                          &tm.tm_mon,
8496
                                          &tm.tm_mday) == 3) {
8497
                            tm.tm_hour = 0;
8498
                            tm.tm_min = 0;
8499
                            tm.tm_sec = 0;
8500
                        } else {
8501
                            goto date_fail;
8502
                        }
8503
                        tm.tm_year -= 1900;
8504
                        tm.tm_mon--;
8505
                        rtc_start_date = mktimegm(&tm);
8506
                        if (rtc_start_date == -1) {
8507
                        date_fail:
8508
                            fprintf(stderr, "Invalid date format. Valid format are:\n"
8509
                                    "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8510
                            exit(1);
8511
                        }
8512
                        rtc_date_offset = time(NULL) - rtc_start_date;
8513
                    }
8514
                }
8515
                break;
8516
            case QEMU_OPTION_tb_size:
8517
                tb_size = strtol(optarg, NULL, 0);
8518
                if (tb_size < 0)
8519
                    tb_size = 0;
8520
                break;
8521
            case QEMU_OPTION_icount:
8522
                use_icount = 1;
8523
                if (strcmp(optarg, "auto") == 0) {
8524
                    icount_time_shift = -1;
8525
                } else {
8526
                    icount_time_shift = strtol(optarg, NULL, 0);
8527
                }
8528
                break;
8529
            }
8530
        }
8531
    }
8532

    
8533
#ifndef _WIN32
8534
    if (daemonize && !nographic && vnc_display == NULL) {
8535
        fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
8536
        daemonize = 0;
8537
    }
8538

    
8539
    if (daemonize) {
8540
        pid_t pid;
8541

    
8542
        if (pipe(fds) == -1)
8543
            exit(1);
8544

    
8545
        pid = fork();
8546
        if (pid > 0) {
8547
            uint8_t status;
8548
            ssize_t len;
8549

    
8550
            close(fds[1]);
8551

    
8552
        again:
8553
            len = read(fds[0], &status, 1);
8554
            if (len == -1 && (errno == EINTR))
8555
                goto again;
8556

    
8557
            if (len != 1)
8558
                exit(1);
8559
            else if (status == 1) {
8560
                fprintf(stderr, "Could not acquire pidfile\n");
8561
                exit(1);
8562
            } else
8563
                exit(0);
8564
        } else if (pid < 0)
8565
            exit(1);
8566

    
8567
        setsid();
8568

    
8569
        pid = fork();
8570
        if (pid > 0)
8571
            exit(0);
8572
        else if (pid < 0)
8573
            exit(1);
8574

    
8575
        umask(027);
8576
        chdir("/");
8577

    
8578
        signal(SIGTSTP, SIG_IGN);
8579
        signal(SIGTTOU, SIG_IGN);
8580
        signal(SIGTTIN, SIG_IGN);
8581
    }
8582
#endif
8583

    
8584
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8585
        if (daemonize) {
8586
            uint8_t status = 1;
8587
            write(fds[1], &status, 1);
8588
        } else
8589
            fprintf(stderr, "Could not acquire pid file\n");
8590
        exit(1);
8591
    }
8592

    
8593
#ifdef USE_KQEMU
8594
    if (smp_cpus > 1)
8595
        kqemu_allowed = 0;
8596
#endif
8597
    linux_boot = (kernel_filename != NULL);
8598
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8599

    
8600
    /* XXX: this should not be: some embedded targets just have flash */
8601
    if (!linux_boot && net_boot == 0 &&
8602
        nb_drives_opt == 0)
8603
        help(1);
8604

    
8605
    if (!linux_boot && *kernel_cmdline != '\0') {
8606
        fprintf(stderr, "-append only allowed with -kernel option\n");
8607
        exit(1);
8608
    }
8609

    
8610
    if (!linux_boot && initrd_filename != NULL) {
8611
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
8612
        exit(1);
8613
    }
8614

    
8615
    /* boot to floppy or the default cd if no hard disk defined yet */
8616
    if (!boot_devices[0]) {
8617
        boot_devices = "cad";
8618
    }
8619
    setvbuf(stdout, NULL, _IOLBF, 0);
8620

    
8621
    init_timers();
8622
    init_timer_alarm();
8623
    qemu_aio_init();
8624
    if (use_icount && icount_time_shift < 0) {
8625
        use_icount = 2;
8626
        /* 125MIPS seems a reasonable initial guess at the guest speed.
8627
           It will be corrected fairly quickly anyway.  */
8628
        icount_time_shift = 3;
8629
        init_icount_adjust();
8630
    }
8631

    
8632
#ifdef _WIN32
8633
    socket_init();
8634
#endif
8635

    
8636
    /* init network clients */
8637
    if (nb_net_clients == 0) {
8638
        /* if no clients, we use a default config */
8639
        net_clients[0] = "nic";
8640
        net_clients[1] = "user";
8641
        nb_net_clients = 2;
8642
    }
8643

    
8644
    for(i = 0;i < nb_net_clients; i++) {
8645
        if (net_client_init(net_clients[i]) < 0)
8646
            exit(1);
8647
    }
8648
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8649
        if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8650
            continue;
8651
        if (vlan->nb_guest_devs == 0) {
8652
            fprintf(stderr, "Invalid vlan (%d) with no nics\n", vlan->id);
8653
            exit(1);
8654
        }
8655
        if (vlan->nb_host_devs == 0)
8656
            fprintf(stderr,
8657
                    "Warning: vlan %d is not connected to host network\n",
8658
                    vlan->id);
8659
    }
8660

    
8661
#ifdef TARGET_I386
8662
    /* XXX: this should be moved in the PC machine instantiation code */
8663
    if (net_boot != 0) {
8664
        int netroms = 0;
8665
        for (i = 0; i < nb_nics && i < 4; i++) {
8666
            const char *model = nd_table[i].model;
8667
            char buf[1024];
8668
            if (net_boot & (1 << i)) {
8669
                if (model == NULL)
8670
                    model = "ne2k_pci";
8671
                snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
8672
                if (get_image_size(buf) > 0) {
8673
                    if (nb_option_roms >= MAX_OPTION_ROMS) {
8674
                        fprintf(stderr, "Too many option ROMs\n");
8675
                        exit(1);
8676
                    }
8677
                    option_rom[nb_option_roms] = strdup(buf);
8678
                    nb_option_roms++;
8679
                    netroms++;
8680
                }
8681
            }
8682
        }
8683
        if (netroms == 0) {
8684
            fprintf(stderr, "No valid PXE rom found for network device\n");
8685
            exit(1);
8686
        }
8687
    }
8688
#endif
8689

    
8690
    /* init the memory */
8691
    phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
8692

    
8693
    if (machine->ram_require & RAMSIZE_FIXED) {
8694
        if (ram_size > 0) {
8695
            if (ram_size < phys_ram_size) {
8696
                fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
8697
                                machine->name, (unsigned long long) phys_ram_size);
8698
                exit(-1);
8699
            }
8700

    
8701
            phys_ram_size = ram_size;
8702
        } else
8703
            ram_size = phys_ram_size;
8704
    } else {
8705
        if (ram_size == 0)
8706
            ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
8707

    
8708
        phys_ram_size += ram_size;
8709
    }
8710

    
8711
    phys_ram_base = qemu_vmalloc(phys_ram_size);
8712
    if (!phys_ram_base) {
8713
        fprintf(stderr, "Could not allocate physical memory\n");
8714
        exit(1);
8715
    }
8716

    
8717
    /* init the dynamic translator */
8718
    cpu_exec_init_all(tb_size * 1024 * 1024);
8719

    
8720
    bdrv_init();
8721

    
8722
    /* we always create the cdrom drive, even if no disk is there */
8723

    
8724
    if (nb_drives_opt < MAX_DRIVES)
8725
        drive_add(NULL, CDROM_ALIAS);
8726

    
8727
    /* we always create at least one floppy */
8728

    
8729
    if (nb_drives_opt < MAX_DRIVES)
8730
        drive_add(NULL, FD_ALIAS, 0);
8731

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

    
8734
    if (nb_drives_opt < MAX_DRIVES)
8735
        drive_add(NULL, SD_ALIAS);
8736

    
8737
    /* open the virtual block devices */
8738

    
8739
    for(i = 0; i < nb_drives_opt; i++)
8740
        if (drive_init(&drives_opt[i], snapshot, machine) == -1)
8741
            exit(1);
8742

    
8743
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
8744
    register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
8745

    
8746
    init_ioports();
8747

    
8748
    /* terminal init */
8749
    memset(&display_state, 0, sizeof(display_state));
8750
    if (nographic) {
8751
        if (curses) {
8752
            fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
8753
            exit(1);
8754
        }
8755
        /* nearly nothing to do */
8756
        dumb_display_init(ds);
8757
    } else if (vnc_display != NULL) {
8758
        vnc_display_init(ds);
8759
        if (vnc_display_open(ds, vnc_display) < 0)
8760
            exit(1);
8761
    } else
8762
#if defined(CONFIG_CURSES)
8763
    if (curses) {
8764
        curses_display_init(ds, full_screen);
8765
    } else
8766
#endif
8767
    {
8768
#if defined(CONFIG_SDL)
8769
        sdl_display_init(ds, full_screen, no_frame);
8770
#elif defined(CONFIG_COCOA)
8771
        cocoa_display_init(ds, full_screen);
8772
#else
8773
        dumb_display_init(ds);
8774
#endif
8775
    }
8776

    
8777
    /* Maintain compatibility with multiple stdio monitors */
8778
    if (!strcmp(monitor_device,"stdio")) {
8779
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
8780
            const char *devname = serial_devices[i];
8781
            if (devname && !strcmp(devname,"mon:stdio")) {
8782
                monitor_device = NULL;
8783
                break;
8784
            } else if (devname && !strcmp(devname,"stdio")) {
8785
                monitor_device = NULL;
8786
                serial_devices[i] = "mon:stdio";
8787
                break;
8788
            }
8789
        }
8790
    }
8791
    if (monitor_device) {
8792
        monitor_hd = qemu_chr_open(monitor_device);
8793
        if (!monitor_hd) {
8794
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
8795
            exit(1);
8796
        }
8797
        monitor_init(monitor_hd, !nographic);
8798
    }
8799

    
8800
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
8801
        const char *devname = serial_devices[i];
8802
        if (devname && strcmp(devname, "none")) {
8803
            serial_hds[i] = qemu_chr_open(devname);
8804
            if (!serial_hds[i]) {
8805
                fprintf(stderr, "qemu: could not open serial device '%s'\n",
8806
                        devname);
8807
                exit(1);
8808
            }
8809
            if (strstart(devname, "vc", 0))
8810
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
8811
        }
8812
    }
8813

    
8814
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
8815
        const char *devname = parallel_devices[i];
8816
        if (devname && strcmp(devname, "none")) {
8817
            parallel_hds[i] = qemu_chr_open(devname);
8818
            if (!parallel_hds[i]) {
8819
                fprintf(stderr, "qemu: could not open parallel device '%s'\n",
8820
                        devname);
8821
                exit(1);
8822
            }
8823
            if (strstart(devname, "vc", 0))
8824
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
8825
        }
8826
    }
8827

    
8828
    machine->init(ram_size, vga_ram_size, boot_devices, ds,
8829
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
8830

    
8831
    /* init USB devices */
8832
    if (usb_enabled) {
8833
        for(i = 0; i < usb_devices_index; i++) {
8834
            if (usb_device_add(usb_devices[i]) < 0) {
8835
                fprintf(stderr, "Warning: could not add USB device %s\n",
8836
                        usb_devices[i]);
8837
            }
8838
        }
8839
    }
8840

    
8841
    if (display_state.dpy_refresh) {
8842
        display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
8843
        qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
8844
    }
8845

    
8846
#ifdef CONFIG_GDBSTUB
8847
    if (use_gdbstub) {
8848
        /* XXX: use standard host:port notation and modify options
8849
           accordingly. */
8850
        if (gdbserver_start(gdbstub_port) < 0) {
8851
            fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
8852
                    gdbstub_port);
8853
            exit(1);
8854
        }
8855
    }
8856
#endif
8857

    
8858
    if (loadvm)
8859
        do_loadvm(loadvm);
8860

    
8861
    {
8862
        /* XXX: simplify init */
8863
        read_passwords();
8864
        if (autostart) {
8865
            vm_start();
8866
        }
8867
    }
8868

    
8869
    if (daemonize) {
8870
        uint8_t status = 0;
8871
        ssize_t len;
8872
        int fd;
8873

    
8874
    again1:
8875
        len = write(fds[1], &status, 1);
8876
        if (len == -1 && (errno == EINTR))
8877
            goto again1;
8878

    
8879
        if (len != 1)
8880
            exit(1);
8881

    
8882
        TFR(fd = open("/dev/null", O_RDWR));
8883
        if (fd == -1)
8884
            exit(1);
8885

    
8886
        dup2(fd, 0);
8887
        dup2(fd, 1);
8888
        dup2(fd, 2);
8889

    
8890
        close(fd);
8891
    }
8892

    
8893
    main_loop();
8894
    quit_timers();
8895

    
8896
#if !defined(_WIN32)
8897
    /* close network clients */
8898
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8899
        VLANClientState *vc;
8900

    
8901
        for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
8902
            if (vc->fd_read == tap_receive) {
8903
                char ifname[64];
8904
                TAPState *s = vc->opaque;
8905

    
8906
                if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
8907
                    s->down_script[0])
8908
                    launch_script(s->down_script, ifname, s->fd);
8909
            }
8910
        }
8911
    }
8912
#endif
8913
    return 0;
8914
}