Statistics
| Branch: | Revision:

root / vl.c @ 8632fb9a

History | View | Annotate | Download (239.7 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
#if !defined(__APPLE__) && !defined(__OpenBSD__)
65
#include <libutil.h>
66
#endif
67
#ifdef __OpenBSD__
68
#include <net/if.h>
69
#endif
70
#elif defined (__GLIBC__) && defined (__FreeBSD_kernel__)
71
#include <freebsd/stdlib.h>
72
#else
73
#ifndef __sun__
74
#include <linux/if.h>
75
#include <linux/if_tun.h>
76
#include <pty.h>
77
#include <malloc.h>
78
#include <linux/rtc.h>
79

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

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

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

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

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

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

    
128
#include "qemu_socket.h"
129

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

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

    
141
#include "disas.h"
142

    
143
#include "exec-all.h"
144

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

    
153
//#define DEBUG_UNUSED_IOPORT
154
//#define DEBUG_IOPORT
155

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

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

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

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

    
248
static CPUState *cur_cpu;
249
static CPUState *next_cpu;
250
static int event_pending = 1;
251
/* Conversion factor from emulated instructions to virtual clock ticks.  */
252
static int icount_time_shift;
253
/* Arbitrarily pick 1MIPS as the minimum allowable speed.  */
254
#define MAX_ICOUNT_SHIFT 10
255
/* Compensate for varying guest execution speed.  */
256
static int64_t qemu_icount_bias;
257
QEMUTimer *icount_rt_timer;
258
QEMUTimer *icount_vm_timer;
259

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

    
262
/***********************************************************/
263
/* x86 ISA bus support */
264

    
265
target_phys_addr_t isa_mem_base = 0;
266
PicState2 *isa_pic;
267

    
268
static IOPortReadFunc default_ioport_readb, default_ioport_readw, default_ioport_readl;
269
static IOPortWriteFunc default_ioport_writeb, default_ioport_writew, default_ioport_writel;
270

    
271
static uint32_t ioport_read(int index, uint32_t address)
272
{
273
    static IOPortReadFunc *default_func[3] = {
274
        default_ioport_readb,
275
        default_ioport_readw,
276
        default_ioport_readl
277
    };
278
    IOPortReadFunc *func = ioport_read_table[index][address];
279
    if (!func)
280
        func = default_func[index];
281
    return func(ioport_opaque[address], address);
282
}
283

    
284
static void ioport_write(int index, uint32_t address, uint32_t data)
285
{
286
    static IOPortWriteFunc *default_func[3] = {
287
        default_ioport_writeb,
288
        default_ioport_writew,
289
        default_ioport_writel
290
    };
291
    IOPortWriteFunc *func = ioport_write_table[index][address];
292
    if (!func)
293
        func = default_func[index];
294
    func(ioport_opaque[address], address, data);
295
}
296

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

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

    
312
/* default is to make two byte accesses */
313
static uint32_t default_ioport_readw(void *opaque, uint32_t address)
314
{
315
    uint32_t data;
316
    data = ioport_read(0, address);
317
    address = (address + 1) & (MAX_IOPORTS - 1);
318
    data |= ioport_read(0, address) << 8;
319
    return data;
320
}
321

    
322
static void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
323
{
324
    ioport_write(0, address, data & 0xff);
325
    address = (address + 1) & (MAX_IOPORTS - 1);
326
    ioport_write(0, address, (data >> 8) & 0xff);
327
}
328

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

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

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

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

    
369
/* size is the word size in byte */
370
int register_ioport_write(int start, int length, int size,
371
                          IOPortWriteFunc *func, void *opaque)
372
{
373
    int i, bsize;
374

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

    
394
void isa_unassign_ioport(int start, int length)
395
{
396
    int i;
397

    
398
    for(i = start; i < start + length; i++) {
399
        ioport_read_table[0][i] = default_ioport_readb;
400
        ioport_read_table[1][i] = default_ioport_readw;
401
        ioport_read_table[2][i] = default_ioport_readl;
402

    
403
        ioport_write_table[0][i] = default_ioport_writeb;
404
        ioport_write_table[1][i] = default_ioport_writew;
405
        ioport_write_table[2][i] = default_ioport_writel;
406
    }
407
}
408

    
409
/***********************************************************/
410

    
411
void cpu_outb(CPUState *env, int addr, int val)
412
{
413
#ifdef DEBUG_IOPORT
414
    if (loglevel & CPU_LOG_IOPORT)
415
        fprintf(logfile, "outb: %04x %02x\n", addr, val);
416
#endif
417
    ioport_write(0, addr, val);
418
#ifdef USE_KQEMU
419
    if (env)
420
        env->last_io_time = cpu_get_time_fast();
421
#endif
422
}
423

    
424
void cpu_outw(CPUState *env, int addr, int val)
425
{
426
#ifdef DEBUG_IOPORT
427
    if (loglevel & CPU_LOG_IOPORT)
428
        fprintf(logfile, "outw: %04x %04x\n", addr, val);
429
#endif
430
    ioport_write(1, addr, val);
431
#ifdef USE_KQEMU
432
    if (env)
433
        env->last_io_time = cpu_get_time_fast();
434
#endif
435
}
436

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

    
450
int cpu_inb(CPUState *env, int addr)
451
{
452
    int val;
453
    val = ioport_read(0, addr);
454
#ifdef DEBUG_IOPORT
455
    if (loglevel & CPU_LOG_IOPORT)
456
        fprintf(logfile, "inb : %04x %02x\n", addr, val);
457
#endif
458
#ifdef USE_KQEMU
459
    if (env)
460
        env->last_io_time = cpu_get_time_fast();
461
#endif
462
    return val;
463
}
464

    
465
int cpu_inw(CPUState *env, int addr)
466
{
467
    int val;
468
    val = ioport_read(1, addr);
469
#ifdef DEBUG_IOPORT
470
    if (loglevel & CPU_LOG_IOPORT)
471
        fprintf(logfile, "inw : %04x %04x\n", addr, val);
472
#endif
473
#ifdef USE_KQEMU
474
    if (env)
475
        env->last_io_time = cpu_get_time_fast();
476
#endif
477
    return val;
478
}
479

    
480
int cpu_inl(CPUState *env, int addr)
481
{
482
    int val;
483
    val = ioport_read(2, addr);
484
#ifdef DEBUG_IOPORT
485
    if (loglevel & CPU_LOG_IOPORT)
486
        fprintf(logfile, "inl : %04x %08x\n", addr, val);
487
#endif
488
#ifdef USE_KQEMU
489
    if (env)
490
        env->last_io_time = cpu_get_time_fast();
491
#endif
492
    return val;
493
}
494

    
495
/***********************************************************/
496
void hw_error(const char *fmt, ...)
497
{
498
    va_list ap;
499
    CPUState *env;
500

    
501
    va_start(ap, fmt);
502
    fprintf(stderr, "qemu: hardware error: ");
503
    vfprintf(stderr, fmt, ap);
504
    fprintf(stderr, "\n");
505
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
506
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
507
#ifdef TARGET_I386
508
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
509
#else
510
        cpu_dump_state(env, stderr, fprintf, 0);
511
#endif
512
    }
513
    va_end(ap);
514
    abort();
515
}
516

    
517
/***********************************************************/
518
/* keyboard/mouse */
519

    
520
static QEMUPutKBDEvent *qemu_put_kbd_event;
521
static void *qemu_put_kbd_event_opaque;
522
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
523
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
524

    
525
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
526
{
527
    qemu_put_kbd_event_opaque = opaque;
528
    qemu_put_kbd_event = func;
529
}
530

    
531
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
532
                                                void *opaque, int absolute,
533
                                                const char *name)
534
{
535
    QEMUPutMouseEntry *s, *cursor;
536

    
537
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
538
    if (!s)
539
        return NULL;
540

    
541
    s->qemu_put_mouse_event = func;
542
    s->qemu_put_mouse_event_opaque = opaque;
543
    s->qemu_put_mouse_event_absolute = absolute;
544
    s->qemu_put_mouse_event_name = qemu_strdup(name);
545
    s->next = NULL;
546

    
547
    if (!qemu_put_mouse_event_head) {
548
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
549
        return s;
550
    }
551

    
552
    cursor = qemu_put_mouse_event_head;
553
    while (cursor->next != NULL)
554
        cursor = cursor->next;
555

    
556
    cursor->next = s;
557
    qemu_put_mouse_event_current = s;
558

    
559
    return s;
560
}
561

    
562
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
563
{
564
    QEMUPutMouseEntry *prev = NULL, *cursor;
565

    
566
    if (!qemu_put_mouse_event_head || entry == NULL)
567
        return;
568

    
569
    cursor = qemu_put_mouse_event_head;
570
    while (cursor != NULL && cursor != entry) {
571
        prev = cursor;
572
        cursor = cursor->next;
573
    }
574

    
575
    if (cursor == NULL) // does not exist or list empty
576
        return;
577
    else if (prev == NULL) { // entry is head
578
        qemu_put_mouse_event_head = cursor->next;
579
        if (qemu_put_mouse_event_current == entry)
580
            qemu_put_mouse_event_current = cursor->next;
581
        qemu_free(entry->qemu_put_mouse_event_name);
582
        qemu_free(entry);
583
        return;
584
    }
585

    
586
    prev->next = entry->next;
587

    
588
    if (qemu_put_mouse_event_current == entry)
589
        qemu_put_mouse_event_current = prev;
590

    
591
    qemu_free(entry->qemu_put_mouse_event_name);
592
    qemu_free(entry);
593
}
594

    
595
void kbd_put_keycode(int keycode)
596
{
597
    if (qemu_put_kbd_event) {
598
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
599
    }
600
}
601

    
602
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
603
{
604
    QEMUPutMouseEvent *mouse_event;
605
    void *mouse_event_opaque;
606
    int width;
607

    
608
    if (!qemu_put_mouse_event_current) {
609
        return;
610
    }
611

    
612
    mouse_event =
613
        qemu_put_mouse_event_current->qemu_put_mouse_event;
614
    mouse_event_opaque =
615
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
616

    
617
    if (mouse_event) {
618
        if (graphic_rotate) {
619
            if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
620
                width = 0x7fff;
621
            else
622
                width = graphic_width - 1;
623
            mouse_event(mouse_event_opaque,
624
                                 width - dy, dx, dz, buttons_state);
625
        } else
626
            mouse_event(mouse_event_opaque,
627
                                 dx, dy, dz, buttons_state);
628
    }
629
}
630

    
631
int kbd_mouse_is_absolute(void)
632
{
633
    if (!qemu_put_mouse_event_current)
634
        return 0;
635

    
636
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
637
}
638

    
639
void do_info_mice(void)
640
{
641
    QEMUPutMouseEntry *cursor;
642
    int index = 0;
643

    
644
    if (!qemu_put_mouse_event_head) {
645
        term_printf("No mouse devices connected\n");
646
        return;
647
    }
648

    
649
    term_printf("Mouse devices available:\n");
650
    cursor = qemu_put_mouse_event_head;
651
    while (cursor != NULL) {
652
        term_printf("%c Mouse #%d: %s\n",
653
                    (cursor == qemu_put_mouse_event_current ? '*' : ' '),
654
                    index, cursor->qemu_put_mouse_event_name);
655
        index++;
656
        cursor = cursor->next;
657
    }
658
}
659

    
660
void do_mouse_set(int index)
661
{
662
    QEMUPutMouseEntry *cursor;
663
    int i = 0;
664

    
665
    if (!qemu_put_mouse_event_head) {
666
        term_printf("No mouse devices connected\n");
667
        return;
668
    }
669

    
670
    cursor = qemu_put_mouse_event_head;
671
    while (cursor != NULL && index != i) {
672
        i++;
673
        cursor = cursor->next;
674
    }
675

    
676
    if (cursor != NULL)
677
        qemu_put_mouse_event_current = cursor;
678
    else
679
        term_printf("Mouse at given index not found\n");
680
}
681

    
682
/* compute with 96 bit intermediate result: (a*b)/c */
683
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
684
{
685
    union {
686
        uint64_t ll;
687
        struct {
688
#ifdef WORDS_BIGENDIAN
689
            uint32_t high, low;
690
#else
691
            uint32_t low, high;
692
#endif
693
        } l;
694
    } u, res;
695
    uint64_t rl, rh;
696

    
697
    u.ll = a;
698
    rl = (uint64_t)u.l.low * (uint64_t)b;
699
    rh = (uint64_t)u.l.high * (uint64_t)b;
700
    rh += (rl >> 32);
701
    res.l.high = rh / c;
702
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
703
    return res.ll;
704
}
705

    
706
/***********************************************************/
707
/* real time host monotonic timer */
708

    
709
#define QEMU_TIMER_BASE 1000000000LL
710

    
711
#ifdef WIN32
712

    
713
static int64_t clock_freq;
714

    
715
static void init_get_clock(void)
716
{
717
    LARGE_INTEGER freq;
718
    int ret;
719
    ret = QueryPerformanceFrequency(&freq);
720
    if (ret == 0) {
721
        fprintf(stderr, "Could not calibrate ticks\n");
722
        exit(1);
723
    }
724
    clock_freq = freq.QuadPart;
725
}
726

    
727
static int64_t get_clock(void)
728
{
729
    LARGE_INTEGER ti;
730
    QueryPerformanceCounter(&ti);
731
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
732
}
733

    
734
#else
735

    
736
static int use_rt_clock;
737

    
738
static void init_get_clock(void)
739
{
740
    use_rt_clock = 0;
741
#if defined(__linux__)
742
    {
743
        struct timespec ts;
744
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
745
            use_rt_clock = 1;
746
        }
747
    }
748
#endif
749
}
750

    
751
static int64_t get_clock(void)
752
{
753
#if defined(__linux__)
754
    if (use_rt_clock) {
755
        struct timespec ts;
756
        clock_gettime(CLOCK_MONOTONIC, &ts);
757
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
758
    } else
759
#endif
760
    {
761
        /* XXX: using gettimeofday leads to problems if the date
762
           changes, so it should be avoided. */
763
        struct timeval tv;
764
        gettimeofday(&tv, NULL);
765
        return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
766
    }
767
}
768
#endif
769

    
770
/* Return the virtual CPU time, based on the instruction counter.  */
771
static int64_t cpu_get_icount(void)
772
{
773
    int64_t icount;
774
    CPUState *env = cpu_single_env;;
775
    icount = qemu_icount;
776
    if (env) {
777
        if (!can_do_io(env))
778
            fprintf(stderr, "Bad clock read\n");
779
        icount -= (env->icount_decr.u16.low + env->icount_extra);
780
    }
781
    return qemu_icount_bias + (icount << icount_time_shift);
782
}
783

    
784
/***********************************************************/
785
/* guest cycle counter */
786

    
787
static int64_t cpu_ticks_prev;
788
static int64_t cpu_ticks_offset;
789
static int64_t cpu_clock_offset;
790
static int cpu_ticks_enabled;
791

    
792
/* return the host CPU cycle counter and handle stop/restart */
793
int64_t cpu_get_ticks(void)
794
{
795
    if (use_icount) {
796
        return cpu_get_icount();
797
    }
798
    if (!cpu_ticks_enabled) {
799
        return cpu_ticks_offset;
800
    } else {
801
        int64_t ticks;
802
        ticks = cpu_get_real_ticks();
803
        if (cpu_ticks_prev > ticks) {
804
            /* Note: non increasing ticks may happen if the host uses
805
               software suspend */
806
            cpu_ticks_offset += cpu_ticks_prev - ticks;
807
        }
808
        cpu_ticks_prev = ticks;
809
        return ticks + cpu_ticks_offset;
810
    }
811
}
812

    
813
/* return the host CPU monotonic timer and handle stop/restart */
814
static int64_t cpu_get_clock(void)
815
{
816
    int64_t ti;
817
    if (!cpu_ticks_enabled) {
818
        return cpu_clock_offset;
819
    } else {
820
        ti = get_clock();
821
        return ti + cpu_clock_offset;
822
    }
823
}
824

    
825
/* enable cpu_get_ticks() */
826
void cpu_enable_ticks(void)
827
{
828
    if (!cpu_ticks_enabled) {
829
        cpu_ticks_offset -= cpu_get_real_ticks();
830
        cpu_clock_offset -= get_clock();
831
        cpu_ticks_enabled = 1;
832
    }
833
}
834

    
835
/* disable cpu_get_ticks() : the clock is stopped. You must not call
836
   cpu_get_ticks() after that.  */
837
void cpu_disable_ticks(void)
838
{
839
    if (cpu_ticks_enabled) {
840
        cpu_ticks_offset = cpu_get_ticks();
841
        cpu_clock_offset = cpu_get_clock();
842
        cpu_ticks_enabled = 0;
843
    }
844
}
845

    
846
/***********************************************************/
847
/* timers */
848

    
849
#define QEMU_TIMER_REALTIME 0
850
#define QEMU_TIMER_VIRTUAL  1
851

    
852
struct QEMUClock {
853
    int type;
854
    /* XXX: add frequency */
855
};
856

    
857
struct QEMUTimer {
858
    QEMUClock *clock;
859
    int64_t expire_time;
860
    QEMUTimerCB *cb;
861
    void *opaque;
862
    struct QEMUTimer *next;
863
};
864

    
865
struct qemu_alarm_timer {
866
    char const *name;
867
    unsigned int flags;
868

    
869
    int (*start)(struct qemu_alarm_timer *t);
870
    void (*stop)(struct qemu_alarm_timer *t);
871
    void (*rearm)(struct qemu_alarm_timer *t);
872
    void *priv;
873
};
874

    
875
#define ALARM_FLAG_DYNTICKS  0x1
876
#define ALARM_FLAG_EXPIRED   0x2
877

    
878
static inline int alarm_has_dynticks(struct qemu_alarm_timer *t)
879
{
880
    return t->flags & ALARM_FLAG_DYNTICKS;
881
}
882

    
883
static void qemu_rearm_alarm_timer(struct qemu_alarm_timer *t)
884
{
885
    if (!alarm_has_dynticks(t))
886
        return;
887

    
888
    t->rearm(t);
889
}
890

    
891
/* TODO: MIN_TIMER_REARM_US should be optimized */
892
#define MIN_TIMER_REARM_US 250
893

    
894
static struct qemu_alarm_timer *alarm_timer;
895

    
896
#ifdef _WIN32
897

    
898
struct qemu_alarm_win32 {
899
    MMRESULT timerId;
900
    HANDLE host_alarm;
901
    unsigned int period;
902
} alarm_win32_data = {0, NULL, -1};
903

    
904
static int win32_start_timer(struct qemu_alarm_timer *t);
905
static void win32_stop_timer(struct qemu_alarm_timer *t);
906
static void win32_rearm_timer(struct qemu_alarm_timer *t);
907

    
908
#else
909

    
910
static int unix_start_timer(struct qemu_alarm_timer *t);
911
static void unix_stop_timer(struct qemu_alarm_timer *t);
912

    
913
#ifdef __linux__
914

    
915
static int dynticks_start_timer(struct qemu_alarm_timer *t);
916
static void dynticks_stop_timer(struct qemu_alarm_timer *t);
917
static void dynticks_rearm_timer(struct qemu_alarm_timer *t);
918

    
919
static int hpet_start_timer(struct qemu_alarm_timer *t);
920
static void hpet_stop_timer(struct qemu_alarm_timer *t);
921

    
922
static int rtc_start_timer(struct qemu_alarm_timer *t);
923
static void rtc_stop_timer(struct qemu_alarm_timer *t);
924

    
925
#endif /* __linux__ */
926

    
927
#endif /* _WIN32 */
928

    
929
/* Correlation between real and virtual time is always going to be
930
   fairly approximate, so ignore small variation.
931
   When the guest is idle real and virtual time will be aligned in
932
   the IO wait loop.  */
933
#define ICOUNT_WOBBLE (QEMU_TIMER_BASE / 10)
934

    
935
static void icount_adjust(void)
936
{
937
    int64_t cur_time;
938
    int64_t cur_icount;
939
    int64_t delta;
940
    static int64_t last_delta;
941
    /* If the VM is not running, then do nothing.  */
942
    if (!vm_running)
943
        return;
944

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

    
965
static void icount_adjust_rt(void * opaque)
966
{
967
    qemu_mod_timer(icount_rt_timer,
968
                   qemu_get_clock(rt_clock) + 1000);
969
    icount_adjust();
970
}
971

    
972
static void icount_adjust_vm(void * opaque)
973
{
974
    qemu_mod_timer(icount_vm_timer,
975
                   qemu_get_clock(vm_clock) + QEMU_TIMER_BASE / 10);
976
    icount_adjust();
977
}
978

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

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

    
1014
static void show_available_alarms(void)
1015
{
1016
    int i;
1017

    
1018
    printf("Available alarm timers, in order of precedence:\n");
1019
    for (i = 0; alarm_timers[i].name; i++)
1020
        printf("%s\n", alarm_timers[i].name);
1021
}
1022

    
1023
static void configure_alarms(char const *opt)
1024
{
1025
    int i;
1026
    int cur = 0;
1027
    int count = (sizeof(alarm_timers) / sizeof(*alarm_timers)) - 1;
1028
    char *arg;
1029
    char *name;
1030
    struct qemu_alarm_timer tmp;
1031

    
1032
    if (!strcmp(opt, "?")) {
1033
        show_available_alarms();
1034
        exit(0);
1035
    }
1036

    
1037
    arg = strdup(opt);
1038

    
1039
    /* Reorder the array */
1040
    name = strtok(arg, ",");
1041
    while (name) {
1042
        for (i = 0; i < count && alarm_timers[i].name; i++) {
1043
            if (!strcmp(alarm_timers[i].name, name))
1044
                break;
1045
        }
1046

    
1047
        if (i == count) {
1048
            fprintf(stderr, "Unknown clock %s\n", name);
1049
            goto next;
1050
        }
1051

    
1052
        if (i < cur)
1053
            /* Ignore */
1054
            goto next;
1055

    
1056
        /* Swap */
1057
        tmp = alarm_timers[i];
1058
        alarm_timers[i] = alarm_timers[cur];
1059
        alarm_timers[cur] = tmp;
1060

    
1061
        cur++;
1062
next:
1063
        name = strtok(NULL, ",");
1064
    }
1065

    
1066
    free(arg);
1067

    
1068
    if (cur) {
1069
        /* Disable remaining timers */
1070
        for (i = cur; i < count; i++)
1071
            alarm_timers[i].name = NULL;
1072
    } else {
1073
        show_available_alarms();
1074
        exit(1);
1075
    }
1076
}
1077

    
1078
QEMUClock *rt_clock;
1079
QEMUClock *vm_clock;
1080

    
1081
static QEMUTimer *active_timers[2];
1082

    
1083
static QEMUClock *qemu_new_clock(int type)
1084
{
1085
    QEMUClock *clock;
1086
    clock = qemu_mallocz(sizeof(QEMUClock));
1087
    if (!clock)
1088
        return NULL;
1089
    clock->type = type;
1090
    return clock;
1091
}
1092

    
1093
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
1094
{
1095
    QEMUTimer *ts;
1096

    
1097
    ts = qemu_mallocz(sizeof(QEMUTimer));
1098
    ts->clock = clock;
1099
    ts->cb = cb;
1100
    ts->opaque = opaque;
1101
    return ts;
1102
}
1103

    
1104
void qemu_free_timer(QEMUTimer *ts)
1105
{
1106
    qemu_free(ts);
1107
}
1108

    
1109
/* stop a timer, but do not dealloc it */
1110
void qemu_del_timer(QEMUTimer *ts)
1111
{
1112
    QEMUTimer **pt, *t;
1113

    
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 == ts) {
1122
            *pt = t->next;
1123
            break;
1124
        }
1125
        pt = &t->next;
1126
    }
1127
}
1128

    
1129
/* modify the current timer so that it will be fired when current_time
1130
   >= expire_time. The corresponding callback will be called. */
1131
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
1132
{
1133
    QEMUTimer **pt, *t;
1134

    
1135
    qemu_del_timer(ts);
1136

    
1137
    /* add the timer in the sorted list */
1138
    /* NOTE: this code must be signal safe because
1139
       qemu_timer_expired() can be called from a signal. */
1140
    pt = &active_timers[ts->clock->type];
1141
    for(;;) {
1142
        t = *pt;
1143
        if (!t)
1144
            break;
1145
        if (t->expire_time > expire_time)
1146
            break;
1147
        pt = &t->next;
1148
    }
1149
    ts->expire_time = expire_time;
1150
    ts->next = *pt;
1151
    *pt = ts;
1152

    
1153
    /* Rearm if necessary  */
1154
    if (pt == &active_timers[ts->clock->type]) {
1155
        if ((alarm_timer->flags & ALARM_FLAG_EXPIRED) == 0) {
1156
            qemu_rearm_alarm_timer(alarm_timer);
1157
        }
1158
        /* Interrupt execution to force deadline recalculation.  */
1159
        if (use_icount && cpu_single_env) {
1160
            cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
1161
        }
1162
    }
1163
}
1164

    
1165
int qemu_timer_pending(QEMUTimer *ts)
1166
{
1167
    QEMUTimer *t;
1168
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
1169
        if (t == ts)
1170
            return 1;
1171
    }
1172
    return 0;
1173
}
1174

    
1175
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
1176
{
1177
    if (!timer_head)
1178
        return 0;
1179
    return (timer_head->expire_time <= current_time);
1180
}
1181

    
1182
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
1183
{
1184
    QEMUTimer *ts;
1185

    
1186
    for(;;) {
1187
        ts = *ptimer_head;
1188
        if (!ts || ts->expire_time > current_time)
1189
            break;
1190
        /* remove timer from the list before calling the callback */
1191
        *ptimer_head = ts->next;
1192
        ts->next = NULL;
1193

    
1194
        /* run the callback (the timer list can be modified) */
1195
        ts->cb(ts->opaque);
1196
    }
1197
}
1198

    
1199
int64_t qemu_get_clock(QEMUClock *clock)
1200
{
1201
    switch(clock->type) {
1202
    case QEMU_TIMER_REALTIME:
1203
        return get_clock() / 1000000;
1204
    default:
1205
    case QEMU_TIMER_VIRTUAL:
1206
        if (use_icount) {
1207
            return cpu_get_icount();
1208
        } else {
1209
            return cpu_get_clock();
1210
        }
1211
    }
1212
}
1213

    
1214
static void init_timers(void)
1215
{
1216
    init_get_clock();
1217
    ticks_per_sec = QEMU_TIMER_BASE;
1218
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
1219
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
1220
}
1221

    
1222
/* save a timer */
1223
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
1224
{
1225
    uint64_t expire_time;
1226

    
1227
    if (qemu_timer_pending(ts)) {
1228
        expire_time = ts->expire_time;
1229
    } else {
1230
        expire_time = -1;
1231
    }
1232
    qemu_put_be64(f, expire_time);
1233
}
1234

    
1235
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
1236
{
1237
    uint64_t expire_time;
1238

    
1239
    expire_time = qemu_get_be64(f);
1240
    if (expire_time != -1) {
1241
        qemu_mod_timer(ts, expire_time);
1242
    } else {
1243
        qemu_del_timer(ts);
1244
    }
1245
}
1246

    
1247
static void timer_save(QEMUFile *f, void *opaque)
1248
{
1249
    if (cpu_ticks_enabled) {
1250
        hw_error("cannot save state if virtual timers are running");
1251
    }
1252
    qemu_put_be64(f, cpu_ticks_offset);
1253
    qemu_put_be64(f, ticks_per_sec);
1254
    qemu_put_be64(f, cpu_clock_offset);
1255
}
1256

    
1257
static int timer_load(QEMUFile *f, void *opaque, int version_id)
1258
{
1259
    if (version_id != 1 && version_id != 2)
1260
        return -EINVAL;
1261
    if (cpu_ticks_enabled) {
1262
        return -EINVAL;
1263
    }
1264
    cpu_ticks_offset=qemu_get_be64(f);
1265
    ticks_per_sec=qemu_get_be64(f);
1266
    if (version_id == 2) {
1267
        cpu_clock_offset=qemu_get_be64(f);
1268
    }
1269
    return 0;
1270
}
1271

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

    
1320
        alarm_timer->flags |= ALARM_FLAG_EXPIRED;
1321

    
1322
        if (env) {
1323
            /* stop the currently executing cpu because a timer occured */
1324
            cpu_interrupt(env, CPU_INTERRUPT_EXIT);
1325
#ifdef USE_KQEMU
1326
            if (env->kqemu_enabled) {
1327
                kqemu_cpu_interrupt(env);
1328
            }
1329
#endif
1330
        }
1331
        event_pending = 1;
1332
    }
1333
}
1334

    
1335
static int64_t qemu_next_deadline(void)
1336
{
1337
    int64_t delta;
1338

    
1339
    if (active_timers[QEMU_TIMER_VIRTUAL]) {
1340
        delta = active_timers[QEMU_TIMER_VIRTUAL]->expire_time -
1341
                     qemu_get_clock(vm_clock);
1342
    } else {
1343
        /* To avoid problems with overflow limit this to 2^32.  */
1344
        delta = INT32_MAX;
1345
    }
1346

    
1347
    if (delta < 0)
1348
        delta = 0;
1349

    
1350
    return delta;
1351
}
1352

    
1353
#if defined(__linux__) || defined(_WIN32)
1354
static uint64_t qemu_next_deadline_dyntick(void)
1355
{
1356
    int64_t delta;
1357
    int64_t rtdelta;
1358

    
1359
    if (use_icount)
1360
        delta = INT32_MAX;
1361
    else
1362
        delta = (qemu_next_deadline() + 999) / 1000;
1363

    
1364
    if (active_timers[QEMU_TIMER_REALTIME]) {
1365
        rtdelta = (active_timers[QEMU_TIMER_REALTIME]->expire_time -
1366
                 qemu_get_clock(rt_clock))*1000;
1367
        if (rtdelta < delta)
1368
            delta = rtdelta;
1369
    }
1370

    
1371
    if (delta < MIN_TIMER_REARM_US)
1372
        delta = MIN_TIMER_REARM_US;
1373

    
1374
    return delta;
1375
}
1376
#endif
1377

    
1378
#ifndef _WIN32
1379

    
1380
#if defined(__linux__)
1381

    
1382
#define RTC_FREQ 1024
1383

    
1384
static void enable_sigio_timer(int fd)
1385
{
1386
    struct sigaction act;
1387

    
1388
    /* timer signal */
1389
    sigfillset(&act.sa_mask);
1390
    act.sa_flags = 0;
1391
    act.sa_handler = host_alarm_handler;
1392

    
1393
    sigaction(SIGIO, &act, NULL);
1394
    fcntl(fd, F_SETFL, O_ASYNC);
1395
    fcntl(fd, F_SETOWN, getpid());
1396
}
1397

    
1398
static int hpet_start_timer(struct qemu_alarm_timer *t)
1399
{
1400
    struct hpet_info info;
1401
    int r, fd;
1402

    
1403
    fd = open("/dev/hpet", O_RDONLY);
1404
    if (fd < 0)
1405
        return -1;
1406

    
1407
    /* Set frequency */
1408
    r = ioctl(fd, HPET_IRQFREQ, RTC_FREQ);
1409
    if (r < 0) {
1410
        fprintf(stderr, "Could not configure '/dev/hpet' to have a 1024Hz timer. This is not a fatal\n"
1411
                "error, but for better emulation accuracy type:\n"
1412
                "'echo 1024 > /proc/sys/dev/hpet/max-user-freq' as root.\n");
1413
        goto fail;
1414
    }
1415

    
1416
    /* Check capabilities */
1417
    r = ioctl(fd, HPET_INFO, &info);
1418
    if (r < 0)
1419
        goto fail;
1420

    
1421
    /* Enable periodic mode */
1422
    r = ioctl(fd, HPET_EPI, 0);
1423
    if (info.hi_flags && (r < 0))
1424
        goto fail;
1425

    
1426
    /* Enable interrupt */
1427
    r = ioctl(fd, HPET_IE_ON, 0);
1428
    if (r < 0)
1429
        goto fail;
1430

    
1431
    enable_sigio_timer(fd);
1432
    t->priv = (void *)(long)fd;
1433

    
1434
    return 0;
1435
fail:
1436
    close(fd);
1437
    return -1;
1438
}
1439

    
1440
static void hpet_stop_timer(struct qemu_alarm_timer *t)
1441
{
1442
    int fd = (long)t->priv;
1443

    
1444
    close(fd);
1445
}
1446

    
1447
static int rtc_start_timer(struct qemu_alarm_timer *t)
1448
{
1449
    int rtc_fd;
1450
    unsigned long current_rtc_freq = 0;
1451

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

    
1469
    enable_sigio_timer(rtc_fd);
1470

    
1471
    t->priv = (void *)(long)rtc_fd;
1472

    
1473
    return 0;
1474
}
1475

    
1476
static void rtc_stop_timer(struct qemu_alarm_timer *t)
1477
{
1478
    int rtc_fd = (long)t->priv;
1479

    
1480
    close(rtc_fd);
1481
}
1482

    
1483
static int dynticks_start_timer(struct qemu_alarm_timer *t)
1484
{
1485
    struct sigevent ev;
1486
    timer_t host_timer;
1487
    struct sigaction act;
1488

    
1489
    sigfillset(&act.sa_mask);
1490
    act.sa_flags = 0;
1491
    act.sa_handler = host_alarm_handler;
1492

    
1493
    sigaction(SIGALRM, &act, NULL);
1494

    
1495
    ev.sigev_value.sival_int = 0;
1496
    ev.sigev_notify = SIGEV_SIGNAL;
1497
    ev.sigev_signo = SIGALRM;
1498

    
1499
    if (timer_create(CLOCK_REALTIME, &ev, &host_timer)) {
1500
        perror("timer_create");
1501

    
1502
        /* disable dynticks */
1503
        fprintf(stderr, "Dynamic Ticks disabled\n");
1504

    
1505
        return -1;
1506
    }
1507

    
1508
    t->priv = (void *)host_timer;
1509

    
1510
    return 0;
1511
}
1512

    
1513
static void dynticks_stop_timer(struct qemu_alarm_timer *t)
1514
{
1515
    timer_t host_timer = (timer_t)t->priv;
1516

    
1517
    timer_delete(host_timer);
1518
}
1519

    
1520
static void dynticks_rearm_timer(struct qemu_alarm_timer *t)
1521
{
1522
    timer_t host_timer = (timer_t)t->priv;
1523
    struct itimerspec timeout;
1524
    int64_t nearest_delta_us = INT64_MAX;
1525
    int64_t current_us;
1526

    
1527
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1528
                !active_timers[QEMU_TIMER_VIRTUAL])
1529
        return;
1530

    
1531
    nearest_delta_us = qemu_next_deadline_dyntick();
1532

    
1533
    /* check whether a timer is already running */
1534
    if (timer_gettime(host_timer, &timeout)) {
1535
        perror("gettime");
1536
        fprintf(stderr, "Internal timer error: aborting\n");
1537
        exit(1);
1538
    }
1539
    current_us = timeout.it_value.tv_sec * 1000000 + timeout.it_value.tv_nsec/1000;
1540
    if (current_us && current_us <= nearest_delta_us)
1541
        return;
1542

    
1543
    timeout.it_interval.tv_sec = 0;
1544
    timeout.it_interval.tv_nsec = 0; /* 0 for one-shot timer */
1545
    timeout.it_value.tv_sec =  nearest_delta_us / 1000000;
1546
    timeout.it_value.tv_nsec = (nearest_delta_us % 1000000) * 1000;
1547
    if (timer_settime(host_timer, 0 /* RELATIVE */, &timeout, NULL)) {
1548
        perror("settime");
1549
        fprintf(stderr, "Internal timer error: aborting\n");
1550
        exit(1);
1551
    }
1552
}
1553

    
1554
#endif /* defined(__linux__) */
1555

    
1556
static int unix_start_timer(struct qemu_alarm_timer *t)
1557
{
1558
    struct sigaction act;
1559
    struct itimerval itv;
1560
    int err;
1561

    
1562
    /* timer signal */
1563
    sigfillset(&act.sa_mask);
1564
    act.sa_flags = 0;
1565
    act.sa_handler = host_alarm_handler;
1566

    
1567
    sigaction(SIGALRM, &act, NULL);
1568

    
1569
    itv.it_interval.tv_sec = 0;
1570
    /* for i386 kernel 2.6 to get 1 ms */
1571
    itv.it_interval.tv_usec = 999;
1572
    itv.it_value.tv_sec = 0;
1573
    itv.it_value.tv_usec = 10 * 1000;
1574

    
1575
    err = setitimer(ITIMER_REAL, &itv, NULL);
1576
    if (err)
1577
        return -1;
1578

    
1579
    return 0;
1580
}
1581

    
1582
static void unix_stop_timer(struct qemu_alarm_timer *t)
1583
{
1584
    struct itimerval itv;
1585

    
1586
    memset(&itv, 0, sizeof(itv));
1587
    setitimer(ITIMER_REAL, &itv, NULL);
1588
}
1589

    
1590
#endif /* !defined(_WIN32) */
1591

    
1592
#ifdef _WIN32
1593

    
1594
static int win32_start_timer(struct qemu_alarm_timer *t)
1595
{
1596
    TIMECAPS tc;
1597
    struct qemu_alarm_win32 *data = t->priv;
1598
    UINT flags;
1599

    
1600
    data->host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1601
    if (!data->host_alarm) {
1602
        perror("Failed CreateEvent");
1603
        return -1;
1604
    }
1605

    
1606
    memset(&tc, 0, sizeof(tc));
1607
    timeGetDevCaps(&tc, sizeof(tc));
1608

    
1609
    if (data->period < tc.wPeriodMin)
1610
        data->period = tc.wPeriodMin;
1611

    
1612
    timeBeginPeriod(data->period);
1613

    
1614
    flags = TIME_CALLBACK_FUNCTION;
1615
    if (alarm_has_dynticks(t))
1616
        flags |= TIME_ONESHOT;
1617
    else
1618
        flags |= TIME_PERIODIC;
1619

    
1620
    data->timerId = timeSetEvent(1,         // interval (ms)
1621
                        data->period,       // resolution
1622
                        host_alarm_handler, // function
1623
                        (DWORD)t,           // parameter
1624
                        flags);
1625

    
1626
    if (!data->timerId) {
1627
        perror("Failed to initialize win32 alarm timer");
1628

    
1629
        timeEndPeriod(data->period);
1630
        CloseHandle(data->host_alarm);
1631
        return -1;
1632
    }
1633

    
1634
    qemu_add_wait_object(data->host_alarm, NULL, NULL);
1635

    
1636
    return 0;
1637
}
1638

    
1639
static void win32_stop_timer(struct qemu_alarm_timer *t)
1640
{
1641
    struct qemu_alarm_win32 *data = t->priv;
1642

    
1643
    timeKillEvent(data->timerId);
1644
    timeEndPeriod(data->period);
1645

    
1646
    CloseHandle(data->host_alarm);
1647
}
1648

    
1649
static void win32_rearm_timer(struct qemu_alarm_timer *t)
1650
{
1651
    struct qemu_alarm_win32 *data = t->priv;
1652
    uint64_t nearest_delta_us;
1653

    
1654
    if (!active_timers[QEMU_TIMER_REALTIME] &&
1655
                !active_timers[QEMU_TIMER_VIRTUAL])
1656
        return;
1657

    
1658
    nearest_delta_us = qemu_next_deadline_dyntick();
1659
    nearest_delta_us /= 1000;
1660

    
1661
    timeKillEvent(data->timerId);
1662

    
1663
    data->timerId = timeSetEvent(1,
1664
                        data->period,
1665
                        host_alarm_handler,
1666
                        (DWORD)t,
1667
                        TIME_ONESHOT | TIME_PERIODIC);
1668

    
1669
    if (!data->timerId) {
1670
        perror("Failed to re-arm win32 alarm timer");
1671

    
1672
        timeEndPeriod(data->period);
1673
        CloseHandle(data->host_alarm);
1674
        exit(1);
1675
    }
1676
}
1677

    
1678
#endif /* _WIN32 */
1679

    
1680
static void init_timer_alarm(void)
1681
{
1682
    struct qemu_alarm_timer *t;
1683
    int i, err = -1;
1684

    
1685
    for (i = 0; alarm_timers[i].name; i++) {
1686
        t = &alarm_timers[i];
1687

    
1688
        err = t->start(t);
1689
        if (!err)
1690
            break;
1691
    }
1692

    
1693
    if (err) {
1694
        fprintf(stderr, "Unable to find any suitable alarm timer.\n");
1695
        fprintf(stderr, "Terminating\n");
1696
        exit(1);
1697
    }
1698

    
1699
    alarm_timer = t;
1700
}
1701

    
1702
static void quit_timers(void)
1703
{
1704
    alarm_timer->stop(alarm_timer);
1705
    alarm_timer = NULL;
1706
}
1707

    
1708
/***********************************************************/
1709
/* host time/date access */
1710
void qemu_get_timedate(struct tm *tm, int offset)
1711
{
1712
    time_t ti;
1713
    struct tm *ret;
1714

    
1715
    time(&ti);
1716
    ti += offset;
1717
    if (rtc_date_offset == -1) {
1718
        if (rtc_utc)
1719
            ret = gmtime(&ti);
1720
        else
1721
            ret = localtime(&ti);
1722
    } else {
1723
        ti -= rtc_date_offset;
1724
        ret = gmtime(&ti);
1725
    }
1726

    
1727
    memcpy(tm, ret, sizeof(struct tm));
1728
}
1729

    
1730
int qemu_timedate_diff(struct tm *tm)
1731
{
1732
    time_t seconds;
1733

    
1734
    if (rtc_date_offset == -1)
1735
        if (rtc_utc)
1736
            seconds = mktimegm(tm);
1737
        else
1738
            seconds = mktime(tm);
1739
    else
1740
        seconds = mktimegm(tm) + rtc_date_offset;
1741

    
1742
    return seconds - time(NULL);
1743
}
1744

    
1745
/***********************************************************/
1746
/* character device */
1747

    
1748
static void qemu_chr_event(CharDriverState *s, int event)
1749
{
1750
    if (!s->chr_event)
1751
        return;
1752
    s->chr_event(s->handler_opaque, event);
1753
}
1754

    
1755
static void qemu_chr_reset_bh(void *opaque)
1756
{
1757
    CharDriverState *s = opaque;
1758
    qemu_chr_event(s, CHR_EVENT_RESET);
1759
    qemu_bh_delete(s->bh);
1760
    s->bh = NULL;
1761
}
1762

    
1763
void qemu_chr_reset(CharDriverState *s)
1764
{
1765
    if (s->bh == NULL) {
1766
        s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1767
        qemu_bh_schedule(s->bh);
1768
    }
1769
}
1770

    
1771
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1772
{
1773
    return s->chr_write(s, buf, len);
1774
}
1775

    
1776
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1777
{
1778
    if (!s->chr_ioctl)
1779
        return -ENOTSUP;
1780
    return s->chr_ioctl(s, cmd, arg);
1781
}
1782

    
1783
int qemu_chr_can_read(CharDriverState *s)
1784
{
1785
    if (!s->chr_can_read)
1786
        return 0;
1787
    return s->chr_can_read(s->handler_opaque);
1788
}
1789

    
1790
void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1791
{
1792
    s->chr_read(s->handler_opaque, buf, len);
1793
}
1794

    
1795
void qemu_chr_accept_input(CharDriverState *s)
1796
{
1797
    if (s->chr_accept_input)
1798
        s->chr_accept_input(s);
1799
}
1800

    
1801
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1802
{
1803
    char buf[4096];
1804
    va_list ap;
1805
    va_start(ap, fmt);
1806
    vsnprintf(buf, sizeof(buf), fmt, ap);
1807
    qemu_chr_write(s, (uint8_t *)buf, strlen(buf));
1808
    va_end(ap);
1809
}
1810

    
1811
void qemu_chr_send_event(CharDriverState *s, int event)
1812
{
1813
    if (s->chr_send_event)
1814
        s->chr_send_event(s, event);
1815
}
1816

    
1817
void qemu_chr_add_handlers(CharDriverState *s,
1818
                           IOCanRWHandler *fd_can_read,
1819
                           IOReadHandler *fd_read,
1820
                           IOEventHandler *fd_event,
1821
                           void *opaque)
1822
{
1823
    s->chr_can_read = fd_can_read;
1824
    s->chr_read = fd_read;
1825
    s->chr_event = fd_event;
1826
    s->handler_opaque = opaque;
1827
    if (s->chr_update_read_handler)
1828
        s->chr_update_read_handler(s);
1829
}
1830

    
1831
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1832
{
1833
    return len;
1834
}
1835

    
1836
static CharDriverState *qemu_chr_open_null(void)
1837
{
1838
    CharDriverState *chr;
1839

    
1840
    chr = qemu_mallocz(sizeof(CharDriverState));
1841
    if (!chr)
1842
        return NULL;
1843
    chr->chr_write = null_chr_write;
1844
    return chr;
1845
}
1846

    
1847
/* MUX driver for serial I/O splitting */
1848
static int term_timestamps;
1849
static int64_t term_timestamps_start;
1850
#define MAX_MUX 4
1851
#define MUX_BUFFER_SIZE 32        /* Must be a power of 2.  */
1852
#define MUX_BUFFER_MASK (MUX_BUFFER_SIZE - 1)
1853
typedef struct {
1854
    IOCanRWHandler *chr_can_read[MAX_MUX];
1855
    IOReadHandler *chr_read[MAX_MUX];
1856
    IOEventHandler *chr_event[MAX_MUX];
1857
    void *ext_opaque[MAX_MUX];
1858
    CharDriverState *drv;
1859
    unsigned char buffer[MUX_BUFFER_SIZE];
1860
    int prod;
1861
    int cons;
1862
    int mux_cnt;
1863
    int term_got_escape;
1864
    int max_size;
1865
} MuxDriver;
1866

    
1867

    
1868
static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1869
{
1870
    MuxDriver *d = chr->opaque;
1871
    int ret;
1872
    if (!term_timestamps) {
1873
        ret = d->drv->chr_write(d->drv, buf, len);
1874
    } else {
1875
        int i;
1876

    
1877
        ret = 0;
1878
        for(i = 0; i < len; i++) {
1879
            ret += d->drv->chr_write(d->drv, buf+i, 1);
1880
            if (buf[i] == '\n') {
1881
                char buf1[64];
1882
                int64_t ti;
1883
                int secs;
1884

    
1885
                ti = get_clock();
1886
                if (term_timestamps_start == -1)
1887
                    term_timestamps_start = ti;
1888
                ti -= term_timestamps_start;
1889
                secs = ti / 1000000000;
1890
                snprintf(buf1, sizeof(buf1),
1891
                         "[%02d:%02d:%02d.%03d] ",
1892
                         secs / 3600,
1893
                         (secs / 60) % 60,
1894
                         secs % 60,
1895
                         (int)((ti / 1000000) % 1000));
1896
                d->drv->chr_write(d->drv, (uint8_t *)buf1, strlen(buf1));
1897
            }
1898
        }
1899
    }
1900
    return ret;
1901
}
1902

    
1903
static const char * const mux_help[] = {
1904
    "% h    print this help\n\r",
1905
    "% x    exit emulator\n\r",
1906
    "% s    save disk data back to file (if -snapshot)\n\r",
1907
    "% t    toggle console timestamps\n\r"
1908
    "% b    send break (magic sysrq)\n\r",
1909
    "% c    switch between console and monitor\n\r",
1910
    "% %  sends %\n\r",
1911
    NULL
1912
};
1913

    
1914
static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1915
static void mux_print_help(CharDriverState *chr)
1916
{
1917
    int i, j;
1918
    char ebuf[15] = "Escape-Char";
1919
    char cbuf[50] = "\n\r";
1920

    
1921
    if (term_escape_char > 0 && term_escape_char < 26) {
1922
        snprintf(cbuf, sizeof(cbuf), "\n\r");
1923
        snprintf(ebuf, sizeof(ebuf), "C-%c", term_escape_char - 1 + 'a');
1924
    } else {
1925
        snprintf(cbuf, sizeof(cbuf),
1926
                 "\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r",
1927
                 term_escape_char);
1928
    }
1929
    chr->chr_write(chr, (uint8_t *)cbuf, strlen(cbuf));
1930
    for (i = 0; mux_help[i] != NULL; i++) {
1931
        for (j=0; mux_help[i][j] != '\0'; j++) {
1932
            if (mux_help[i][j] == '%')
1933
                chr->chr_write(chr, (uint8_t *)ebuf, strlen(ebuf));
1934
            else
1935
                chr->chr_write(chr, (uint8_t *)&mux_help[i][j], 1);
1936
        }
1937
    }
1938
}
1939

    
1940
static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1941
{
1942
    if (d->term_got_escape) {
1943
        d->term_got_escape = 0;
1944
        if (ch == term_escape_char)
1945
            goto send_char;
1946
        switch(ch) {
1947
        case '?':
1948
        case 'h':
1949
            mux_print_help(chr);
1950
            break;
1951
        case 'x':
1952
            {
1953
                 const char *term =  "QEMU: Terminated\n\r";
1954
                 chr->chr_write(chr,(uint8_t *)term,strlen(term));
1955
                 exit(0);
1956
                 break;
1957
            }
1958
        case 's':
1959
            {
1960
                int i;
1961
                for (i = 0; i < nb_drives; i++) {
1962
                        bdrv_commit(drives_table[i].bdrv);
1963
                }
1964
            }
1965
            break;
1966
        case 'b':
1967
            qemu_chr_event(chr, CHR_EVENT_BREAK);
1968
            break;
1969
        case 'c':
1970
            /* Switch to the next registered device */
1971
            chr->focus++;
1972
            if (chr->focus >= d->mux_cnt)
1973
                chr->focus = 0;
1974
            break;
1975
       case 't':
1976
           term_timestamps = !term_timestamps;
1977
           term_timestamps_start = -1;
1978
           break;
1979
        }
1980
    } else if (ch == term_escape_char) {
1981
        d->term_got_escape = 1;
1982
    } else {
1983
    send_char:
1984
        return 1;
1985
    }
1986
    return 0;
1987
}
1988

    
1989
static void mux_chr_accept_input(CharDriverState *chr)
1990
{
1991
    int m = chr->focus;
1992
    MuxDriver *d = chr->opaque;
1993

    
1994
    while (d->prod != d->cons &&
1995
           d->chr_can_read[m] &&
1996
           d->chr_can_read[m](d->ext_opaque[m])) {
1997
        d->chr_read[m](d->ext_opaque[m],
1998
                       &d->buffer[d->cons++ & MUX_BUFFER_MASK], 1);
1999
    }
2000
}
2001

    
2002
static int mux_chr_can_read(void *opaque)
2003
{
2004
    CharDriverState *chr = opaque;
2005
    MuxDriver *d = chr->opaque;
2006

    
2007
    if ((d->prod - d->cons) < MUX_BUFFER_SIZE)
2008
        return 1;
2009
    if (d->chr_can_read[chr->focus])
2010
        return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
2011
    return 0;
2012
}
2013

    
2014
static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
2015
{
2016
    CharDriverState *chr = opaque;
2017
    MuxDriver *d = chr->opaque;
2018
    int m = chr->focus;
2019
    int i;
2020

    
2021
    mux_chr_accept_input (opaque);
2022

    
2023
    for(i = 0; i < size; i++)
2024
        if (mux_proc_byte(chr, d, buf[i])) {
2025
            if (d->prod == d->cons &&
2026
                d->chr_can_read[m] &&
2027
                d->chr_can_read[m](d->ext_opaque[m]))
2028
                d->chr_read[m](d->ext_opaque[m], &buf[i], 1);
2029
            else
2030
                d->buffer[d->prod++ & MUX_BUFFER_MASK] = buf[i];
2031
        }
2032
}
2033

    
2034
static void mux_chr_event(void *opaque, int event)
2035
{
2036
    CharDriverState *chr = opaque;
2037
    MuxDriver *d = chr->opaque;
2038
    int i;
2039

    
2040
    /* Send the event to all registered listeners */
2041
    for (i = 0; i < d->mux_cnt; i++)
2042
        if (d->chr_event[i])
2043
            d->chr_event[i](d->ext_opaque[i], event);
2044
}
2045

    
2046
static void mux_chr_update_read_handler(CharDriverState *chr)
2047
{
2048
    MuxDriver *d = chr->opaque;
2049

    
2050
    if (d->mux_cnt >= MAX_MUX) {
2051
        fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
2052
        return;
2053
    }
2054
    d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
2055
    d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
2056
    d->chr_read[d->mux_cnt] = chr->chr_read;
2057
    d->chr_event[d->mux_cnt] = chr->chr_event;
2058
    /* Fix up the real driver with mux routines */
2059
    if (d->mux_cnt == 0) {
2060
        qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
2061
                              mux_chr_event, chr);
2062
    }
2063
    chr->focus = d->mux_cnt;
2064
    d->mux_cnt++;
2065
}
2066

    
2067
static CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
2068
{
2069
    CharDriverState *chr;
2070
    MuxDriver *d;
2071

    
2072
    chr = qemu_mallocz(sizeof(CharDriverState));
2073
    if (!chr)
2074
        return NULL;
2075
    d = qemu_mallocz(sizeof(MuxDriver));
2076
    if (!d) {
2077
        free(chr);
2078
        return NULL;
2079
    }
2080

    
2081
    chr->opaque = d;
2082
    d->drv = drv;
2083
    chr->focus = -1;
2084
    chr->chr_write = mux_chr_write;
2085
    chr->chr_update_read_handler = mux_chr_update_read_handler;
2086
    chr->chr_accept_input = mux_chr_accept_input;
2087
    return chr;
2088
}
2089

    
2090

    
2091
#ifdef _WIN32
2092

    
2093
static void socket_cleanup(void)
2094
{
2095
    WSACleanup();
2096
}
2097

    
2098
static int socket_init(void)
2099
{
2100
    WSADATA Data;
2101
    int ret, err;
2102

    
2103
    ret = WSAStartup(MAKEWORD(2,2), &Data);
2104
    if (ret != 0) {
2105
        err = WSAGetLastError();
2106
        fprintf(stderr, "WSAStartup: %d\n", err);
2107
        return -1;
2108
    }
2109
    atexit(socket_cleanup);
2110
    return 0;
2111
}
2112

    
2113
static int send_all(int fd, const uint8_t *buf, int len1)
2114
{
2115
    int ret, len;
2116

    
2117
    len = len1;
2118
    while (len > 0) {
2119
        ret = send(fd, buf, len, 0);
2120
        if (ret < 0) {
2121
            int errno;
2122
            errno = WSAGetLastError();
2123
            if (errno != WSAEWOULDBLOCK) {
2124
                return -1;
2125
            }
2126
        } else if (ret == 0) {
2127
            break;
2128
        } else {
2129
            buf += ret;
2130
            len -= ret;
2131
        }
2132
    }
2133
    return len1 - len;
2134
}
2135

    
2136
void socket_set_nonblock(int fd)
2137
{
2138
    unsigned long opt = 1;
2139
    ioctlsocket(fd, FIONBIO, &opt);
2140
}
2141

    
2142
#else
2143

    
2144
static int unix_write(int fd, const uint8_t *buf, int len1)
2145
{
2146
    int ret, len;
2147

    
2148
    len = len1;
2149
    while (len > 0) {
2150
        ret = write(fd, buf, len);
2151
        if (ret < 0) {
2152
            if (errno != EINTR && errno != EAGAIN)
2153
                return -1;
2154
        } else if (ret == 0) {
2155
            break;
2156
        } else {
2157
            buf += ret;
2158
            len -= ret;
2159
        }
2160
    }
2161
    return len1 - len;
2162
}
2163

    
2164
static inline int send_all(int fd, const uint8_t *buf, int len1)
2165
{
2166
    return unix_write(fd, buf, len1);
2167
}
2168

    
2169
void socket_set_nonblock(int fd)
2170
{
2171
    int f;
2172
    f = fcntl(fd, F_GETFL);
2173
    fcntl(fd, F_SETFL, f | O_NONBLOCK);
2174
}
2175
#endif /* !_WIN32 */
2176

    
2177
#ifndef _WIN32
2178

    
2179
typedef struct {
2180
    int fd_in, fd_out;
2181
    int max_size;
2182
} FDCharDriver;
2183

    
2184
#define STDIO_MAX_CLIENTS 1
2185
static int stdio_nb_clients = 0;
2186

    
2187
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2188
{
2189
    FDCharDriver *s = chr->opaque;
2190
    return unix_write(s->fd_out, buf, len);
2191
}
2192

    
2193
static int fd_chr_read_poll(void *opaque)
2194
{
2195
    CharDriverState *chr = opaque;
2196
    FDCharDriver *s = chr->opaque;
2197

    
2198
    s->max_size = qemu_chr_can_read(chr);
2199
    return s->max_size;
2200
}
2201

    
2202
static void fd_chr_read(void *opaque)
2203
{
2204
    CharDriverState *chr = opaque;
2205
    FDCharDriver *s = chr->opaque;
2206
    int size, len;
2207
    uint8_t buf[1024];
2208

    
2209
    len = sizeof(buf);
2210
    if (len > s->max_size)
2211
        len = s->max_size;
2212
    if (len == 0)
2213
        return;
2214
    size = read(s->fd_in, buf, len);
2215
    if (size == 0) {
2216
        /* FD has been closed. Remove it from the active list.  */
2217
        qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2218
        return;
2219
    }
2220
    if (size > 0) {
2221
        qemu_chr_read(chr, buf, size);
2222
    }
2223
}
2224

    
2225
static void fd_chr_update_read_handler(CharDriverState *chr)
2226
{
2227
    FDCharDriver *s = chr->opaque;
2228

    
2229
    if (s->fd_in >= 0) {
2230
        if (nographic && s->fd_in == 0) {
2231
        } else {
2232
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll,
2233
                                 fd_chr_read, NULL, chr);
2234
        }
2235
    }
2236
}
2237

    
2238
static void fd_chr_close(struct CharDriverState *chr)
2239
{
2240
    FDCharDriver *s = chr->opaque;
2241

    
2242
    if (s->fd_in >= 0) {
2243
        if (nographic && s->fd_in == 0) {
2244
        } else {
2245
            qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
2246
        }
2247
    }
2248

    
2249
    qemu_free(s);
2250
}
2251

    
2252
/* open a character device to a unix fd */
2253
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
2254
{
2255
    CharDriverState *chr;
2256
    FDCharDriver *s;
2257

    
2258
    chr = qemu_mallocz(sizeof(CharDriverState));
2259
    if (!chr)
2260
        return NULL;
2261
    s = qemu_mallocz(sizeof(FDCharDriver));
2262
    if (!s) {
2263
        free(chr);
2264
        return NULL;
2265
    }
2266
    s->fd_in = fd_in;
2267
    s->fd_out = fd_out;
2268
    chr->opaque = s;
2269
    chr->chr_write = fd_chr_write;
2270
    chr->chr_update_read_handler = fd_chr_update_read_handler;
2271
    chr->chr_close = fd_chr_close;
2272

    
2273
    qemu_chr_reset(chr);
2274

    
2275
    return chr;
2276
}
2277

    
2278
static CharDriverState *qemu_chr_open_file_out(const char *file_out)
2279
{
2280
    int fd_out;
2281

    
2282
    TFR(fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666));
2283
    if (fd_out < 0)
2284
        return NULL;
2285
    return qemu_chr_open_fd(-1, fd_out);
2286
}
2287

    
2288
static CharDriverState *qemu_chr_open_pipe(const char *filename)
2289
{
2290
    int fd_in, fd_out;
2291
    char filename_in[256], filename_out[256];
2292

    
2293
    snprintf(filename_in, 256, "%s.in", filename);
2294
    snprintf(filename_out, 256, "%s.out", filename);
2295
    TFR(fd_in = open(filename_in, O_RDWR | O_BINARY));
2296
    TFR(fd_out = open(filename_out, O_RDWR | O_BINARY));
2297
    if (fd_in < 0 || fd_out < 0) {
2298
        if (fd_in >= 0)
2299
            close(fd_in);
2300
        if (fd_out >= 0)
2301
            close(fd_out);
2302
        TFR(fd_in = fd_out = open(filename, O_RDWR | O_BINARY));
2303
        if (fd_in < 0)
2304
            return NULL;
2305
    }
2306
    return qemu_chr_open_fd(fd_in, fd_out);
2307
}
2308

    
2309

    
2310
/* for STDIO, we handle the case where several clients use it
2311
   (nographic mode) */
2312

    
2313
#define TERM_FIFO_MAX_SIZE 1
2314

    
2315
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
2316
static int term_fifo_size;
2317

    
2318
static int stdio_read_poll(void *opaque)
2319
{
2320
    CharDriverState *chr = opaque;
2321

    
2322
    /* try to flush the queue if needed */
2323
    if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
2324
        qemu_chr_read(chr, term_fifo, 1);
2325
        term_fifo_size = 0;
2326
    }
2327
    /* see if we can absorb more chars */
2328
    if (term_fifo_size == 0)
2329
        return 1;
2330
    else
2331
        return 0;
2332
}
2333

    
2334
static void stdio_read(void *opaque)
2335
{
2336
    int size;
2337
    uint8_t buf[1];
2338
    CharDriverState *chr = opaque;
2339

    
2340
    size = read(0, buf, 1);
2341
    if (size == 0) {
2342
        /* stdin has been closed. Remove it from the active list.  */
2343
        qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2344
        return;
2345
    }
2346
    if (size > 0) {
2347
        if (qemu_chr_can_read(chr) > 0) {
2348
            qemu_chr_read(chr, buf, 1);
2349
        } else if (term_fifo_size == 0) {
2350
            term_fifo[term_fifo_size++] = buf[0];
2351
        }
2352
    }
2353
}
2354

    
2355
/* init terminal so that we can grab keys */
2356
static struct termios oldtty;
2357
static int old_fd0_flags;
2358
static int term_atexit_done;
2359

    
2360
static void term_exit(void)
2361
{
2362
    tcsetattr (0, TCSANOW, &oldtty);
2363
    fcntl(0, F_SETFL, old_fd0_flags);
2364
}
2365

    
2366
static void term_init(void)
2367
{
2368
    struct termios tty;
2369

    
2370
    tcgetattr (0, &tty);
2371
    oldtty = tty;
2372
    old_fd0_flags = fcntl(0, F_GETFL);
2373

    
2374
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2375
                          |INLCR|IGNCR|ICRNL|IXON);
2376
    tty.c_oflag |= OPOST;
2377
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2378
    /* if graphical mode, we allow Ctrl-C handling */
2379
    if (nographic)
2380
        tty.c_lflag &= ~ISIG;
2381
    tty.c_cflag &= ~(CSIZE|PARENB);
2382
    tty.c_cflag |= CS8;
2383
    tty.c_cc[VMIN] = 1;
2384
    tty.c_cc[VTIME] = 0;
2385

    
2386
    tcsetattr (0, TCSANOW, &tty);
2387

    
2388
    if (!term_atexit_done++)
2389
        atexit(term_exit);
2390

    
2391
    fcntl(0, F_SETFL, O_NONBLOCK);
2392
}
2393

    
2394
static void qemu_chr_close_stdio(struct CharDriverState *chr)
2395
{
2396
    term_exit();
2397
    stdio_nb_clients--;
2398
    qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
2399
    fd_chr_close(chr);
2400
}
2401

    
2402
static CharDriverState *qemu_chr_open_stdio(void)
2403
{
2404
    CharDriverState *chr;
2405

    
2406
    if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
2407
        return NULL;
2408
    chr = qemu_chr_open_fd(0, 1);
2409
    chr->chr_close = qemu_chr_close_stdio;
2410
    qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
2411
    stdio_nb_clients++;
2412
    term_init();
2413

    
2414
    return chr;
2415
}
2416

    
2417
#ifdef __sun__
2418
/* Once Solaris has openpty(), this is going to be removed. */
2419
int openpty(int *amaster, int *aslave, char *name,
2420
            struct termios *termp, struct winsize *winp)
2421
{
2422
        const char *slave;
2423
        int mfd = -1, sfd = -1;
2424

    
2425
        *amaster = *aslave = -1;
2426

    
2427
        mfd = open("/dev/ptmx", O_RDWR | O_NOCTTY);
2428
        if (mfd < 0)
2429
                goto err;
2430

    
2431
        if (grantpt(mfd) == -1 || unlockpt(mfd) == -1)
2432
                goto err;
2433

    
2434
        if ((slave = ptsname(mfd)) == NULL)
2435
                goto err;
2436

    
2437
        if ((sfd = open(slave, O_RDONLY | O_NOCTTY)) == -1)
2438
                goto err;
2439

    
2440
        if (ioctl(sfd, I_PUSH, "ptem") == -1 ||
2441
            (termp != NULL && tcgetattr(sfd, termp) < 0))
2442
                goto err;
2443

    
2444
        if (amaster)
2445
                *amaster = mfd;
2446
        if (aslave)
2447
                *aslave = sfd;
2448
        if (winp)
2449
                ioctl(sfd, TIOCSWINSZ, winp);
2450

    
2451
        return 0;
2452

    
2453
err:
2454
        if (sfd != -1)
2455
                close(sfd);
2456
        close(mfd);
2457
        return -1;
2458
}
2459

    
2460
void cfmakeraw (struct termios *termios_p)
2461
{
2462
        termios_p->c_iflag &=
2463
                ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
2464
        termios_p->c_oflag &= ~OPOST;
2465
        termios_p->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
2466
        termios_p->c_cflag &= ~(CSIZE|PARENB);
2467
        termios_p->c_cflag |= CS8;
2468

    
2469
        termios_p->c_cc[VMIN] = 0;
2470
        termios_p->c_cc[VTIME] = 0;
2471
}
2472
#endif
2473

    
2474
#if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
2475
    || defined(__NetBSD__) || defined(__OpenBSD__)
2476

    
2477
typedef struct {
2478
    int fd;
2479
    int connected;
2480
    int polling;
2481
    int read_bytes;
2482
    QEMUTimer *timer;
2483
} PtyCharDriver;
2484

    
2485
static void pty_chr_update_read_handler(CharDriverState *chr);
2486
static void pty_chr_state(CharDriverState *chr, int connected);
2487

    
2488
static int pty_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2489
{
2490
    PtyCharDriver *s = chr->opaque;
2491

    
2492
    if (!s->connected) {
2493
        /* guest sends data, check for (re-)connect */
2494
        pty_chr_update_read_handler(chr);
2495
        return 0;
2496
    }
2497
    return unix_write(s->fd, buf, len);
2498
}
2499

    
2500
static int pty_chr_read_poll(void *opaque)
2501
{
2502
    CharDriverState *chr = opaque;
2503
    PtyCharDriver *s = chr->opaque;
2504

    
2505
    s->read_bytes = qemu_chr_can_read(chr);
2506
    return s->read_bytes;
2507
}
2508

    
2509
static void pty_chr_read(void *opaque)
2510
{
2511
    CharDriverState *chr = opaque;
2512
    PtyCharDriver *s = chr->opaque;
2513
    int size, len;
2514
    uint8_t buf[1024];
2515

    
2516
    len = sizeof(buf);
2517
    if (len > s->read_bytes)
2518
        len = s->read_bytes;
2519
    if (len == 0)
2520
        return;
2521
    size = read(s->fd, buf, len);
2522
    if ((size == -1 && errno == EIO) ||
2523
        (size == 0)) {
2524
        pty_chr_state(chr, 0);
2525
        return;
2526
    }
2527
    if (size > 0) {
2528
        pty_chr_state(chr, 1);
2529
        qemu_chr_read(chr, buf, size);
2530
    }
2531
}
2532

    
2533
static void pty_chr_update_read_handler(CharDriverState *chr)
2534
{
2535
    PtyCharDriver *s = chr->opaque;
2536

    
2537
    qemu_set_fd_handler2(s->fd, pty_chr_read_poll,
2538
                         pty_chr_read, NULL, chr);
2539
    s->polling = 1;
2540
    /*
2541
     * Short timeout here: just need wait long enougth that qemu makes
2542
     * it through the poll loop once.  When reconnected we want a
2543
     * short timeout so we notice it almost instantly.  Otherwise
2544
     * read() gives us -EIO instantly, making pty_chr_state() reset the
2545
     * timeout to the normal (much longer) poll interval before the
2546
     * timer triggers.
2547
     */
2548
    qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 10);
2549
}
2550

    
2551
static void pty_chr_state(CharDriverState *chr, int connected)
2552
{
2553
    PtyCharDriver *s = chr->opaque;
2554

    
2555
    if (!connected) {
2556
        qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2557
        s->connected = 0;
2558
        s->polling = 0;
2559
        /* (re-)connect poll interval for idle guests: once per second.
2560
         * We check more frequently in case the guests sends data to
2561
         * the virtual device linked to our pty. */
2562
        qemu_mod_timer(s->timer, qemu_get_clock(rt_clock) + 1000);
2563
    } else {
2564
        if (!s->connected)
2565
            qemu_chr_reset(chr);
2566
        s->connected = 1;
2567
    }
2568
}
2569

    
2570
static void pty_chr_timer(void *opaque)
2571
{
2572
    struct CharDriverState *chr = opaque;
2573
    PtyCharDriver *s = chr->opaque;
2574

    
2575
    if (s->connected)
2576
        return;
2577
    if (s->polling) {
2578
        /* If we arrive here without polling being cleared due
2579
         * read returning -EIO, then we are (re-)connected */
2580
        pty_chr_state(chr, 1);
2581
        return;
2582
    }
2583

    
2584
    /* Next poll ... */
2585
    pty_chr_update_read_handler(chr);
2586
}
2587

    
2588
static void pty_chr_close(struct CharDriverState *chr)
2589
{
2590
    PtyCharDriver *s = chr->opaque;
2591

    
2592
    qemu_set_fd_handler2(s->fd, NULL, NULL, NULL, NULL);
2593
    close(s->fd);
2594
    qemu_free(s);
2595
}
2596

    
2597
static CharDriverState *qemu_chr_open_pty(void)
2598
{
2599
    CharDriverState *chr;
2600
    PtyCharDriver *s;
2601
    struct termios tty;
2602
    int slave_fd;
2603
#if defined(__OpenBSD__)
2604
    char pty_name[PATH_MAX];
2605
#define q_ptsname(x) pty_name
2606
#else
2607
    char *pty_name = NULL;
2608
#define q_ptsname(x) ptsname(x)
2609
#endif
2610

    
2611
    chr = qemu_mallocz(sizeof(CharDriverState));
2612
    if (!chr)
2613
        return NULL;
2614
    s = qemu_mallocz(sizeof(PtyCharDriver));
2615
    if (!s) {
2616
        qemu_free(chr);
2617
        return NULL;
2618
    }
2619

    
2620
    if (openpty(&s->fd, &slave_fd, pty_name, NULL, NULL) < 0) {
2621
        return NULL;
2622
    }
2623

    
2624
    /* Set raw attributes on the pty. */
2625
    cfmakeraw(&tty);
2626
    tcsetattr(slave_fd, TCSAFLUSH, &tty);
2627
    close(slave_fd);
2628

    
2629
    fprintf(stderr, "char device redirected to %s\n", q_ptsname(s->fd));
2630

    
2631
    chr->opaque = s;
2632
    chr->chr_write = pty_chr_write;
2633
    chr->chr_update_read_handler = pty_chr_update_read_handler;
2634
    chr->chr_close = pty_chr_close;
2635

    
2636
    s->timer = qemu_new_timer(rt_clock, pty_chr_timer, chr);
2637

    
2638
    return chr;
2639
}
2640

    
2641
static void tty_serial_init(int fd, int speed,
2642
                            int parity, int data_bits, int stop_bits)
2643
{
2644
    struct termios tty;
2645
    speed_t spd;
2646

    
2647
#if 0
2648
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n",
2649
           speed, parity, data_bits, stop_bits);
2650
#endif
2651
    tcgetattr (fd, &tty);
2652

    
2653
#define MARGIN 1.1
2654
    if (speed <= 50 * MARGIN)
2655
        spd = B50;
2656
    else if (speed <= 75 * MARGIN)
2657
        spd = B75;
2658
    else if (speed <= 300 * MARGIN)
2659
        spd = B300;
2660
    else if (speed <= 600 * MARGIN)
2661
        spd = B600;
2662
    else if (speed <= 1200 * MARGIN)
2663
        spd = B1200;
2664
    else if (speed <= 2400 * MARGIN)
2665
        spd = B2400;
2666
    else if (speed <= 4800 * MARGIN)
2667
        spd = B4800;
2668
    else if (speed <= 9600 * MARGIN)
2669
        spd = B9600;
2670
    else if (speed <= 19200 * MARGIN)
2671
        spd = B19200;
2672
    else if (speed <= 38400 * MARGIN)
2673
        spd = B38400;
2674
    else if (speed <= 57600 * MARGIN)
2675
        spd = B57600;
2676
    else if (speed <= 115200 * MARGIN)
2677
        spd = B115200;
2678
    else
2679
        spd = B115200;
2680

    
2681
    cfsetispeed(&tty, spd);
2682
    cfsetospeed(&tty, spd);
2683

    
2684
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2685
                          |INLCR|IGNCR|ICRNL|IXON);
2686
    tty.c_oflag |= OPOST;
2687
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
2688
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
2689
    switch(data_bits) {
2690
    default:
2691
    case 8:
2692
        tty.c_cflag |= CS8;
2693
        break;
2694
    case 7:
2695
        tty.c_cflag |= CS7;
2696
        break;
2697
    case 6:
2698
        tty.c_cflag |= CS6;
2699
        break;
2700
    case 5:
2701
        tty.c_cflag |= CS5;
2702
        break;
2703
    }
2704
    switch(parity) {
2705
    default:
2706
    case 'N':
2707
        break;
2708
    case 'E':
2709
        tty.c_cflag |= PARENB;
2710
        break;
2711
    case 'O':
2712
        tty.c_cflag |= PARENB | PARODD;
2713
        break;
2714
    }
2715
    if (stop_bits == 2)
2716
        tty.c_cflag |= CSTOPB;
2717

    
2718
    tcsetattr (fd, TCSANOW, &tty);
2719
}
2720

    
2721
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
2722
{
2723
    FDCharDriver *s = chr->opaque;
2724

    
2725
    switch(cmd) {
2726
    case CHR_IOCTL_SERIAL_SET_PARAMS:
2727
        {
2728
            QEMUSerialSetParams *ssp = arg;
2729
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity,
2730
                            ssp->data_bits, ssp->stop_bits);
2731
        }
2732
        break;
2733
    case CHR_IOCTL_SERIAL_SET_BREAK:
2734
        {
2735
            int enable = *(int *)arg;
2736
            if (enable)
2737
                tcsendbreak(s->fd_in, 1);
2738
        }
2739
        break;
2740
    case CHR_IOCTL_SERIAL_GET_TIOCM:
2741
        {
2742
            int sarg = 0;
2743
            int *targ = (int *)arg;
2744
            ioctl(s->fd_in, TIOCMGET, &sarg);
2745
            *targ = 0;
2746
            if (sarg | TIOCM_CTS)
2747
                *targ |= CHR_TIOCM_CTS;
2748
            if (sarg | TIOCM_CAR)
2749
                *targ |= CHR_TIOCM_CAR;
2750
            if (sarg | TIOCM_DSR)
2751
                *targ |= CHR_TIOCM_DSR;
2752
            if (sarg | TIOCM_RI)
2753
                *targ |= CHR_TIOCM_RI;
2754
            if (sarg | TIOCM_DTR)
2755
                *targ |= CHR_TIOCM_DTR;
2756
            if (sarg | TIOCM_RTS)
2757
                *targ |= CHR_TIOCM_RTS;
2758
        }
2759
        break;
2760
    case CHR_IOCTL_SERIAL_SET_TIOCM:
2761
        {
2762
            int sarg = *(int *)arg;
2763
            int targ = 0;
2764
            if (sarg | CHR_TIOCM_DTR)
2765
                targ |= TIOCM_DTR;
2766
            if (sarg | CHR_TIOCM_RTS)
2767
                targ |= TIOCM_RTS;
2768
            ioctl(s->fd_in, TIOCMSET, &targ);
2769
        }
2770
        break;
2771
    default:
2772
        return -ENOTSUP;
2773
    }
2774
    return 0;
2775
}
2776

    
2777
static CharDriverState *qemu_chr_open_tty(const char *filename)
2778
{
2779
    CharDriverState *chr;
2780
    int fd;
2781

    
2782
    TFR(fd = open(filename, O_RDWR | O_NONBLOCK));
2783
    tty_serial_init(fd, 115200, 'N', 8, 1);
2784
    chr = qemu_chr_open_fd(fd, fd);
2785
    if (!chr) {
2786
        close(fd);
2787
        return NULL;
2788
    }
2789
    chr->chr_ioctl = tty_serial_ioctl;
2790
    qemu_chr_reset(chr);
2791
    return chr;
2792
}
2793
#else  /* ! __linux__ && ! __sun__ */
2794
static CharDriverState *qemu_chr_open_pty(void)
2795
{
2796
    return NULL;
2797
}
2798
#endif /* __linux__ || __sun__ */
2799

    
2800
#if defined(__linux__)
2801
typedef struct {
2802
    int fd;
2803
    int mode;
2804
} ParallelCharDriver;
2805

    
2806
static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
2807
{
2808
    if (s->mode != mode) {
2809
        int m = mode;
2810
        if (ioctl(s->fd, PPSETMODE, &m) < 0)
2811
            return 0;
2812
        s->mode = mode;
2813
    }
2814
    return 1;
2815
}
2816

    
2817
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
2818
{
2819
    ParallelCharDriver *drv = chr->opaque;
2820
    int fd = drv->fd;
2821
    uint8_t b;
2822

    
2823
    switch(cmd) {
2824
    case CHR_IOCTL_PP_READ_DATA:
2825
        if (ioctl(fd, PPRDATA, &b) < 0)
2826
            return -ENOTSUP;
2827
        *(uint8_t *)arg = b;
2828
        break;
2829
    case CHR_IOCTL_PP_WRITE_DATA:
2830
        b = *(uint8_t *)arg;
2831
        if (ioctl(fd, PPWDATA, &b) < 0)
2832
            return -ENOTSUP;
2833
        break;
2834
    case CHR_IOCTL_PP_READ_CONTROL:
2835
        if (ioctl(fd, PPRCONTROL, &b) < 0)
2836
            return -ENOTSUP;
2837
        /* Linux gives only the lowest bits, and no way to know data
2838
           direction! For better compatibility set the fixed upper
2839
           bits. */
2840
        *(uint8_t *)arg = b | 0xc0;
2841
        break;
2842
    case CHR_IOCTL_PP_WRITE_CONTROL:
2843
        b = *(uint8_t *)arg;
2844
        if (ioctl(fd, PPWCONTROL, &b) < 0)
2845
            return -ENOTSUP;
2846
        break;
2847
    case CHR_IOCTL_PP_READ_STATUS:
2848
        if (ioctl(fd, PPRSTATUS, &b) < 0)
2849
            return -ENOTSUP;
2850
        *(uint8_t *)arg = b;
2851
        break;
2852
    case CHR_IOCTL_PP_DATA_DIR:
2853
        if (ioctl(fd, PPDATADIR, (int *)arg) < 0)
2854
            return -ENOTSUP;
2855
        break;
2856
    case CHR_IOCTL_PP_EPP_READ_ADDR:
2857
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2858
            struct ParallelIOArg *parg = arg;
2859
            int n = read(fd, parg->buffer, parg->count);
2860
            if (n != parg->count) {
2861
                return -EIO;
2862
            }
2863
        }
2864
        break;
2865
    case CHR_IOCTL_PP_EPP_READ:
2866
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2867
            struct ParallelIOArg *parg = arg;
2868
            int n = read(fd, parg->buffer, parg->count);
2869
            if (n != parg->count) {
2870
                return -EIO;
2871
            }
2872
        }
2873
        break;
2874
    case CHR_IOCTL_PP_EPP_WRITE_ADDR:
2875
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
2876
            struct ParallelIOArg *parg = arg;
2877
            int n = write(fd, parg->buffer, parg->count);
2878
            if (n != parg->count) {
2879
                return -EIO;
2880
            }
2881
        }
2882
        break;
2883
    case CHR_IOCTL_PP_EPP_WRITE:
2884
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
2885
            struct ParallelIOArg *parg = arg;
2886
            int n = write(fd, parg->buffer, parg->count);
2887
            if (n != parg->count) {
2888
                return -EIO;
2889
            }
2890
        }
2891
        break;
2892
    default:
2893
        return -ENOTSUP;
2894
    }
2895
    return 0;
2896
}
2897

    
2898
static void pp_close(CharDriverState *chr)
2899
{
2900
    ParallelCharDriver *drv = chr->opaque;
2901
    int fd = drv->fd;
2902

    
2903
    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2904
    ioctl(fd, PPRELEASE);
2905
    close(fd);
2906
    qemu_free(drv);
2907
}
2908

    
2909
static CharDriverState *qemu_chr_open_pp(const char *filename)
2910
{
2911
    CharDriverState *chr;
2912
    ParallelCharDriver *drv;
2913
    int fd;
2914

    
2915
    TFR(fd = open(filename, O_RDWR));
2916
    if (fd < 0)
2917
        return NULL;
2918

    
2919
    if (ioctl(fd, PPCLAIM) < 0) {
2920
        close(fd);
2921
        return NULL;
2922
    }
2923

    
2924
    drv = qemu_mallocz(sizeof(ParallelCharDriver));
2925
    if (!drv) {
2926
        close(fd);
2927
        return NULL;
2928
    }
2929
    drv->fd = fd;
2930
    drv->mode = IEEE1284_MODE_COMPAT;
2931

    
2932
    chr = qemu_mallocz(sizeof(CharDriverState));
2933
    if (!chr) {
2934
        qemu_free(drv);
2935
        close(fd);
2936
        return NULL;
2937
    }
2938
    chr->chr_write = null_chr_write;
2939
    chr->chr_ioctl = pp_ioctl;
2940
    chr->chr_close = pp_close;
2941
    chr->opaque = drv;
2942

    
2943
    qemu_chr_reset(chr);
2944

    
2945
    return chr;
2946
}
2947
#endif /* __linux__ */
2948

    
2949
#else /* _WIN32 */
2950

    
2951
typedef struct {
2952
    int max_size;
2953
    HANDLE hcom, hrecv, hsend;
2954
    OVERLAPPED orecv, osend;
2955
    BOOL fpipe;
2956
    DWORD len;
2957
} WinCharState;
2958

    
2959
#define NSENDBUF 2048
2960
#define NRECVBUF 2048
2961
#define MAXCONNECT 1
2962
#define NTIMEOUT 5000
2963

    
2964
static int win_chr_poll(void *opaque);
2965
static int win_chr_pipe_poll(void *opaque);
2966

    
2967
static void win_chr_close(CharDriverState *chr)
2968
{
2969
    WinCharState *s = chr->opaque;
2970

    
2971
    if (s->hsend) {
2972
        CloseHandle(s->hsend);
2973
        s->hsend = NULL;
2974
    }
2975
    if (s->hrecv) {
2976
        CloseHandle(s->hrecv);
2977
        s->hrecv = NULL;
2978
    }
2979
    if (s->hcom) {
2980
        CloseHandle(s->hcom);
2981
        s->hcom = NULL;
2982
    }
2983
    if (s->fpipe)
2984
        qemu_del_polling_cb(win_chr_pipe_poll, chr);
2985
    else
2986
        qemu_del_polling_cb(win_chr_poll, chr);
2987
}
2988

    
2989
static int win_chr_init(CharDriverState *chr, const char *filename)
2990
{
2991
    WinCharState *s = chr->opaque;
2992
    COMMCONFIG comcfg;
2993
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2994
    COMSTAT comstat;
2995
    DWORD size;
2996
    DWORD err;
2997

    
2998
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2999
    if (!s->hsend) {
3000
        fprintf(stderr, "Failed CreateEvent\n");
3001
        goto fail;
3002
    }
3003
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
3004
    if (!s->hrecv) {
3005
        fprintf(stderr, "Failed CreateEvent\n");
3006
        goto fail;
3007
    }
3008

    
3009
    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
3010
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
3011
    if (s->hcom == INVALID_HANDLE_VALUE) {
3012
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
3013
        s->hcom = NULL;
3014
        goto fail;
3015
    }
3016

    
3017
    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
3018
        fprintf(stderr, "Failed SetupComm\n");
3019
        goto fail;
3020
    }
3021

    
3022
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
3023
    size = sizeof(COMMCONFIG);
3024
    GetDefaultCommConfig(filename, &comcfg, &size);
3025
    comcfg.dcb.DCBlength = sizeof(DCB);
3026
    CommConfigDialog(filename, NULL, &comcfg);
3027

    
3028
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
3029
        fprintf(stderr, "Failed SetCommState\n");
3030
        goto fail;
3031
    }
3032

    
3033
    if (!SetCommMask(s->hcom, EV_ERR)) {
3034
        fprintf(stderr, "Failed SetCommMask\n");
3035
        goto fail;
3036
    }
3037

    
3038
    cto.ReadIntervalTimeout = MAXDWORD;
3039
    if (!SetCommTimeouts(s->hcom, &cto)) {
3040
        fprintf(stderr, "Failed SetCommTimeouts\n");
3041
        goto fail;
3042
    }
3043

    
3044
    if (!ClearCommError(s->hcom, &err, &comstat)) {
3045
        fprintf(stderr, "Failed ClearCommError\n");
3046
        goto fail;
3047
    }
3048
    qemu_add_polling_cb(win_chr_poll, chr);
3049
    return 0;
3050

    
3051
 fail:
3052
    win_chr_close(chr);
3053
    return -1;
3054
}
3055

    
3056
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
3057
{
3058
    WinCharState *s = chr->opaque;
3059
    DWORD len, ret, size, err;
3060

    
3061
    len = len1;
3062
    ZeroMemory(&s->osend, sizeof(s->osend));
3063
    s->osend.hEvent = s->hsend;
3064
    while (len > 0) {
3065
        if (s->hsend)
3066
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
3067
        else
3068
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
3069
        if (!ret) {
3070
            err = GetLastError();
3071
            if (err == ERROR_IO_PENDING) {
3072
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
3073
                if (ret) {
3074
                    buf += size;
3075
                    len -= size;
3076
                } else {
3077
                    break;
3078
                }
3079
            } else {
3080
                break;
3081
            }
3082
        } else {
3083
            buf += size;
3084
            len -= size;
3085
        }
3086
    }
3087
    return len1 - len;
3088
}
3089

    
3090
static int win_chr_read_poll(CharDriverState *chr)
3091
{
3092
    WinCharState *s = chr->opaque;
3093

    
3094
    s->max_size = qemu_chr_can_read(chr);
3095
    return s->max_size;
3096
}
3097

    
3098
static void win_chr_readfile(CharDriverState *chr)
3099
{
3100
    WinCharState *s = chr->opaque;
3101
    int ret, err;
3102
    uint8_t buf[1024];
3103
    DWORD size;
3104

    
3105
    ZeroMemory(&s->orecv, sizeof(s->orecv));
3106
    s->orecv.hEvent = s->hrecv;
3107
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
3108
    if (!ret) {
3109
        err = GetLastError();
3110
        if (err == ERROR_IO_PENDING) {
3111
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
3112
        }
3113
    }
3114

    
3115
    if (size > 0) {
3116
        qemu_chr_read(chr, buf, size);
3117
    }
3118
}
3119

    
3120
static void win_chr_read(CharDriverState *chr)
3121
{
3122
    WinCharState *s = chr->opaque;
3123

    
3124
    if (s->len > s->max_size)
3125
        s->len = s->max_size;
3126
    if (s->len == 0)
3127
        return;
3128

    
3129
    win_chr_readfile(chr);
3130
}
3131

    
3132
static int win_chr_poll(void *opaque)
3133
{
3134
    CharDriverState *chr = opaque;
3135
    WinCharState *s = chr->opaque;
3136
    COMSTAT status;
3137
    DWORD comerr;
3138

    
3139
    ClearCommError(s->hcom, &comerr, &status);
3140
    if (status.cbInQue > 0) {
3141
        s->len = status.cbInQue;
3142
        win_chr_read_poll(chr);
3143
        win_chr_read(chr);
3144
        return 1;
3145
    }
3146
    return 0;
3147
}
3148

    
3149
static CharDriverState *qemu_chr_open_win(const char *filename)
3150
{
3151
    CharDriverState *chr;
3152
    WinCharState *s;
3153

    
3154
    chr = qemu_mallocz(sizeof(CharDriverState));
3155
    if (!chr)
3156
        return NULL;
3157
    s = qemu_mallocz(sizeof(WinCharState));
3158
    if (!s) {
3159
        free(chr);
3160
        return NULL;
3161
    }
3162
    chr->opaque = s;
3163
    chr->chr_write = win_chr_write;
3164
    chr->chr_close = win_chr_close;
3165

    
3166
    if (win_chr_init(chr, filename) < 0) {
3167
        free(s);
3168
        free(chr);
3169
        return NULL;
3170
    }
3171
    qemu_chr_reset(chr);
3172
    return chr;
3173
}
3174

    
3175
static int win_chr_pipe_poll(void *opaque)
3176
{
3177
    CharDriverState *chr = opaque;
3178
    WinCharState *s = chr->opaque;
3179
    DWORD size;
3180

    
3181
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
3182
    if (size > 0) {
3183
        s->len = size;
3184
        win_chr_read_poll(chr);
3185
        win_chr_read(chr);
3186
        return 1;
3187
    }
3188
    return 0;
3189
}
3190

    
3191
static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
3192
{
3193
    WinCharState *s = chr->opaque;
3194
    OVERLAPPED ov;
3195
    int ret;
3196
    DWORD size;
3197
    char openname[256];
3198

    
3199
    s->fpipe = TRUE;
3200

    
3201
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
3202
    if (!s->hsend) {
3203
        fprintf(stderr, "Failed CreateEvent\n");
3204
        goto fail;
3205
    }
3206
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
3207
    if (!s->hrecv) {
3208
        fprintf(stderr, "Failed CreateEvent\n");
3209
        goto fail;
3210
    }
3211

    
3212
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
3213
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
3214
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
3215
                              PIPE_WAIT,
3216
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
3217
    if (s->hcom == INVALID_HANDLE_VALUE) {
3218
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
3219
        s->hcom = NULL;
3220
        goto fail;
3221
    }
3222

    
3223
    ZeroMemory(&ov, sizeof(ov));
3224
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
3225
    ret = ConnectNamedPipe(s->hcom, &ov);
3226
    if (ret) {
3227
        fprintf(stderr, "Failed ConnectNamedPipe\n");
3228
        goto fail;
3229
    }
3230

    
3231
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
3232
    if (!ret) {
3233
        fprintf(stderr, "Failed GetOverlappedResult\n");
3234
        if (ov.hEvent) {
3235
            CloseHandle(ov.hEvent);
3236
            ov.hEvent = NULL;
3237
        }
3238
        goto fail;
3239
    }
3240

    
3241
    if (ov.hEvent) {
3242
        CloseHandle(ov.hEvent);
3243
        ov.hEvent = NULL;
3244
    }
3245
    qemu_add_polling_cb(win_chr_pipe_poll, chr);
3246
    return 0;
3247

    
3248
 fail:
3249
    win_chr_close(chr);
3250
    return -1;
3251
}
3252

    
3253

    
3254
static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
3255
{
3256
    CharDriverState *chr;
3257
    WinCharState *s;
3258

    
3259
    chr = qemu_mallocz(sizeof(CharDriverState));
3260
    if (!chr)
3261
        return NULL;
3262
    s = qemu_mallocz(sizeof(WinCharState));
3263
    if (!s) {
3264
        free(chr);
3265
        return NULL;
3266
    }
3267
    chr->opaque = s;
3268
    chr->chr_write = win_chr_write;
3269
    chr->chr_close = win_chr_close;
3270

    
3271
    if (win_chr_pipe_init(chr, filename) < 0) {
3272
        free(s);
3273
        free(chr);
3274
        return NULL;
3275
    }
3276
    qemu_chr_reset(chr);
3277
    return chr;
3278
}
3279

    
3280
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
3281
{
3282
    CharDriverState *chr;
3283
    WinCharState *s;
3284

    
3285
    chr = qemu_mallocz(sizeof(CharDriverState));
3286
    if (!chr)
3287
        return NULL;
3288
    s = qemu_mallocz(sizeof(WinCharState));
3289
    if (!s) {
3290
        free(chr);
3291
        return NULL;
3292
    }
3293
    s->hcom = fd_out;
3294
    chr->opaque = s;
3295
    chr->chr_write = win_chr_write;
3296
    qemu_chr_reset(chr);
3297
    return chr;
3298
}
3299

    
3300
static CharDriverState *qemu_chr_open_win_con(const char *filename)
3301
{
3302
    return qemu_chr_open_win_file(GetStdHandle(STD_OUTPUT_HANDLE));
3303
}
3304

    
3305
static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
3306
{
3307
    HANDLE fd_out;
3308

    
3309
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
3310
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
3311
    if (fd_out == INVALID_HANDLE_VALUE)
3312
        return NULL;
3313

    
3314
    return qemu_chr_open_win_file(fd_out);
3315
}
3316
#endif /* !_WIN32 */
3317

    
3318
/***********************************************************/
3319
/* UDP Net console */
3320

    
3321
typedef struct {
3322
    int fd;
3323
    struct sockaddr_in daddr;
3324
    uint8_t buf[1024];
3325
    int bufcnt;
3326
    int bufptr;
3327
    int max_size;
3328
} NetCharDriver;
3329

    
3330
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3331
{
3332
    NetCharDriver *s = chr->opaque;
3333

    
3334
    return sendto(s->fd, buf, len, 0,
3335
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
3336
}
3337

    
3338
static int udp_chr_read_poll(void *opaque)
3339
{
3340
    CharDriverState *chr = opaque;
3341
    NetCharDriver *s = chr->opaque;
3342

    
3343
    s->max_size = qemu_chr_can_read(chr);
3344

    
3345
    /* If there were any stray characters in the queue process them
3346
     * first
3347
     */
3348
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3349
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3350
        s->bufptr++;
3351
        s->max_size = qemu_chr_can_read(chr);
3352
    }
3353
    return s->max_size;
3354
}
3355

    
3356
static void udp_chr_read(void *opaque)
3357
{
3358
    CharDriverState *chr = opaque;
3359
    NetCharDriver *s = chr->opaque;
3360

    
3361
    if (s->max_size == 0)
3362
        return;
3363
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
3364
    s->bufptr = s->bufcnt;
3365
    if (s->bufcnt <= 0)
3366
        return;
3367

    
3368
    s->bufptr = 0;
3369
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
3370
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
3371
        s->bufptr++;
3372
        s->max_size = qemu_chr_can_read(chr);
3373
    }
3374
}
3375

    
3376
static void udp_chr_update_read_handler(CharDriverState *chr)
3377
{
3378
    NetCharDriver *s = chr->opaque;
3379

    
3380
    if (s->fd >= 0) {
3381
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
3382
                             udp_chr_read, NULL, chr);
3383
    }
3384
}
3385

    
3386
int parse_host_port(struct sockaddr_in *saddr, const char *str);
3387
#ifndef _WIN32
3388
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
3389
#endif
3390
int parse_host_src_port(struct sockaddr_in *haddr,
3391
                        struct sockaddr_in *saddr,
3392
                        const char *str);
3393

    
3394
static CharDriverState *qemu_chr_open_udp(const char *def)
3395
{
3396
    CharDriverState *chr = NULL;
3397
    NetCharDriver *s = NULL;
3398
    int fd = -1;
3399
    struct sockaddr_in saddr;
3400

    
3401
    chr = qemu_mallocz(sizeof(CharDriverState));
3402
    if (!chr)
3403
        goto return_err;
3404
    s = qemu_mallocz(sizeof(NetCharDriver));
3405
    if (!s)
3406
        goto return_err;
3407

    
3408
    fd = socket(PF_INET, SOCK_DGRAM, 0);
3409
    if (fd < 0) {
3410
        perror("socket(PF_INET, SOCK_DGRAM)");
3411
        goto return_err;
3412
    }
3413

    
3414
    if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
3415
        printf("Could not parse: %s\n", def);
3416
        goto return_err;
3417
    }
3418

    
3419
    if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
3420
    {
3421
        perror("bind");
3422
        goto return_err;
3423
    }
3424

    
3425
    s->fd = fd;
3426
    s->bufcnt = 0;
3427
    s->bufptr = 0;
3428
    chr->opaque = s;
3429
    chr->chr_write = udp_chr_write;
3430
    chr->chr_update_read_handler = udp_chr_update_read_handler;
3431
    return chr;
3432

    
3433
return_err:
3434
    if (chr)
3435
        free(chr);
3436
    if (s)
3437
        free(s);
3438
    if (fd >= 0)
3439
        closesocket(fd);
3440
    return NULL;
3441
}
3442

    
3443
/***********************************************************/
3444
/* TCP Net console */
3445

    
3446
typedef struct {
3447
    int fd, listen_fd;
3448
    int connected;
3449
    int max_size;
3450
    int do_telnetopt;
3451
    int do_nodelay;
3452
    int is_unix;
3453
} TCPCharDriver;
3454

    
3455
static void tcp_chr_accept(void *opaque);
3456

    
3457
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
3458
{
3459
    TCPCharDriver *s = chr->opaque;
3460
    if (s->connected) {
3461
        return send_all(s->fd, buf, len);
3462
    } else {
3463
        /* XXX: indicate an error ? */
3464
        return len;
3465
    }
3466
}
3467

    
3468
static int tcp_chr_read_poll(void *opaque)
3469
{
3470
    CharDriverState *chr = opaque;
3471
    TCPCharDriver *s = chr->opaque;
3472
    if (!s->connected)
3473
        return 0;
3474
    s->max_size = qemu_chr_can_read(chr);
3475
    return s->max_size;
3476
}
3477

    
3478
#define IAC 255
3479
#define IAC_BREAK 243
3480
static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
3481
                                      TCPCharDriver *s,
3482
                                      uint8_t *buf, int *size)
3483
{
3484
    /* Handle any telnet client's basic IAC options to satisfy char by
3485
     * char mode with no echo.  All IAC options will be removed from
3486
     * the buf and the do_telnetopt variable will be used to track the
3487
     * state of the width of the IAC information.
3488
     *
3489
     * IAC commands come in sets of 3 bytes with the exception of the
3490
     * "IAC BREAK" command and the double IAC.
3491
     */
3492

    
3493
    int i;
3494
    int j = 0;
3495

    
3496
    for (i = 0; i < *size; i++) {
3497
        if (s->do_telnetopt > 1) {
3498
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
3499
                /* Double IAC means send an IAC */
3500
                if (j != i)
3501
                    buf[j] = buf[i];
3502
                j++;
3503
                s->do_telnetopt = 1;
3504
            } else {
3505
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
3506
                    /* Handle IAC break commands by sending a serial break */
3507
                    qemu_chr_event(chr, CHR_EVENT_BREAK);
3508
                    s->do_telnetopt++;
3509
                }
3510
                s->do_telnetopt++;
3511
            }
3512
            if (s->do_telnetopt >= 4) {
3513
                s->do_telnetopt = 1;
3514
            }
3515
        } else {
3516
            if ((unsigned char)buf[i] == IAC) {
3517
                s->do_telnetopt = 2;
3518
            } else {
3519
                if (j != i)
3520
                    buf[j] = buf[i];
3521
                j++;
3522
            }
3523
        }
3524
    }
3525
    *size = j;
3526
}
3527

    
3528
static void tcp_chr_read(void *opaque)
3529
{
3530
    CharDriverState *chr = opaque;
3531
    TCPCharDriver *s = chr->opaque;
3532
    uint8_t buf[1024];
3533
    int len, size;
3534

    
3535
    if (!s->connected || s->max_size <= 0)
3536
        return;
3537
    len = sizeof(buf);
3538
    if (len > s->max_size)
3539
        len = s->max_size;
3540
    size = recv(s->fd, buf, len, 0);
3541
    if (size == 0) {
3542
        /* connection closed */
3543
        s->connected = 0;
3544
        if (s->listen_fd >= 0) {
3545
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3546
        }
3547
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3548
        closesocket(s->fd);
3549
        s->fd = -1;
3550
    } else if (size > 0) {
3551
        if (s->do_telnetopt)
3552
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
3553
        if (size > 0)
3554
            qemu_chr_read(chr, buf, size);
3555
    }
3556
}
3557

    
3558
static void tcp_chr_connect(void *opaque)
3559
{
3560
    CharDriverState *chr = opaque;
3561
    TCPCharDriver *s = chr->opaque;
3562

    
3563
    s->connected = 1;
3564
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
3565
                         tcp_chr_read, NULL, chr);
3566
    qemu_chr_reset(chr);
3567
}
3568

    
3569
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
3570
static void tcp_chr_telnet_init(int fd)
3571
{
3572
    char buf[3];
3573
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
3574
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
3575
    send(fd, (char *)buf, 3, 0);
3576
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
3577
    send(fd, (char *)buf, 3, 0);
3578
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
3579
    send(fd, (char *)buf, 3, 0);
3580
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
3581
    send(fd, (char *)buf, 3, 0);
3582
}
3583

    
3584
static void socket_set_nodelay(int fd)
3585
{
3586
    int val = 1;
3587
    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
3588
}
3589

    
3590
static void tcp_chr_accept(void *opaque)
3591
{
3592
    CharDriverState *chr = opaque;
3593
    TCPCharDriver *s = chr->opaque;
3594
    struct sockaddr_in saddr;
3595
#ifndef _WIN32
3596
    struct sockaddr_un uaddr;
3597
#endif
3598
    struct sockaddr *addr;
3599
    socklen_t len;
3600
    int fd;
3601

    
3602
    for(;;) {
3603
#ifndef _WIN32
3604
        if (s->is_unix) {
3605
            len = sizeof(uaddr);
3606
            addr = (struct sockaddr *)&uaddr;
3607
        } else
3608
#endif
3609
        {
3610
            len = sizeof(saddr);
3611
            addr = (struct sockaddr *)&saddr;
3612
        }
3613
        fd = accept(s->listen_fd, addr, &len);
3614
        if (fd < 0 && errno != EINTR) {
3615
            return;
3616
        } else if (fd >= 0) {
3617
            if (s->do_telnetopt)
3618
                tcp_chr_telnet_init(fd);
3619
            break;
3620
        }
3621
    }
3622
    socket_set_nonblock(fd);
3623
    if (s->do_nodelay)
3624
        socket_set_nodelay(fd);
3625
    s->fd = fd;
3626
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
3627
    tcp_chr_connect(chr);
3628
}
3629

    
3630
static void tcp_chr_close(CharDriverState *chr)
3631
{
3632
    TCPCharDriver *s = chr->opaque;
3633
    if (s->fd >= 0)
3634
        closesocket(s->fd);
3635
    if (s->listen_fd >= 0)
3636
        closesocket(s->listen_fd);
3637
    qemu_free(s);
3638
}
3639

    
3640
static CharDriverState *qemu_chr_open_tcp(const char *host_str,
3641
                                          int is_telnet,
3642
                                          int is_unix)
3643
{
3644
    CharDriverState *chr = NULL;
3645
    TCPCharDriver *s = NULL;
3646
    int fd = -1, ret, err, val;
3647
    int is_listen = 0;
3648
    int is_waitconnect = 1;
3649
    int do_nodelay = 0;
3650
    const char *ptr;
3651
    struct sockaddr_in saddr;
3652
#ifndef _WIN32
3653
    struct sockaddr_un uaddr;
3654
#endif
3655
    struct sockaddr *addr;
3656
    socklen_t addrlen;
3657

    
3658
#ifndef _WIN32
3659
    if (is_unix) {
3660
        addr = (struct sockaddr *)&uaddr;
3661
        addrlen = sizeof(uaddr);
3662
        if (parse_unix_path(&uaddr, host_str) < 0)
3663
            goto fail;
3664
    } else
3665
#endif
3666
    {
3667
        addr = (struct sockaddr *)&saddr;
3668
        addrlen = sizeof(saddr);
3669
        if (parse_host_port(&saddr, host_str) < 0)
3670
            goto fail;
3671
    }
3672

    
3673
    ptr = host_str;
3674
    while((ptr = strchr(ptr,','))) {
3675
        ptr++;
3676
        if (!strncmp(ptr,"server",6)) {
3677
            is_listen = 1;
3678
        } else if (!strncmp(ptr,"nowait",6)) {
3679
            is_waitconnect = 0;
3680
        } else if (!strncmp(ptr,"nodelay",6)) {
3681
            do_nodelay = 1;
3682
        } else {
3683
            printf("Unknown option: %s\n", ptr);
3684
            goto fail;
3685
        }
3686
    }
3687
    if (!is_listen)
3688
        is_waitconnect = 0;
3689

    
3690
    chr = qemu_mallocz(sizeof(CharDriverState));
3691
    if (!chr)
3692
        goto fail;
3693
    s = qemu_mallocz(sizeof(TCPCharDriver));
3694
    if (!s)
3695
        goto fail;
3696

    
3697
#ifndef _WIN32
3698
    if (is_unix)
3699
        fd = socket(PF_UNIX, SOCK_STREAM, 0);
3700
    else
3701
#endif
3702
        fd = socket(PF_INET, SOCK_STREAM, 0);
3703

    
3704
    if (fd < 0)
3705
        goto fail;
3706

    
3707
    if (!is_waitconnect)
3708
        socket_set_nonblock(fd);
3709

    
3710
    s->connected = 0;
3711
    s->fd = -1;
3712
    s->listen_fd = -1;
3713
    s->is_unix = is_unix;
3714
    s->do_nodelay = do_nodelay && !is_unix;
3715

    
3716
    chr->opaque = s;
3717
    chr->chr_write = tcp_chr_write;
3718
    chr->chr_close = tcp_chr_close;
3719

    
3720
    if (is_listen) {
3721
        /* allow fast reuse */
3722
#ifndef _WIN32
3723
        if (is_unix) {
3724
            char path[109];
3725
            pstrcpy(path, sizeof(path), uaddr.sun_path);
3726
            unlink(path);
3727
        } else
3728
#endif
3729
        {
3730
            val = 1;
3731
            setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3732
        }
3733

    
3734
        ret = bind(fd, addr, addrlen);
3735
        if (ret < 0)
3736
            goto fail;
3737

    
3738
        ret = listen(fd, 0);
3739
        if (ret < 0)
3740
            goto fail;
3741

    
3742
        s->listen_fd = fd;
3743
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
3744
        if (is_telnet)
3745
            s->do_telnetopt = 1;
3746
    } else {
3747
        for(;;) {
3748
            ret = connect(fd, addr, addrlen);
3749
            if (ret < 0) {
3750
                err = socket_error();
3751
                if (err == EINTR || err == EWOULDBLOCK) {
3752
                } else if (err == EINPROGRESS) {
3753
                    break;
3754
#ifdef _WIN32
3755
                } else if (err == WSAEALREADY) {
3756
                    break;
3757
#endif
3758
                } else {
3759
                    goto fail;
3760
                }
3761
            } else {
3762
                s->connected = 1;
3763
                break;
3764
            }
3765
        }
3766
        s->fd = fd;
3767
        socket_set_nodelay(fd);
3768
        if (s->connected)
3769
            tcp_chr_connect(chr);
3770
        else
3771
            qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
3772
    }
3773

    
3774
    if (is_listen && is_waitconnect) {
3775
        printf("QEMU waiting for connection on: %s\n", host_str);
3776
        tcp_chr_accept(chr);
3777
        socket_set_nonblock(s->listen_fd);
3778
    }
3779

    
3780
    return chr;
3781
 fail:
3782
    if (fd >= 0)
3783
        closesocket(fd);
3784
    qemu_free(s);
3785
    qemu_free(chr);
3786
    return NULL;
3787
}
3788

    
3789
CharDriverState *qemu_chr_open(const char *filename)
3790
{
3791
    const char *p;
3792

    
3793
    if (!strcmp(filename, "vc")) {
3794
        return text_console_init(&display_state, 0);
3795
    } else if (strstart(filename, "vc:", &p)) {
3796
        return text_console_init(&display_state, p);
3797
    } else if (!strcmp(filename, "null")) {
3798
        return qemu_chr_open_null();
3799
    } else
3800
    if (strstart(filename, "tcp:", &p)) {
3801
        return qemu_chr_open_tcp(p, 0, 0);
3802
    } else
3803
    if (strstart(filename, "telnet:", &p)) {
3804
        return qemu_chr_open_tcp(p, 1, 0);
3805
    } else
3806
    if (strstart(filename, "udp:", &p)) {
3807
        return qemu_chr_open_udp(p);
3808
    } else
3809
    if (strstart(filename, "mon:", &p)) {
3810
        CharDriverState *drv = qemu_chr_open(p);
3811
        if (drv) {
3812
            drv = qemu_chr_open_mux(drv);
3813
            monitor_init(drv, !nographic);
3814
            return drv;
3815
        }
3816
        printf("Unable to open driver: %s\n", p);
3817
        return 0;
3818
    } else
3819
#ifndef _WIN32
3820
    if (strstart(filename, "unix:", &p)) {
3821
        return qemu_chr_open_tcp(p, 0, 1);
3822
    } else if (strstart(filename, "file:", &p)) {
3823
        return qemu_chr_open_file_out(p);
3824
    } else if (strstart(filename, "pipe:", &p)) {
3825
        return qemu_chr_open_pipe(p);
3826
    } else if (!strcmp(filename, "pty")) {
3827
        return qemu_chr_open_pty();
3828
    } else if (!strcmp(filename, "stdio")) {
3829
        return qemu_chr_open_stdio();
3830
    } else
3831
#if defined(__linux__)
3832
    if (strstart(filename, "/dev/parport", NULL)) {
3833
        return qemu_chr_open_pp(filename);
3834
    } else
3835
#endif
3836
#if defined(__linux__) || defined(__sun__) || defined(__FreeBSD__) \
3837
    || defined(__NetBSD__) || defined(__OpenBSD__)
3838
    if (strstart(filename, "/dev/", NULL)) {
3839
        return qemu_chr_open_tty(filename);
3840
    } else
3841
#endif
3842
#else /* !_WIN32 */
3843
    if (strstart(filename, "COM", NULL)) {
3844
        return qemu_chr_open_win(filename);
3845
    } else
3846
    if (strstart(filename, "pipe:", &p)) {
3847
        return qemu_chr_open_win_pipe(p);
3848
    } else
3849
    if (strstart(filename, "con:", NULL)) {
3850
        return qemu_chr_open_win_con(filename);
3851
    } else
3852
    if (strstart(filename, "file:", &p)) {
3853
        return qemu_chr_open_win_file_out(p);
3854
    } else
3855
#endif
3856
#ifdef CONFIG_BRLAPI
3857
    if (!strcmp(filename, "braille")) {
3858
        return chr_baum_init();
3859
    } else
3860
#endif
3861
    {
3862
        return NULL;
3863
    }
3864
}
3865

    
3866
void qemu_chr_close(CharDriverState *chr)
3867
{
3868
    if (chr->chr_close)
3869
        chr->chr_close(chr);
3870
    qemu_free(chr);
3871
}
3872

    
3873
/***********************************************************/
3874
/* network device redirectors */
3875

    
3876
__attribute__ (( unused ))
3877
static void hex_dump(FILE *f, const uint8_t *buf, int size)
3878
{
3879
    int len, i, j, c;
3880

    
3881
    for(i=0;i<size;i+=16) {
3882
        len = size - i;
3883
        if (len > 16)
3884
            len = 16;
3885
        fprintf(f, "%08x ", i);
3886
        for(j=0;j<16;j++) {
3887
            if (j < len)
3888
                fprintf(f, " %02x", buf[i+j]);
3889
            else
3890
                fprintf(f, "   ");
3891
        }
3892
        fprintf(f, " ");
3893
        for(j=0;j<len;j++) {
3894
            c = buf[i+j];
3895
            if (c < ' ' || c > '~')
3896
                c = '.';
3897
            fprintf(f, "%c", c);
3898
        }
3899
        fprintf(f, "\n");
3900
    }
3901
}
3902

    
3903
static int parse_macaddr(uint8_t *macaddr, const char *p)
3904
{
3905
    int i;
3906
    char *last_char;
3907
    long int offset;
3908

    
3909
    errno = 0;
3910
    offset = strtol(p, &last_char, 0);    
3911
    if (0 == errno && '\0' == *last_char &&
3912
            offset >= 0 && offset <= 0xFFFFFF) {
3913
        macaddr[3] = (offset & 0xFF0000) >> 16;
3914
        macaddr[4] = (offset & 0xFF00) >> 8;
3915
        macaddr[5] = offset & 0xFF;
3916
        return 0;
3917
    } else {
3918
        for(i = 0; i < 6; i++) {
3919
            macaddr[i] = strtol(p, (char **)&p, 16);
3920
            if (i == 5) {
3921
                if (*p != '\0')
3922
                    return -1;
3923
            } else {
3924
                if (*p != ':' && *p != '-')
3925
                    return -1;
3926
                p++;
3927
            }
3928
        }
3929
        return 0;    
3930
    }
3931

    
3932
    return -1;
3933
}
3934

    
3935
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3936
{
3937
    const char *p, *p1;
3938
    int len;
3939
    p = *pp;
3940
    p1 = strchr(p, sep);
3941
    if (!p1)
3942
        return -1;
3943
    len = p1 - p;
3944
    p1++;
3945
    if (buf_size > 0) {
3946
        if (len > buf_size - 1)
3947
            len = buf_size - 1;
3948
        memcpy(buf, p, len);
3949
        buf[len] = '\0';
3950
    }
3951
    *pp = p1;
3952
    return 0;
3953
}
3954

    
3955
int parse_host_src_port(struct sockaddr_in *haddr,
3956
                        struct sockaddr_in *saddr,
3957
                        const char *input_str)
3958
{
3959
    char *str = strdup(input_str);
3960
    char *host_str = str;
3961
    char *src_str;
3962
    const char *src_str2;
3963
    char *ptr;
3964

    
3965
    /*
3966
     * Chop off any extra arguments at the end of the string which
3967
     * would start with a comma, then fill in the src port information
3968
     * if it was provided else use the "any address" and "any port".
3969
     */
3970
    if ((ptr = strchr(str,',')))
3971
        *ptr = '\0';
3972

    
3973
    if ((src_str = strchr(input_str,'@'))) {
3974
        *src_str = '\0';
3975
        src_str++;
3976
    }
3977

    
3978
    if (parse_host_port(haddr, host_str) < 0)
3979
        goto fail;
3980

    
3981
    src_str2 = src_str;
3982
    if (!src_str || *src_str == '\0')
3983
        src_str2 = ":0";
3984

    
3985
    if (parse_host_port(saddr, src_str2) < 0)
3986
        goto fail;
3987

    
3988
    free(str);
3989
    return(0);
3990

    
3991
fail:
3992
    free(str);
3993
    return -1;
3994
}
3995

    
3996
int parse_host_port(struct sockaddr_in *saddr, const char *str)
3997
{
3998
    char buf[512];
3999
    struct hostent *he;
4000
    const char *p, *r;
4001
    int port;
4002

    
4003
    p = str;
4004
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4005
        return -1;
4006
    saddr->sin_family = AF_INET;
4007
    if (buf[0] == '\0') {
4008
        saddr->sin_addr.s_addr = 0;
4009
    } else {
4010
        if (isdigit(buf[0])) {
4011
            if (!inet_aton(buf, &saddr->sin_addr))
4012
                return -1;
4013
        } else {
4014
            if ((he = gethostbyname(buf)) == NULL)
4015
                return - 1;
4016
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
4017
        }
4018
    }
4019
    port = strtol(p, (char **)&r, 0);
4020
    if (r == p)
4021
        return -1;
4022
    saddr->sin_port = htons(port);
4023
    return 0;
4024
}
4025

    
4026
#ifndef _WIN32
4027
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
4028
{
4029
    const char *p;
4030
    int len;
4031

    
4032
    len = MIN(108, strlen(str));
4033
    p = strchr(str, ',');
4034
    if (p)
4035
        len = MIN(len, p - str);
4036

    
4037
    memset(uaddr, 0, sizeof(*uaddr));
4038

    
4039
    uaddr->sun_family = AF_UNIX;
4040
    memcpy(uaddr->sun_path, str, len);
4041

    
4042
    return 0;
4043
}
4044
#endif
4045

    
4046
/* find or alloc a new VLAN */
4047
VLANState *qemu_find_vlan(int id)
4048
{
4049
    VLANState **pvlan, *vlan;
4050
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4051
        if (vlan->id == id)
4052
            return vlan;
4053
    }
4054
    vlan = qemu_mallocz(sizeof(VLANState));
4055
    if (!vlan)
4056
        return NULL;
4057
    vlan->id = id;
4058
    vlan->next = NULL;
4059
    pvlan = &first_vlan;
4060
    while (*pvlan != NULL)
4061
        pvlan = &(*pvlan)->next;
4062
    *pvlan = vlan;
4063
    return vlan;
4064
}
4065

    
4066
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
4067
                                      IOReadHandler *fd_read,
4068
                                      IOCanRWHandler *fd_can_read,
4069
                                      void *opaque)
4070
{
4071
    VLANClientState *vc, **pvc;
4072
    vc = qemu_mallocz(sizeof(VLANClientState));
4073
    if (!vc)
4074
        return NULL;
4075
    vc->fd_read = fd_read;
4076
    vc->fd_can_read = fd_can_read;
4077
    vc->opaque = opaque;
4078
    vc->vlan = vlan;
4079

    
4080
    vc->next = NULL;
4081
    pvc = &vlan->first_client;
4082
    while (*pvc != NULL)
4083
        pvc = &(*pvc)->next;
4084
    *pvc = vc;
4085
    return vc;
4086
}
4087

    
4088
void qemu_del_vlan_client(VLANClientState *vc)
4089
{
4090
    VLANClientState **pvc = &vc->vlan->first_client;
4091

    
4092
    while (*pvc != NULL)
4093
        if (*pvc == vc) {
4094
            *pvc = vc->next;
4095
            free(vc);
4096
            break;
4097
        } else
4098
            pvc = &(*pvc)->next;
4099
}
4100

    
4101
int qemu_can_send_packet(VLANClientState *vc1)
4102
{
4103
    VLANState *vlan = vc1->vlan;
4104
    VLANClientState *vc;
4105

    
4106
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4107
        if (vc != vc1) {
4108
            if (vc->fd_can_read && vc->fd_can_read(vc->opaque))
4109
                return 1;
4110
        }
4111
    }
4112
    return 0;
4113
}
4114

    
4115
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
4116
{
4117
    VLANState *vlan = vc1->vlan;
4118
    VLANClientState *vc;
4119

    
4120
#if 0
4121
    printf("vlan %d send:\n", vlan->id);
4122
    hex_dump(stdout, buf, size);
4123
#endif
4124
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
4125
        if (vc != vc1) {
4126
            vc->fd_read(vc->opaque, buf, size);
4127
        }
4128
    }
4129
}
4130

    
4131
#if defined(CONFIG_SLIRP)
4132

    
4133
/* slirp network adapter */
4134

    
4135
static int slirp_inited;
4136
static VLANClientState *slirp_vc;
4137

    
4138
int slirp_can_output(void)
4139
{
4140
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
4141
}
4142

    
4143
void slirp_output(const uint8_t *pkt, int pkt_len)
4144
{
4145
#if 0
4146
    printf("slirp output:\n");
4147
    hex_dump(stdout, pkt, pkt_len);
4148
#endif
4149
    if (!slirp_vc)
4150
        return;
4151
    qemu_send_packet(slirp_vc, pkt, pkt_len);
4152
}
4153

    
4154
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
4155
{
4156
#if 0
4157
    printf("slirp input:\n");
4158
    hex_dump(stdout, buf, size);
4159
#endif
4160
    slirp_input(buf, size);
4161
}
4162

    
4163
static int net_slirp_init(VLANState *vlan)
4164
{
4165
    if (!slirp_inited) {
4166
        slirp_inited = 1;
4167
        slirp_init();
4168
    }
4169
    slirp_vc = qemu_new_vlan_client(vlan,
4170
                                    slirp_receive, NULL, NULL);
4171
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
4172
    return 0;
4173
}
4174

    
4175
static void net_slirp_redir(const char *redir_str)
4176
{
4177
    int is_udp;
4178
    char buf[256], *r;
4179
    const char *p;
4180
    struct in_addr guest_addr;
4181
    int host_port, guest_port;
4182

    
4183
    if (!slirp_inited) {
4184
        slirp_inited = 1;
4185
        slirp_init();
4186
    }
4187

    
4188
    p = redir_str;
4189
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4190
        goto fail;
4191
    if (!strcmp(buf, "tcp")) {
4192
        is_udp = 0;
4193
    } else if (!strcmp(buf, "udp")) {
4194
        is_udp = 1;
4195
    } else {
4196
        goto fail;
4197
    }
4198

    
4199
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4200
        goto fail;
4201
    host_port = strtol(buf, &r, 0);
4202
    if (r == buf)
4203
        goto fail;
4204

    
4205
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
4206
        goto fail;
4207
    if (buf[0] == '\0') {
4208
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
4209
    }
4210
    if (!inet_aton(buf, &guest_addr))
4211
        goto fail;
4212

    
4213
    guest_port = strtol(p, &r, 0);
4214
    if (r == p)
4215
        goto fail;
4216

    
4217
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
4218
        fprintf(stderr, "qemu: could not set up redirection\n");
4219
        exit(1);
4220
    }
4221
    return;
4222
 fail:
4223
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
4224
    exit(1);
4225
}
4226

    
4227
#ifndef _WIN32
4228

    
4229
char smb_dir[1024];
4230

    
4231
static void erase_dir(char *dir_name)
4232
{
4233
    DIR *d;
4234
    struct dirent *de;
4235
    char filename[1024];
4236

    
4237
    /* erase all the files in the directory */
4238
    if ((d = opendir(dir_name)) != 0) {
4239
        for(;;) {
4240
            de = readdir(d);
4241
            if (!de)
4242
                break;
4243
            if (strcmp(de->d_name, ".") != 0 &&
4244
                strcmp(de->d_name, "..") != 0) {
4245
                snprintf(filename, sizeof(filename), "%s/%s",
4246
                         smb_dir, de->d_name);
4247
                if (unlink(filename) != 0)  /* is it a directory? */
4248
                    erase_dir(filename);
4249
            }
4250
        }
4251
        closedir(d);
4252
        rmdir(dir_name);
4253
    }
4254
}
4255

    
4256
/* automatic user mode samba server configuration */
4257
static void smb_exit(void)
4258
{
4259
    erase_dir(smb_dir);
4260
}
4261

    
4262
/* automatic user mode samba server configuration */
4263
static void net_slirp_smb(const char *exported_dir)
4264
{
4265
    char smb_conf[1024];
4266
    char smb_cmdline[1024];
4267
    FILE *f;
4268

    
4269
    if (!slirp_inited) {
4270
        slirp_inited = 1;
4271
        slirp_init();
4272
    }
4273

    
4274
    /* XXX: better tmp dir construction */
4275
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
4276
    if (mkdir(smb_dir, 0700) < 0) {
4277
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
4278
        exit(1);
4279
    }
4280
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
4281

    
4282
    f = fopen(smb_conf, "w");
4283
    if (!f) {
4284
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
4285
        exit(1);
4286
    }
4287
    fprintf(f,
4288
            "[global]\n"
4289
            "private dir=%s\n"
4290
            "smb ports=0\n"
4291
            "socket address=127.0.0.1\n"
4292
            "pid directory=%s\n"
4293
            "lock directory=%s\n"
4294
            "log file=%s/log.smbd\n"
4295
            "smb passwd file=%s/smbpasswd\n"
4296
            "security = share\n"
4297
            "[qemu]\n"
4298
            "path=%s\n"
4299
            "read only=no\n"
4300
            "guest ok=yes\n",
4301
            smb_dir,
4302
            smb_dir,
4303
            smb_dir,
4304
            smb_dir,
4305
            smb_dir,
4306
            exported_dir
4307
            );
4308
    fclose(f);
4309
    atexit(smb_exit);
4310

    
4311
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
4312
             SMBD_COMMAND, smb_conf);
4313

    
4314
    slirp_add_exec(0, smb_cmdline, 4, 139);
4315
}
4316

    
4317
#endif /* !defined(_WIN32) */
4318
void do_info_slirp(void)
4319
{
4320
    slirp_stats();
4321
}
4322

    
4323
#endif /* CONFIG_SLIRP */
4324

    
4325
#if !defined(_WIN32)
4326

    
4327
typedef struct TAPState {
4328
    VLANClientState *vc;
4329
    int fd;
4330
    char down_script[1024];
4331
} TAPState;
4332

    
4333
static void tap_receive(void *opaque, const uint8_t *buf, int size)
4334
{
4335
    TAPState *s = opaque;
4336
    int ret;
4337
    for(;;) {
4338
        ret = write(s->fd, buf, size);
4339
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
4340
        } else {
4341
            break;
4342
        }
4343
    }
4344
}
4345

    
4346
static void tap_send(void *opaque)
4347
{
4348
    TAPState *s = opaque;
4349
    uint8_t buf[4096];
4350
    int size;
4351

    
4352
#ifdef __sun__
4353
    struct strbuf sbuf;
4354
    int f = 0;
4355
    sbuf.maxlen = sizeof(buf);
4356
    sbuf.buf = buf;
4357
    size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
4358
#else
4359
    size = read(s->fd, buf, sizeof(buf));
4360
#endif
4361
    if (size > 0) {
4362
        qemu_send_packet(s->vc, buf, size);
4363
    }
4364
}
4365

    
4366
/* fd support */
4367

    
4368
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
4369
{
4370
    TAPState *s;
4371

    
4372
    s = qemu_mallocz(sizeof(TAPState));
4373
    if (!s)
4374
        return NULL;
4375
    s->fd = fd;
4376
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
4377
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
4378
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
4379
    return s;
4380
}
4381

    
4382
#if defined (_BSD) || defined (__FreeBSD_kernel__)
4383
static int tap_open(char *ifname, int ifname_size)
4384
{
4385
    int fd;
4386
    char *dev;
4387
    struct stat s;
4388

    
4389
    TFR(fd = open("/dev/tap", O_RDWR));
4390
    if (fd < 0) {
4391
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
4392
        return -1;
4393
    }
4394

    
4395
    fstat(fd, &s);
4396
    dev = devname(s.st_rdev, S_IFCHR);
4397
    pstrcpy(ifname, ifname_size, dev);
4398

    
4399
    fcntl(fd, F_SETFL, O_NONBLOCK);
4400
    return fd;
4401
}
4402
#elif defined(__sun__)
4403
#define TUNNEWPPA       (('T'<<16) | 0x0001)
4404
/*
4405
 * Allocate TAP device, returns opened fd.
4406
 * Stores dev name in the first arg(must be large enough).
4407
 */
4408
int tap_alloc(char *dev, size_t dev_size)
4409
{
4410
    int tap_fd, if_fd, ppa = -1;
4411
    static int ip_fd = 0;
4412
    char *ptr;
4413

    
4414
    static int arp_fd = 0;
4415
    int ip_muxid, arp_muxid;
4416
    struct strioctl  strioc_if, strioc_ppa;
4417
    int link_type = I_PLINK;;
4418
    struct lifreq ifr;
4419
    char actual_name[32] = "";
4420

    
4421
    memset(&ifr, 0x0, sizeof(ifr));
4422

    
4423
    if( *dev ){
4424
       ptr = dev;
4425
       while( *ptr && !isdigit((int)*ptr) ) ptr++;
4426
       ppa = atoi(ptr);
4427
    }
4428

    
4429
    /* Check if IP device was opened */
4430
    if( ip_fd )
4431
       close(ip_fd);
4432

    
4433
    TFR(ip_fd = open("/dev/udp", O_RDWR, 0));
4434
    if (ip_fd < 0) {
4435
       syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
4436
       return -1;
4437
    }
4438

    
4439
    TFR(tap_fd = open("/dev/tap", O_RDWR, 0));
4440
    if (tap_fd < 0) {
4441
       syslog(LOG_ERR, "Can't open /dev/tap");
4442
       return -1;
4443
    }
4444

    
4445
    /* Assign a new PPA and get its unit number. */
4446
    strioc_ppa.ic_cmd = TUNNEWPPA;
4447
    strioc_ppa.ic_timout = 0;
4448
    strioc_ppa.ic_len = sizeof(ppa);
4449
    strioc_ppa.ic_dp = (char *)&ppa;
4450
    if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
4451
       syslog (LOG_ERR, "Can't assign new interface");
4452

    
4453
    TFR(if_fd = open("/dev/tap", O_RDWR, 0));
4454
    if (if_fd < 0) {
4455
       syslog(LOG_ERR, "Can't open /dev/tap (2)");
4456
       return -1;
4457
    }
4458
    if(ioctl(if_fd, I_PUSH, "ip") < 0){
4459
       syslog(LOG_ERR, "Can't push IP module");
4460
       return -1;
4461
    }
4462

    
4463
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
4464
        syslog(LOG_ERR, "Can't get flags\n");
4465

    
4466
    snprintf (actual_name, 32, "tap%d", ppa);
4467
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4468

    
4469
    ifr.lifr_ppa = ppa;
4470
    /* Assign ppa according to the unit number returned by tun device */
4471

    
4472
    if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
4473
        syslog (LOG_ERR, "Can't set PPA %d", ppa);
4474
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
4475
        syslog (LOG_ERR, "Can't get flags\n");
4476
    /* Push arp module to if_fd */
4477
    if (ioctl (if_fd, I_PUSH, "arp") < 0)
4478
        syslog (LOG_ERR, "Can't push ARP module (2)");
4479

    
4480
    /* Push arp module to ip_fd */
4481
    if (ioctl (ip_fd, I_POP, NULL) < 0)
4482
        syslog (LOG_ERR, "I_POP failed\n");
4483
    if (ioctl (ip_fd, I_PUSH, "arp") < 0)
4484
        syslog (LOG_ERR, "Can't push ARP module (3)\n");
4485
    /* Open arp_fd */
4486
    TFR(arp_fd = open ("/dev/tap", O_RDWR, 0));
4487
    if (arp_fd < 0)
4488
       syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
4489

    
4490
    /* Set ifname to arp */
4491
    strioc_if.ic_cmd = SIOCSLIFNAME;
4492
    strioc_if.ic_timout = 0;
4493
    strioc_if.ic_len = sizeof(ifr);
4494
    strioc_if.ic_dp = (char *)&ifr;
4495
    if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
4496
        syslog (LOG_ERR, "Can't set ifname to arp\n");
4497
    }
4498

    
4499
    if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
4500
       syslog(LOG_ERR, "Can't link TAP device to IP");
4501
       return -1;
4502
    }
4503

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

    
4507
    close (if_fd);
4508

    
4509
    memset(&ifr, 0x0, sizeof(ifr));
4510
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
4511
    ifr.lifr_ip_muxid  = ip_muxid;
4512
    ifr.lifr_arp_muxid = arp_muxid;
4513

    
4514
    if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
4515
    {
4516
      ioctl (ip_fd, I_PUNLINK , arp_muxid);
4517
      ioctl (ip_fd, I_PUNLINK, ip_muxid);
4518
      syslog (LOG_ERR, "Can't set multiplexor id");
4519
    }
4520

    
4521
    snprintf(dev, dev_size, "tap%d", ppa);
4522
    return tap_fd;
4523
}
4524

    
4525
static int tap_open(char *ifname, int ifname_size)
4526
{
4527
    char  dev[10]="";
4528
    int fd;
4529
    if( (fd = tap_alloc(dev, sizeof(dev))) < 0 ){
4530
       fprintf(stderr, "Cannot allocate TAP device\n");
4531
       return -1;
4532
    }
4533
    pstrcpy(ifname, ifname_size, dev);
4534
    fcntl(fd, F_SETFL, O_NONBLOCK);
4535
    return fd;
4536
}
4537
#else
4538
static int tap_open(char *ifname, int ifname_size)
4539
{
4540
    struct ifreq ifr;
4541
    int fd, ret;
4542

    
4543
    TFR(fd = open("/dev/net/tun", O_RDWR));
4544
    if (fd < 0) {
4545
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
4546
        return -1;
4547
    }
4548
    memset(&ifr, 0, sizeof(ifr));
4549
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
4550
    if (ifname[0] != '\0')
4551
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
4552
    else
4553
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
4554
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
4555
    if (ret != 0) {
4556
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
4557
        close(fd);
4558
        return -1;
4559
    }
4560
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
4561
    fcntl(fd, F_SETFL, O_NONBLOCK);
4562
    return fd;
4563
}
4564
#endif
4565

    
4566
static int launch_script(const char *setup_script, const char *ifname, int fd)
4567
{
4568
    int pid, status;
4569
    char *args[3];
4570
    char **parg;
4571

    
4572
        /* try to launch network script */
4573
        pid = fork();
4574
        if (pid >= 0) {
4575
            if (pid == 0) {
4576
                int open_max = sysconf (_SC_OPEN_MAX), i;
4577
                for (i = 0; i < open_max; i++)
4578
                    if (i != STDIN_FILENO &&
4579
                        i != STDOUT_FILENO &&
4580
                        i != STDERR_FILENO &&
4581
                        i != fd)
4582
                        close(i);
4583

    
4584
                parg = args;
4585
                *parg++ = (char *)setup_script;
4586
                *parg++ = (char *)ifname;
4587
                *parg++ = NULL;
4588
                execv(setup_script, args);
4589
                _exit(1);
4590
            }
4591
            while (waitpid(pid, &status, 0) != pid);
4592
            if (!WIFEXITED(status) ||
4593
                WEXITSTATUS(status) != 0) {
4594
                fprintf(stderr, "%s: could not launch network script\n",
4595
                        setup_script);
4596
                return -1;
4597
            }
4598
        }
4599
    return 0;
4600
}
4601

    
4602
static int net_tap_init(VLANState *vlan, const char *ifname1,
4603
                        const char *setup_script, const char *down_script)
4604
{
4605
    TAPState *s;
4606
    int fd;
4607
    char ifname[128];
4608

    
4609
    if (ifname1 != NULL)
4610
        pstrcpy(ifname, sizeof(ifname), ifname1);
4611
    else
4612
        ifname[0] = '\0';
4613
    TFR(fd = tap_open(ifname, sizeof(ifname)));
4614
    if (fd < 0)
4615
        return -1;
4616

    
4617
    if (!setup_script || !strcmp(setup_script, "no"))
4618
        setup_script = "";
4619
    if (setup_script[0] != '\0') {
4620
        if (launch_script(setup_script, ifname, fd))
4621
            return -1;
4622
    }
4623
    s = net_tap_fd_init(vlan, fd);
4624
    if (!s)
4625
        return -1;
4626
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4627
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
4628
    if (down_script && strcmp(down_script, "no"))
4629
        snprintf(s->down_script, sizeof(s->down_script), "%s", down_script);
4630
    return 0;
4631
}
4632

    
4633
#endif /* !_WIN32 */
4634

    
4635
#if defined(CONFIG_VDE)
4636
typedef struct VDEState {
4637
    VLANClientState *vc;
4638
    VDECONN *vde;
4639
} VDEState;
4640

    
4641
static void vde_to_qemu(void *opaque)
4642
{
4643
    VDEState *s = opaque;
4644
    uint8_t buf[4096];
4645
    int size;
4646

    
4647
    size = vde_recv(s->vde, buf, sizeof(buf), 0);
4648
    if (size > 0) {
4649
        qemu_send_packet(s->vc, buf, size);
4650
    }
4651
}
4652

    
4653
static void vde_from_qemu(void *opaque, const uint8_t *buf, int size)
4654
{
4655
    VDEState *s = opaque;
4656
    int ret;
4657
    for(;;) {
4658
        ret = vde_send(s->vde, buf, size, 0);
4659
        if (ret < 0 && errno == EINTR) {
4660
        } else {
4661
            break;
4662
        }
4663
    }
4664
}
4665

    
4666
static int net_vde_init(VLANState *vlan, const char *sock, int port,
4667
                        const char *group, int mode)
4668
{
4669
    VDEState *s;
4670
    char *init_group = strlen(group) ? (char *)group : NULL;
4671
    char *init_sock = strlen(sock) ? (char *)sock : NULL;
4672

    
4673
    struct vde_open_args args = {
4674
        .port = port,
4675
        .group = init_group,
4676
        .mode = mode,
4677
    };
4678

    
4679
    s = qemu_mallocz(sizeof(VDEState));
4680
    if (!s)
4681
        return -1;
4682
    s->vde = vde_open(init_sock, "QEMU", &args);
4683
    if (!s->vde){
4684
        free(s);
4685
        return -1;
4686
    }
4687
    s->vc = qemu_new_vlan_client(vlan, vde_from_qemu, NULL, s);
4688
    qemu_set_fd_handler(vde_datafd(s->vde), vde_to_qemu, NULL, s);
4689
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "vde: sock=%s fd=%d",
4690
             sock, vde_datafd(s->vde));
4691
    return 0;
4692
}
4693
#endif
4694

    
4695
/* network connection */
4696
typedef struct NetSocketState {
4697
    VLANClientState *vc;
4698
    int fd;
4699
    int state; /* 0 = getting length, 1 = getting data */
4700
    int index;
4701
    int packet_len;
4702
    uint8_t buf[4096];
4703
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
4704
} NetSocketState;
4705

    
4706
typedef struct NetSocketListenState {
4707
    VLANState *vlan;
4708
    int fd;
4709
} NetSocketListenState;
4710

    
4711
/* XXX: we consider we can send the whole packet without blocking */
4712
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
4713
{
4714
    NetSocketState *s = opaque;
4715
    uint32_t len;
4716
    len = htonl(size);
4717

    
4718
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
4719
    send_all(s->fd, buf, size);
4720
}
4721

    
4722
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
4723
{
4724
    NetSocketState *s = opaque;
4725
    sendto(s->fd, buf, size, 0,
4726
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
4727
}
4728

    
4729
static void net_socket_send(void *opaque)
4730
{
4731
    NetSocketState *s = opaque;
4732
    int l, size, err;
4733
    uint8_t buf1[4096];
4734
    const uint8_t *buf;
4735

    
4736
    size = recv(s->fd, buf1, sizeof(buf1), 0);
4737
    if (size < 0) {
4738
        err = socket_error();
4739
        if (err != EWOULDBLOCK)
4740
            goto eoc;
4741
    } else if (size == 0) {
4742
        /* end of connection */
4743
    eoc:
4744
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4745
        closesocket(s->fd);
4746
        return;
4747
    }
4748
    buf = buf1;
4749
    while (size > 0) {
4750
        /* reassemble a packet from the network */
4751
        switch(s->state) {
4752
        case 0:
4753
            l = 4 - s->index;
4754
            if (l > size)
4755
                l = size;
4756
            memcpy(s->buf + s->index, buf, l);
4757
            buf += l;
4758
            size -= l;
4759
            s->index += l;
4760
            if (s->index == 4) {
4761
                /* got length */
4762
                s->packet_len = ntohl(*(uint32_t *)s->buf);
4763
                s->index = 0;
4764
                s->state = 1;
4765
            }
4766
            break;
4767
        case 1:
4768
            l = s->packet_len - s->index;
4769
            if (l > size)
4770
                l = size;
4771
            memcpy(s->buf + s->index, buf, l);
4772
            s->index += l;
4773
            buf += l;
4774
            size -= l;
4775
            if (s->index >= s->packet_len) {
4776
                qemu_send_packet(s->vc, s->buf, s->packet_len);
4777
                s->index = 0;
4778
                s->state = 0;
4779
            }
4780
            break;
4781
        }
4782
    }
4783
}
4784

    
4785
static void net_socket_send_dgram(void *opaque)
4786
{
4787
    NetSocketState *s = opaque;
4788
    int size;
4789

    
4790
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
4791
    if (size < 0)
4792
        return;
4793
    if (size == 0) {
4794
        /* end of connection */
4795
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
4796
        return;
4797
    }
4798
    qemu_send_packet(s->vc, s->buf, size);
4799
}
4800

    
4801
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
4802
{
4803
    struct ip_mreq imr;
4804
    int fd;
4805
    int val, ret;
4806
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
4807
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
4808
                inet_ntoa(mcastaddr->sin_addr),
4809
                (int)ntohl(mcastaddr->sin_addr.s_addr));
4810
        return -1;
4811

    
4812
    }
4813
    fd = socket(PF_INET, SOCK_DGRAM, 0);
4814
    if (fd < 0) {
4815
        perror("socket(PF_INET, SOCK_DGRAM)");
4816
        return -1;
4817
    }
4818

    
4819
    val = 1;
4820
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR,
4821
                   (const char *)&val, sizeof(val));
4822
    if (ret < 0) {
4823
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
4824
        goto fail;
4825
    }
4826

    
4827
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
4828
    if (ret < 0) {
4829
        perror("bind");
4830
        goto fail;
4831
    }
4832

    
4833
    /* Add host to multicast group */
4834
    imr.imr_multiaddr = mcastaddr->sin_addr;
4835
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
4836

    
4837
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP,
4838
                     (const char *)&imr, sizeof(struct ip_mreq));
4839
    if (ret < 0) {
4840
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
4841
        goto fail;
4842
    }
4843

    
4844
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
4845
    val = 1;
4846
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP,
4847
                   (const char *)&val, sizeof(val));
4848
    if (ret < 0) {
4849
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
4850
        goto fail;
4851
    }
4852

    
4853
    socket_set_nonblock(fd);
4854
    return fd;
4855
fail:
4856
    if (fd >= 0)
4857
        closesocket(fd);
4858
    return -1;
4859
}
4860

    
4861
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd,
4862
                                          int is_connected)
4863
{
4864
    struct sockaddr_in saddr;
4865
    int newfd;
4866
    socklen_t saddr_len;
4867
    NetSocketState *s;
4868

    
4869
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
4870
     * Because this may be "shared" socket from a "master" process, datagrams would be recv()
4871
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
4872
     */
4873

    
4874
    if (is_connected) {
4875
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
4876
            /* must be bound */
4877
            if (saddr.sin_addr.s_addr==0) {
4878
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
4879
                        fd);
4880
                return NULL;
4881
            }
4882
            /* clone dgram socket */
4883
            newfd = net_socket_mcast_create(&saddr);
4884
            if (newfd < 0) {
4885
                /* error already reported by net_socket_mcast_create() */
4886
                close(fd);
4887
                return NULL;
4888
            }
4889
            /* clone newfd to fd, close newfd */
4890
            dup2(newfd, fd);
4891
            close(newfd);
4892

    
4893
        } else {
4894
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
4895
                    fd, strerror(errno));
4896
            return NULL;
4897
        }
4898
    }
4899

    
4900
    s = qemu_mallocz(sizeof(NetSocketState));
4901
    if (!s)
4902
        return NULL;
4903
    s->fd = fd;
4904

    
4905
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
4906
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
4907

    
4908
    /* mcast: save bound address as dst */
4909
    if (is_connected) s->dgram_dst=saddr;
4910

    
4911
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4912
            "socket: fd=%d (%s mcast=%s:%d)",
4913
            fd, is_connected? "cloned" : "",
4914
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4915
    return s;
4916
}
4917

    
4918
static void net_socket_connect(void *opaque)
4919
{
4920
    NetSocketState *s = opaque;
4921
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
4922
}
4923

    
4924
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd,
4925
                                          int is_connected)
4926
{
4927
    NetSocketState *s;
4928
    s = qemu_mallocz(sizeof(NetSocketState));
4929
    if (!s)
4930
        return NULL;
4931
    s->fd = fd;
4932
    s->vc = qemu_new_vlan_client(vlan,
4933
                                 net_socket_receive, NULL, s);
4934
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4935
             "socket: fd=%d", fd);
4936
    if (is_connected) {
4937
        net_socket_connect(s);
4938
    } else {
4939
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
4940
    }
4941
    return s;
4942
}
4943

    
4944
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd,
4945
                                          int is_connected)
4946
{
4947
    int so_type=-1, optlen=sizeof(so_type);
4948

    
4949
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type,
4950
        (socklen_t *)&optlen)< 0) {
4951
        fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
4952
        return NULL;
4953
    }
4954
    switch(so_type) {
4955
    case SOCK_DGRAM:
4956
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
4957
    case SOCK_STREAM:
4958
        return net_socket_fd_init_stream(vlan, fd, is_connected);
4959
    default:
4960
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
4961
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
4962
        return net_socket_fd_init_stream(vlan, fd, is_connected);
4963
    }
4964
    return NULL;
4965
}
4966

    
4967
static void net_socket_accept(void *opaque)
4968
{
4969
    NetSocketListenState *s = opaque;
4970
    NetSocketState *s1;
4971
    struct sockaddr_in saddr;
4972
    socklen_t len;
4973
    int fd;
4974

    
4975
    for(;;) {
4976
        len = sizeof(saddr);
4977
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
4978
        if (fd < 0 && errno != EINTR) {
4979
            return;
4980
        } else if (fd >= 0) {
4981
            break;
4982
        }
4983
    }
4984
    s1 = net_socket_fd_init(s->vlan, fd, 1);
4985
    if (!s1) {
4986
        closesocket(fd);
4987
    } else {
4988
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
4989
                 "socket: connection from %s:%d",
4990
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4991
    }
4992
}
4993

    
4994
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
4995
{
4996
    NetSocketListenState *s;
4997
    int fd, val, ret;
4998
    struct sockaddr_in saddr;
4999

    
5000
    if (parse_host_port(&saddr, host_str) < 0)
5001
        return -1;
5002

    
5003
    s = qemu_mallocz(sizeof(NetSocketListenState));
5004
    if (!s)
5005
        return -1;
5006

    
5007
    fd = socket(PF_INET, SOCK_STREAM, 0);
5008
    if (fd < 0) {
5009
        perror("socket");
5010
        return -1;
5011
    }
5012
    socket_set_nonblock(fd);
5013

    
5014
    /* allow fast reuse */
5015
    val = 1;
5016
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
5017

    
5018
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
5019
    if (ret < 0) {
5020
        perror("bind");
5021
        return -1;
5022
    }
5023
    ret = listen(fd, 0);
5024
    if (ret < 0) {
5025
        perror("listen");
5026
        return -1;
5027
    }
5028
    s->vlan = vlan;
5029
    s->fd = fd;
5030
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
5031
    return 0;
5032
}
5033

    
5034
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
5035
{
5036
    NetSocketState *s;
5037
    int fd, connected, ret, err;
5038
    struct sockaddr_in saddr;
5039

    
5040
    if (parse_host_port(&saddr, host_str) < 0)
5041
        return -1;
5042

    
5043
    fd = socket(PF_INET, SOCK_STREAM, 0);
5044
    if (fd < 0) {
5045
        perror("socket");
5046
        return -1;
5047
    }
5048
    socket_set_nonblock(fd);
5049

    
5050
    connected = 0;
5051
    for(;;) {
5052
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
5053
        if (ret < 0) {
5054
            err = socket_error();
5055
            if (err == EINTR || err == EWOULDBLOCK) {
5056
            } else if (err == EINPROGRESS) {
5057
                break;
5058
#ifdef _WIN32
5059
            } else if (err == WSAEALREADY) {
5060
                break;
5061
#endif
5062
            } else {
5063
                perror("connect");
5064
                closesocket(fd);
5065
                return -1;
5066
            }
5067
        } else {
5068
            connected = 1;
5069
            break;
5070
        }
5071
    }
5072
    s = net_socket_fd_init(vlan, fd, connected);
5073
    if (!s)
5074
        return -1;
5075
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5076
             "socket: connect to %s:%d",
5077
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5078
    return 0;
5079
}
5080

    
5081
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
5082
{
5083
    NetSocketState *s;
5084
    int fd;
5085
    struct sockaddr_in saddr;
5086

    
5087
    if (parse_host_port(&saddr, host_str) < 0)
5088
        return -1;
5089

    
5090

    
5091
    fd = net_socket_mcast_create(&saddr);
5092
    if (fd < 0)
5093
        return -1;
5094

    
5095
    s = net_socket_fd_init(vlan, fd, 0);
5096
    if (!s)
5097
        return -1;
5098

    
5099
    s->dgram_dst = saddr;
5100

    
5101
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
5102
             "socket: mcast=%s:%d",
5103
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
5104
    return 0;
5105

    
5106
}
5107

    
5108
static const char *get_opt_name(char *buf, int buf_size, const char *p)
5109
{
5110
    char *q;
5111

    
5112
    q = buf;
5113
    while (*p != '\0' && *p != '=') {
5114
        if (q && (q - buf) < buf_size - 1)
5115
            *q++ = *p;
5116
        p++;
5117
    }
5118
    if (q)
5119
        *q = '\0';
5120

    
5121
    return p;
5122
}
5123

    
5124
static const char *get_opt_value(char *buf, int buf_size, const char *p)
5125
{
5126
    char *q;
5127

    
5128
    q = buf;
5129
    while (*p != '\0') {
5130
        if (*p == ',') {
5131
            if (*(p + 1) != ',')
5132
                break;
5133
            p++;
5134
        }
5135
        if (q && (q - buf) < buf_size - 1)
5136
            *q++ = *p;
5137
        p++;
5138
    }
5139
    if (q)
5140
        *q = '\0';
5141

    
5142
    return p;
5143
}
5144

    
5145
static int get_param_value(char *buf, int buf_size,
5146
                           const char *tag, const char *str)
5147
{
5148
    const char *p;
5149
    char option[128];
5150

    
5151
    p = str;
5152
    for(;;) {
5153
        p = get_opt_name(option, sizeof(option), p);
5154
        if (*p != '=')
5155
            break;
5156
        p++;
5157
        if (!strcmp(tag, option)) {
5158
            (void)get_opt_value(buf, buf_size, p);
5159
            return strlen(buf);
5160
        } else {
5161
            p = get_opt_value(NULL, 0, p);
5162
        }
5163
        if (*p != ',')
5164
            break;
5165
        p++;
5166
    }
5167
    return 0;
5168
}
5169

    
5170
static int check_params(char *buf, int buf_size,
5171
                        const char * const *params, const char *str)
5172
{
5173
    const char *p;
5174
    int i;
5175

    
5176
    p = str;
5177
    for(;;) {
5178
        p = get_opt_name(buf, buf_size, p);
5179
        if (*p != '=')
5180
            return -1;
5181
        p++;
5182
        for(i = 0; params[i] != NULL; i++)
5183
            if (!strcmp(params[i], buf))
5184
                break;
5185
        if (params[i] == NULL)
5186
            return -1;
5187
        p = get_opt_value(NULL, 0, p);
5188
        if (*p != ',')
5189
            break;
5190
        p++;
5191
    }
5192
    return 0;
5193
}
5194

    
5195
static int net_client_init(const char *device, const char *p)
5196
{
5197
    char buf[1024];
5198
    int vlan_id, ret;
5199
    VLANState *vlan;
5200

    
5201
    vlan_id = 0;
5202
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
5203
        vlan_id = strtol(buf, NULL, 0);
5204
    }
5205
    vlan = qemu_find_vlan(vlan_id);
5206
    if (!vlan) {
5207
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
5208
        return -1;
5209
    }
5210
    if (!strcmp(device, "nic")) {
5211
        NICInfo *nd;
5212
        uint8_t *macaddr;
5213

    
5214
        if (nb_nics >= MAX_NICS) {
5215
            fprintf(stderr, "Too Many NICs\n");
5216
            return -1;
5217
        }
5218
        nd = &nd_table[nb_nics];
5219
        macaddr = nd->macaddr;
5220
        macaddr[0] = 0x52;
5221
        macaddr[1] = 0x54;
5222
        macaddr[2] = 0x00;
5223
        macaddr[3] = 0x12;
5224
        macaddr[4] = 0x34;
5225
        macaddr[5] = 0x56 + nb_nics;
5226

    
5227
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
5228
            if (parse_macaddr(macaddr, buf) < 0) {
5229
                fprintf(stderr, "invalid syntax for ethernet address\n");
5230
                return -1;
5231
            }
5232
        }
5233
        if (get_param_value(buf, sizeof(buf), "model", p)) {
5234
            nd->model = strdup(buf);
5235
        }
5236
        nd->vlan = vlan;
5237
        nb_nics++;
5238
        vlan->nb_guest_devs++;
5239
        ret = 0;
5240
    } else
5241
    if (!strcmp(device, "none")) {
5242
        /* does nothing. It is needed to signal that no network cards
5243
           are wanted */
5244
        ret = 0;
5245
    } else
5246
#ifdef CONFIG_SLIRP
5247
    if (!strcmp(device, "user")) {
5248
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
5249
            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
5250
        }
5251
        vlan->nb_host_devs++;
5252
        ret = net_slirp_init(vlan);
5253
    } else
5254
#endif
5255
#ifdef _WIN32
5256
    if (!strcmp(device, "tap")) {
5257
        char ifname[64];
5258
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5259
            fprintf(stderr, "tap: no interface name\n");
5260
            return -1;
5261
        }
5262
        vlan->nb_host_devs++;
5263
        ret = tap_win32_init(vlan, ifname);
5264
    } else
5265
#else
5266
    if (!strcmp(device, "tap")) {
5267
        char ifname[64];
5268
        char setup_script[1024], down_script[1024];
5269
        int fd;
5270
        vlan->nb_host_devs++;
5271
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5272
            fd = strtol(buf, NULL, 0);
5273
            fcntl(fd, F_SETFL, O_NONBLOCK);
5274
            ret = -1;
5275
            if (net_tap_fd_init(vlan, fd))
5276
                ret = 0;
5277
        } else {
5278
            if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
5279
                ifname[0] = '\0';
5280
            }
5281
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
5282
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
5283
            }
5284
            if (get_param_value(down_script, sizeof(down_script), "downscript", p) == 0) {
5285
                pstrcpy(down_script, sizeof(down_script), DEFAULT_NETWORK_DOWN_SCRIPT);
5286
            }
5287
            ret = net_tap_init(vlan, ifname, setup_script, down_script);
5288
        }
5289
    } else
5290
#endif
5291
    if (!strcmp(device, "socket")) {
5292
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
5293
            int fd;
5294
            fd = strtol(buf, NULL, 0);
5295
            ret = -1;
5296
            if (net_socket_fd_init(vlan, fd, 1))
5297
                ret = 0;
5298
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
5299
            ret = net_socket_listen_init(vlan, buf);
5300
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
5301
            ret = net_socket_connect_init(vlan, buf);
5302
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
5303
            ret = net_socket_mcast_init(vlan, buf);
5304
        } else {
5305
            fprintf(stderr, "Unknown socket options: %s\n", p);
5306
            return -1;
5307
        }
5308
        vlan->nb_host_devs++;
5309
    } else
5310
#ifdef CONFIG_VDE
5311
    if (!strcmp(device, "vde")) {
5312
        char vde_sock[1024], vde_group[512];
5313
        int vde_port, vde_mode;
5314
        vlan->nb_host_devs++;
5315
        if (get_param_value(vde_sock, sizeof(vde_sock), "sock", p) <= 0) {
5316
            vde_sock[0] = '\0';
5317
        }
5318
        if (get_param_value(buf, sizeof(buf), "port", p) > 0) {
5319
            vde_port = strtol(buf, NULL, 10);
5320
        } else {
5321
            vde_port = 0;
5322
        }
5323
        if (get_param_value(vde_group, sizeof(vde_group), "group", p) <= 0) {
5324
            vde_group[0] = '\0';
5325
        }
5326
        if (get_param_value(buf, sizeof(buf), "mode", p) > 0) {
5327
            vde_mode = strtol(buf, NULL, 8);
5328
        } else {
5329
            vde_mode = 0700;
5330
        }
5331
        ret = net_vde_init(vlan, vde_sock, vde_port, vde_group, vde_mode);
5332
    } else
5333
#endif
5334
    {
5335
        fprintf(stderr, "Unknown network device: %s\n", device);
5336
        return -1;
5337
    }
5338
    if (ret < 0) {
5339
        fprintf(stderr, "Could not initialize device '%s'\n", device);
5340
    }
5341

    
5342
    return ret;
5343
}
5344

    
5345
static int net_client_parse(const char *str)
5346
{
5347
    const char *p;
5348
    char *q;
5349
    char device[64];
5350

    
5351
    p = str;
5352
    q = device;
5353
    while (*p != '\0' && *p != ',') {
5354
        if ((q - device) < sizeof(device) - 1)
5355
            *q++ = *p;
5356
        p++;
5357
    }
5358
    *q = '\0';
5359
    if (*p == ',')
5360
        p++;
5361

    
5362
    return net_client_init(device, p);
5363
}
5364

    
5365
void do_info_network(void)
5366
{
5367
    VLANState *vlan;
5368
    VLANClientState *vc;
5369

    
5370
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
5371
        term_printf("VLAN %d devices:\n", vlan->id);
5372
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
5373
            term_printf("  %s\n", vc->info_str);
5374
    }
5375
}
5376

    
5377
#define HD_ALIAS "index=%d,media=disk"
5378
#ifdef TARGET_PPC
5379
#define CDROM_ALIAS "index=1,media=cdrom"
5380
#else
5381
#define CDROM_ALIAS "index=2,media=cdrom"
5382
#endif
5383
#define FD_ALIAS "index=%d,if=floppy"
5384
#define PFLASH_ALIAS "if=pflash"
5385
#define MTD_ALIAS "if=mtd"
5386
#define SD_ALIAS "index=0,if=sd"
5387

    
5388
static int drive_add(const char *file, const char *fmt, ...)
5389
{
5390
    va_list ap;
5391

    
5392
    if (nb_drives_opt >= MAX_DRIVES) {
5393
        fprintf(stderr, "qemu: too many drives\n");
5394
        exit(1);
5395
    }
5396

    
5397
    drives_opt[nb_drives_opt].file = file;
5398
    va_start(ap, fmt);
5399
    vsnprintf(drives_opt[nb_drives_opt].opt,
5400
              sizeof(drives_opt[0].opt), fmt, ap);
5401
    va_end(ap);
5402

    
5403
    return nb_drives_opt++;
5404
}
5405

    
5406
int drive_get_index(BlockInterfaceType type, int bus, int unit)
5407
{
5408
    int index;
5409

    
5410
    /* seek interface, bus and unit */
5411

    
5412
    for (index = 0; index < nb_drives; index++)
5413
        if (drives_table[index].type == type &&
5414
            drives_table[index].bus == bus &&
5415
            drives_table[index].unit == unit)
5416
        return index;
5417

    
5418
    return -1;
5419
}
5420

    
5421
int drive_get_max_bus(BlockInterfaceType type)
5422
{
5423
    int max_bus;
5424
    int index;
5425

    
5426
    max_bus = -1;
5427
    for (index = 0; index < nb_drives; index++) {
5428
        if(drives_table[index].type == type &&
5429
           drives_table[index].bus > max_bus)
5430
            max_bus = drives_table[index].bus;
5431
    }
5432
    return max_bus;
5433
}
5434

    
5435
static void bdrv_format_print(void *opaque, const char *name)
5436
{
5437
    fprintf(stderr, " %s", name);
5438
}
5439

    
5440
static int drive_init(struct drive_opt *arg, int snapshot,
5441
                      QEMUMachine *machine)
5442
{
5443
    char buf[128];
5444
    char file[1024];
5445
    char devname[128];
5446
    const char *mediastr = "";
5447
    BlockInterfaceType type;
5448
    enum { MEDIA_DISK, MEDIA_CDROM } media;
5449
    int bus_id, unit_id;
5450
    int cyls, heads, secs, translation;
5451
    BlockDriverState *bdrv;
5452
    BlockDriver *drv = NULL;
5453
    int max_devs;
5454
    int index;
5455
    int cache;
5456
    int bdrv_flags;
5457
    char *str = arg->opt;
5458
    static const char * const params[] = { "bus", "unit", "if", "index",
5459
                                           "cyls", "heads", "secs", "trans",
5460
                                           "media", "snapshot", "file",
5461
                                           "cache", "format", NULL };
5462

    
5463
    if (check_params(buf, sizeof(buf), params, str) < 0) {
5464
         fprintf(stderr, "qemu: unknown parameter '%s' in '%s'\n",
5465
                         buf, str);
5466
         return -1;
5467
    }
5468

    
5469
    file[0] = 0;
5470
    cyls = heads = secs = 0;
5471
    bus_id = 0;
5472
    unit_id = -1;
5473
    translation = BIOS_ATA_TRANSLATION_AUTO;
5474
    index = -1;
5475
    cache = 1;
5476

    
5477
    if (!strcmp(machine->name, "realview") ||
5478
        !strcmp(machine->name, "SS-5") ||
5479
        !strcmp(machine->name, "SS-10") ||
5480
        !strcmp(machine->name, "SS-600MP") ||
5481
        !strcmp(machine->name, "versatilepb") ||
5482
        !strcmp(machine->name, "versatileab")) {
5483
        type = IF_SCSI;
5484
        max_devs = MAX_SCSI_DEVS;
5485
        pstrcpy(devname, sizeof(devname), "scsi");
5486
    } else {
5487
        type = IF_IDE;
5488
        max_devs = MAX_IDE_DEVS;
5489
        pstrcpy(devname, sizeof(devname), "ide");
5490
    }
5491
    media = MEDIA_DISK;
5492

    
5493
    /* extract parameters */
5494

    
5495
    if (get_param_value(buf, sizeof(buf), "bus", str)) {
5496
        bus_id = strtol(buf, NULL, 0);
5497
        if (bus_id < 0) {
5498
            fprintf(stderr, "qemu: '%s' invalid bus id\n", str);
5499
            return -1;
5500
        }
5501
    }
5502

    
5503
    if (get_param_value(buf, sizeof(buf), "unit", str)) {
5504
        unit_id = strtol(buf, NULL, 0);
5505
        if (unit_id < 0) {
5506
            fprintf(stderr, "qemu: '%s' invalid unit id\n", str);
5507
            return -1;
5508
        }
5509
    }
5510

    
5511
    if (get_param_value(buf, sizeof(buf), "if", str)) {
5512
        pstrcpy(devname, sizeof(devname), buf);
5513
        if (!strcmp(buf, "ide")) {
5514
            type = IF_IDE;
5515
            max_devs = MAX_IDE_DEVS;
5516
        } else if (!strcmp(buf, "scsi")) {
5517
            type = IF_SCSI;
5518
            max_devs = MAX_SCSI_DEVS;
5519
        } else if (!strcmp(buf, "floppy")) {
5520
            type = IF_FLOPPY;
5521
            max_devs = 0;
5522
        } else if (!strcmp(buf, "pflash")) {
5523
            type = IF_PFLASH;
5524
            max_devs = 0;
5525
        } else if (!strcmp(buf, "mtd")) {
5526
            type = IF_MTD;
5527
            max_devs = 0;
5528
        } else if (!strcmp(buf, "sd")) {
5529
            type = IF_SD;
5530
            max_devs = 0;
5531
        } else {
5532
            fprintf(stderr, "qemu: '%s' unsupported bus type '%s'\n", str, buf);
5533
            return -1;
5534
        }
5535
    }
5536

    
5537
    if (get_param_value(buf, sizeof(buf), "index", str)) {
5538
        index = strtol(buf, NULL, 0);
5539
        if (index < 0) {
5540
            fprintf(stderr, "qemu: '%s' invalid index\n", str);
5541
            return -1;
5542
        }
5543
    }
5544

    
5545
    if (get_param_value(buf, sizeof(buf), "cyls", str)) {
5546
        cyls = strtol(buf, NULL, 0);
5547
    }
5548

    
5549
    if (get_param_value(buf, sizeof(buf), "heads", str)) {
5550
        heads = strtol(buf, NULL, 0);
5551
    }
5552

    
5553
    if (get_param_value(buf, sizeof(buf), "secs", str)) {
5554
        secs = strtol(buf, NULL, 0);
5555
    }
5556

    
5557
    if (cyls || heads || secs) {
5558
        if (cyls < 1 || cyls > 16383) {
5559
            fprintf(stderr, "qemu: '%s' invalid physical cyls number\n", str);
5560
            return -1;
5561
        }
5562
        if (heads < 1 || heads > 16) {
5563
            fprintf(stderr, "qemu: '%s' invalid physical heads number\n", str);
5564
            return -1;
5565
        }
5566
        if (secs < 1 || secs > 63) {
5567
            fprintf(stderr, "qemu: '%s' invalid physical secs number\n", str);
5568
            return -1;
5569
        }
5570
    }
5571

    
5572
    if (get_param_value(buf, sizeof(buf), "trans", str)) {
5573
        if (!cyls) {
5574
            fprintf(stderr,
5575
                    "qemu: '%s' trans must be used with cyls,heads and secs\n",
5576
                    str);
5577
            return -1;
5578
        }
5579
        if (!strcmp(buf, "none"))
5580
            translation = BIOS_ATA_TRANSLATION_NONE;
5581
        else if (!strcmp(buf, "lba"))
5582
            translation = BIOS_ATA_TRANSLATION_LBA;
5583
        else if (!strcmp(buf, "auto"))
5584
            translation = BIOS_ATA_TRANSLATION_AUTO;
5585
        else {
5586
            fprintf(stderr, "qemu: '%s' invalid translation type\n", str);
5587
            return -1;
5588
        }
5589
    }
5590

    
5591
    if (get_param_value(buf, sizeof(buf), "media", str)) {
5592
        if (!strcmp(buf, "disk")) {
5593
            media = MEDIA_DISK;
5594
        } else if (!strcmp(buf, "cdrom")) {
5595
            if (cyls || secs || heads) {
5596
                fprintf(stderr,
5597
                        "qemu: '%s' invalid physical CHS format\n", str);
5598
                return -1;
5599
            }
5600
            media = MEDIA_CDROM;
5601
        } else {
5602
            fprintf(stderr, "qemu: '%s' invalid media\n", str);
5603
            return -1;
5604
        }
5605
    }
5606

    
5607
    if (get_param_value(buf, sizeof(buf), "snapshot", str)) {
5608
        if (!strcmp(buf, "on"))
5609
            snapshot = 1;
5610
        else if (!strcmp(buf, "off"))
5611
            snapshot = 0;
5612
        else {
5613
            fprintf(stderr, "qemu: '%s' invalid snapshot option\n", str);
5614
            return -1;
5615
        }
5616
    }
5617

    
5618
    if (get_param_value(buf, sizeof(buf), "cache", str)) {
5619
        if (!strcmp(buf, "off"))
5620
            cache = 0;
5621
        else if (!strcmp(buf, "on"))
5622
            cache = 1;
5623
        else {
5624
           fprintf(stderr, "qemu: invalid cache option\n");
5625
           return -1;
5626
        }
5627
    }
5628

    
5629
    if (get_param_value(buf, sizeof(buf), "format", str)) {
5630
       if (strcmp(buf, "?") == 0) {
5631
            fprintf(stderr, "qemu: Supported formats:");
5632
            bdrv_iterate_format(bdrv_format_print, NULL);
5633
            fprintf(stderr, "\n");
5634
            return -1;
5635
        }
5636
        drv = bdrv_find_format(buf);
5637
        if (!drv) {
5638
            fprintf(stderr, "qemu: '%s' invalid format\n", buf);
5639
            return -1;
5640
        }
5641
    }
5642

    
5643
    if (arg->file == NULL)
5644
        get_param_value(file, sizeof(file), "file", str);
5645
    else
5646
        pstrcpy(file, sizeof(file), arg->file);
5647

    
5648
    /* compute bus and unit according index */
5649

    
5650
    if (index != -1) {
5651
        if (bus_id != 0 || unit_id != -1) {
5652
            fprintf(stderr,
5653
                    "qemu: '%s' index cannot be used with bus and unit\n", str);
5654
            return -1;
5655
        }
5656
        if (max_devs == 0)
5657
        {
5658
            unit_id = index;
5659
            bus_id = 0;
5660
        } else {
5661
            unit_id = index % max_devs;
5662
            bus_id = index / max_devs;
5663
        }
5664
    }
5665

    
5666
    /* if user doesn't specify a unit_id,
5667
     * try to find the first free
5668
     */
5669

    
5670
    if (unit_id == -1) {
5671
       unit_id = 0;
5672
       while (drive_get_index(type, bus_id, unit_id) != -1) {
5673
           unit_id++;
5674
           if (max_devs && unit_id >= max_devs) {
5675
               unit_id -= max_devs;
5676
               bus_id++;
5677
           }
5678
       }
5679
    }
5680

    
5681
    /* check unit id */
5682

    
5683
    if (max_devs && unit_id >= max_devs) {
5684
        fprintf(stderr, "qemu: '%s' unit %d too big (max is %d)\n",
5685
                        str, unit_id, max_devs - 1);
5686
        return -1;
5687
    }
5688

    
5689
    /*
5690
     * ignore multiple definitions
5691
     */
5692

    
5693
    if (drive_get_index(type, bus_id, unit_id) != -1)
5694
        return 0;
5695

    
5696
    /* init */
5697

    
5698
    if (type == IF_IDE || type == IF_SCSI)
5699
        mediastr = (media == MEDIA_CDROM) ? "-cd" : "-hd";
5700
    if (max_devs)
5701
        snprintf(buf, sizeof(buf), "%s%i%s%i",
5702
                 devname, bus_id, mediastr, unit_id);
5703
    else
5704
        snprintf(buf, sizeof(buf), "%s%s%i",
5705
                 devname, mediastr, unit_id);
5706
    bdrv = bdrv_new(buf);
5707
    drives_table[nb_drives].bdrv = bdrv;
5708
    drives_table[nb_drives].type = type;
5709
    drives_table[nb_drives].bus = bus_id;
5710
    drives_table[nb_drives].unit = unit_id;
5711
    nb_drives++;
5712

    
5713
    switch(type) {
5714
    case IF_IDE:
5715
    case IF_SCSI:
5716
        switch(media) {
5717
        case MEDIA_DISK:
5718
            if (cyls != 0) {
5719
                bdrv_set_geometry_hint(bdrv, cyls, heads, secs);
5720
                bdrv_set_translation_hint(bdrv, translation);
5721
            }
5722
            break;
5723
        case MEDIA_CDROM:
5724
            bdrv_set_type_hint(bdrv, BDRV_TYPE_CDROM);
5725
            break;
5726
        }
5727
        break;
5728
    case IF_SD:
5729
        /* FIXME: This isn't really a floppy, but it's a reasonable
5730
           approximation.  */
5731
    case IF_FLOPPY:
5732
        bdrv_set_type_hint(bdrv, BDRV_TYPE_FLOPPY);
5733
        break;
5734
    case IF_PFLASH:
5735
    case IF_MTD:
5736
        break;
5737
    }
5738
    if (!file[0])
5739
        return 0;
5740
    bdrv_flags = 0;
5741
    if (snapshot)
5742
        bdrv_flags |= BDRV_O_SNAPSHOT;
5743
    if (!cache)
5744
        bdrv_flags |= BDRV_O_DIRECT;
5745
    if (bdrv_open2(bdrv, file, bdrv_flags, drv) < 0 || qemu_key_check(bdrv, file)) {
5746
        fprintf(stderr, "qemu: could not open disk image %s\n",
5747
                        file);
5748
        return -1;
5749
    }
5750
    return 0;
5751
}
5752

    
5753
/***********************************************************/
5754
/* USB devices */
5755

    
5756
static USBPort *used_usb_ports;
5757
static USBPort *free_usb_ports;
5758

    
5759
/* ??? Maybe change this to register a hub to keep track of the topology.  */
5760
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
5761
                            usb_attachfn attach)
5762
{
5763
    port->opaque = opaque;
5764
    port->index = index;
5765
    port->attach = attach;
5766
    port->next = free_usb_ports;
5767
    free_usb_ports = port;
5768
}
5769

    
5770
int usb_device_add_dev(USBDevice *dev)
5771
{
5772
    USBPort *port;
5773

    
5774
    /* Find a USB port to add the device to.  */
5775
    port = free_usb_ports;
5776
    if (!port->next) {
5777
        USBDevice *hub;
5778

    
5779
        /* Create a new hub and chain it on.  */
5780
        free_usb_ports = NULL;
5781
        port->next = used_usb_ports;
5782
        used_usb_ports = port;
5783

    
5784
        hub = usb_hub_init(VM_USB_HUB_SIZE);
5785
        usb_attach(port, hub);
5786
        port = free_usb_ports;
5787
    }
5788

    
5789
    free_usb_ports = port->next;
5790
    port->next = used_usb_ports;
5791
    used_usb_ports = port;
5792
    usb_attach(port, dev);
5793
    return 0;
5794
}
5795

    
5796
static int usb_device_add(const char *devname)
5797
{
5798
    const char *p;
5799
    USBDevice *dev;
5800

    
5801
    if (!free_usb_ports)
5802
        return -1;
5803

    
5804
    if (strstart(devname, "host:", &p)) {
5805
        dev = usb_host_device_open(p);
5806
    } else if (!strcmp(devname, "mouse")) {
5807
        dev = usb_mouse_init();
5808
    } else if (!strcmp(devname, "tablet")) {
5809
        dev = usb_tablet_init();
5810
    } else if (!strcmp(devname, "keyboard")) {
5811
        dev = usb_keyboard_init();
5812
    } else if (strstart(devname, "disk:", &p)) {
5813
        dev = usb_msd_init(p);
5814
    } else if (!strcmp(devname, "wacom-tablet")) {
5815
        dev = usb_wacom_init();
5816
    } else if (strstart(devname, "serial:", &p)) {
5817
        dev = usb_serial_init(p);
5818
#ifdef CONFIG_BRLAPI
5819
    } else if (!strcmp(devname, "braille")) {
5820
        dev = usb_baum_init();
5821
#endif
5822
    } else if (strstart(devname, "net:", &p)) {
5823
        int nic = nb_nics;
5824

    
5825
        if (net_client_init("nic", p) < 0)
5826
            return -1;
5827
        nd_table[nic].model = "usb";
5828
        dev = usb_net_init(&nd_table[nic]);
5829
    } else {
5830
        return -1;
5831
    }
5832
    if (!dev)
5833
        return -1;
5834

    
5835
    return usb_device_add_dev(dev);
5836
}
5837

    
5838
int usb_device_del_addr(int bus_num, int addr)
5839
{
5840
    USBPort *port;
5841
    USBPort **lastp;
5842
    USBDevice *dev;
5843

    
5844
    if (!used_usb_ports)
5845
        return -1;
5846

    
5847
    if (bus_num != 0)
5848
        return -1;
5849

    
5850
    lastp = &used_usb_ports;
5851
    port = used_usb_ports;
5852
    while (port && port->dev->addr != addr) {
5853
        lastp = &port->next;
5854
        port = port->next;
5855
    }
5856

    
5857
    if (!port)
5858
        return -1;
5859

    
5860
    dev = port->dev;
5861
    *lastp = port->next;
5862
    usb_attach(port, NULL);
5863
    dev->handle_destroy(dev);
5864
    port->next = free_usb_ports;
5865
    free_usb_ports = port;
5866
    return 0;
5867
}
5868

    
5869
static int usb_device_del(const char *devname)
5870
{
5871
    int bus_num, addr;
5872
    const char *p;
5873

    
5874
    if (strstart(devname, "host:", &p))
5875
        return usb_host_device_close(p);
5876

    
5877
    if (!used_usb_ports)
5878
        return -1;
5879

    
5880
    p = strchr(devname, '.');
5881
    if (!p)
5882
        return -1;
5883
    bus_num = strtoul(devname, NULL, 0);
5884
    addr = strtoul(p + 1, NULL, 0);
5885

    
5886
    return usb_device_del_addr(bus_num, addr);
5887
}
5888

    
5889
void do_usb_add(const char *devname)
5890
{
5891
    usb_device_add(devname);
5892
}
5893

    
5894
void do_usb_del(const char *devname)
5895
{
5896
    usb_device_del(devname);
5897
}
5898

    
5899
void usb_info(void)
5900
{
5901
    USBDevice *dev;
5902
    USBPort *port;
5903
    const char *speed_str;
5904

    
5905
    if (!usb_enabled) {
5906
        term_printf("USB support not enabled\n");
5907
        return;
5908
    }
5909

    
5910
    for (port = used_usb_ports; port; port = port->next) {
5911
        dev = port->dev;
5912
        if (!dev)
5913
            continue;
5914
        switch(dev->speed) {
5915
        case USB_SPEED_LOW:
5916
            speed_str = "1.5";
5917
            break;
5918
        case USB_SPEED_FULL:
5919
            speed_str = "12";
5920
            break;
5921
        case USB_SPEED_HIGH:
5922
            speed_str = "480";
5923
            break;
5924
        default:
5925
            speed_str = "?";
5926
            break;
5927
        }
5928
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n",
5929
                    0, dev->addr, speed_str, dev->devname);
5930
    }
5931
}
5932

    
5933
/***********************************************************/
5934
/* PCMCIA/Cardbus */
5935

    
5936
static struct pcmcia_socket_entry_s {
5937
    struct pcmcia_socket_s *socket;
5938
    struct pcmcia_socket_entry_s *next;
5939
} *pcmcia_sockets = 0;
5940

    
5941
void pcmcia_socket_register(struct pcmcia_socket_s *socket)
5942
{
5943
    struct pcmcia_socket_entry_s *entry;
5944

    
5945
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
5946
    entry->socket = socket;
5947
    entry->next = pcmcia_sockets;
5948
    pcmcia_sockets = entry;
5949
}
5950

    
5951
void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
5952
{
5953
    struct pcmcia_socket_entry_s *entry, **ptr;
5954

    
5955
    ptr = &pcmcia_sockets;
5956
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
5957
        if (entry->socket == socket) {
5958
            *ptr = entry->next;
5959
            qemu_free(entry);
5960
        }
5961
}
5962

    
5963
void pcmcia_info(void)
5964
{
5965
    struct pcmcia_socket_entry_s *iter;
5966
    if (!pcmcia_sockets)
5967
        term_printf("No PCMCIA sockets\n");
5968

    
5969
    for (iter = pcmcia_sockets; iter; iter = iter->next)
5970
        term_printf("%s: %s\n", iter->socket->slot_string,
5971
                    iter->socket->attached ? iter->socket->card_string :
5972
                    "Empty");
5973
}
5974

    
5975
/***********************************************************/
5976
/* dumb display */
5977

    
5978
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
5979
{
5980
}
5981

    
5982
static void dumb_resize(DisplayState *ds, int w, int h)
5983
{
5984
}
5985

    
5986
static void dumb_refresh(DisplayState *ds)
5987
{
5988
#if defined(CONFIG_SDL)
5989
    vga_hw_update();
5990
#endif
5991
}
5992

    
5993
static void dumb_display_init(DisplayState *ds)
5994
{
5995
    ds->data = NULL;
5996
    ds->linesize = 0;
5997
    ds->depth = 0;
5998
    ds->dpy_update = dumb_update;
5999
    ds->dpy_resize = dumb_resize;
6000
    ds->dpy_refresh = dumb_refresh;
6001
    ds->gui_timer_interval = 500;
6002
    ds->idle = 1;
6003
}
6004

    
6005
/***********************************************************/
6006
/* I/O handling */
6007

    
6008
#define MAX_IO_HANDLERS 64
6009

    
6010
typedef struct IOHandlerRecord {
6011
    int fd;
6012
    IOCanRWHandler *fd_read_poll;
6013
    IOHandler *fd_read;
6014
    IOHandler *fd_write;
6015
    int deleted;
6016
    void *opaque;
6017
    /* temporary data */
6018
    struct pollfd *ufd;
6019
    struct IOHandlerRecord *next;
6020
} IOHandlerRecord;
6021

    
6022
static IOHandlerRecord *first_io_handler;
6023

    
6024
/* XXX: fd_read_poll should be suppressed, but an API change is
6025
   necessary in the character devices to suppress fd_can_read(). */
6026
int qemu_set_fd_handler2(int fd,
6027
                         IOCanRWHandler *fd_read_poll,
6028
                         IOHandler *fd_read,
6029
                         IOHandler *fd_write,
6030
                         void *opaque)
6031
{
6032
    IOHandlerRecord **pioh, *ioh;
6033

    
6034
    if (!fd_read && !fd_write) {
6035
        pioh = &first_io_handler;
6036
        for(;;) {
6037
            ioh = *pioh;
6038
            if (ioh == NULL)
6039
                break;
6040
            if (ioh->fd == fd) {
6041
                ioh->deleted = 1;
6042
                break;
6043
            }
6044
            pioh = &ioh->next;
6045
        }
6046
    } else {
6047
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6048
            if (ioh->fd == fd)
6049
                goto found;
6050
        }
6051
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
6052
        if (!ioh)
6053
            return -1;
6054
        ioh->next = first_io_handler;
6055
        first_io_handler = ioh;
6056
    found:
6057
        ioh->fd = fd;
6058
        ioh->fd_read_poll = fd_read_poll;
6059
        ioh->fd_read = fd_read;
6060
        ioh->fd_write = fd_write;
6061
        ioh->opaque = opaque;
6062
        ioh->deleted = 0;
6063
    }
6064
    return 0;
6065
}
6066

    
6067
int qemu_set_fd_handler(int fd,
6068
                        IOHandler *fd_read,
6069
                        IOHandler *fd_write,
6070
                        void *opaque)
6071
{
6072
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
6073
}
6074

    
6075
/***********************************************************/
6076
/* Polling handling */
6077

    
6078
typedef struct PollingEntry {
6079
    PollingFunc *func;
6080
    void *opaque;
6081
    struct PollingEntry *next;
6082
} PollingEntry;
6083

    
6084
static PollingEntry *first_polling_entry;
6085

    
6086
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
6087
{
6088
    PollingEntry **ppe, *pe;
6089
    pe = qemu_mallocz(sizeof(PollingEntry));
6090
    if (!pe)
6091
        return -1;
6092
    pe->func = func;
6093
    pe->opaque = opaque;
6094
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
6095
    *ppe = pe;
6096
    return 0;
6097
}
6098

    
6099
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
6100
{
6101
    PollingEntry **ppe, *pe;
6102
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
6103
        pe = *ppe;
6104
        if (pe->func == func && pe->opaque == opaque) {
6105
            *ppe = pe->next;
6106
            qemu_free(pe);
6107
            break;
6108
        }
6109
    }
6110
}
6111

    
6112
#ifdef _WIN32
6113
/***********************************************************/
6114
/* Wait objects support */
6115
typedef struct WaitObjects {
6116
    int num;
6117
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
6118
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
6119
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
6120
} WaitObjects;
6121

    
6122
static WaitObjects wait_objects = {0};
6123

    
6124
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6125
{
6126
    WaitObjects *w = &wait_objects;
6127

    
6128
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
6129
        return -1;
6130
    w->events[w->num] = handle;
6131
    w->func[w->num] = func;
6132
    w->opaque[w->num] = opaque;
6133
    w->num++;
6134
    return 0;
6135
}
6136

    
6137
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
6138
{
6139
    int i, found;
6140
    WaitObjects *w = &wait_objects;
6141

    
6142
    found = 0;
6143
    for (i = 0; i < w->num; i++) {
6144
        if (w->events[i] == handle)
6145
            found = 1;
6146
        if (found) {
6147
            w->events[i] = w->events[i + 1];
6148
            w->func[i] = w->func[i + 1];
6149
            w->opaque[i] = w->opaque[i + 1];
6150
        }
6151
    }
6152
    if (found)
6153
        w->num--;
6154
}
6155
#endif
6156

    
6157
/***********************************************************/
6158
/* savevm/loadvm support */
6159

    
6160
#define IO_BUF_SIZE 32768
6161

    
6162
struct QEMUFile {
6163
    FILE *outfile;
6164
    BlockDriverState *bs;
6165
    int is_file;
6166
    int is_writable;
6167
    int64_t base_offset;
6168
    int64_t buf_offset; /* start of buffer when writing, end of buffer
6169
                           when reading */
6170
    int buf_index;
6171
    int buf_size; /* 0 when writing */
6172
    uint8_t buf[IO_BUF_SIZE];
6173
};
6174

    
6175
QEMUFile *qemu_fopen(const char *filename, const char *mode)
6176
{
6177
    QEMUFile *f;
6178

    
6179
    f = qemu_mallocz(sizeof(QEMUFile));
6180
    if (!f)
6181
        return NULL;
6182
    if (!strcmp(mode, "wb")) {
6183
        f->is_writable = 1;
6184
    } else if (!strcmp(mode, "rb")) {
6185
        f->is_writable = 0;
6186
    } else {
6187
        goto fail;
6188
    }
6189
    f->outfile = fopen(filename, mode);
6190
    if (!f->outfile)
6191
        goto fail;
6192
    f->is_file = 1;
6193
    return f;
6194
 fail:
6195
    if (f->outfile)
6196
        fclose(f->outfile);
6197
    qemu_free(f);
6198
    return NULL;
6199
}
6200

    
6201
static QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
6202
{
6203
    QEMUFile *f;
6204

    
6205
    f = qemu_mallocz(sizeof(QEMUFile));
6206
    if (!f)
6207
        return NULL;
6208
    f->is_file = 0;
6209
    f->bs = bs;
6210
    f->is_writable = is_writable;
6211
    f->base_offset = offset;
6212
    return f;
6213
}
6214

    
6215
void qemu_fflush(QEMUFile *f)
6216
{
6217
    if (!f->is_writable)
6218
        return;
6219
    if (f->buf_index > 0) {
6220
        if (f->is_file) {
6221
            fseek(f->outfile, f->buf_offset, SEEK_SET);
6222
            fwrite(f->buf, 1, f->buf_index, f->outfile);
6223
        } else {
6224
            bdrv_pwrite(f->bs, f->base_offset + f->buf_offset,
6225
                        f->buf, f->buf_index);
6226
        }
6227
        f->buf_offset += f->buf_index;
6228
        f->buf_index = 0;
6229
    }
6230
}
6231

    
6232
static void qemu_fill_buffer(QEMUFile *f)
6233
{
6234
    int len;
6235

    
6236
    if (f->is_writable)
6237
        return;
6238
    if (f->is_file) {
6239
        fseek(f->outfile, f->buf_offset, SEEK_SET);
6240
        len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
6241
        if (len < 0)
6242
            len = 0;
6243
    } else {
6244
        len = bdrv_pread(f->bs, f->base_offset + f->buf_offset,
6245
                         f->buf, IO_BUF_SIZE);
6246
        if (len < 0)
6247
            len = 0;
6248
    }
6249
    f->buf_index = 0;
6250
    f->buf_size = len;
6251
    f->buf_offset += len;
6252
}
6253

    
6254
void qemu_fclose(QEMUFile *f)
6255
{
6256
    if (f->is_writable)
6257
        qemu_fflush(f);
6258
    if (f->is_file) {
6259
        fclose(f->outfile);
6260
    }
6261
    qemu_free(f);
6262
}
6263

    
6264
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
6265
{
6266
    int l;
6267
    while (size > 0) {
6268
        l = IO_BUF_SIZE - f->buf_index;
6269
        if (l > size)
6270
            l = size;
6271
        memcpy(f->buf + f->buf_index, buf, l);
6272
        f->buf_index += l;
6273
        buf += l;
6274
        size -= l;
6275
        if (f->buf_index >= IO_BUF_SIZE)
6276
            qemu_fflush(f);
6277
    }
6278
}
6279

    
6280
void qemu_put_byte(QEMUFile *f, int v)
6281
{
6282
    f->buf[f->buf_index++] = v;
6283
    if (f->buf_index >= IO_BUF_SIZE)
6284
        qemu_fflush(f);
6285
}
6286

    
6287
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
6288
{
6289
    int size, l;
6290

    
6291
    size = size1;
6292
    while (size > 0) {
6293
        l = f->buf_size - f->buf_index;
6294
        if (l == 0) {
6295
            qemu_fill_buffer(f);
6296
            l = f->buf_size - f->buf_index;
6297
            if (l == 0)
6298
                break;
6299
        }
6300
        if (l > size)
6301
            l = size;
6302
        memcpy(buf, f->buf + f->buf_index, l);
6303
        f->buf_index += l;
6304
        buf += l;
6305
        size -= l;
6306
    }
6307
    return size1 - size;
6308
}
6309

    
6310
int qemu_get_byte(QEMUFile *f)
6311
{
6312
    if (f->buf_index >= f->buf_size) {
6313
        qemu_fill_buffer(f);
6314
        if (f->buf_index >= f->buf_size)
6315
            return 0;
6316
    }
6317
    return f->buf[f->buf_index++];
6318
}
6319

    
6320
int64_t qemu_ftell(QEMUFile *f)
6321
{
6322
    return f->buf_offset - f->buf_size + f->buf_index;
6323
}
6324

    
6325
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
6326
{
6327
    if (whence == SEEK_SET) {
6328
        /* nothing to do */
6329
    } else if (whence == SEEK_CUR) {
6330
        pos += qemu_ftell(f);
6331
    } else {
6332
        /* SEEK_END not supported */
6333
        return -1;
6334
    }
6335
    if (f->is_writable) {
6336
        qemu_fflush(f);
6337
        f->buf_offset = pos;
6338
    } else {
6339
        f->buf_offset = pos;
6340
        f->buf_index = 0;
6341
        f->buf_size = 0;
6342
    }
6343
    return pos;
6344
}
6345

    
6346
void qemu_put_be16(QEMUFile *f, unsigned int v)
6347
{
6348
    qemu_put_byte(f, v >> 8);
6349
    qemu_put_byte(f, v);
6350
}
6351

    
6352
void qemu_put_be32(QEMUFile *f, unsigned int v)
6353
{
6354
    qemu_put_byte(f, v >> 24);
6355
    qemu_put_byte(f, v >> 16);
6356
    qemu_put_byte(f, v >> 8);
6357
    qemu_put_byte(f, v);
6358
}
6359

    
6360
void qemu_put_be64(QEMUFile *f, uint64_t v)
6361
{
6362
    qemu_put_be32(f, v >> 32);
6363
    qemu_put_be32(f, v);
6364
}
6365

    
6366
unsigned int qemu_get_be16(QEMUFile *f)
6367
{
6368
    unsigned int v;
6369
    v = qemu_get_byte(f) << 8;
6370
    v |= qemu_get_byte(f);
6371
    return v;
6372
}
6373

    
6374
unsigned int qemu_get_be32(QEMUFile *f)
6375
{
6376
    unsigned int v;
6377
    v = qemu_get_byte(f) << 24;
6378
    v |= qemu_get_byte(f) << 16;
6379
    v |= qemu_get_byte(f) << 8;
6380
    v |= qemu_get_byte(f);
6381
    return v;
6382
}
6383

    
6384
uint64_t qemu_get_be64(QEMUFile *f)
6385
{
6386
    uint64_t v;
6387
    v = (uint64_t)qemu_get_be32(f) << 32;
6388
    v |= qemu_get_be32(f);
6389
    return v;
6390
}
6391

    
6392
typedef struct SaveStateEntry {
6393
    char idstr[256];
6394
    int instance_id;
6395
    int version_id;
6396
    SaveStateHandler *save_state;
6397
    LoadStateHandler *load_state;
6398
    void *opaque;
6399
    struct SaveStateEntry *next;
6400
} SaveStateEntry;
6401

    
6402
static SaveStateEntry *first_se;
6403

    
6404
/* TODO: Individual devices generally have very little idea about the rest
6405
   of the system, so instance_id should be removed/replaced.
6406
   Meanwhile pass -1 as instance_id if you do not already have a clearly
6407
   distinguishing id for all instances of your device class. */
6408
int register_savevm(const char *idstr,
6409
                    int instance_id,
6410
                    int version_id,
6411
                    SaveStateHandler *save_state,
6412
                    LoadStateHandler *load_state,
6413
                    void *opaque)
6414
{
6415
    SaveStateEntry *se, **pse;
6416

    
6417
    se = qemu_malloc(sizeof(SaveStateEntry));
6418
    if (!se)
6419
        return -1;
6420
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
6421
    se->instance_id = (instance_id == -1) ? 0 : instance_id;
6422
    se->version_id = version_id;
6423
    se->save_state = save_state;
6424
    se->load_state = load_state;
6425
    se->opaque = opaque;
6426
    se->next = NULL;
6427

    
6428
    /* add at the end of list */
6429
    pse = &first_se;
6430
    while (*pse != NULL) {
6431
        if (instance_id == -1
6432
                && strcmp(se->idstr, (*pse)->idstr) == 0
6433
                && se->instance_id <= (*pse)->instance_id)
6434
            se->instance_id = (*pse)->instance_id + 1;
6435
        pse = &(*pse)->next;
6436
    }
6437
    *pse = se;
6438
    return 0;
6439
}
6440

    
6441
#define QEMU_VM_FILE_MAGIC   0x5145564d
6442
#define QEMU_VM_FILE_VERSION 0x00000002
6443

    
6444
static int qemu_savevm_state(QEMUFile *f)
6445
{
6446
    SaveStateEntry *se;
6447
    int len, ret;
6448
    int64_t cur_pos, len_pos, total_len_pos;
6449

    
6450
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
6451
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
6452
    total_len_pos = qemu_ftell(f);
6453
    qemu_put_be64(f, 0); /* total size */
6454

    
6455
    for(se = first_se; se != NULL; se = se->next) {
6456
        if (se->save_state == NULL)
6457
            /* this one has a loader only, for backwards compatibility */
6458
            continue;
6459

    
6460
        /* ID string */
6461
        len = strlen(se->idstr);
6462
        qemu_put_byte(f, len);
6463
        qemu_put_buffer(f, (uint8_t *)se->idstr, len);
6464

    
6465
        qemu_put_be32(f, se->instance_id);
6466
        qemu_put_be32(f, se->version_id);
6467

    
6468
        /* record size: filled later */
6469
        len_pos = qemu_ftell(f);
6470
        qemu_put_be32(f, 0);
6471
        se->save_state(f, se->opaque);
6472

    
6473
        /* fill record size */
6474
        cur_pos = qemu_ftell(f);
6475
        len = cur_pos - len_pos - 4;
6476
        qemu_fseek(f, len_pos, SEEK_SET);
6477
        qemu_put_be32(f, len);
6478
        qemu_fseek(f, cur_pos, SEEK_SET);
6479
    }
6480
    cur_pos = qemu_ftell(f);
6481
    qemu_fseek(f, total_len_pos, SEEK_SET);
6482
    qemu_put_be64(f, cur_pos - total_len_pos - 8);
6483
    qemu_fseek(f, cur_pos, SEEK_SET);
6484

    
6485
    ret = 0;
6486
    return ret;
6487
}
6488

    
6489
static SaveStateEntry *find_se(const char *idstr, int instance_id)
6490
{
6491
    SaveStateEntry *se;
6492

    
6493
    for(se = first_se; se != NULL; se = se->next) {
6494
        if (!strcmp(se->idstr, idstr) &&
6495
            instance_id == se->instance_id)
6496
            return se;
6497
    }
6498
    return NULL;
6499
}
6500

    
6501
static int qemu_loadvm_state(QEMUFile *f)
6502
{
6503
    SaveStateEntry *se;
6504
    int len, ret, instance_id, record_len, version_id;
6505
    int64_t total_len, end_pos, cur_pos;
6506
    unsigned int v;
6507
    char idstr[256];
6508

    
6509
    v = qemu_get_be32(f);
6510
    if (v != QEMU_VM_FILE_MAGIC)
6511
        goto fail;
6512
    v = qemu_get_be32(f);
6513
    if (v != QEMU_VM_FILE_VERSION) {
6514
    fail:
6515
        ret = -1;
6516
        goto the_end;
6517
    }
6518
    total_len = qemu_get_be64(f);
6519
    end_pos = total_len + qemu_ftell(f);
6520
    for(;;) {
6521
        if (qemu_ftell(f) >= end_pos)
6522
            break;
6523
        len = qemu_get_byte(f);
6524
        qemu_get_buffer(f, (uint8_t *)idstr, len);
6525
        idstr[len] = '\0';
6526
        instance_id = qemu_get_be32(f);
6527
        version_id = qemu_get_be32(f);
6528
        record_len = qemu_get_be32(f);
6529
#if 0
6530
        printf("idstr=%s instance=0x%x version=%d len=%d\n",
6531
               idstr, instance_id, version_id, record_len);
6532
#endif
6533
        cur_pos = qemu_ftell(f);
6534
        se = find_se(idstr, instance_id);
6535
        if (!se) {
6536
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n",
6537
                    instance_id, idstr);
6538
        } else {
6539
            ret = se->load_state(f, se->opaque, version_id);
6540
            if (ret < 0) {
6541
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n",
6542
                        instance_id, idstr);
6543
            }
6544
        }
6545
        /* always seek to exact end of record */
6546
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
6547
    }
6548
    ret = 0;
6549
 the_end:
6550
    return ret;
6551
}
6552

    
6553
/* device can contain snapshots */
6554
static int bdrv_can_snapshot(BlockDriverState *bs)
6555
{
6556
    return (bs &&
6557
            !bdrv_is_removable(bs) &&
6558
            !bdrv_is_read_only(bs));
6559
}
6560

    
6561
/* device must be snapshots in order to have a reliable snapshot */
6562
static int bdrv_has_snapshot(BlockDriverState *bs)
6563
{
6564
    return (bs &&
6565
            !bdrv_is_removable(bs) &&
6566
            !bdrv_is_read_only(bs));
6567
}
6568

    
6569
static BlockDriverState *get_bs_snapshots(void)
6570
{
6571
    BlockDriverState *bs;
6572
    int i;
6573

    
6574
    if (bs_snapshots)
6575
        return bs_snapshots;
6576
    for(i = 0; i <= nb_drives; i++) {
6577
        bs = drives_table[i].bdrv;
6578
        if (bdrv_can_snapshot(bs))
6579
            goto ok;
6580
    }
6581
    return NULL;
6582
 ok:
6583
    bs_snapshots = bs;
6584
    return bs;
6585
}
6586

    
6587
static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
6588
                              const char *name)
6589
{
6590
    QEMUSnapshotInfo *sn_tab, *sn;
6591
    int nb_sns, i, ret;
6592

    
6593
    ret = -ENOENT;
6594
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6595
    if (nb_sns < 0)
6596
        return ret;
6597
    for(i = 0; i < nb_sns; i++) {
6598
        sn = &sn_tab[i];
6599
        if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
6600
            *sn_info = *sn;
6601
            ret = 0;
6602
            break;
6603
        }
6604
    }
6605
    qemu_free(sn_tab);
6606
    return ret;
6607
}
6608

    
6609
void do_savevm(const char *name)
6610
{
6611
    BlockDriverState *bs, *bs1;
6612
    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
6613
    int must_delete, ret, i;
6614
    BlockDriverInfo bdi1, *bdi = &bdi1;
6615
    QEMUFile *f;
6616
    int saved_vm_running;
6617
#ifdef _WIN32
6618
    struct _timeb tb;
6619
#else
6620
    struct timeval tv;
6621
#endif
6622

    
6623
    bs = get_bs_snapshots();
6624
    if (!bs) {
6625
        term_printf("No block device can accept snapshots\n");
6626
        return;
6627
    }
6628

    
6629
    /* ??? Should this occur after vm_stop?  */
6630
    qemu_aio_flush();
6631

    
6632
    saved_vm_running = vm_running;
6633
    vm_stop(0);
6634

    
6635
    must_delete = 0;
6636
    if (name) {
6637
        ret = bdrv_snapshot_find(bs, old_sn, name);
6638
        if (ret >= 0) {
6639
            must_delete = 1;
6640
        }
6641
    }
6642
    memset(sn, 0, sizeof(*sn));
6643
    if (must_delete) {
6644
        pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
6645
        pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
6646
    } else {
6647
        if (name)
6648
            pstrcpy(sn->name, sizeof(sn->name), name);
6649
    }
6650

    
6651
    /* fill auxiliary fields */
6652
#ifdef _WIN32
6653
    _ftime(&tb);
6654
    sn->date_sec = tb.time;
6655
    sn->date_nsec = tb.millitm * 1000000;
6656
#else
6657
    gettimeofday(&tv, NULL);
6658
    sn->date_sec = tv.tv_sec;
6659
    sn->date_nsec = tv.tv_usec * 1000;
6660
#endif
6661
    sn->vm_clock_nsec = qemu_get_clock(vm_clock);
6662

    
6663
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6664
        term_printf("Device %s does not support VM state snapshots\n",
6665
                    bdrv_get_device_name(bs));
6666
        goto the_end;
6667
    }
6668

    
6669
    /* save the VM state */
6670
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
6671
    if (!f) {
6672
        term_printf("Could not open VM state file\n");
6673
        goto the_end;
6674
    }
6675
    ret = qemu_savevm_state(f);
6676
    sn->vm_state_size = qemu_ftell(f);
6677
    qemu_fclose(f);
6678
    if (ret < 0) {
6679
        term_printf("Error %d while writing VM\n", ret);
6680
        goto the_end;
6681
    }
6682

    
6683
    /* create the snapshots */
6684

    
6685
    for(i = 0; i < nb_drives; i++) {
6686
        bs1 = drives_table[i].bdrv;
6687
        if (bdrv_has_snapshot(bs1)) {
6688
            if (must_delete) {
6689
                ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
6690
                if (ret < 0) {
6691
                    term_printf("Error while deleting snapshot on '%s'\n",
6692
                                bdrv_get_device_name(bs1));
6693
                }
6694
            }
6695
            ret = bdrv_snapshot_create(bs1, sn);
6696
            if (ret < 0) {
6697
                term_printf("Error while creating snapshot on '%s'\n",
6698
                            bdrv_get_device_name(bs1));
6699
            }
6700
        }
6701
    }
6702

    
6703
 the_end:
6704
    if (saved_vm_running)
6705
        vm_start();
6706
}
6707

    
6708
void do_loadvm(const char *name)
6709
{
6710
    BlockDriverState *bs, *bs1;
6711
    BlockDriverInfo bdi1, *bdi = &bdi1;
6712
    QEMUFile *f;
6713
    int i, ret;
6714
    int saved_vm_running;
6715

    
6716
    bs = get_bs_snapshots();
6717
    if (!bs) {
6718
        term_printf("No block device supports snapshots\n");
6719
        return;
6720
    }
6721

    
6722
    /* Flush all IO requests so they don't interfere with the new state.  */
6723
    qemu_aio_flush();
6724

    
6725
    saved_vm_running = vm_running;
6726
    vm_stop(0);
6727

    
6728
    for(i = 0; i <= nb_drives; i++) {
6729
        bs1 = drives_table[i].bdrv;
6730
        if (bdrv_has_snapshot(bs1)) {
6731
            ret = bdrv_snapshot_goto(bs1, name);
6732
            if (ret < 0) {
6733
                if (bs != bs1)
6734
                    term_printf("Warning: ");
6735
                switch(ret) {
6736
                case -ENOTSUP:
6737
                    term_printf("Snapshots not supported on device '%s'\n",
6738
                                bdrv_get_device_name(bs1));
6739
                    break;
6740
                case -ENOENT:
6741
                    term_printf("Could not find snapshot '%s' on device '%s'\n",
6742
                                name, bdrv_get_device_name(bs1));
6743
                    break;
6744
                default:
6745
                    term_printf("Error %d while activating snapshot on '%s'\n",
6746
                                ret, bdrv_get_device_name(bs1));
6747
                    break;
6748
                }
6749
                /* fatal on snapshot block device */
6750
                if (bs == bs1)
6751
                    goto the_end;
6752
            }
6753
        }
6754
    }
6755

    
6756
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
6757
        term_printf("Device %s does not support VM state snapshots\n",
6758
                    bdrv_get_device_name(bs));
6759
        return;
6760
    }
6761

    
6762
    /* restore the VM state */
6763
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
6764
    if (!f) {
6765
        term_printf("Could not open VM state file\n");
6766
        goto the_end;
6767
    }
6768
    ret = qemu_loadvm_state(f);
6769
    qemu_fclose(f);
6770
    if (ret < 0) {
6771
        term_printf("Error %d while loading VM state\n", ret);
6772
    }
6773
 the_end:
6774
    if (saved_vm_running)
6775
        vm_start();
6776
}
6777

    
6778
void do_delvm(const char *name)
6779
{
6780
    BlockDriverState *bs, *bs1;
6781
    int i, ret;
6782

    
6783
    bs = get_bs_snapshots();
6784
    if (!bs) {
6785
        term_printf("No block device supports snapshots\n");
6786
        return;
6787
    }
6788

    
6789
    for(i = 0; i <= nb_drives; i++) {
6790
        bs1 = drives_table[i].bdrv;
6791
        if (bdrv_has_snapshot(bs1)) {
6792
            ret = bdrv_snapshot_delete(bs1, name);
6793
            if (ret < 0) {
6794
                if (ret == -ENOTSUP)
6795
                    term_printf("Snapshots not supported on device '%s'\n",
6796
                                bdrv_get_device_name(bs1));
6797
                else
6798
                    term_printf("Error %d while deleting snapshot on '%s'\n",
6799
                                ret, bdrv_get_device_name(bs1));
6800
            }
6801
        }
6802
    }
6803
}
6804

    
6805
void do_info_snapshots(void)
6806
{
6807
    BlockDriverState *bs, *bs1;
6808
    QEMUSnapshotInfo *sn_tab, *sn;
6809
    int nb_sns, i;
6810
    char buf[256];
6811

    
6812
    bs = get_bs_snapshots();
6813
    if (!bs) {
6814
        term_printf("No available block device supports snapshots\n");
6815
        return;
6816
    }
6817
    term_printf("Snapshot devices:");
6818
    for(i = 0; i <= nb_drives; i++) {
6819
        bs1 = drives_table[i].bdrv;
6820
        if (bdrv_has_snapshot(bs1)) {
6821
            if (bs == bs1)
6822
                term_printf(" %s", bdrv_get_device_name(bs1));
6823
        }
6824
    }
6825
    term_printf("\n");
6826

    
6827
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
6828
    if (nb_sns < 0) {
6829
        term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
6830
        return;
6831
    }
6832
    term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
6833
    term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
6834
    for(i = 0; i < nb_sns; i++) {
6835
        sn = &sn_tab[i];
6836
        term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
6837
    }
6838
    qemu_free(sn_tab);
6839
}
6840

    
6841
/***********************************************************/
6842
/* ram save/restore */
6843

    
6844
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
6845
{
6846
    int v;
6847

    
6848
    v = qemu_get_byte(f);
6849
    switch(v) {
6850
    case 0:
6851
        if (qemu_get_buffer(f, buf, len) != len)
6852
            return -EIO;
6853
        break;
6854
    case 1:
6855
        v = qemu_get_byte(f);
6856
        memset(buf, v, len);
6857
        break;
6858
    default:
6859
        return -EINVAL;
6860
    }
6861
    return 0;
6862
}
6863

    
6864
static int ram_load_v1(QEMUFile *f, void *opaque)
6865
{
6866
    int ret;
6867
    ram_addr_t i;
6868

    
6869
    if (qemu_get_be32(f) != phys_ram_size)
6870
        return -EINVAL;
6871
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
6872
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
6873
        if (ret)
6874
            return ret;
6875
    }
6876
    return 0;
6877
}
6878

    
6879
#define BDRV_HASH_BLOCK_SIZE 1024
6880
#define IOBUF_SIZE 4096
6881
#define RAM_CBLOCK_MAGIC 0xfabe
6882

    
6883
typedef struct RamCompressState {
6884
    z_stream zstream;
6885
    QEMUFile *f;
6886
    uint8_t buf[IOBUF_SIZE];
6887
} RamCompressState;
6888

    
6889
static int ram_compress_open(RamCompressState *s, QEMUFile *f)
6890
{
6891
    int ret;
6892
    memset(s, 0, sizeof(*s));
6893
    s->f = f;
6894
    ret = deflateInit2(&s->zstream, 1,
6895
                       Z_DEFLATED, 15,
6896
                       9, Z_DEFAULT_STRATEGY);
6897
    if (ret != Z_OK)
6898
        return -1;
6899
    s->zstream.avail_out = IOBUF_SIZE;
6900
    s->zstream.next_out = s->buf;
6901
    return 0;
6902
}
6903

    
6904
static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
6905
{
6906
    qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
6907
    qemu_put_be16(s->f, len);
6908
    qemu_put_buffer(s->f, buf, len);
6909
}
6910

    
6911
static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
6912
{
6913
    int ret;
6914

    
6915
    s->zstream.avail_in = len;
6916
    s->zstream.next_in = (uint8_t *)buf;
6917
    while (s->zstream.avail_in > 0) {
6918
        ret = deflate(&s->zstream, Z_NO_FLUSH);
6919
        if (ret != Z_OK)
6920
            return -1;
6921
        if (s->zstream.avail_out == 0) {
6922
            ram_put_cblock(s, s->buf, IOBUF_SIZE);
6923
            s->zstream.avail_out = IOBUF_SIZE;
6924
            s->zstream.next_out = s->buf;
6925
        }
6926
    }
6927
    return 0;
6928
}
6929

    
6930
static void ram_compress_close(RamCompressState *s)
6931
{
6932
    int len, ret;
6933

    
6934
    /* compress last bytes */
6935
    for(;;) {
6936
        ret = deflate(&s->zstream, Z_FINISH);
6937
        if (ret == Z_OK || ret == Z_STREAM_END) {
6938
            len = IOBUF_SIZE - s->zstream.avail_out;
6939
            if (len > 0) {
6940
                ram_put_cblock(s, s->buf, len);
6941
            }
6942
            s->zstream.avail_out = IOBUF_SIZE;
6943
            s->zstream.next_out = s->buf;
6944
            if (ret == Z_STREAM_END)
6945
                break;
6946
        } else {
6947
            goto fail;
6948
        }
6949
    }
6950
fail:
6951
    deflateEnd(&s->zstream);
6952
}
6953

    
6954
typedef struct RamDecompressState {
6955
    z_stream zstream;
6956
    QEMUFile *f;
6957
    uint8_t buf[IOBUF_SIZE];
6958
} RamDecompressState;
6959

    
6960
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
6961
{
6962
    int ret;
6963
    memset(s, 0, sizeof(*s));
6964
    s->f = f;
6965
    ret = inflateInit(&s->zstream);
6966
    if (ret != Z_OK)
6967
        return -1;
6968
    return 0;
6969
}
6970

    
6971
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
6972
{
6973
    int ret, clen;
6974

    
6975
    s->zstream.avail_out = len;
6976
    s->zstream.next_out = buf;
6977
    while (s->zstream.avail_out > 0) {
6978
        if (s->zstream.avail_in == 0) {
6979
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
6980
                return -1;
6981
            clen = qemu_get_be16(s->f);
6982
            if (clen > IOBUF_SIZE)
6983
                return -1;
6984
            qemu_get_buffer(s->f, s->buf, clen);
6985
            s->zstream.avail_in = clen;
6986
            s->zstream.next_in = s->buf;
6987
        }
6988
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
6989
        if (ret != Z_OK && ret != Z_STREAM_END) {
6990
            return -1;
6991
        }
6992
    }
6993
    return 0;
6994
}
6995

    
6996
static void ram_decompress_close(RamDecompressState *s)
6997
{
6998
    inflateEnd(&s->zstream);
6999
}
7000

    
7001
static void ram_save(QEMUFile *f, void *opaque)
7002
{
7003
    ram_addr_t i;
7004
    RamCompressState s1, *s = &s1;
7005
    uint8_t buf[10];
7006

    
7007
    qemu_put_be32(f, phys_ram_size);
7008
    if (ram_compress_open(s, f) < 0)
7009
        return;
7010
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7011
#if 0
7012
        if (tight_savevm_enabled) {
7013
            int64_t sector_num;
7014
            int j;
7015

7016
            /* find if the memory block is available on a virtual
7017
               block device */
7018
            sector_num = -1;
7019
            for(j = 0; j < nb_drives; j++) {
7020
                sector_num = bdrv_hash_find(drives_table[j].bdrv,
7021
                                            phys_ram_base + i,
7022
                                            BDRV_HASH_BLOCK_SIZE);
7023
                if (sector_num >= 0)
7024
                    break;
7025
            }
7026
            if (j == nb_drives)
7027
                goto normal_compress;
7028
            buf[0] = 1;
7029
            buf[1] = j;
7030
            cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
7031
            ram_compress_buf(s, buf, 10);
7032
        } else
7033
#endif
7034
        {
7035
            //        normal_compress:
7036
            buf[0] = 0;
7037
            ram_compress_buf(s, buf, 1);
7038
            ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
7039
        }
7040
    }
7041
    ram_compress_close(s);
7042
}
7043

    
7044
static int ram_load(QEMUFile *f, void *opaque, int version_id)
7045
{
7046
    RamDecompressState s1, *s = &s1;
7047
    uint8_t buf[10];
7048
    ram_addr_t i;
7049

    
7050
    if (version_id == 1)
7051
        return ram_load_v1(f, opaque);
7052
    if (version_id != 2)
7053
        return -EINVAL;
7054
    if (qemu_get_be32(f) != phys_ram_size)
7055
        return -EINVAL;
7056
    if (ram_decompress_open(s, f) < 0)
7057
        return -EINVAL;
7058
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
7059
        if (ram_decompress_buf(s, buf, 1) < 0) {
7060
            fprintf(stderr, "Error while reading ram block header\n");
7061
            goto error;
7062
        }
7063
        if (buf[0] == 0) {
7064
            if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
7065
                fprintf(stderr, "Error while reading ram block address=0x%08" PRIx64, (uint64_t)i);
7066
                goto error;
7067
            }
7068
        } else
7069
#if 0
7070
        if (buf[0] == 1) {
7071
            int bs_index;
7072
            int64_t sector_num;
7073

7074
            ram_decompress_buf(s, buf + 1, 9);
7075
            bs_index = buf[1];
7076
            sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
7077
            if (bs_index >= nb_drives) {
7078
                fprintf(stderr, "Invalid block device index %d\n", bs_index);
7079
                goto error;
7080
            }
7081
            if (bdrv_read(drives_table[bs_index].bdrv, sector_num,
7082
                          phys_ram_base + i,
7083
                          BDRV_HASH_BLOCK_SIZE / 512) < 0) {
7084
                fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n",
7085
                        bs_index, sector_num);
7086
                goto error;
7087
            }
7088
        } else
7089
#endif
7090
        {
7091
        error:
7092
            printf("Error block header\n");
7093
            return -EINVAL;
7094
        }
7095
    }
7096
    ram_decompress_close(s);
7097
    return 0;
7098
}
7099

    
7100
/***********************************************************/
7101
/* bottom halves (can be seen as timers which expire ASAP) */
7102

    
7103
struct QEMUBH {
7104
    QEMUBHFunc *cb;
7105
    void *opaque;
7106
    int scheduled;
7107
    QEMUBH *next;
7108
};
7109

    
7110
static QEMUBH *first_bh = NULL;
7111

    
7112
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
7113
{
7114
    QEMUBH *bh;
7115
    bh = qemu_mallocz(sizeof(QEMUBH));
7116
    if (!bh)
7117
        return NULL;
7118
    bh->cb = cb;
7119
    bh->opaque = opaque;
7120
    return bh;
7121
}
7122

    
7123
int qemu_bh_poll(void)
7124
{
7125
    QEMUBH *bh, **pbh;
7126
    int ret;
7127

    
7128
    ret = 0;
7129
    for(;;) {
7130
        pbh = &first_bh;
7131
        bh = *pbh;
7132
        if (!bh)
7133
            break;
7134
        ret = 1;
7135
        *pbh = bh->next;
7136
        bh->scheduled = 0;
7137
        bh->cb(bh->opaque);
7138
    }
7139
    return ret;
7140
}
7141

    
7142
void qemu_bh_schedule(QEMUBH *bh)
7143
{
7144
    CPUState *env = cpu_single_env;
7145
    if (bh->scheduled)
7146
        return;
7147
    bh->scheduled = 1;
7148
    bh->next = first_bh;
7149
    first_bh = bh;
7150

    
7151
    /* stop the currently executing CPU to execute the BH ASAP */
7152
    if (env) {
7153
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
7154
    }
7155
}
7156

    
7157
void qemu_bh_cancel(QEMUBH *bh)
7158
{
7159
    QEMUBH **pbh;
7160
    if (bh->scheduled) {
7161
        pbh = &first_bh;
7162
        while (*pbh != bh)
7163
            pbh = &(*pbh)->next;
7164
        *pbh = bh->next;
7165
        bh->scheduled = 0;
7166
    }
7167
}
7168

    
7169
void qemu_bh_delete(QEMUBH *bh)
7170
{
7171
    qemu_bh_cancel(bh);
7172
    qemu_free(bh);
7173
}
7174

    
7175
/***********************************************************/
7176
/* machine registration */
7177

    
7178
QEMUMachine *first_machine = NULL;
7179

    
7180
int qemu_register_machine(QEMUMachine *m)
7181
{
7182
    QEMUMachine **pm;
7183
    pm = &first_machine;
7184
    while (*pm != NULL)
7185
        pm = &(*pm)->next;
7186
    m->next = NULL;
7187
    *pm = m;
7188
    return 0;
7189
}
7190

    
7191
static QEMUMachine *find_machine(const char *name)
7192
{
7193
    QEMUMachine *m;
7194

    
7195
    for(m = first_machine; m != NULL; m = m->next) {
7196
        if (!strcmp(m->name, name))
7197
            return m;
7198
    }
7199
    return NULL;
7200
}
7201

    
7202
/***********************************************************/
7203
/* main execution loop */
7204

    
7205
static void gui_update(void *opaque)
7206
{
7207
    DisplayState *ds = opaque;
7208
    ds->dpy_refresh(ds);
7209
    qemu_mod_timer(ds->gui_timer,
7210
        (ds->gui_timer_interval ?
7211
            ds->gui_timer_interval :
7212
            GUI_REFRESH_INTERVAL)
7213
        + qemu_get_clock(rt_clock));
7214
}
7215

    
7216
struct vm_change_state_entry {
7217
    VMChangeStateHandler *cb;
7218
    void *opaque;
7219
    LIST_ENTRY (vm_change_state_entry) entries;
7220
};
7221

    
7222
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
7223

    
7224
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
7225
                                                     void *opaque)
7226
{
7227
    VMChangeStateEntry *e;
7228

    
7229
    e = qemu_mallocz(sizeof (*e));
7230
    if (!e)
7231
        return NULL;
7232

    
7233
    e->cb = cb;
7234
    e->opaque = opaque;
7235
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
7236
    return e;
7237
}
7238

    
7239
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
7240
{
7241
    LIST_REMOVE (e, entries);
7242
    qemu_free (e);
7243
}
7244

    
7245
static void vm_state_notify(int running)
7246
{
7247
    VMChangeStateEntry *e;
7248

    
7249
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
7250
        e->cb(e->opaque, running);
7251
    }
7252
}
7253

    
7254
/* XXX: support several handlers */
7255
static VMStopHandler *vm_stop_cb;
7256
static void *vm_stop_opaque;
7257

    
7258
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
7259
{
7260
    vm_stop_cb = cb;
7261
    vm_stop_opaque = opaque;
7262
    return 0;
7263
}
7264

    
7265
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
7266
{
7267
    vm_stop_cb = NULL;
7268
}
7269

    
7270
void vm_start(void)
7271
{
7272
    if (!vm_running) {
7273
        cpu_enable_ticks();
7274
        vm_running = 1;
7275
        vm_state_notify(1);
7276
        qemu_rearm_alarm_timer(alarm_timer);
7277
    }
7278
}
7279

    
7280
void vm_stop(int reason)
7281
{
7282
    if (vm_running) {
7283
        cpu_disable_ticks();
7284
        vm_running = 0;
7285
        if (reason != 0) {
7286
            if (vm_stop_cb) {
7287
                vm_stop_cb(vm_stop_opaque, reason);
7288
            }
7289
        }
7290
        vm_state_notify(0);
7291
    }
7292
}
7293

    
7294
/* reset/shutdown handler */
7295

    
7296
typedef struct QEMUResetEntry {
7297
    QEMUResetHandler *func;
7298
    void *opaque;
7299
    struct QEMUResetEntry *next;
7300
} QEMUResetEntry;
7301

    
7302
static QEMUResetEntry *first_reset_entry;
7303
static int reset_requested;
7304
static int shutdown_requested;
7305
static int powerdown_requested;
7306

    
7307
int qemu_shutdown_requested(void)
7308
{
7309
    int r = shutdown_requested;
7310
    shutdown_requested = 0;
7311
    return r;
7312
}
7313

    
7314
int qemu_reset_requested(void)
7315
{
7316
    int r = reset_requested;
7317
    reset_requested = 0;
7318
    return r;
7319
}
7320

    
7321
int qemu_powerdown_requested(void)
7322
{
7323
    int r = powerdown_requested;
7324
    powerdown_requested = 0;
7325
    return r;
7326
}
7327

    
7328
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
7329
{
7330
    QEMUResetEntry **pre, *re;
7331

    
7332
    pre = &first_reset_entry;
7333
    while (*pre != NULL)
7334
        pre = &(*pre)->next;
7335
    re = qemu_mallocz(sizeof(QEMUResetEntry));
7336
    re->func = func;
7337
    re->opaque = opaque;
7338
    re->next = NULL;
7339
    *pre = re;
7340
}
7341

    
7342
void qemu_system_reset(void)
7343
{
7344
    QEMUResetEntry *re;
7345

    
7346
    /* reset all devices */
7347
    for(re = first_reset_entry; re != NULL; re = re->next) {
7348
        re->func(re->opaque);
7349
    }
7350
}
7351

    
7352
void qemu_system_reset_request(void)
7353
{
7354
    if (no_reboot) {
7355
        shutdown_requested = 1;
7356
    } else {
7357
        reset_requested = 1;
7358
    }
7359
    if (cpu_single_env)
7360
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7361
}
7362

    
7363
void qemu_system_shutdown_request(void)
7364
{
7365
    shutdown_requested = 1;
7366
    if (cpu_single_env)
7367
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7368
}
7369

    
7370
void qemu_system_powerdown_request(void)
7371
{
7372
    powerdown_requested = 1;
7373
    if (cpu_single_env)
7374
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
7375
}
7376

    
7377
void main_loop_wait(int timeout)
7378
{
7379
    IOHandlerRecord *ioh;
7380
    fd_set rfds, wfds, xfds;
7381
    int ret, nfds;
7382
#ifdef _WIN32
7383
    int ret2, i;
7384
#endif
7385
    struct timeval tv;
7386
    PollingEntry *pe;
7387

    
7388

    
7389
    /* XXX: need to suppress polling by better using win32 events */
7390
    ret = 0;
7391
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
7392
        ret |= pe->func(pe->opaque);
7393
    }
7394
#ifdef _WIN32
7395
    if (ret == 0) {
7396
        int err;
7397
        WaitObjects *w = &wait_objects;
7398

    
7399
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
7400
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
7401
            if (w->func[ret - WAIT_OBJECT_0])
7402
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
7403

    
7404
            /* Check for additional signaled events */
7405
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
7406

    
7407
                /* Check if event is signaled */
7408
                ret2 = WaitForSingleObject(w->events[i], 0);
7409
                if(ret2 == WAIT_OBJECT_0) {
7410
                    if (w->func[i])
7411
                        w->func[i](w->opaque[i]);
7412
                } else if (ret2 == WAIT_TIMEOUT) {
7413
                } else {
7414
                    err = GetLastError();
7415
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
7416
                }
7417
            }
7418
        } else if (ret == WAIT_TIMEOUT) {
7419
        } else {
7420
            err = GetLastError();
7421
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
7422
        }
7423
    }
7424
#endif
7425
    /* poll any events */
7426
    /* XXX: separate device handlers from system ones */
7427
    nfds = -1;
7428
    FD_ZERO(&rfds);
7429
    FD_ZERO(&wfds);
7430
    FD_ZERO(&xfds);
7431
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7432
        if (ioh->deleted)
7433
            continue;
7434
        if (ioh->fd_read &&
7435
            (!ioh->fd_read_poll ||
7436
             ioh->fd_read_poll(ioh->opaque) != 0)) {
7437
            FD_SET(ioh->fd, &rfds);
7438
            if (ioh->fd > nfds)
7439
                nfds = ioh->fd;
7440
        }
7441
        if (ioh->fd_write) {
7442
            FD_SET(ioh->fd, &wfds);
7443
            if (ioh->fd > nfds)
7444
                nfds = ioh->fd;
7445
        }
7446
    }
7447

    
7448
    tv.tv_sec = 0;
7449
#ifdef _WIN32
7450
    tv.tv_usec = 0;
7451
#else
7452
    tv.tv_usec = timeout * 1000;
7453
#endif
7454
#if defined(CONFIG_SLIRP)
7455
    if (slirp_inited) {
7456
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
7457
    }
7458
#endif
7459
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
7460
    if (ret > 0) {
7461
        IOHandlerRecord **pioh;
7462

    
7463
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
7464
            if (!ioh->deleted && ioh->fd_read && FD_ISSET(ioh->fd, &rfds)) {
7465
                ioh->fd_read(ioh->opaque);
7466
            }
7467
            if (!ioh->deleted && ioh->fd_write && FD_ISSET(ioh->fd, &wfds)) {
7468
                ioh->fd_write(ioh->opaque);
7469
            }
7470
        }
7471

    
7472
        /* remove deleted IO handlers */
7473
        pioh = &first_io_handler;
7474
        while (*pioh) {
7475
            ioh = *pioh;
7476
            if (ioh->deleted) {
7477
                *pioh = ioh->next;
7478
                qemu_free(ioh);
7479
            } else
7480
                pioh = &ioh->next;
7481
        }
7482
    }
7483
#if defined(CONFIG_SLIRP)
7484
    if (slirp_inited) {
7485
        if (ret < 0) {
7486
            FD_ZERO(&rfds);
7487
            FD_ZERO(&wfds);
7488
            FD_ZERO(&xfds);
7489
        }
7490
        slirp_select_poll(&rfds, &wfds, &xfds);
7491
    }
7492
#endif
7493

    
7494
    if (vm_running) {
7495
        if (likely(!(cur_cpu->singlestep_enabled & SSTEP_NOTIMER)))
7496
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL],
7497
                        qemu_get_clock(vm_clock));
7498
        /* run dma transfers, if any */
7499
        DMA_run();
7500
    }
7501

    
7502
    /* real time timers */
7503
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME],
7504
                    qemu_get_clock(rt_clock));
7505

    
7506
    if (alarm_timer->flags & ALARM_FLAG_EXPIRED) {
7507
        alarm_timer->flags &= ~(ALARM_FLAG_EXPIRED);
7508
        qemu_rearm_alarm_timer(alarm_timer);
7509
    }
7510

    
7511
    /* Check bottom-halves last in case any of the earlier events triggered
7512
       them.  */
7513
    qemu_bh_poll();
7514

    
7515
}
7516

    
7517
static int main_loop(void)
7518
{
7519
    int ret, timeout;
7520
#ifdef CONFIG_PROFILER
7521
    int64_t ti;
7522
#endif
7523
    CPUState *env;
7524

    
7525
    cur_cpu = first_cpu;
7526
    next_cpu = cur_cpu->next_cpu ?: first_cpu;
7527
    for(;;) {
7528
        if (vm_running) {
7529

    
7530
            for(;;) {
7531
                /* get next cpu */
7532
                env = next_cpu;
7533
#ifdef CONFIG_PROFILER
7534
                ti = profile_getclock();
7535
#endif
7536
                if (use_icount) {
7537
                    int64_t count;
7538
                    int decr;
7539
                    qemu_icount -= (env->icount_decr.u16.low + env->icount_extra);
7540
                    env->icount_decr.u16.low = 0;
7541
                    env->icount_extra = 0;
7542
                    count = qemu_next_deadline();
7543
                    count = (count + (1 << icount_time_shift) - 1)
7544
                            >> icount_time_shift;
7545
                    qemu_icount += count;
7546
                    decr = (count > 0xffff) ? 0xffff : count;
7547
                    count -= decr;
7548
                    env->icount_decr.u16.low = decr;
7549
                    env->icount_extra = count;
7550
                }
7551
                ret = cpu_exec(env);
7552
#ifdef CONFIG_PROFILER
7553
                qemu_time += profile_getclock() - ti;
7554
#endif
7555
                if (use_icount) {
7556
                    /* Fold pending instructions back into the
7557
                       instruction counter, and clear the interrupt flag.  */
7558
                    qemu_icount -= (env->icount_decr.u16.low
7559
                                    + env->icount_extra);
7560
                    env->icount_decr.u32 = 0;
7561
                    env->icount_extra = 0;
7562
                }
7563
                next_cpu = env->next_cpu ?: first_cpu;
7564
                if (event_pending && likely(ret != EXCP_DEBUG)) {
7565
                    ret = EXCP_INTERRUPT;
7566
                    event_pending = 0;
7567
                    break;
7568
                }
7569
                if (ret == EXCP_HLT) {
7570
                    /* Give the next CPU a chance to run.  */
7571
                    cur_cpu = env;
7572
                    continue;
7573
                }
7574
                if (ret != EXCP_HALTED)
7575
                    break;
7576
                /* all CPUs are halted ? */
7577
                if (env == cur_cpu)
7578
                    break;
7579
            }
7580
            cur_cpu = env;
7581

    
7582
            if (shutdown_requested) {
7583
                ret = EXCP_INTERRUPT;
7584
                if (no_shutdown) {
7585
                    vm_stop(0);
7586
                    no_shutdown = 0;
7587
                }
7588
                else
7589
                    break;
7590
            }
7591
            if (reset_requested) {
7592
                reset_requested = 0;
7593
                qemu_system_reset();
7594
                ret = EXCP_INTERRUPT;
7595
            }
7596
            if (powerdown_requested) {
7597
                powerdown_requested = 0;
7598
                qemu_system_powerdown();
7599
                ret = EXCP_INTERRUPT;
7600
            }
7601
            if (unlikely(ret == EXCP_DEBUG)) {
7602
                vm_stop(EXCP_DEBUG);
7603
            }
7604
            /* If all cpus are halted then wait until the next IRQ */
7605
            /* XXX: use timeout computed from timers */
7606
            if (ret == EXCP_HALTED) {
7607
                if (use_icount) {
7608
                    int64_t add;
7609
                    int64_t delta;
7610
                    /* Advance virtual time to the next event.  */
7611
                    if (use_icount == 1) {
7612
                        /* When not using an adaptive execution frequency
7613
                           we tend to get badly out of sync with real time,
7614
                           so just delay for a reasonable amount of time.  */
7615
                        delta = 0;
7616
                    } else {
7617
                        delta = cpu_get_icount() - cpu_get_clock();
7618
                    }
7619
                    if (delta > 0) {
7620
                        /* If virtual time is ahead of real time then just
7621
                           wait for IO.  */
7622
                        timeout = (delta / 1000000) + 1;
7623
                    } else {
7624
                        /* Wait for either IO to occur or the next
7625
                           timer event.  */
7626
                        add = qemu_next_deadline();
7627
                        /* We advance the timer before checking for IO.
7628
                           Limit the amount we advance so that early IO
7629
                           activity won't get the guest too far ahead.  */
7630
                        if (add > 10000000)
7631
                            add = 10000000;
7632
                        delta += add;
7633
                        add = (add + (1 << icount_time_shift) - 1)
7634
                              >> icount_time_shift;
7635
                        qemu_icount += add;
7636
                        timeout = delta / 1000000;
7637
                        if (timeout < 0)
7638
                            timeout = 0;
7639
                    }
7640
                } else {
7641
                    timeout = 10;
7642
                }
7643
            } else {
7644
                timeout = 0;
7645
            }
7646
        } else {
7647
            if (shutdown_requested)
7648
                break;
7649
            timeout = 10;
7650
        }
7651
#ifdef CONFIG_PROFILER
7652
        ti = profile_getclock();
7653
#endif
7654
        main_loop_wait(timeout);
7655
#ifdef CONFIG_PROFILER
7656
        dev_time += profile_getclock() - ti;
7657
#endif
7658
    }
7659
    cpu_disable_ticks();
7660
    return ret;
7661
}
7662

    
7663
static void help(int exitcode)
7664
{
7665
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2008 Fabrice Bellard\n"
7666
           "usage: %s [options] [disk_image]\n"
7667
           "\n"
7668
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
7669
           "\n"
7670
           "Standard options:\n"
7671
           "-M machine      select emulated machine (-M ? for list)\n"
7672
           "-cpu cpu        select CPU (-cpu ? for list)\n"
7673
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
7674
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
7675
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
7676
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
7677
           "-drive [file=file][,if=type][,bus=n][,unit=m][,media=d][,index=i]\n"
7678
           "       [,cyls=c,heads=h,secs=s[,trans=t]][,snapshot=on|off]\n"
7679
           "       [,cache=on|off][,format=f]\n"
7680
           "                use 'file' as a drive image\n"
7681
           "-mtdblock file  use 'file' as on-board Flash memory image\n"
7682
           "-sd file        use 'file' as SecureDigital card image\n"
7683
           "-pflash file    use 'file' as a parallel flash image\n"
7684
           "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
7685
           "-snapshot       write to temporary files instead of disk image files\n"
7686
#ifdef CONFIG_SDL
7687
           "-no-frame       open SDL window without a frame and window decorations\n"
7688
           "-alt-grab       use Ctrl-Alt-Shift to grab mouse (instead of Ctrl-Alt)\n"
7689
           "-no-quit        disable SDL window close capability\n"
7690
#endif
7691
#ifdef TARGET_I386
7692
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
7693
#endif
7694
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
7695
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
7696
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
7697
           "-portrait       rotate graphical output 90 deg left (only PXA LCD)\n"
7698
#ifndef _WIN32
7699
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
7700
#endif
7701
#ifdef HAS_AUDIO
7702
           "-audio-help     print list of audio drivers and their options\n"
7703
           "-soundhw c1,... enable audio support\n"
7704
           "                and only specified sound cards (comma separated list)\n"
7705
           "                use -soundhw ? to get the list of supported cards\n"
7706
           "                use -soundhw all to enable all of them\n"
7707
#endif
7708
           "-localtime      set the real time clock to local time [default=utc]\n"
7709
           "-full-screen    start in full screen\n"
7710
#ifdef TARGET_I386
7711
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
7712
#endif
7713
           "-usb            enable the USB driver (will be the default soon)\n"
7714
           "-usbdevice name add the host or guest USB device 'name'\n"
7715
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7716
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
7717
#endif
7718
           "-name string    set the name of the guest\n"
7719
           "\n"
7720
           "Network options:\n"
7721
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
7722
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
7723
#ifdef CONFIG_SLIRP
7724
           "-net user[,vlan=n][,hostname=host]\n"
7725
           "                connect the user mode network stack to VLAN 'n' and send\n"
7726
           "                hostname 'host' to DHCP clients\n"
7727
#endif
7728
#ifdef _WIN32
7729
           "-net tap[,vlan=n],ifname=name\n"
7730
           "                connect the host TAP network interface to VLAN 'n'\n"
7731
#else
7732
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file][,downscript=dfile]\n"
7733
           "                connect the host TAP network interface to VLAN 'n' and use the\n"
7734
           "                network scripts 'file' (default=%s)\n"
7735
           "                and 'dfile' (default=%s);\n"
7736
           "                use '[down]script=no' to disable script execution;\n"
7737
           "                use 'fd=h' to connect to an already opened TAP interface\n"
7738
#endif
7739
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
7740
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
7741
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
7742
           "                connect the vlan 'n' to multicast maddr and port\n"
7743
#ifdef CONFIG_VDE
7744
           "-net vde[,vlan=n][,sock=socketpath][,port=n][,group=groupname][,mode=octalmode]\n"
7745
           "                connect the vlan 'n' to port 'n' of a vde switch running\n"
7746
           "                on host and listening for incoming connections on 'socketpath'.\n"
7747
           "                Use group 'groupname' and mode 'octalmode' to change default\n"
7748
           "                ownership and permissions for communication port.\n"
7749
#endif
7750
           "-net none       use it alone to have zero network devices; if no -net option\n"
7751
           "                is provided, the default is '-net nic -net user'\n"
7752
           "\n"
7753
#ifdef CONFIG_SLIRP
7754
           "-tftp dir       allow tftp access to files in dir [-net user]\n"
7755
           "-bootp file     advertise file in BOOTP replies\n"
7756
#ifndef _WIN32
7757
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
7758
#endif
7759
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
7760
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
7761
#endif
7762
           "\n"
7763
           "Linux boot specific:\n"
7764
           "-kernel bzImage use 'bzImage' as kernel image\n"
7765
           "-append cmdline use 'cmdline' as kernel command line\n"
7766
           "-initrd file    use 'file' as initial ram disk\n"
7767
           "\n"
7768
           "Debug/Expert options:\n"
7769
           "-monitor dev    redirect the monitor to char device 'dev'\n"
7770
           "-serial dev     redirect the serial port to char device 'dev'\n"
7771
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
7772
           "-pidfile file   Write PID to 'file'\n"
7773
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
7774
           "-s              wait gdb connection to port\n"
7775
           "-p port         set gdb connection port [default=%s]\n"
7776
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
7777
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
7778
           "                translation (t=none or lba) (usually qemu can guess them)\n"
7779
           "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
7780
#ifdef USE_KQEMU
7781
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
7782
           "-no-kqemu       disable KQEMU kernel module usage\n"
7783
#endif
7784
#ifdef TARGET_I386
7785
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
7786
           "                (default is CL-GD5446 PCI VGA)\n"
7787
           "-no-acpi        disable ACPI\n"
7788
#endif
7789
#ifdef CONFIG_CURSES
7790
           "-curses         use a curses/ncurses interface instead of SDL\n"
7791
#endif
7792
           "-no-reboot      exit instead of rebooting\n"
7793
           "-no-shutdown    stop before shutdown\n"
7794
           "-loadvm [tag|id]  start right away with a saved state (loadvm in monitor)\n"
7795
           "-vnc display    start a VNC server on display\n"
7796
#ifndef _WIN32
7797
           "-daemonize      daemonize QEMU after initializing\n"
7798
#endif
7799
           "-option-rom rom load a file, rom, into the option ROM space\n"
7800
#ifdef TARGET_SPARC
7801
           "-prom-env variable=value  set OpenBIOS nvram variables\n"
7802
#endif
7803
           "-clock          force the use of the given methods for timer alarm.\n"
7804
           "                To see what timers are available use -clock ?\n"
7805
           "-startdate      select initial date of the clock\n"
7806
           "-icount [N|auto]\n"
7807
           "                Enable virtual instruction counter with 2^N clock ticks per instruction\n"
7808
           "\n"
7809
           "During emulation, the following keys are useful:\n"
7810
           "ctrl-alt-f      toggle full screen\n"
7811
           "ctrl-alt-n      switch to virtual console 'n'\n"
7812
           "ctrl-alt        toggle mouse and keyboard grab\n"
7813
           "\n"
7814
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
7815
           ,
7816
           "qemu",
7817
           DEFAULT_RAM_SIZE,
7818
#ifndef _WIN32
7819
           DEFAULT_NETWORK_SCRIPT,
7820
           DEFAULT_NETWORK_DOWN_SCRIPT,
7821
#endif
7822
           DEFAULT_GDBSTUB_PORT,
7823
           "/tmp/qemu.log");
7824
    exit(exitcode);
7825
}
7826

    
7827
#define HAS_ARG 0x0001
7828

    
7829
enum {
7830
    QEMU_OPTION_h,
7831

    
7832
    QEMU_OPTION_M,
7833
    QEMU_OPTION_cpu,
7834
    QEMU_OPTION_fda,
7835
    QEMU_OPTION_fdb,
7836
    QEMU_OPTION_hda,
7837
    QEMU_OPTION_hdb,
7838
    QEMU_OPTION_hdc,
7839
    QEMU_OPTION_hdd,
7840
    QEMU_OPTION_drive,
7841
    QEMU_OPTION_cdrom,
7842
    QEMU_OPTION_mtdblock,
7843
    QEMU_OPTION_sd,
7844
    QEMU_OPTION_pflash,
7845
    QEMU_OPTION_boot,
7846
    QEMU_OPTION_snapshot,
7847
#ifdef TARGET_I386
7848
    QEMU_OPTION_no_fd_bootchk,
7849
#endif
7850
    QEMU_OPTION_m,
7851
    QEMU_OPTION_nographic,
7852
    QEMU_OPTION_portrait,
7853
#ifdef HAS_AUDIO
7854
    QEMU_OPTION_audio_help,
7855
    QEMU_OPTION_soundhw,
7856
#endif
7857

    
7858
    QEMU_OPTION_net,
7859
    QEMU_OPTION_tftp,
7860
    QEMU_OPTION_bootp,
7861
    QEMU_OPTION_smb,
7862
    QEMU_OPTION_redir,
7863

    
7864
    QEMU_OPTION_kernel,
7865
    QEMU_OPTION_append,
7866
    QEMU_OPTION_initrd,
7867

    
7868
    QEMU_OPTION_S,
7869
    QEMU_OPTION_s,
7870
    QEMU_OPTION_p,
7871
    QEMU_OPTION_d,
7872
    QEMU_OPTION_hdachs,
7873
    QEMU_OPTION_L,
7874
    QEMU_OPTION_bios,
7875
    QEMU_OPTION_k,
7876
    QEMU_OPTION_localtime,
7877
    QEMU_OPTION_cirrusvga,
7878
    QEMU_OPTION_vmsvga,
7879
    QEMU_OPTION_g,
7880
    QEMU_OPTION_std_vga,
7881
    QEMU_OPTION_echr,
7882
    QEMU_OPTION_monitor,
7883
    QEMU_OPTION_serial,
7884
    QEMU_OPTION_parallel,
7885
    QEMU_OPTION_loadvm,
7886
    QEMU_OPTION_full_screen,
7887
    QEMU_OPTION_no_frame,
7888
    QEMU_OPTION_alt_grab,
7889
    QEMU_OPTION_no_quit,
7890
    QEMU_OPTION_pidfile,
7891
    QEMU_OPTION_no_kqemu,
7892
    QEMU_OPTION_kernel_kqemu,
7893
    QEMU_OPTION_win2k_hack,
7894
    QEMU_OPTION_usb,
7895
    QEMU_OPTION_usbdevice,
7896
    QEMU_OPTION_smp,
7897
    QEMU_OPTION_vnc,
7898
    QEMU_OPTION_no_acpi,
7899
    QEMU_OPTION_curses,
7900
    QEMU_OPTION_no_reboot,
7901
    QEMU_OPTION_no_shutdown,
7902
    QEMU_OPTION_show_cursor,
7903
    QEMU_OPTION_daemonize,
7904
    QEMU_OPTION_option_rom,
7905
    QEMU_OPTION_semihosting,
7906
    QEMU_OPTION_name,
7907
    QEMU_OPTION_prom_env,
7908
    QEMU_OPTION_old_param,
7909
    QEMU_OPTION_clock,
7910
    QEMU_OPTION_startdate,
7911
    QEMU_OPTION_tb_size,
7912
    QEMU_OPTION_icount,
7913
};
7914

    
7915
typedef struct QEMUOption {
7916
    const char *name;
7917
    int flags;
7918
    int index;
7919
} QEMUOption;
7920

    
7921
const QEMUOption qemu_options[] = {
7922
    { "h", 0, QEMU_OPTION_h },
7923
    { "help", 0, QEMU_OPTION_h },
7924

    
7925
    { "M", HAS_ARG, QEMU_OPTION_M },
7926
    { "cpu", HAS_ARG, QEMU_OPTION_cpu },
7927
    { "fda", HAS_ARG, QEMU_OPTION_fda },
7928
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
7929
    { "hda", HAS_ARG, QEMU_OPTION_hda },
7930
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
7931
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
7932
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
7933
    { "drive", HAS_ARG, QEMU_OPTION_drive },
7934
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
7935
    { "mtdblock", HAS_ARG, QEMU_OPTION_mtdblock },
7936
    { "sd", HAS_ARG, QEMU_OPTION_sd },
7937
    { "pflash", HAS_ARG, QEMU_OPTION_pflash },
7938
    { "boot", HAS_ARG, QEMU_OPTION_boot },
7939
    { "snapshot", 0, QEMU_OPTION_snapshot },
7940
#ifdef TARGET_I386
7941
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
7942
#endif
7943
    { "m", HAS_ARG, QEMU_OPTION_m },
7944
    { "nographic", 0, QEMU_OPTION_nographic },
7945
    { "portrait", 0, QEMU_OPTION_portrait },
7946
    { "k", HAS_ARG, QEMU_OPTION_k },
7947
#ifdef HAS_AUDIO
7948
    { "audio-help", 0, QEMU_OPTION_audio_help },
7949
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
7950
#endif
7951

    
7952
    { "net", HAS_ARG, QEMU_OPTION_net},
7953
#ifdef CONFIG_SLIRP
7954
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
7955
    { "bootp", HAS_ARG, QEMU_OPTION_bootp },
7956
#ifndef _WIN32
7957
    { "smb", HAS_ARG, QEMU_OPTION_smb },
7958
#endif
7959
    { "redir", HAS_ARG, QEMU_OPTION_redir },
7960
#endif
7961

    
7962
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
7963
    { "append", HAS_ARG, QEMU_OPTION_append },
7964
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
7965

    
7966
    { "S", 0, QEMU_OPTION_S },
7967
    { "s", 0, QEMU_OPTION_s },
7968
    { "p", HAS_ARG, QEMU_OPTION_p },
7969
    { "d", HAS_ARG, QEMU_OPTION_d },
7970
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
7971
    { "L", HAS_ARG, QEMU_OPTION_L },
7972
    { "bios", HAS_ARG, QEMU_OPTION_bios },
7973
#ifdef USE_KQEMU
7974
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
7975
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
7976
#endif
7977
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
7978
    { "g", 1, QEMU_OPTION_g },
7979
#endif
7980
    { "localtime", 0, QEMU_OPTION_localtime },
7981
    { "std-vga", 0, QEMU_OPTION_std_vga },
7982
    { "echr", HAS_ARG, QEMU_OPTION_echr },
7983
    { "monitor", HAS_ARG, QEMU_OPTION_monitor },
7984
    { "serial", HAS_ARG, QEMU_OPTION_serial },
7985
    { "parallel", HAS_ARG, QEMU_OPTION_parallel },
7986
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
7987
    { "full-screen", 0, QEMU_OPTION_full_screen },
7988
#ifdef CONFIG_SDL
7989
    { "no-frame", 0, QEMU_OPTION_no_frame },
7990
    { "alt-grab", 0, QEMU_OPTION_alt_grab },
7991
    { "no-quit", 0, QEMU_OPTION_no_quit },
7992
#endif
7993
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
7994
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
7995
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
7996
    { "smp", HAS_ARG, QEMU_OPTION_smp },
7997
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
7998
#ifdef CONFIG_CURSES
7999
    { "curses", 0, QEMU_OPTION_curses },
8000
#endif
8001

    
8002
    /* temporary options */
8003
    { "usb", 0, QEMU_OPTION_usb },
8004
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
8005
    { "vmwarevga", 0, QEMU_OPTION_vmsvga },
8006
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
8007
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
8008
    { "no-shutdown", 0, QEMU_OPTION_no_shutdown },
8009
    { "show-cursor", 0, QEMU_OPTION_show_cursor },
8010
    { "daemonize", 0, QEMU_OPTION_daemonize },
8011
    { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
8012
#if defined(TARGET_ARM) || defined(TARGET_M68K)
8013
    { "semihosting", 0, QEMU_OPTION_semihosting },
8014
#endif
8015
    { "name", HAS_ARG, QEMU_OPTION_name },
8016
#if defined(TARGET_SPARC)
8017
    { "prom-env", HAS_ARG, QEMU_OPTION_prom_env },
8018
#endif
8019
#if defined(TARGET_ARM)
8020
    { "old-param", 0, QEMU_OPTION_old_param },
8021
#endif
8022
    { "clock", HAS_ARG, QEMU_OPTION_clock },
8023
    { "startdate", HAS_ARG, QEMU_OPTION_startdate },
8024
    { "tb-size", HAS_ARG, QEMU_OPTION_tb_size },
8025
    { "icount", HAS_ARG, QEMU_OPTION_icount },
8026
    { NULL },
8027
};
8028

    
8029
/* password input */
8030

    
8031
int qemu_key_check(BlockDriverState *bs, const char *name)
8032
{
8033
    char password[256];
8034
    int i;
8035

    
8036
    if (!bdrv_is_encrypted(bs))
8037
        return 0;
8038

    
8039
    term_printf("%s is encrypted.\n", name);
8040
    for(i = 0; i < 3; i++) {
8041
        monitor_readline("Password: ", 1, password, sizeof(password));
8042
        if (bdrv_set_key(bs, password) == 0)
8043
            return 0;
8044
        term_printf("invalid password\n");
8045
    }
8046
    return -EPERM;
8047
}
8048

    
8049
static BlockDriverState *get_bdrv(int index)
8050
{
8051
    if (index > nb_drives)
8052
        return NULL;
8053
    return drives_table[index].bdrv;
8054
}
8055

    
8056
static void read_passwords(void)
8057
{
8058
    BlockDriverState *bs;
8059
    int i;
8060

    
8061
    for(i = 0; i < 6; i++) {
8062
        bs = get_bdrv(i);
8063
        if (bs)
8064
            qemu_key_check(bs, bdrv_get_device_name(bs));
8065
    }
8066
}
8067

    
8068
#ifdef HAS_AUDIO
8069
struct soundhw soundhw[] = {
8070
#ifdef HAS_AUDIO_CHOICE
8071
#if defined(TARGET_I386) || defined(TARGET_MIPS)
8072
    {
8073
        "pcspk",
8074
        "PC speaker",
8075
        0,
8076
        1,
8077
        { .init_isa = pcspk_audio_init }
8078
    },
8079
#endif
8080
    {
8081
        "sb16",
8082
        "Creative Sound Blaster 16",
8083
        0,
8084
        1,
8085
        { .init_isa = SB16_init }
8086
    },
8087

    
8088
#ifdef CONFIG_CS4231A
8089
    {
8090
        "cs4231a",
8091
        "CS4231A",
8092
        0,
8093
        1,
8094
        { .init_isa = cs4231a_init }
8095
    },
8096
#endif
8097

    
8098
#ifdef CONFIG_ADLIB
8099
    {
8100
        "adlib",
8101
#ifdef HAS_YMF262
8102
        "Yamaha YMF262 (OPL3)",
8103
#else
8104
        "Yamaha YM3812 (OPL2)",
8105
#endif
8106
        0,
8107
        1,
8108
        { .init_isa = Adlib_init }
8109
    },
8110
#endif
8111

    
8112
#ifdef CONFIG_GUS
8113
    {
8114
        "gus",
8115
        "Gravis Ultrasound GF1",
8116
        0,
8117
        1,
8118
        { .init_isa = GUS_init }
8119
    },
8120
#endif
8121

    
8122
#ifdef CONFIG_AC97
8123
    {
8124
        "ac97",
8125
        "Intel 82801AA AC97 Audio",
8126
        0,
8127
        0,
8128
        { .init_pci = ac97_init }
8129
    },
8130
#endif
8131

    
8132
    {
8133
        "es1370",
8134
        "ENSONIQ AudioPCI ES1370",
8135
        0,
8136
        0,
8137
        { .init_pci = es1370_init }
8138
    },
8139
#endif
8140

    
8141
    { NULL, NULL, 0, 0, { NULL } }
8142
};
8143

    
8144
static void select_soundhw (const char *optarg)
8145
{
8146
    struct soundhw *c;
8147

    
8148
    if (*optarg == '?') {
8149
    show_valid_cards:
8150

    
8151
        printf ("Valid sound card names (comma separated):\n");
8152
        for (c = soundhw; c->name; ++c) {
8153
            printf ("%-11s %s\n", c->name, c->descr);
8154
        }
8155
        printf ("\n-soundhw all will enable all of the above\n");
8156
        exit (*optarg != '?');
8157
    }
8158
    else {
8159
        size_t l;
8160
        const char *p;
8161
        char *e;
8162
        int bad_card = 0;
8163

    
8164
        if (!strcmp (optarg, "all")) {
8165
            for (c = soundhw; c->name; ++c) {
8166
                c->enabled = 1;
8167
            }
8168
            return;
8169
        }
8170

    
8171
        p = optarg;
8172
        while (*p) {
8173
            e = strchr (p, ',');
8174
            l = !e ? strlen (p) : (size_t) (e - p);
8175

    
8176
            for (c = soundhw; c->name; ++c) {
8177
                if (!strncmp (c->name, p, l)) {
8178
                    c->enabled = 1;
8179
                    break;
8180
                }
8181
            }
8182

    
8183
            if (!c->name) {
8184
                if (l > 80) {
8185
                    fprintf (stderr,
8186
                             "Unknown sound card name (too big to show)\n");
8187
                }
8188
                else {
8189
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
8190
                             (int) l, p);
8191
                }
8192
                bad_card = 1;
8193
            }
8194
            p += l + (e != NULL);
8195
        }
8196

    
8197
        if (bad_card)
8198
            goto show_valid_cards;
8199
    }
8200
}
8201
#endif
8202

    
8203
#ifdef _WIN32
8204
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
8205
{
8206
    exit(STATUS_CONTROL_C_EXIT);
8207
    return TRUE;
8208
}
8209
#endif
8210

    
8211
#define MAX_NET_CLIENTS 32
8212

    
8213
#ifndef _WIN32
8214

    
8215
static void termsig_handler(int signal)
8216
{
8217
    qemu_system_shutdown_request();
8218
}
8219

    
8220
static void termsig_setup(void)
8221
{
8222
    struct sigaction act;
8223

    
8224
    memset(&act, 0, sizeof(act));
8225
    act.sa_handler = termsig_handler;
8226
    sigaction(SIGINT,  &act, NULL);
8227
    sigaction(SIGHUP,  &act, NULL);
8228
    sigaction(SIGTERM, &act, NULL);
8229
}
8230

    
8231
#endif
8232

    
8233
int main(int argc, char **argv)
8234
{
8235
#ifdef CONFIG_GDBSTUB
8236
    int use_gdbstub;
8237
    const char *gdbstub_port;
8238
#endif
8239
    uint32_t boot_devices_bitmap = 0;
8240
    int i;
8241
    int snapshot, linux_boot, net_boot;
8242
    const char *initrd_filename;
8243
    const char *kernel_filename, *kernel_cmdline;
8244
    const char *boot_devices = "";
8245
    DisplayState *ds = &display_state;
8246
    int cyls, heads, secs, translation;
8247
    const char *net_clients[MAX_NET_CLIENTS];
8248
    int nb_net_clients;
8249
    int hda_index;
8250
    int optind;
8251
    const char *r, *optarg;
8252
    CharDriverState *monitor_hd;
8253
    const char *monitor_device;
8254
    const char *serial_devices[MAX_SERIAL_PORTS];
8255
    int serial_device_index;
8256
    const char *parallel_devices[MAX_PARALLEL_PORTS];
8257
    int parallel_device_index;
8258
    const char *loadvm = NULL;
8259
    QEMUMachine *machine;
8260
    const char *cpu_model;
8261
    const char *usb_devices[MAX_USB_CMDLINE];
8262
    int usb_devices_index;
8263
    int fds[2];
8264
    int tb_size;
8265
    const char *pid_file = NULL;
8266
    VLANState *vlan;
8267

    
8268
    LIST_INIT (&vm_change_state_head);
8269
#ifndef _WIN32
8270
    {
8271
        struct sigaction act;
8272
        sigfillset(&act.sa_mask);
8273
        act.sa_flags = 0;
8274
        act.sa_handler = SIG_IGN;
8275
        sigaction(SIGPIPE, &act, NULL);
8276
    }
8277
#else
8278
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
8279
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
8280
       QEMU to run on a single CPU */
8281
    {
8282
        HANDLE h;
8283
        DWORD mask, smask;
8284
        int i;
8285
        h = GetCurrentProcess();
8286
        if (GetProcessAffinityMask(h, &mask, &smask)) {
8287
            for(i = 0; i < 32; i++) {
8288
                if (mask & (1 << i))
8289
                    break;
8290
            }
8291
            if (i != 32) {
8292
                mask = 1 << i;
8293
                SetProcessAffinityMask(h, mask);
8294
            }
8295
        }
8296
    }
8297
#endif
8298

    
8299
    register_machines();
8300
    machine = first_machine;
8301
    cpu_model = NULL;
8302
    initrd_filename = NULL;
8303
    ram_size = 0;
8304
    vga_ram_size = VGA_RAM_SIZE;
8305
#ifdef CONFIG_GDBSTUB
8306
    use_gdbstub = 0;
8307
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
8308
#endif
8309
    snapshot = 0;
8310
    nographic = 0;
8311
    curses = 0;
8312
    kernel_filename = NULL;
8313
    kernel_cmdline = "";
8314
    cyls = heads = secs = 0;
8315
    translation = BIOS_ATA_TRANSLATION_AUTO;
8316
    monitor_device = "vc";
8317

    
8318
    serial_devices[0] = "vc:80Cx24C";
8319
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
8320
        serial_devices[i] = NULL;
8321
    serial_device_index = 0;
8322

    
8323
    parallel_devices[0] = "vc:640x480";
8324
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
8325
        parallel_devices[i] = NULL;
8326
    parallel_device_index = 0;
8327

    
8328
    usb_devices_index = 0;
8329

    
8330
    nb_net_clients = 0;
8331
    nb_drives = 0;
8332
    nb_drives_opt = 0;
8333
    hda_index = -1;
8334

    
8335
    nb_nics = 0;
8336

    
8337
    tb_size = 0;
8338
    
8339
    optind = 1;
8340
    for(;;) {
8341
        if (optind >= argc)
8342
            break;
8343
        r = argv[optind];
8344
        if (r[0] != '-') {
8345
            hda_index = drive_add(argv[optind++], HD_ALIAS, 0);
8346
        } else {
8347
            const QEMUOption *popt;
8348

    
8349
            optind++;
8350
            /* Treat --foo the same as -foo.  */
8351
            if (r[1] == '-')
8352
                r++;
8353
            popt = qemu_options;
8354
            for(;;) {
8355
                if (!popt->name) {
8356
                    fprintf(stderr, "%s: invalid option -- '%s'\n",
8357
                            argv[0], r);
8358
                    exit(1);
8359
                }
8360
                if (!strcmp(popt->name, r + 1))
8361
                    break;
8362
                popt++;
8363
            }
8364
            if (popt->flags & HAS_ARG) {
8365
                if (optind >= argc) {
8366
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
8367
                            argv[0], r);
8368
                    exit(1);
8369
                }
8370
                optarg = argv[optind++];
8371
            } else {
8372
                optarg = NULL;
8373
            }
8374

    
8375
            switch(popt->index) {
8376
            case QEMU_OPTION_M:
8377
                machine = find_machine(optarg);
8378
                if (!machine) {
8379
                    QEMUMachine *m;
8380
                    printf("Supported machines are:\n");
8381
                    for(m = first_machine; m != NULL; m = m->next) {
8382
                        printf("%-10s %s%s\n",
8383
                               m->name, m->desc,
8384
                               m == first_machine ? " (default)" : "");
8385
                    }
8386
                    exit(*optarg != '?');
8387
                }
8388
                break;
8389
            case QEMU_OPTION_cpu:
8390
                /* hw initialization will check this */
8391
                if (*optarg == '?') {
8392
/* XXX: implement xxx_cpu_list for targets that still miss it */
8393
#if defined(cpu_list)
8394
                    cpu_list(stdout, &fprintf);
8395
#endif
8396
                    exit(0);
8397
                } else {
8398
                    cpu_model = optarg;
8399
                }
8400
                break;
8401
            case QEMU_OPTION_initrd:
8402
                initrd_filename = optarg;
8403
                break;
8404
            case QEMU_OPTION_hda:
8405
                if (cyls == 0)
8406
                    hda_index = drive_add(optarg, HD_ALIAS, 0);
8407
                else
8408
                    hda_index = drive_add(optarg, HD_ALIAS
8409
                             ",cyls=%d,heads=%d,secs=%d%s",
8410
                             0, cyls, heads, secs,
8411
                             translation == BIOS_ATA_TRANSLATION_LBA ?
8412
                                 ",trans=lba" :
8413
                             translation == BIOS_ATA_TRANSLATION_NONE ?
8414
                                 ",trans=none" : "");
8415
                 break;
8416
            case QEMU_OPTION_hdb:
8417
            case QEMU_OPTION_hdc:
8418
            case QEMU_OPTION_hdd:
8419
                drive_add(optarg, HD_ALIAS, popt->index - QEMU_OPTION_hda);
8420
                break;
8421
            case QEMU_OPTION_drive:
8422
                drive_add(NULL, "%s", optarg);
8423
                break;
8424
            case QEMU_OPTION_mtdblock:
8425
                drive_add(optarg, MTD_ALIAS);
8426
                break;
8427
            case QEMU_OPTION_sd:
8428
                drive_add(optarg, SD_ALIAS);
8429
                break;
8430
            case QEMU_OPTION_pflash:
8431
                drive_add(optarg, PFLASH_ALIAS);
8432
                break;
8433
            case QEMU_OPTION_snapshot:
8434
                snapshot = 1;
8435
                break;
8436
            case QEMU_OPTION_hdachs:
8437
                {
8438
                    const char *p;
8439
                    p = optarg;
8440
                    cyls = strtol(p, (char **)&p, 0);
8441
                    if (cyls < 1 || cyls > 16383)
8442
                        goto chs_fail;
8443
                    if (*p != ',')
8444
                        goto chs_fail;
8445
                    p++;
8446
                    heads = strtol(p, (char **)&p, 0);
8447
                    if (heads < 1 || heads > 16)
8448
                        goto chs_fail;
8449
                    if (*p != ',')
8450
                        goto chs_fail;
8451
                    p++;
8452
                    secs = strtol(p, (char **)&p, 0);
8453
                    if (secs < 1 || secs > 63)
8454
                        goto chs_fail;
8455
                    if (*p == ',') {
8456
                        p++;
8457
                        if (!strcmp(p, "none"))
8458
                            translation = BIOS_ATA_TRANSLATION_NONE;
8459
                        else if (!strcmp(p, "lba"))
8460
                            translation = BIOS_ATA_TRANSLATION_LBA;
8461
                        else if (!strcmp(p, "auto"))
8462
                            translation = BIOS_ATA_TRANSLATION_AUTO;
8463
                        else
8464
                            goto chs_fail;
8465
                    } else if (*p != '\0') {
8466
                    chs_fail:
8467
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
8468
                        exit(1);
8469
                    }
8470
                    if (hda_index != -1)
8471
                        snprintf(drives_opt[hda_index].opt,
8472
                                 sizeof(drives_opt[hda_index].opt),
8473
                                 HD_ALIAS ",cyls=%d,heads=%d,secs=%d%s",
8474
                                 0, cyls, heads, secs,
8475
                                 translation == BIOS_ATA_TRANSLATION_LBA ?
8476
                                         ",trans=lba" :
8477
                                 translation == BIOS_ATA_TRANSLATION_NONE ?
8478
                                     ",trans=none" : "");
8479
                }
8480
                break;
8481
            case QEMU_OPTION_nographic:
8482
                nographic = 1;
8483
                break;
8484
#ifdef CONFIG_CURSES
8485
            case QEMU_OPTION_curses:
8486
                curses = 1;
8487
                break;
8488
#endif
8489
            case QEMU_OPTION_portrait:
8490
                graphic_rotate = 1;
8491
                break;
8492
            case QEMU_OPTION_kernel:
8493
                kernel_filename = optarg;
8494
                break;
8495
            case QEMU_OPTION_append:
8496
                kernel_cmdline = optarg;
8497
                break;
8498
            case QEMU_OPTION_cdrom:
8499
                drive_add(optarg, CDROM_ALIAS);
8500
                break;
8501
            case QEMU_OPTION_boot:
8502
                boot_devices = optarg;
8503
                /* We just do some generic consistency checks */
8504
                {
8505
                    /* Could easily be extended to 64 devices if needed */
8506
                    const char *p;
8507
                    
8508
                    boot_devices_bitmap = 0;
8509
                    for (p = boot_devices; *p != '\0'; p++) {
8510
                        /* Allowed boot devices are:
8511
                         * a b     : floppy disk drives
8512
                         * c ... f : IDE disk drives
8513
                         * g ... m : machine implementation dependant drives
8514
                         * n ... p : network devices
8515
                         * It's up to each machine implementation to check
8516
                         * if the given boot devices match the actual hardware
8517
                         * implementation and firmware features.
8518
                         */
8519
                        if (*p < 'a' || *p > 'q') {
8520
                            fprintf(stderr, "Invalid boot device '%c'\n", *p);
8521
                            exit(1);
8522
                        }
8523
                        if (boot_devices_bitmap & (1 << (*p - 'a'))) {
8524
                            fprintf(stderr,
8525
                                    "Boot device '%c' was given twice\n",*p);
8526
                            exit(1);
8527
                        }
8528
                        boot_devices_bitmap |= 1 << (*p - 'a');
8529
                    }
8530
                }
8531
                break;
8532
            case QEMU_OPTION_fda:
8533
            case QEMU_OPTION_fdb:
8534
                drive_add(optarg, FD_ALIAS, popt->index - QEMU_OPTION_fda);
8535
                break;
8536
#ifdef TARGET_I386
8537
            case QEMU_OPTION_no_fd_bootchk:
8538
                fd_bootchk = 0;
8539
                break;
8540
#endif
8541
            case QEMU_OPTION_net:
8542
                if (nb_net_clients >= MAX_NET_CLIENTS) {
8543
                    fprintf(stderr, "qemu: too many network clients\n");
8544
                    exit(1);
8545
                }
8546
                net_clients[nb_net_clients] = optarg;
8547
                nb_net_clients++;
8548
                break;
8549
#ifdef CONFIG_SLIRP
8550
            case QEMU_OPTION_tftp:
8551
                tftp_prefix = optarg;
8552
                break;
8553
            case QEMU_OPTION_bootp:
8554
                bootp_filename = optarg;
8555
                break;
8556
#ifndef _WIN32
8557
            case QEMU_OPTION_smb:
8558
                net_slirp_smb(optarg);
8559
                break;
8560
#endif
8561
            case QEMU_OPTION_redir:
8562
                net_slirp_redir(optarg);
8563
                break;
8564
#endif
8565
#ifdef HAS_AUDIO
8566
            case QEMU_OPTION_audio_help:
8567
                AUD_help ();
8568
                exit (0);
8569
                break;
8570
            case QEMU_OPTION_soundhw:
8571
                select_soundhw (optarg);
8572
                break;
8573
#endif
8574
            case QEMU_OPTION_h:
8575
                help(0);
8576
                break;
8577
            case QEMU_OPTION_m: {
8578
                uint64_t value;
8579
                char *ptr;
8580

    
8581
                value = strtoul(optarg, &ptr, 10);
8582
                switch (*ptr) {
8583
                case 0: case 'M': case 'm':
8584
                    value <<= 20;
8585
                    break;
8586
                case 'G': case 'g':
8587
                    value <<= 30;
8588
                    break;
8589
                default:
8590
                    fprintf(stderr, "qemu: invalid ram size: %s\n", optarg);
8591
                    exit(1);
8592
                }
8593

    
8594
                /* On 32-bit hosts, QEMU is limited by virtual address space */
8595
                if (value > (2047 << 20)
8596
#ifndef USE_KQEMU
8597
                    && HOST_LONG_BITS == 32
8598
#endif
8599
                    ) {
8600
                    fprintf(stderr, "qemu: at most 2047 MB RAM can be simulated\n");
8601
                    exit(1);
8602
                }
8603
                if (value != (uint64_t)(ram_addr_t)value) {
8604
                    fprintf(stderr, "qemu: ram size too large\n");
8605
                    exit(1);
8606
                }
8607
                ram_size = value;
8608
                break;
8609
            }
8610
            case QEMU_OPTION_d:
8611
                {
8612
                    int mask;
8613
                    CPULogItem *item;
8614

    
8615
                    mask = cpu_str_to_log_mask(optarg);
8616
                    if (!mask) {
8617
                        printf("Log items (comma separated):\n");
8618
                    for(item = cpu_log_items; item->mask != 0; item++) {
8619
                        printf("%-10s %s\n", item->name, item->help);
8620
                    }
8621
                    exit(1);
8622
                    }
8623
                    cpu_set_log(mask);
8624
                }
8625
                break;
8626
#ifdef CONFIG_GDBSTUB
8627
            case QEMU_OPTION_s:
8628
                use_gdbstub = 1;
8629
                break;
8630
            case QEMU_OPTION_p:
8631
                gdbstub_port = optarg;
8632
                break;
8633
#endif
8634
            case QEMU_OPTION_L:
8635
                bios_dir = optarg;
8636
                break;
8637
            case QEMU_OPTION_bios:
8638
                bios_name = optarg;
8639
                break;
8640
            case QEMU_OPTION_S:
8641
                autostart = 0;
8642
                break;
8643
            case QEMU_OPTION_k:
8644
                keyboard_layout = optarg;
8645
                break;
8646
            case QEMU_OPTION_localtime:
8647
                rtc_utc = 0;
8648
                break;
8649
            case QEMU_OPTION_cirrusvga:
8650
                cirrus_vga_enabled = 1;
8651
                vmsvga_enabled = 0;
8652
                break;
8653
            case QEMU_OPTION_vmsvga:
8654
                cirrus_vga_enabled = 0;
8655
                vmsvga_enabled = 1;
8656
                break;
8657
            case QEMU_OPTION_std_vga:
8658
                cirrus_vga_enabled = 0;
8659
                vmsvga_enabled = 0;
8660
                break;
8661
            case QEMU_OPTION_g:
8662
                {
8663
                    const char *p;
8664
                    int w, h, depth;
8665
                    p = optarg;
8666
                    w = strtol(p, (char **)&p, 10);
8667
                    if (w <= 0) {
8668
                    graphic_error:
8669
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
8670
                        exit(1);
8671
                    }
8672
                    if (*p != 'x')
8673
                        goto graphic_error;
8674
                    p++;
8675
                    h = strtol(p, (char **)&p, 10);
8676
                    if (h <= 0)
8677
                        goto graphic_error;
8678
                    if (*p == 'x') {
8679
                        p++;
8680
                        depth = strtol(p, (char **)&p, 10);
8681
                        if (depth != 8 && depth != 15 && depth != 16 &&
8682
                            depth != 24 && depth != 32)
8683
                            goto graphic_error;
8684
                    } else if (*p == '\0') {
8685
                        depth = graphic_depth;
8686
                    } else {
8687
                        goto graphic_error;
8688
                    }
8689

    
8690
                    graphic_width = w;
8691
                    graphic_height = h;
8692
                    graphic_depth = depth;
8693
                }
8694
                break;
8695
            case QEMU_OPTION_echr:
8696
                {
8697
                    char *r;
8698
                    term_escape_char = strtol(optarg, &r, 0);
8699
                    if (r == optarg)
8700
                        printf("Bad argument to echr\n");
8701
                    break;
8702
                }
8703
            case QEMU_OPTION_monitor:
8704
                monitor_device = optarg;
8705
                break;
8706
            case QEMU_OPTION_serial:
8707
                if (serial_device_index >= MAX_SERIAL_PORTS) {
8708
                    fprintf(stderr, "qemu: too many serial ports\n");
8709
                    exit(1);
8710
                }
8711
                serial_devices[serial_device_index] = optarg;
8712
                serial_device_index++;
8713
                break;
8714
            case QEMU_OPTION_parallel:
8715
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
8716
                    fprintf(stderr, "qemu: too many parallel ports\n");
8717
                    exit(1);
8718
                }
8719
                parallel_devices[parallel_device_index] = optarg;
8720
                parallel_device_index++;
8721
                break;
8722
            case QEMU_OPTION_loadvm:
8723
                loadvm = optarg;
8724
                break;
8725
            case QEMU_OPTION_full_screen:
8726
                full_screen = 1;
8727
                break;
8728
#ifdef CONFIG_SDL
8729
            case QEMU_OPTION_no_frame:
8730
                no_frame = 1;
8731
                break;
8732
            case QEMU_OPTION_alt_grab:
8733
                alt_grab = 1;
8734
                break;
8735
            case QEMU_OPTION_no_quit:
8736
                no_quit = 1;
8737
                break;
8738
#endif
8739
            case QEMU_OPTION_pidfile:
8740
                pid_file = optarg;
8741
                break;
8742
#ifdef TARGET_I386
8743
            case QEMU_OPTION_win2k_hack:
8744
                win2k_install_hack = 1;
8745
                break;
8746
#endif
8747
#ifdef USE_KQEMU
8748
            case QEMU_OPTION_no_kqemu:
8749
                kqemu_allowed = 0;
8750
                break;
8751
            case QEMU_OPTION_kernel_kqemu:
8752
                kqemu_allowed = 2;
8753
                break;
8754
#endif
8755
            case QEMU_OPTION_usb:
8756
                usb_enabled = 1;
8757
                break;
8758
            case QEMU_OPTION_usbdevice:
8759
                usb_enabled = 1;
8760
                if (usb_devices_index >= MAX_USB_CMDLINE) {
8761
                    fprintf(stderr, "Too many USB devices\n");
8762
                    exit(1);
8763
                }
8764
                usb_devices[usb_devices_index] = optarg;
8765
                usb_devices_index++;
8766
                break;
8767
            case QEMU_OPTION_smp:
8768
                smp_cpus = atoi(optarg);
8769
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
8770
                    fprintf(stderr, "Invalid number of CPUs\n");
8771
                    exit(1);
8772
                }
8773
                break;
8774
            case QEMU_OPTION_vnc:
8775
                vnc_display = optarg;
8776
                break;
8777
            case QEMU_OPTION_no_acpi:
8778
                acpi_enabled = 0;
8779
                break;
8780
            case QEMU_OPTION_no_reboot:
8781
                no_reboot = 1;
8782
                break;
8783
            case QEMU_OPTION_no_shutdown:
8784
                no_shutdown = 1;
8785
                break;
8786
            case QEMU_OPTION_show_cursor:
8787
                cursor_hide = 0;
8788
                break;
8789
            case QEMU_OPTION_daemonize:
8790
                daemonize = 1;
8791
                break;
8792
            case QEMU_OPTION_option_rom:
8793
                if (nb_option_roms >= MAX_OPTION_ROMS) {
8794
                    fprintf(stderr, "Too many option ROMs\n");
8795
                    exit(1);
8796
                }
8797
                option_rom[nb_option_roms] = optarg;
8798
                nb_option_roms++;
8799
                break;
8800
            case QEMU_OPTION_semihosting:
8801
                semihosting_enabled = 1;
8802
                break;
8803
            case QEMU_OPTION_name:
8804
                qemu_name = optarg;
8805
                break;
8806
#ifdef TARGET_SPARC
8807
            case QEMU_OPTION_prom_env:
8808
                if (nb_prom_envs >= MAX_PROM_ENVS) {
8809
                    fprintf(stderr, "Too many prom variables\n");
8810
                    exit(1);
8811
                }
8812
                prom_envs[nb_prom_envs] = optarg;
8813
                nb_prom_envs++;
8814
                break;
8815
#endif
8816
#ifdef TARGET_ARM
8817
            case QEMU_OPTION_old_param:
8818
                old_param = 1;
8819
                break;
8820
#endif
8821
            case QEMU_OPTION_clock:
8822
                configure_alarms(optarg);
8823
                break;
8824
            case QEMU_OPTION_startdate:
8825
                {
8826
                    struct tm tm;
8827
                    time_t rtc_start_date;
8828
                    if (!strcmp(optarg, "now")) {
8829
                        rtc_date_offset = -1;
8830
                    } else {
8831
                        if (sscanf(optarg, "%d-%d-%dT%d:%d:%d",
8832
                               &tm.tm_year,
8833
                               &tm.tm_mon,
8834
                               &tm.tm_mday,
8835
                               &tm.tm_hour,
8836
                               &tm.tm_min,
8837
                               &tm.tm_sec) == 6) {
8838
                            /* OK */
8839
                        } else if (sscanf(optarg, "%d-%d-%d",
8840
                                          &tm.tm_year,
8841
                                          &tm.tm_mon,
8842
                                          &tm.tm_mday) == 3) {
8843
                            tm.tm_hour = 0;
8844
                            tm.tm_min = 0;
8845
                            tm.tm_sec = 0;
8846
                        } else {
8847
                            goto date_fail;
8848
                        }
8849
                        tm.tm_year -= 1900;
8850
                        tm.tm_mon--;
8851
                        rtc_start_date = mktimegm(&tm);
8852
                        if (rtc_start_date == -1) {
8853
                        date_fail:
8854
                            fprintf(stderr, "Invalid date format. Valid format are:\n"
8855
                                    "'now' or '2006-06-17T16:01:21' or '2006-06-17'\n");
8856
                            exit(1);
8857
                        }
8858
                        rtc_date_offset = time(NULL) - rtc_start_date;
8859
                    }
8860
                }
8861
                break;
8862
            case QEMU_OPTION_tb_size:
8863
                tb_size = strtol(optarg, NULL, 0);
8864
                if (tb_size < 0)
8865
                    tb_size = 0;
8866
                break;
8867
            case QEMU_OPTION_icount:
8868
                use_icount = 1;
8869
                if (strcmp(optarg, "auto") == 0) {
8870
                    icount_time_shift = -1;
8871
                } else {
8872
                    icount_time_shift = strtol(optarg, NULL, 0);
8873
                }
8874
                break;
8875
            }
8876
        }
8877
    }
8878

    
8879
    if (nographic) {
8880
       if (serial_device_index == 0)
8881
           serial_devices[0] = "stdio";
8882
       if (parallel_device_index == 0)
8883
           parallel_devices[0] = "null";
8884
       if (strncmp(monitor_device, "vc", 2) == 0)
8885
           monitor_device = "stdio";
8886
    }
8887

    
8888
#ifndef _WIN32
8889
    if (daemonize) {
8890
        pid_t pid;
8891

    
8892
        if (pipe(fds) == -1)
8893
            exit(1);
8894

    
8895
        pid = fork();
8896
        if (pid > 0) {
8897
            uint8_t status;
8898
            ssize_t len;
8899

    
8900
            close(fds[1]);
8901

    
8902
        again:
8903
            len = read(fds[0], &status, 1);
8904
            if (len == -1 && (errno == EINTR))
8905
                goto again;
8906

    
8907
            if (len != 1)
8908
                exit(1);
8909
            else if (status == 1) {
8910
                fprintf(stderr, "Could not acquire pidfile\n");
8911
                exit(1);
8912
            } else
8913
                exit(0);
8914
        } else if (pid < 0)
8915
            exit(1);
8916

    
8917
        setsid();
8918

    
8919
        pid = fork();
8920
        if (pid > 0)
8921
            exit(0);
8922
        else if (pid < 0)
8923
            exit(1);
8924

    
8925
        umask(027);
8926

    
8927
        signal(SIGTSTP, SIG_IGN);
8928
        signal(SIGTTOU, SIG_IGN);
8929
        signal(SIGTTIN, SIG_IGN);
8930
    }
8931
#endif
8932

    
8933
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
8934
        if (daemonize) {
8935
            uint8_t status = 1;
8936
            write(fds[1], &status, 1);
8937
        } else
8938
            fprintf(stderr, "Could not acquire pid file\n");
8939
        exit(1);
8940
    }
8941

    
8942
#ifdef USE_KQEMU
8943
    if (smp_cpus > 1)
8944
        kqemu_allowed = 0;
8945
#endif
8946
    linux_boot = (kernel_filename != NULL);
8947
    net_boot = (boot_devices_bitmap >> ('n' - 'a')) & 0xF;
8948

    
8949
    if (!linux_boot && net_boot == 0 &&
8950
        !machine->nodisk_ok && nb_drives_opt == 0)
8951
        help(1);
8952

    
8953
    if (!linux_boot && *kernel_cmdline != '\0') {
8954
        fprintf(stderr, "-append only allowed with -kernel option\n");
8955
        exit(1);
8956
    }
8957

    
8958
    if (!linux_boot && initrd_filename != NULL) {
8959
        fprintf(stderr, "-initrd only allowed with -kernel option\n");
8960
        exit(1);
8961
    }
8962

    
8963
    /* boot to floppy or the default cd if no hard disk defined yet */
8964
    if (!boot_devices[0]) {
8965
        boot_devices = "cad";
8966
    }
8967
    setvbuf(stdout, NULL, _IOLBF, 0);
8968

    
8969
    init_timers();
8970
    init_timer_alarm();
8971
    qemu_aio_init();
8972
    if (use_icount && icount_time_shift < 0) {
8973
        use_icount = 2;
8974
        /* 125MIPS seems a reasonable initial guess at the guest speed.
8975
           It will be corrected fairly quickly anyway.  */
8976
        icount_time_shift = 3;
8977
        init_icount_adjust();
8978
    }
8979

    
8980
#ifdef _WIN32
8981
    socket_init();
8982
#endif
8983

    
8984
    /* init network clients */
8985
    if (nb_net_clients == 0) {
8986
        /* if no clients, we use a default config */
8987
        net_clients[nb_net_clients++] = "nic";
8988
#ifdef CONFIG_SLIRP
8989
        net_clients[nb_net_clients++] = "user";
8990
#endif
8991
    }
8992

    
8993
    for(i = 0;i < nb_net_clients; i++) {
8994
        if (net_client_parse(net_clients[i]) < 0)
8995
            exit(1);
8996
    }
8997
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
8998
        if (vlan->nb_guest_devs == 0 && vlan->nb_host_devs == 0)
8999
            continue;
9000
        if (vlan->nb_guest_devs == 0)
9001
            fprintf(stderr, "Warning: vlan %d with no nics\n", vlan->id);
9002
        if (vlan->nb_host_devs == 0)
9003
            fprintf(stderr,
9004
                    "Warning: vlan %d is not connected to host network\n",
9005
                    vlan->id);
9006
    }
9007

    
9008
#ifdef TARGET_I386
9009
    /* XXX: this should be moved in the PC machine instantiation code */
9010
    if (net_boot != 0) {
9011
        int netroms = 0;
9012
        for (i = 0; i < nb_nics && i < 4; i++) {
9013
            const char *model = nd_table[i].model;
9014
            char buf[1024];
9015
            if (net_boot & (1 << i)) {
9016
                if (model == NULL)
9017
                    model = "ne2k_pci";
9018
                snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
9019
                if (get_image_size(buf) > 0) {
9020
                    if (nb_option_roms >= MAX_OPTION_ROMS) {
9021
                        fprintf(stderr, "Too many option ROMs\n");
9022
                        exit(1);
9023
                    }
9024
                    option_rom[nb_option_roms] = strdup(buf);
9025
                    nb_option_roms++;
9026
                    netroms++;
9027
                }
9028
            }
9029
        }
9030
        if (netroms == 0) {
9031
            fprintf(stderr, "No valid PXE rom found for network device\n");
9032
            exit(1);
9033
        }
9034
    }
9035
#endif
9036

    
9037
    /* init the memory */
9038
    phys_ram_size = machine->ram_require & ~RAMSIZE_FIXED;
9039

    
9040
    if (machine->ram_require & RAMSIZE_FIXED) {
9041
        if (ram_size > 0) {
9042
            if (ram_size < phys_ram_size) {
9043
                fprintf(stderr, "Machine `%s' requires %llu bytes of memory\n",
9044
                                machine->name, (unsigned long long) phys_ram_size);
9045
                exit(-1);
9046
            }
9047

    
9048
            phys_ram_size = ram_size;
9049
        } else
9050
            ram_size = phys_ram_size;
9051
    } else {
9052
        if (ram_size == 0)
9053
            ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
9054

    
9055
        phys_ram_size += ram_size;
9056
    }
9057

    
9058
    phys_ram_base = qemu_vmalloc(phys_ram_size);
9059
    if (!phys_ram_base) {
9060
        fprintf(stderr, "Could not allocate physical memory\n");
9061
        exit(1);
9062
    }
9063

    
9064
    /* init the dynamic translator */
9065
    cpu_exec_init_all(tb_size * 1024 * 1024);
9066

    
9067
    bdrv_init();
9068

    
9069
    /* we always create the cdrom drive, even if no disk is there */
9070

    
9071
    if (nb_drives_opt < MAX_DRIVES)
9072
        drive_add(NULL, CDROM_ALIAS);
9073

    
9074
    /* we always create at least one floppy */
9075

    
9076
    if (nb_drives_opt < MAX_DRIVES)
9077
        drive_add(NULL, FD_ALIAS, 0);
9078

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

    
9081
    if (nb_drives_opt < MAX_DRIVES)
9082
        drive_add(NULL, SD_ALIAS);
9083

    
9084
    /* open the virtual block devices */
9085

    
9086
    for(i = 0; i < nb_drives_opt; i++)
9087
        if (drive_init(&drives_opt[i], snapshot, machine) == -1)
9088
            exit(1);
9089

    
9090
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
9091
    register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
9092

    
9093
    /* terminal init */
9094
    memset(&display_state, 0, sizeof(display_state));
9095
    if (nographic) {
9096
        if (curses) {
9097
            fprintf(stderr, "fatal: -nographic can't be used with -curses\n");
9098
            exit(1);
9099
        }
9100
        /* nearly nothing to do */
9101
        dumb_display_init(ds);
9102
    } else if (vnc_display != NULL) {
9103
        vnc_display_init(ds);
9104
        if (vnc_display_open(ds, vnc_display) < 0)
9105
            exit(1);
9106
    } else
9107
#if defined(CONFIG_CURSES)
9108
    if (curses) {
9109
        curses_display_init(ds, full_screen);
9110
    } else
9111
#endif
9112
    {
9113
#if defined(CONFIG_SDL)
9114
        sdl_display_init(ds, full_screen, no_frame);
9115
#elif defined(CONFIG_COCOA)
9116
        cocoa_display_init(ds, full_screen);
9117
#else
9118
        dumb_display_init(ds);
9119
#endif
9120
    }
9121

    
9122
#ifndef _WIN32
9123
    /* must be after terminal init, SDL library changes signal handlers */
9124
    termsig_setup();
9125
#endif
9126

    
9127
    /* Maintain compatibility with multiple stdio monitors */
9128
    if (!strcmp(monitor_device,"stdio")) {
9129
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
9130
            const char *devname = serial_devices[i];
9131
            if (devname && !strcmp(devname,"mon:stdio")) {
9132
                monitor_device = NULL;
9133
                break;
9134
            } else if (devname && !strcmp(devname,"stdio")) {
9135
                monitor_device = NULL;
9136
                serial_devices[i] = "mon:stdio";
9137
                break;
9138
            }
9139
        }
9140
    }
9141
    if (monitor_device) {
9142
        monitor_hd = qemu_chr_open(monitor_device);
9143
        if (!monitor_hd) {
9144
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
9145
            exit(1);
9146
        }
9147
        monitor_init(monitor_hd, !nographic);
9148
    }
9149

    
9150
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
9151
        const char *devname = serial_devices[i];
9152
        if (devname && strcmp(devname, "none")) {
9153
            serial_hds[i] = qemu_chr_open(devname);
9154
            if (!serial_hds[i]) {
9155
                fprintf(stderr, "qemu: could not open serial device '%s'\n",
9156
                        devname);
9157
                exit(1);
9158
            }
9159
            if (strstart(devname, "vc", 0))
9160
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
9161
        }
9162
    }
9163

    
9164
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
9165
        const char *devname = parallel_devices[i];
9166
        if (devname && strcmp(devname, "none")) {
9167
            parallel_hds[i] = qemu_chr_open(devname);
9168
            if (!parallel_hds[i]) {
9169
                fprintf(stderr, "qemu: could not open parallel device '%s'\n",
9170
                        devname);
9171
                exit(1);
9172
            }
9173
            if (strstart(devname, "vc", 0))
9174
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
9175
        }
9176
    }
9177

    
9178
    machine->init(ram_size, vga_ram_size, boot_devices, ds,
9179
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
9180

    
9181
    /* init USB devices */
9182
    if (usb_enabled) {
9183
        for(i = 0; i < usb_devices_index; i++) {
9184
            if (usb_device_add(usb_devices[i]) < 0) {
9185
                fprintf(stderr, "Warning: could not add USB device %s\n",
9186
                        usb_devices[i]);
9187
            }
9188
        }
9189
    }
9190

    
9191
    if (display_state.dpy_refresh) {
9192
        display_state.gui_timer = qemu_new_timer(rt_clock, gui_update, &display_state);
9193
        qemu_mod_timer(display_state.gui_timer, qemu_get_clock(rt_clock));
9194
    }
9195

    
9196
#ifdef CONFIG_GDBSTUB
9197
    if (use_gdbstub) {
9198
        /* XXX: use standard host:port notation and modify options
9199
           accordingly. */
9200
        if (gdbserver_start(gdbstub_port) < 0) {
9201
            fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
9202
                    gdbstub_port);
9203
            exit(1);
9204
        }
9205
    }
9206
#endif
9207

    
9208
    if (loadvm)
9209
        do_loadvm(loadvm);
9210

    
9211
    {
9212
        /* XXX: simplify init */
9213
        read_passwords();
9214
        if (autostart) {
9215
            vm_start();
9216
        }
9217
    }
9218

    
9219
    if (daemonize) {
9220
        uint8_t status = 0;
9221
        ssize_t len;
9222
        int fd;
9223

    
9224
    again1:
9225
        len = write(fds[1], &status, 1);
9226
        if (len == -1 && (errno == EINTR))
9227
            goto again1;
9228

    
9229
        if (len != 1)
9230
            exit(1);
9231

    
9232
        chdir("/");
9233
        TFR(fd = open("/dev/null", O_RDWR));
9234
        if (fd == -1)
9235
            exit(1);
9236

    
9237
        dup2(fd, 0);
9238
        dup2(fd, 1);
9239
        dup2(fd, 2);
9240

    
9241
        close(fd);
9242
    }
9243

    
9244
    main_loop();
9245
    quit_timers();
9246

    
9247
#if !defined(_WIN32)
9248
    /* close network clients */
9249
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
9250
        VLANClientState *vc;
9251

    
9252
        for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
9253
            if (vc->fd_read == tap_receive) {
9254
                char ifname[64];
9255
                TAPState *s = vc->opaque;
9256

    
9257
                if (sscanf(vc->info_str, "tap: ifname=%63s ", ifname) == 1 &&
9258
                    s->down_script[0])
9259
                    launch_script(s->down_script, ifname, s->fd);
9260
            }
9261
#if defined(CONFIG_VDE)
9262
            if (vc->fd_read == vde_from_qemu) {
9263
                VDEState *s = vc->opaque;
9264
                vde_close(s->vde);
9265
            }
9266
#endif
9267
        }
9268
    }
9269
#endif
9270
    return 0;
9271
}