Statistics
| Branch: | Revision:

root / vl.c @ e6b1e558

History | View | Annotate | Download (196.7 kB)

1
/*
2
 * QEMU System Emulator
3
 * 
4
 * Copyright (c) 2003-2007 Fabrice Bellard
5
 * 
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in
14
 * all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
 * THE SOFTWARE.
23
 */
24
#include "vl.h"
25

    
26
#include <unistd.h>
27
#include <fcntl.h>
28
#include <signal.h>
29
#include <time.h>
30
#include <errno.h>
31
#include <sys/time.h>
32
#include <zlib.h>
33

    
34
#ifndef _WIN32
35
#include <sys/times.h>
36
#include <sys/wait.h>
37
#include <termios.h>
38
#include <sys/poll.h>
39
#include <sys/mman.h>
40
#include <sys/ioctl.h>
41
#include <sys/socket.h>
42
#include <netinet/in.h>
43
#include <dirent.h>
44
#include <netdb.h>
45
#ifdef _BSD
46
#include <sys/stat.h>
47
#ifndef __APPLE__
48
#include <libutil.h>
49
#endif
50
#else
51
#ifndef __sun__
52
#include <linux/if.h>
53
#include <linux/if_tun.h>
54
#include <pty.h>
55
#include <malloc.h>
56
#include <linux/rtc.h>
57
#include <linux/ppdev.h>
58
#include <linux/parport.h>
59
#else
60
#include <sys/stat.h>
61
#include <sys/ethernet.h>
62
#include <sys/sockio.h>
63
#include <arpa/inet.h>
64
#include <netinet/arp.h>
65
#include <netinet/in.h>
66
#include <netinet/in_systm.h>
67
#include <netinet/ip.h>
68
#include <netinet/ip_icmp.h> // must come after ip.h
69
#include <netinet/udp.h>
70
#include <netinet/tcp.h>
71
#include <net/if.h>
72
#include <syslog.h>
73
#include <stropts.h>
74
#endif
75
#endif
76
#endif
77

    
78
#if defined(CONFIG_SLIRP)
79
#include "libslirp.h"
80
#endif
81

    
82
#ifdef _WIN32
83
#include <malloc.h>
84
#include <sys/timeb.h>
85
#include <windows.h>
86
#define getopt_long_only getopt_long
87
#define memalign(align, size) malloc(size)
88
#endif
89

    
90
#include "qemu_socket.h"
91

    
92
#ifdef CONFIG_SDL
93
#ifdef __APPLE__
94
#include <SDL/SDL.h>
95
#endif
96
#endif /* CONFIG_SDL */
97

    
98
#ifdef CONFIG_COCOA
99
#undef main
100
#define main qemu_main
101
#endif /* CONFIG_COCOA */
102

    
103
#include "disas.h"
104

    
105
#include "exec-all.h"
106

    
107
#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
108
#ifdef __sun__
109
#define SMBD_COMMAND "/usr/sfw/sbin/smbd"
110
#else
111
#define SMBD_COMMAND "/usr/sbin/smbd"
112
#endif
113

    
114
//#define DEBUG_UNUSED_IOPORT
115
//#define DEBUG_IOPORT
116

    
117
#define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
118

    
119
#ifdef TARGET_PPC
120
#define DEFAULT_RAM_SIZE 144
121
#else
122
#define DEFAULT_RAM_SIZE 128
123
#endif
124
/* in ms */
125
#define GUI_REFRESH_INTERVAL 30
126

    
127
/* Max number of USB devices that can be specified on the commandline.  */
128
#define MAX_USB_CMDLINE 8
129

    
130
/* XXX: use a two level table to limit memory usage */
131
#define MAX_IOPORTS 65536
132

    
133
const char *bios_dir = CONFIG_QEMU_SHAREDIR;
134
char phys_ram_file[1024];
135
void *ioport_opaque[MAX_IOPORTS];
136
IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
137
IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
138
/* Note: bs_table[MAX_DISKS] is a dummy block driver if none available
139
   to store the VM snapshots */
140
BlockDriverState *bs_table[MAX_DISKS + 1], *fd_table[MAX_FD];
141
BlockDriverState *sd_bdrv;
142
/* point to the block driver where the snapshots are managed */
143
BlockDriverState *bs_snapshots;
144
int vga_ram_size;
145
static DisplayState display_state;
146
int nographic;
147
const char* keyboard_layout = NULL;
148
int64_t ticks_per_sec;
149
int boot_device = 'c';
150
int ram_size;
151
int pit_min_timer_count = 0;
152
int nb_nics;
153
NICInfo nd_table[MAX_NICS];
154
QEMUTimer *gui_timer;
155
int vm_running;
156
int rtc_utc = 1;
157
int cirrus_vga_enabled = 1;
158
int vmsvga_enabled = 0;
159
#ifdef TARGET_SPARC
160
int graphic_width = 1024;
161
int graphic_height = 768;
162
#else
163
int graphic_width = 800;
164
int graphic_height = 600;
165
#endif
166
int graphic_depth = 15;
167
int full_screen = 0;
168
int no_frame = 0;
169
int no_quit = 0;
170
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
171
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
172
#ifdef TARGET_I386
173
int win2k_install_hack = 0;
174
#endif
175
int usb_enabled = 0;
176
static VLANState *first_vlan;
177
int smp_cpus = 1;
178
const char *vnc_display;
179
#if defined(TARGET_SPARC)
180
#define MAX_CPUS 16
181
#elif defined(TARGET_I386)
182
#define MAX_CPUS 255
183
#else
184
#define MAX_CPUS 1
185
#endif
186
int acpi_enabled = 1;
187
int fd_bootchk = 1;
188
int no_reboot = 0;
189
int daemonize = 0;
190
const char *option_rom[MAX_OPTION_ROMS];
191
int nb_option_roms;
192
int semihosting_enabled = 0;
193
int autostart = 1;
194
const char *qemu_name;
195

    
196
/***********************************************************/
197
/* x86 ISA bus support */
198

    
199
target_phys_addr_t isa_mem_base = 0;
200
PicState2 *isa_pic;
201

    
202
uint32_t default_ioport_readb(void *opaque, uint32_t address)
203
{
204
#ifdef DEBUG_UNUSED_IOPORT
205
    fprintf(stderr, "unused inb: port=0x%04x\n", address);
206
#endif
207
    return 0xff;
208
}
209

    
210
void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
211
{
212
#ifdef DEBUG_UNUSED_IOPORT
213
    fprintf(stderr, "unused outb: port=0x%04x data=0x%02x\n", address, data);
214
#endif
215
}
216

    
217
/* default is to make two byte accesses */
218
uint32_t default_ioport_readw(void *opaque, uint32_t address)
219
{
220
    uint32_t data;
221
    data = ioport_read_table[0][address](ioport_opaque[address], address);
222
    address = (address + 1) & (MAX_IOPORTS - 1);
223
    data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
224
    return data;
225
}
226

    
227
void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
228
{
229
    ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
230
    address = (address + 1) & (MAX_IOPORTS - 1);
231
    ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
232
}
233

    
234
uint32_t default_ioport_readl(void *opaque, uint32_t address)
235
{
236
#ifdef DEBUG_UNUSED_IOPORT
237
    fprintf(stderr, "unused inl: port=0x%04x\n", address);
238
#endif
239
    return 0xffffffff;
240
}
241

    
242
void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
243
{
244
#ifdef DEBUG_UNUSED_IOPORT
245
    fprintf(stderr, "unused outl: port=0x%04x data=0x%02x\n", address, data);
246
#endif
247
}
248

    
249
void init_ioports(void)
250
{
251
    int i;
252

    
253
    for(i = 0; i < MAX_IOPORTS; i++) {
254
        ioport_read_table[0][i] = default_ioport_readb;
255
        ioport_write_table[0][i] = default_ioport_writeb;
256
        ioport_read_table[1][i] = default_ioport_readw;
257
        ioport_write_table[1][i] = default_ioport_writew;
258
        ioport_read_table[2][i] = default_ioport_readl;
259
        ioport_write_table[2][i] = default_ioport_writel;
260
    }
261
}
262

    
263
/* size is the word size in byte */
264
int register_ioport_read(int start, int length, int size, 
265
                         IOPortReadFunc *func, void *opaque)
266
{
267
    int i, bsize;
268

    
269
    if (size == 1) {
270
        bsize = 0;
271
    } else if (size == 2) {
272
        bsize = 1;
273
    } else if (size == 4) {
274
        bsize = 2;
275
    } else {
276
        hw_error("register_ioport_read: invalid size");
277
        return -1;
278
    }
279
    for(i = start; i < start + length; i += size) {
280
        ioport_read_table[bsize][i] = func;
281
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
282
            hw_error("register_ioport_read: invalid opaque");
283
        ioport_opaque[i] = opaque;
284
    }
285
    return 0;
286
}
287

    
288
/* size is the word size in byte */
289
int register_ioport_write(int start, int length, int size, 
290
                          IOPortWriteFunc *func, void *opaque)
291
{
292
    int i, bsize;
293

    
294
    if (size == 1) {
295
        bsize = 0;
296
    } else if (size == 2) {
297
        bsize = 1;
298
    } else if (size == 4) {
299
        bsize = 2;
300
    } else {
301
        hw_error("register_ioport_write: invalid size");
302
        return -1;
303
    }
304
    for(i = start; i < start + length; i += size) {
305
        ioport_write_table[bsize][i] = func;
306
        if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
307
            hw_error("register_ioport_write: invalid opaque");
308
        ioport_opaque[i] = opaque;
309
    }
310
    return 0;
311
}
312

    
313
void isa_unassign_ioport(int start, int length)
314
{
315
    int i;
316

    
317
    for(i = start; i < start + length; i++) {
318
        ioport_read_table[0][i] = default_ioport_readb;
319
        ioport_read_table[1][i] = default_ioport_readw;
320
        ioport_read_table[2][i] = default_ioport_readl;
321

    
322
        ioport_write_table[0][i] = default_ioport_writeb;
323
        ioport_write_table[1][i] = default_ioport_writew;
324
        ioport_write_table[2][i] = default_ioport_writel;
325
    }
326
}
327

    
328
/***********************************************************/
329

    
330
void cpu_outb(CPUState *env, int addr, int val)
331
{
332
#ifdef DEBUG_IOPORT
333
    if (loglevel & CPU_LOG_IOPORT)
334
        fprintf(logfile, "outb: %04x %02x\n", addr, val);
335
#endif    
336
    ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
337
#ifdef USE_KQEMU
338
    if (env)
339
        env->last_io_time = cpu_get_time_fast();
340
#endif
341
}
342

    
343
void cpu_outw(CPUState *env, int addr, int val)
344
{
345
#ifdef DEBUG_IOPORT
346
    if (loglevel & CPU_LOG_IOPORT)
347
        fprintf(logfile, "outw: %04x %04x\n", addr, val);
348
#endif    
349
    ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
350
#ifdef USE_KQEMU
351
    if (env)
352
        env->last_io_time = cpu_get_time_fast();
353
#endif
354
}
355

    
356
void cpu_outl(CPUState *env, int addr, int val)
357
{
358
#ifdef DEBUG_IOPORT
359
    if (loglevel & CPU_LOG_IOPORT)
360
        fprintf(logfile, "outl: %04x %08x\n", addr, val);
361
#endif
362
    ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
363
#ifdef USE_KQEMU
364
    if (env)
365
        env->last_io_time = cpu_get_time_fast();
366
#endif
367
}
368

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

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

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

    
414
/***********************************************************/
415
void hw_error(const char *fmt, ...)
416
{
417
    va_list ap;
418
    CPUState *env;
419

    
420
    va_start(ap, fmt);
421
    fprintf(stderr, "qemu: hardware error: ");
422
    vfprintf(stderr, fmt, ap);
423
    fprintf(stderr, "\n");
424
    for(env = first_cpu; env != NULL; env = env->next_cpu) {
425
        fprintf(stderr, "CPU #%d:\n", env->cpu_index);
426
#ifdef TARGET_I386
427
        cpu_dump_state(env, stderr, fprintf, X86_DUMP_FPU);
428
#else
429
        cpu_dump_state(env, stderr, fprintf, 0);
430
#endif
431
    }
432
    va_end(ap);
433
    abort();
434
}
435

    
436
/***********************************************************/
437
/* keyboard/mouse */
438

    
439
static QEMUPutKBDEvent *qemu_put_kbd_event;
440
static void *qemu_put_kbd_event_opaque;
441
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
442
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
443

    
444
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
445
{
446
    qemu_put_kbd_event_opaque = opaque;
447
    qemu_put_kbd_event = func;
448
}
449

    
450
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
451
                                                void *opaque, int absolute,
452
                                                const char *name)
453
{
454
    QEMUPutMouseEntry *s, *cursor;
455

    
456
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
457
    if (!s)
458
        return NULL;
459

    
460
    s->qemu_put_mouse_event = func;
461
    s->qemu_put_mouse_event_opaque = opaque;
462
    s->qemu_put_mouse_event_absolute = absolute;
463
    s->qemu_put_mouse_event_name = qemu_strdup(name);
464
    s->next = NULL;
465

    
466
    if (!qemu_put_mouse_event_head) {
467
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
468
        return s;
469
    }
470

    
471
    cursor = qemu_put_mouse_event_head;
472
    while (cursor->next != NULL)
473
        cursor = cursor->next;
474

    
475
    cursor->next = s;
476
    qemu_put_mouse_event_current = s;
477

    
478
    return s;
479
}
480

    
481
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
482
{
483
    QEMUPutMouseEntry *prev = NULL, *cursor;
484

    
485
    if (!qemu_put_mouse_event_head || entry == NULL)
486
        return;
487

    
488
    cursor = qemu_put_mouse_event_head;
489
    while (cursor != NULL && cursor != entry) {
490
        prev = cursor;
491
        cursor = cursor->next;
492
    }
493

    
494
    if (cursor == NULL) // does not exist or list empty
495
        return;
496
    else if (prev == NULL) { // entry is head
497
        qemu_put_mouse_event_head = cursor->next;
498
        if (qemu_put_mouse_event_current == entry)
499
            qemu_put_mouse_event_current = cursor->next;
500
        qemu_free(entry->qemu_put_mouse_event_name);
501
        qemu_free(entry);
502
        return;
503
    }
504

    
505
    prev->next = entry->next;
506

    
507
    if (qemu_put_mouse_event_current == entry)
508
        qemu_put_mouse_event_current = prev;
509

    
510
    qemu_free(entry->qemu_put_mouse_event_name);
511
    qemu_free(entry);
512
}
513

    
514
void kbd_put_keycode(int keycode)
515
{
516
    if (qemu_put_kbd_event) {
517
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
518
    }
519
}
520

    
521
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
522
{
523
    QEMUPutMouseEvent *mouse_event;
524
    void *mouse_event_opaque;
525

    
526
    if (!qemu_put_mouse_event_current) {
527
        return;
528
    }
529

    
530
    mouse_event =
531
        qemu_put_mouse_event_current->qemu_put_mouse_event;
532
    mouse_event_opaque =
533
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
534

    
535
    if (mouse_event) {
536
        mouse_event(mouse_event_opaque, dx, dy, dz, buttons_state);
537
    }
538
}
539

    
540
int kbd_mouse_is_absolute(void)
541
{
542
    if (!qemu_put_mouse_event_current)
543
        return 0;
544

    
545
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
546
}
547

    
548
void (*kbd_mouse_set)(int x, int y, int on) = NULL;
549
void (*kbd_cursor_define)(int width, int height, int bpp, int hot_x, int hot_y,
550
                          uint8_t *image, uint8_t *mask) = NULL;
551

    
552
void do_info_mice(void)
553
{
554
    QEMUPutMouseEntry *cursor;
555
    int index = 0;
556

    
557
    if (!qemu_put_mouse_event_head) {
558
        term_printf("No mouse devices connected\n");
559
        return;
560
    }
561

    
562
    term_printf("Mouse devices available:\n");
563
    cursor = qemu_put_mouse_event_head;
564
    while (cursor != NULL) {
565
        term_printf("%c Mouse #%d: %s\n",
566
                    (cursor == qemu_put_mouse_event_current ? '*' : ' '),
567
                    index, cursor->qemu_put_mouse_event_name);
568
        index++;
569
        cursor = cursor->next;
570
    }
571
}
572

    
573
void do_mouse_set(int index)
574
{
575
    QEMUPutMouseEntry *cursor;
576
    int i = 0;
577

    
578
    if (!qemu_put_mouse_event_head) {
579
        term_printf("No mouse devices connected\n");
580
        return;
581
    }
582

    
583
    cursor = qemu_put_mouse_event_head;
584
    while (cursor != NULL && index != i) {
585
        i++;
586
        cursor = cursor->next;
587
    }
588

    
589
    if (cursor != NULL)
590
        qemu_put_mouse_event_current = cursor;
591
    else
592
        term_printf("Mouse at given index not found\n");
593
}
594

    
595
/* compute with 96 bit intermediate result: (a*b)/c */
596
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
597
{
598
    union {
599
        uint64_t ll;
600
        struct {
601
#ifdef WORDS_BIGENDIAN
602
            uint32_t high, low;
603
#else
604
            uint32_t low, high;
605
#endif            
606
        } l;
607
    } u, res;
608
    uint64_t rl, rh;
609

    
610
    u.ll = a;
611
    rl = (uint64_t)u.l.low * (uint64_t)b;
612
    rh = (uint64_t)u.l.high * (uint64_t)b;
613
    rh += (rl >> 32);
614
    res.l.high = rh / c;
615
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
616
    return res.ll;
617
}
618

    
619
/***********************************************************/
620
/* real time host monotonic timer */
621

    
622
#define QEMU_TIMER_BASE 1000000000LL
623

    
624
#ifdef WIN32
625

    
626
static int64_t clock_freq;
627

    
628
static void init_get_clock(void)
629
{
630
    LARGE_INTEGER freq;
631
    int ret;
632
    ret = QueryPerformanceFrequency(&freq);
633
    if (ret == 0) {
634
        fprintf(stderr, "Could not calibrate ticks\n");
635
        exit(1);
636
    }
637
    clock_freq = freq.QuadPart;
638
}
639

    
640
static int64_t get_clock(void)
641
{
642
    LARGE_INTEGER ti;
643
    QueryPerformanceCounter(&ti);
644
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
645
}
646

    
647
#else
648

    
649
static int use_rt_clock;
650

    
651
static void init_get_clock(void)
652
{
653
    use_rt_clock = 0;
654
#if defined(__linux__)
655
    {
656
        struct timespec ts;
657
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
658
            use_rt_clock = 1;
659
        }
660
    }
661
#endif
662
}
663

    
664
static int64_t get_clock(void)
665
{
666
#if defined(__linux__)
667
    if (use_rt_clock) {
668
        struct timespec ts;
669
        clock_gettime(CLOCK_MONOTONIC, &ts);
670
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
671
    } else 
672
#endif
673
    {
674
        /* XXX: using gettimeofday leads to problems if the date
675
           changes, so it should be avoided. */
676
        struct timeval tv;
677
        gettimeofday(&tv, NULL);
678
        return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
679
    }
680
}
681

    
682
#endif
683

    
684
/***********************************************************/
685
/* guest cycle counter */
686

    
687
static int64_t cpu_ticks_prev;
688
static int64_t cpu_ticks_offset;
689
static int64_t cpu_clock_offset;
690
static int cpu_ticks_enabled;
691

    
692
/* return the host CPU cycle counter and handle stop/restart */
693
int64_t cpu_get_ticks(void)
694
{
695
    if (!cpu_ticks_enabled) {
696
        return cpu_ticks_offset;
697
    } else {
698
        int64_t ticks;
699
        ticks = cpu_get_real_ticks();
700
        if (cpu_ticks_prev > ticks) {
701
            /* Note: non increasing ticks may happen if the host uses
702
               software suspend */
703
            cpu_ticks_offset += cpu_ticks_prev - ticks;
704
        }
705
        cpu_ticks_prev = ticks;
706
        return ticks + cpu_ticks_offset;
707
    }
708
}
709

    
710
/* return the host CPU monotonic timer and handle stop/restart */
711
static int64_t cpu_get_clock(void)
712
{
713
    int64_t ti;
714
    if (!cpu_ticks_enabled) {
715
        return cpu_clock_offset;
716
    } else {
717
        ti = get_clock();
718
        return ti + cpu_clock_offset;
719
    }
720
}
721

    
722
/* enable cpu_get_ticks() */
723
void cpu_enable_ticks(void)
724
{
725
    if (!cpu_ticks_enabled) {
726
        cpu_ticks_offset -= cpu_get_real_ticks();
727
        cpu_clock_offset -= get_clock();
728
        cpu_ticks_enabled = 1;
729
    }
730
}
731

    
732
/* disable cpu_get_ticks() : the clock is stopped. You must not call
733
   cpu_get_ticks() after that.  */
734
void cpu_disable_ticks(void)
735
{
736
    if (cpu_ticks_enabled) {
737
        cpu_ticks_offset = cpu_get_ticks();
738
        cpu_clock_offset = cpu_get_clock();
739
        cpu_ticks_enabled = 0;
740
    }
741
}
742

    
743
/***********************************************************/
744
/* timers */
745
 
746
#define QEMU_TIMER_REALTIME 0
747
#define QEMU_TIMER_VIRTUAL  1
748

    
749
struct QEMUClock {
750
    int type;
751
    /* XXX: add frequency */
752
};
753

    
754
struct QEMUTimer {
755
    QEMUClock *clock;
756
    int64_t expire_time;
757
    QEMUTimerCB *cb;
758
    void *opaque;
759
    struct QEMUTimer *next;
760
};
761

    
762
QEMUClock *rt_clock;
763
QEMUClock *vm_clock;
764

    
765
static QEMUTimer *active_timers[2];
766
#ifdef _WIN32
767
static MMRESULT timerID;
768
static HANDLE host_alarm = NULL;
769
static unsigned int period = 1;
770
#else
771
/* frequency of the times() clock tick */
772
static int timer_freq;
773
#endif
774

    
775
QEMUClock *qemu_new_clock(int type)
776
{
777
    QEMUClock *clock;
778
    clock = qemu_mallocz(sizeof(QEMUClock));
779
    if (!clock)
780
        return NULL;
781
    clock->type = type;
782
    return clock;
783
}
784

    
785
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
786
{
787
    QEMUTimer *ts;
788

    
789
    ts = qemu_mallocz(sizeof(QEMUTimer));
790
    ts->clock = clock;
791
    ts->cb = cb;
792
    ts->opaque = opaque;
793
    return ts;
794
}
795

    
796
void qemu_free_timer(QEMUTimer *ts)
797
{
798
    qemu_free(ts);
799
}
800

    
801
/* stop a timer, but do not dealloc it */
802
void qemu_del_timer(QEMUTimer *ts)
803
{
804
    QEMUTimer **pt, *t;
805

    
806
    /* NOTE: this code must be signal safe because
807
       qemu_timer_expired() can be called from a signal. */
808
    pt = &active_timers[ts->clock->type];
809
    for(;;) {
810
        t = *pt;
811
        if (!t)
812
            break;
813
        if (t == ts) {
814
            *pt = t->next;
815
            break;
816
        }
817
        pt = &t->next;
818
    }
819
}
820

    
821
/* modify the current timer so that it will be fired when current_time
822
   >= expire_time. The corresponding callback will be called. */
823
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
824
{
825
    QEMUTimer **pt, *t;
826

    
827
    qemu_del_timer(ts);
828

    
829
    /* add the timer in the sorted list */
830
    /* NOTE: this code must be signal safe because
831
       qemu_timer_expired() can be called from a signal. */
832
    pt = &active_timers[ts->clock->type];
833
    for(;;) {
834
        t = *pt;
835
        if (!t)
836
            break;
837
        if (t->expire_time > expire_time) 
838
            break;
839
        pt = &t->next;
840
    }
841
    ts->expire_time = expire_time;
842
    ts->next = *pt;
843
    *pt = ts;
844
}
845

    
846
int qemu_timer_pending(QEMUTimer *ts)
847
{
848
    QEMUTimer *t;
849
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
850
        if (t == ts)
851
            return 1;
852
    }
853
    return 0;
854
}
855

    
856
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
857
{
858
    if (!timer_head)
859
        return 0;
860
    return (timer_head->expire_time <= current_time);
861
}
862

    
863
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
864
{
865
    QEMUTimer *ts;
866
    
867
    for(;;) {
868
        ts = *ptimer_head;
869
        if (!ts || ts->expire_time > current_time)
870
            break;
871
        /* remove timer from the list before calling the callback */
872
        *ptimer_head = ts->next;
873
        ts->next = NULL;
874
        
875
        /* run the callback (the timer list can be modified) */
876
        ts->cb(ts->opaque);
877
    }
878
}
879

    
880
int64_t qemu_get_clock(QEMUClock *clock)
881
{
882
    switch(clock->type) {
883
    case QEMU_TIMER_REALTIME:
884
        return get_clock() / 1000000;
885
    default:
886
    case QEMU_TIMER_VIRTUAL:
887
        return cpu_get_clock();
888
    }
889
}
890

    
891
static void init_timers(void)
892
{
893
    init_get_clock();
894
    ticks_per_sec = QEMU_TIMER_BASE;
895
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
896
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
897
}
898

    
899
/* save a timer */
900
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
901
{
902
    uint64_t expire_time;
903

    
904
    if (qemu_timer_pending(ts)) {
905
        expire_time = ts->expire_time;
906
    } else {
907
        expire_time = -1;
908
    }
909
    qemu_put_be64(f, expire_time);
910
}
911

    
912
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
913
{
914
    uint64_t expire_time;
915

    
916
    expire_time = qemu_get_be64(f);
917
    if (expire_time != -1) {
918
        qemu_mod_timer(ts, expire_time);
919
    } else {
920
        qemu_del_timer(ts);
921
    }
922
}
923

    
924
static void timer_save(QEMUFile *f, void *opaque)
925
{
926
    if (cpu_ticks_enabled) {
927
        hw_error("cannot save state if virtual timers are running");
928
    }
929
    qemu_put_be64s(f, &cpu_ticks_offset);
930
    qemu_put_be64s(f, &ticks_per_sec);
931
    qemu_put_be64s(f, &cpu_clock_offset);
932
}
933

    
934
static int timer_load(QEMUFile *f, void *opaque, int version_id)
935
{
936
    if (version_id != 1 && version_id != 2)
937
        return -EINVAL;
938
    if (cpu_ticks_enabled) {
939
        return -EINVAL;
940
    }
941
    qemu_get_be64s(f, &cpu_ticks_offset);
942
    qemu_get_be64s(f, &ticks_per_sec);
943
    if (version_id == 2) {
944
        qemu_get_be64s(f, &cpu_clock_offset);
945
    }
946
    return 0;
947
}
948

    
949
#ifdef _WIN32
950
void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg, 
951
                                 DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
952
#else
953
static void host_alarm_handler(int host_signum)
954
#endif
955
{
956
#if 0
957
#define DISP_FREQ 1000
958
    {
959
        static int64_t delta_min = INT64_MAX;
960
        static int64_t delta_max, delta_cum, last_clock, delta, ti;
961
        static int count;
962
        ti = qemu_get_clock(vm_clock);
963
        if (last_clock != 0) {
964
            delta = ti - last_clock;
965
            if (delta < delta_min)
966
                delta_min = delta;
967
            if (delta > delta_max)
968
                delta_max = delta;
969
            delta_cum += delta;
970
            if (++count == DISP_FREQ) {
971
                printf("timer: min=%" PRId64 " us max=%" PRId64 " us avg=%" PRId64 " us avg_freq=%0.3f Hz\n",
972
                       muldiv64(delta_min, 1000000, ticks_per_sec),
973
                       muldiv64(delta_max, 1000000, ticks_per_sec),
974
                       muldiv64(delta_cum, 1000000 / DISP_FREQ, ticks_per_sec),
975
                       (double)ticks_per_sec / ((double)delta_cum / DISP_FREQ));
976
                count = 0;
977
                delta_min = INT64_MAX;
978
                delta_max = 0;
979
                delta_cum = 0;
980
            }
981
        }
982
        last_clock = ti;
983
    }
984
#endif
985
    if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
986
                           qemu_get_clock(vm_clock)) ||
987
        qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
988
                           qemu_get_clock(rt_clock))) {
989
#ifdef _WIN32
990
        SetEvent(host_alarm);
991
#endif
992
        CPUState *env = cpu_single_env;
993
        if (env) {
994
            /* stop the currently executing cpu because a timer occured */
995
            cpu_interrupt(env, CPU_INTERRUPT_EXIT);
996
#ifdef USE_KQEMU
997
            if (env->kqemu_enabled) {
998
                kqemu_cpu_interrupt(env);
999
            }
1000
#endif
1001
        }
1002
    }
1003
}
1004

    
1005
#ifndef _WIN32
1006

    
1007
#if defined(__linux__)
1008

    
1009
#define RTC_FREQ 1024
1010

    
1011
static int rtc_fd;
1012

    
1013
static int start_rtc_timer(void)
1014
{
1015
    rtc_fd = open("/dev/rtc", O_RDONLY);
1016
    if (rtc_fd < 0)
1017
        return -1;
1018
    if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1019
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1020
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1021
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1022
        goto fail;
1023
    }
1024
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1025
    fail:
1026
        close(rtc_fd);
1027
        return -1;
1028
    }
1029
    pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1030
    return 0;
1031
}
1032

    
1033
#else
1034

    
1035
static int start_rtc_timer(void)
1036
{
1037
    return -1;
1038
}
1039

    
1040
#endif /* !defined(__linux__) */
1041

    
1042
#endif /* !defined(_WIN32) */
1043

    
1044
static void init_timer_alarm(void)
1045
{
1046
#ifdef _WIN32
1047
    {
1048
        int count=0;
1049
        TIMECAPS tc;
1050

    
1051
        ZeroMemory(&tc, sizeof(TIMECAPS));
1052
        timeGetDevCaps(&tc, sizeof(TIMECAPS));
1053
        if (period < tc.wPeriodMin)
1054
            period = tc.wPeriodMin;
1055
        timeBeginPeriod(period);
1056
        timerID = timeSetEvent(1,     // interval (ms)
1057
                               period,     // resolution
1058
                               host_alarm_handler, // function
1059
                               (DWORD)&count,  // user parameter
1060
                               TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
1061
         if( !timerID ) {
1062
            perror("failed timer alarm");
1063
            exit(1);
1064
         }
1065
        host_alarm = CreateEvent(NULL, FALSE, FALSE, NULL);
1066
        if (!host_alarm) {
1067
            perror("failed CreateEvent");
1068
            exit(1);
1069
        }
1070
        qemu_add_wait_object(host_alarm, NULL, NULL);
1071
    }
1072
    pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
1073
#else
1074
    {
1075
        struct sigaction act;
1076
        struct itimerval itv;
1077
        
1078
        /* get times() syscall frequency */
1079
        timer_freq = sysconf(_SC_CLK_TCK);
1080
        
1081
        /* timer signal */
1082
        sigfillset(&act.sa_mask);
1083
       act.sa_flags = 0;
1084
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
1085
        act.sa_flags |= SA_ONSTACK;
1086
#endif
1087
        act.sa_handler = host_alarm_handler;
1088
        sigaction(SIGALRM, &act, NULL);
1089

    
1090
        itv.it_interval.tv_sec = 0;
1091
        itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1092
        itv.it_value.tv_sec = 0;
1093
        itv.it_value.tv_usec = 10 * 1000;
1094
        setitimer(ITIMER_REAL, &itv, NULL);
1095
        /* we probe the tick duration of the kernel to inform the user if
1096
           the emulated kernel requested a too high timer frequency */
1097
        getitimer(ITIMER_REAL, &itv);
1098

    
1099
#if defined(__linux__)
1100
        /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1101
           have timers with 1 ms resolution. The correct solution will
1102
           be to use the POSIX real time timers available in recent
1103
           2.6 kernels */
1104
        if (itv.it_interval.tv_usec > 1000 || 1) {
1105
            /* try to use /dev/rtc to have a faster timer */
1106
            if (start_rtc_timer() < 0)
1107
                goto use_itimer;
1108
            /* disable itimer */
1109
            itv.it_interval.tv_sec = 0;
1110
            itv.it_interval.tv_usec = 0;
1111
            itv.it_value.tv_sec = 0;
1112
            itv.it_value.tv_usec = 0;
1113
            setitimer(ITIMER_REAL, &itv, NULL);
1114

    
1115
            /* use the RTC */
1116
            sigaction(SIGIO, &act, NULL);
1117
            fcntl(rtc_fd, F_SETFL, O_ASYNC);
1118
            fcntl(rtc_fd, F_SETOWN, getpid());
1119
        } else 
1120
#endif /* defined(__linux__) */
1121
        {
1122
        use_itimer:
1123
            pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
1124
                                   PIT_FREQ) / 1000000;
1125
        }
1126
    }
1127
#endif
1128
}
1129

    
1130
void quit_timers(void)
1131
{
1132
#ifdef _WIN32
1133
    timeKillEvent(timerID);
1134
    timeEndPeriod(period);
1135
    if (host_alarm) {
1136
        CloseHandle(host_alarm);
1137
        host_alarm = NULL;
1138
    }
1139
#endif
1140
}
1141

    
1142
/***********************************************************/
1143
/* character device */
1144

    
1145
static void qemu_chr_event(CharDriverState *s, int event)
1146
{
1147
    if (!s->chr_event)
1148
        return;
1149
    s->chr_event(s->handler_opaque, event);
1150
}
1151

    
1152
static void qemu_chr_reset_bh(void *opaque)
1153
{
1154
    CharDriverState *s = opaque;
1155
    qemu_chr_event(s, CHR_EVENT_RESET);
1156
    qemu_bh_delete(s->bh);
1157
    s->bh = NULL;
1158
}
1159

    
1160
void qemu_chr_reset(CharDriverState *s)
1161
{
1162
    if (s->bh == NULL) {
1163
        s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1164
        qemu_bh_schedule(s->bh);
1165
    }
1166
}
1167

    
1168
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1169
{
1170
    return s->chr_write(s, buf, len);
1171
}
1172

    
1173
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1174
{
1175
    if (!s->chr_ioctl)
1176
        return -ENOTSUP;
1177
    return s->chr_ioctl(s, cmd, arg);
1178
}
1179

    
1180
int qemu_chr_can_read(CharDriverState *s)
1181
{
1182
    if (!s->chr_can_read)
1183
        return 0;
1184
    return s->chr_can_read(s->handler_opaque);
1185
}
1186

    
1187
void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1188
{
1189
    s->chr_read(s->handler_opaque, buf, len);
1190
}
1191

    
1192

    
1193
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1194
{
1195
    char buf[4096];
1196
    va_list ap;
1197
    va_start(ap, fmt);
1198
    vsnprintf(buf, sizeof(buf), fmt, ap);
1199
    qemu_chr_write(s, buf, strlen(buf));
1200
    va_end(ap);
1201
}
1202

    
1203
void qemu_chr_send_event(CharDriverState *s, int event)
1204
{
1205
    if (s->chr_send_event)
1206
        s->chr_send_event(s, event);
1207
}
1208

    
1209
void qemu_chr_add_handlers(CharDriverState *s, 
1210
                           IOCanRWHandler *fd_can_read, 
1211
                           IOReadHandler *fd_read,
1212
                           IOEventHandler *fd_event,
1213
                           void *opaque)
1214
{
1215
    s->chr_can_read = fd_can_read;
1216
    s->chr_read = fd_read;
1217
    s->chr_event = fd_event;
1218
    s->handler_opaque = opaque;
1219
    if (s->chr_update_read_handler)
1220
        s->chr_update_read_handler(s);
1221
}
1222
             
1223
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1224
{
1225
    return len;
1226
}
1227

    
1228
static CharDriverState *qemu_chr_open_null(void)
1229
{
1230
    CharDriverState *chr;
1231

    
1232
    chr = qemu_mallocz(sizeof(CharDriverState));
1233
    if (!chr)
1234
        return NULL;
1235
    chr->chr_write = null_chr_write;
1236
    return chr;
1237
}
1238

    
1239
/* MUX driver for serial I/O splitting */
1240
static int term_timestamps;
1241
static int64_t term_timestamps_start;
1242
#define MAX_MUX 4
1243
typedef struct {
1244
    IOCanRWHandler *chr_can_read[MAX_MUX];
1245
    IOReadHandler *chr_read[MAX_MUX];
1246
    IOEventHandler *chr_event[MAX_MUX];
1247
    void *ext_opaque[MAX_MUX];
1248
    CharDriverState *drv;
1249
    int mux_cnt;
1250
    int term_got_escape;
1251
    int max_size;
1252
} MuxDriver;
1253

    
1254

    
1255
static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1256
{
1257
    MuxDriver *d = chr->opaque;
1258
    int ret;
1259
    if (!term_timestamps) {
1260
        ret = d->drv->chr_write(d->drv, buf, len);
1261
    } else {
1262
        int i;
1263

    
1264
        ret = 0;
1265
        for(i = 0; i < len; i++) {
1266
            ret += d->drv->chr_write(d->drv, buf+i, 1);
1267
            if (buf[i] == '\n') {
1268
                char buf1[64];
1269
                int64_t ti;
1270
                int secs;
1271

    
1272
                ti = get_clock();
1273
                if (term_timestamps_start == -1)
1274
                    term_timestamps_start = ti;
1275
                ti -= term_timestamps_start;
1276
                secs = ti / 1000000000;
1277
                snprintf(buf1, sizeof(buf1),
1278
                         "[%02d:%02d:%02d.%03d] ",
1279
                         secs / 3600,
1280
                         (secs / 60) % 60,
1281
                         secs % 60,
1282
                         (int)((ti / 1000000) % 1000));
1283
                d->drv->chr_write(d->drv, buf1, strlen(buf1));
1284
            }
1285
        }
1286
    }
1287
    return ret;
1288
}
1289

    
1290
static char *mux_help[] = {
1291
    "% h    print this help\n\r",
1292
    "% x    exit emulator\n\r",
1293
    "% s    save disk data back to file (if -snapshot)\n\r",
1294
    "% t    toggle console timestamps\n\r"
1295
    "% b    send break (magic sysrq)\n\r",
1296
    "% c    switch between console and monitor\n\r",
1297
    "% %  sends %\n\r",
1298
    NULL
1299
};
1300

    
1301
static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1302
static void mux_print_help(CharDriverState *chr)
1303
{
1304
    int i, j;
1305
    char ebuf[15] = "Escape-Char";
1306
    char cbuf[50] = "\n\r";
1307

    
1308
    if (term_escape_char > 0 && term_escape_char < 26) {
1309
        sprintf(cbuf,"\n\r");
1310
        sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1311
    } else {
1312
        sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1313
    }
1314
    chr->chr_write(chr, cbuf, strlen(cbuf));
1315
    for (i = 0; mux_help[i] != NULL; i++) {
1316
        for (j=0; mux_help[i][j] != '\0'; j++) {
1317
            if (mux_help[i][j] == '%')
1318
                chr->chr_write(chr, ebuf, strlen(ebuf));
1319
            else
1320
                chr->chr_write(chr, &mux_help[i][j], 1);
1321
        }
1322
    }
1323
}
1324

    
1325
static int mux_proc_byte(CharDriverState *chr, MuxDriver *d, int ch)
1326
{
1327
    if (d->term_got_escape) {
1328
        d->term_got_escape = 0;
1329
        if (ch == term_escape_char)
1330
            goto send_char;
1331
        switch(ch) {
1332
        case '?':
1333
        case 'h':
1334
            mux_print_help(chr);
1335
            break;
1336
        case 'x':
1337
            {
1338
                 char *term =  "QEMU: Terminated\n\r";
1339
                 chr->chr_write(chr,term,strlen(term));
1340
                 exit(0);
1341
                 break;
1342
            }
1343
        case 's':
1344
            {
1345
                int i;
1346
                for (i = 0; i < MAX_DISKS; i++) {
1347
                    if (bs_table[i])
1348
                        bdrv_commit(bs_table[i]);
1349
                }
1350
            }
1351
            break;
1352
        case 'b':
1353
            if (chr->chr_event)
1354
                chr->chr_event(chr->opaque, CHR_EVENT_BREAK);
1355
            break;
1356
        case 'c':
1357
            /* Switch to the next registered device */
1358
            chr->focus++;
1359
            if (chr->focus >= d->mux_cnt)
1360
                chr->focus = 0;
1361
            break;
1362
       case 't':
1363
           term_timestamps = !term_timestamps;
1364
           term_timestamps_start = -1;
1365
           break;
1366
        }
1367
    } else if (ch == term_escape_char) {
1368
        d->term_got_escape = 1;
1369
    } else {
1370
    send_char:
1371
        return 1;
1372
    }
1373
    return 0;
1374
}
1375

    
1376
static int mux_chr_can_read(void *opaque)
1377
{
1378
    CharDriverState *chr = opaque;
1379
    MuxDriver *d = chr->opaque;
1380
    if (d->chr_can_read[chr->focus])
1381
       return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1382
    return 0;
1383
}
1384

    
1385
static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1386
{
1387
    CharDriverState *chr = opaque;
1388
    MuxDriver *d = chr->opaque;
1389
    int i;
1390
    for(i = 0; i < size; i++)
1391
        if (mux_proc_byte(chr, d, buf[i]))
1392
            d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1393
}
1394

    
1395
static void mux_chr_event(void *opaque, int event)
1396
{
1397
    CharDriverState *chr = opaque;
1398
    MuxDriver *d = chr->opaque;
1399
    int i;
1400

    
1401
    /* Send the event to all registered listeners */
1402
    for (i = 0; i < d->mux_cnt; i++)
1403
        if (d->chr_event[i])
1404
            d->chr_event[i](d->ext_opaque[i], event);
1405
}
1406

    
1407
static void mux_chr_update_read_handler(CharDriverState *chr)
1408
{
1409
    MuxDriver *d = chr->opaque;
1410

    
1411
    if (d->mux_cnt >= MAX_MUX) {
1412
        fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1413
        return;
1414
    }
1415
    d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1416
    d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1417
    d->chr_read[d->mux_cnt] = chr->chr_read;
1418
    d->chr_event[d->mux_cnt] = chr->chr_event;
1419
    /* Fix up the real driver with mux routines */
1420
    if (d->mux_cnt == 0) {
1421
        qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1422
                              mux_chr_event, chr);
1423
    }
1424
    chr->focus = d->mux_cnt;
1425
    d->mux_cnt++;
1426
}
1427

    
1428
CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1429
{
1430
    CharDriverState *chr;
1431
    MuxDriver *d;
1432

    
1433
    chr = qemu_mallocz(sizeof(CharDriverState));
1434
    if (!chr)
1435
        return NULL;
1436
    d = qemu_mallocz(sizeof(MuxDriver));
1437
    if (!d) {
1438
        free(chr);
1439
        return NULL;
1440
    }
1441

    
1442
    chr->opaque = d;
1443
    d->drv = drv;
1444
    chr->focus = -1;
1445
    chr->chr_write = mux_chr_write;
1446
    chr->chr_update_read_handler = mux_chr_update_read_handler;
1447
    return chr;
1448
}
1449

    
1450

    
1451
#ifdef _WIN32
1452

    
1453
static void socket_cleanup(void)
1454
{
1455
    WSACleanup();
1456
}
1457

    
1458
static int socket_init(void)
1459
{
1460
    WSADATA Data;
1461
    int ret, err;
1462

    
1463
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1464
    if (ret != 0) {
1465
        err = WSAGetLastError();
1466
        fprintf(stderr, "WSAStartup: %d\n", err);
1467
        return -1;
1468
    }
1469
    atexit(socket_cleanup);
1470
    return 0;
1471
}
1472

    
1473
static int send_all(int fd, const uint8_t *buf, int len1)
1474
{
1475
    int ret, len;
1476
    
1477
    len = len1;
1478
    while (len > 0) {
1479
        ret = send(fd, buf, len, 0);
1480
        if (ret < 0) {
1481
            int errno;
1482
            errno = WSAGetLastError();
1483
            if (errno != WSAEWOULDBLOCK) {
1484
                return -1;
1485
            }
1486
        } else if (ret == 0) {
1487
            break;
1488
        } else {
1489
            buf += ret;
1490
            len -= ret;
1491
        }
1492
    }
1493
    return len1 - len;
1494
}
1495

    
1496
void socket_set_nonblock(int fd)
1497
{
1498
    unsigned long opt = 1;
1499
    ioctlsocket(fd, FIONBIO, &opt);
1500
}
1501

    
1502
#else
1503

    
1504
static int unix_write(int fd, const uint8_t *buf, int len1)
1505
{
1506
    int ret, len;
1507

    
1508
    len = len1;
1509
    while (len > 0) {
1510
        ret = write(fd, buf, len);
1511
        if (ret < 0) {
1512
            if (errno != EINTR && errno != EAGAIN)
1513
                return -1;
1514
        } else if (ret == 0) {
1515
            break;
1516
        } else {
1517
            buf += ret;
1518
            len -= ret;
1519
        }
1520
    }
1521
    return len1 - len;
1522
}
1523

    
1524
static inline int send_all(int fd, const uint8_t *buf, int len1)
1525
{
1526
    return unix_write(fd, buf, len1);
1527
}
1528

    
1529
void socket_set_nonblock(int fd)
1530
{
1531
    fcntl(fd, F_SETFL, O_NONBLOCK);
1532
}
1533
#endif /* !_WIN32 */
1534

    
1535
#ifndef _WIN32
1536

    
1537
typedef struct {
1538
    int fd_in, fd_out;
1539
    int max_size;
1540
} FDCharDriver;
1541

    
1542
#define STDIO_MAX_CLIENTS 1
1543
static int stdio_nb_clients = 0;
1544

    
1545
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1546
{
1547
    FDCharDriver *s = chr->opaque;
1548
    return unix_write(s->fd_out, buf, len);
1549
}
1550

    
1551
static int fd_chr_read_poll(void *opaque)
1552
{
1553
    CharDriverState *chr = opaque;
1554
    FDCharDriver *s = chr->opaque;
1555

    
1556
    s->max_size = qemu_chr_can_read(chr);
1557
    return s->max_size;
1558
}
1559

    
1560
static void fd_chr_read(void *opaque)
1561
{
1562
    CharDriverState *chr = opaque;
1563
    FDCharDriver *s = chr->opaque;
1564
    int size, len;
1565
    uint8_t buf[1024];
1566
    
1567
    len = sizeof(buf);
1568
    if (len > s->max_size)
1569
        len = s->max_size;
1570
    if (len == 0)
1571
        return;
1572
    size = read(s->fd_in, buf, len);
1573
    if (size == 0) {
1574
        /* FD has been closed. Remove it from the active list.  */
1575
        qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1576
        return;
1577
    }
1578
    if (size > 0) {
1579
        qemu_chr_read(chr, buf, size);
1580
    }
1581
}
1582

    
1583
static void fd_chr_update_read_handler(CharDriverState *chr)
1584
{
1585
    FDCharDriver *s = chr->opaque;
1586

    
1587
    if (s->fd_in >= 0) {
1588
        if (nographic && s->fd_in == 0) {
1589
        } else {
1590
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll, 
1591
                                 fd_chr_read, NULL, chr);
1592
        }
1593
    }
1594
}
1595

    
1596
/* open a character device to a unix fd */
1597
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1598
{
1599
    CharDriverState *chr;
1600
    FDCharDriver *s;
1601

    
1602
    chr = qemu_mallocz(sizeof(CharDriverState));
1603
    if (!chr)
1604
        return NULL;
1605
    s = qemu_mallocz(sizeof(FDCharDriver));
1606
    if (!s) {
1607
        free(chr);
1608
        return NULL;
1609
    }
1610
    s->fd_in = fd_in;
1611
    s->fd_out = fd_out;
1612
    chr->opaque = s;
1613
    chr->chr_write = fd_chr_write;
1614
    chr->chr_update_read_handler = fd_chr_update_read_handler;
1615

    
1616
    qemu_chr_reset(chr);
1617

    
1618
    return chr;
1619
}
1620

    
1621
static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1622
{
1623
    int fd_out;
1624

    
1625
    fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1626
    if (fd_out < 0)
1627
        return NULL;
1628
    return qemu_chr_open_fd(-1, fd_out);
1629
}
1630

    
1631
static CharDriverState *qemu_chr_open_pipe(const char *filename)
1632
{
1633
    int fd_in, fd_out;
1634
    char filename_in[256], filename_out[256];
1635

    
1636
    snprintf(filename_in, 256, "%s.in", filename);
1637
    snprintf(filename_out, 256, "%s.out", filename);
1638
    fd_in = open(filename_in, O_RDWR | O_BINARY);
1639
    fd_out = open(filename_out, O_RDWR | O_BINARY);
1640
    if (fd_in < 0 || fd_out < 0) {
1641
        if (fd_in >= 0)
1642
            close(fd_in);
1643
        if (fd_out >= 0)
1644
            close(fd_out);
1645
        fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1646
        if (fd_in < 0)
1647
            return NULL;
1648
    }
1649
    return qemu_chr_open_fd(fd_in, fd_out);
1650
}
1651

    
1652

    
1653
/* for STDIO, we handle the case where several clients use it
1654
   (nographic mode) */
1655

    
1656
#define TERM_FIFO_MAX_SIZE 1
1657

    
1658
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1659
static int term_fifo_size;
1660

    
1661
static int stdio_read_poll(void *opaque)
1662
{
1663
    CharDriverState *chr = opaque;
1664

    
1665
    /* try to flush the queue if needed */
1666
    if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1667
        qemu_chr_read(chr, term_fifo, 1);
1668
        term_fifo_size = 0;
1669
    }
1670
    /* see if we can absorb more chars */
1671
    if (term_fifo_size == 0)
1672
        return 1;
1673
    else
1674
        return 0;
1675
}
1676

    
1677
static void stdio_read(void *opaque)
1678
{
1679
    int size;
1680
    uint8_t buf[1];
1681
    CharDriverState *chr = opaque;
1682

    
1683
    size = read(0, buf, 1);
1684
    if (size == 0) {
1685
        /* stdin has been closed. Remove it from the active list.  */
1686
        qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1687
        return;
1688
    }
1689
    if (size > 0) {
1690
        if (qemu_chr_can_read(chr) > 0) {
1691
            qemu_chr_read(chr, buf, 1);
1692
        } else if (term_fifo_size == 0) {
1693
            term_fifo[term_fifo_size++] = buf[0];
1694
        }
1695
    }
1696
}
1697

    
1698
/* init terminal so that we can grab keys */
1699
static struct termios oldtty;
1700
static int old_fd0_flags;
1701

    
1702
static void term_exit(void)
1703
{
1704
    tcsetattr (0, TCSANOW, &oldtty);
1705
    fcntl(0, F_SETFL, old_fd0_flags);
1706
}
1707

    
1708
static void term_init(void)
1709
{
1710
    struct termios tty;
1711

    
1712
    tcgetattr (0, &tty);
1713
    oldtty = tty;
1714
    old_fd0_flags = fcntl(0, F_GETFL);
1715

    
1716
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1717
                          |INLCR|IGNCR|ICRNL|IXON);
1718
    tty.c_oflag |= OPOST;
1719
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1720
    /* if graphical mode, we allow Ctrl-C handling */
1721
    if (nographic)
1722
        tty.c_lflag &= ~ISIG;
1723
    tty.c_cflag &= ~(CSIZE|PARENB);
1724
    tty.c_cflag |= CS8;
1725
    tty.c_cc[VMIN] = 1;
1726
    tty.c_cc[VTIME] = 0;
1727
    
1728
    tcsetattr (0, TCSANOW, &tty);
1729

    
1730
    atexit(term_exit);
1731

    
1732
    fcntl(0, F_SETFL, O_NONBLOCK);
1733
}
1734

    
1735
static CharDriverState *qemu_chr_open_stdio(void)
1736
{
1737
    CharDriverState *chr;
1738

    
1739
    if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1740
        return NULL;
1741
    chr = qemu_chr_open_fd(0, 1);
1742
    qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
1743
    stdio_nb_clients++;
1744
    term_init();
1745

    
1746
    return chr;
1747
}
1748

    
1749
#if defined(__linux__)
1750
static CharDriverState *qemu_chr_open_pty(void)
1751
{
1752
    struct termios tty;
1753
    char slave_name[1024];
1754
    int master_fd, slave_fd;
1755
    
1756
    /* Not satisfying */
1757
    if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1758
        return NULL;
1759
    }
1760
    
1761
    /* Disabling local echo and line-buffered output */
1762
    tcgetattr (master_fd, &tty);
1763
    tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1764
    tty.c_cc[VMIN] = 1;
1765
    tty.c_cc[VTIME] = 0;
1766
    tcsetattr (master_fd, TCSAFLUSH, &tty);
1767

    
1768
    fprintf(stderr, "char device redirected to %s\n", slave_name);
1769
    return qemu_chr_open_fd(master_fd, master_fd);
1770
}
1771

    
1772
static void tty_serial_init(int fd, int speed, 
1773
                            int parity, int data_bits, int stop_bits)
1774
{
1775
    struct termios tty;
1776
    speed_t spd;
1777

    
1778
#if 0
1779
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n", 
1780
           speed, parity, data_bits, stop_bits);
1781
#endif
1782
    tcgetattr (fd, &tty);
1783

    
1784
    switch(speed) {
1785
    case 50:
1786
        spd = B50;
1787
        break;
1788
    case 75:
1789
        spd = B75;
1790
        break;
1791
    case 300:
1792
        spd = B300;
1793
        break;
1794
    case 600:
1795
        spd = B600;
1796
        break;
1797
    case 1200:
1798
        spd = B1200;
1799
        break;
1800
    case 2400:
1801
        spd = B2400;
1802
        break;
1803
    case 4800:
1804
        spd = B4800;
1805
        break;
1806
    case 9600:
1807
        spd = B9600;
1808
        break;
1809
    case 19200:
1810
        spd = B19200;
1811
        break;
1812
    case 38400:
1813
        spd = B38400;
1814
        break;
1815
    case 57600:
1816
        spd = B57600;
1817
        break;
1818
    default:
1819
    case 115200:
1820
        spd = B115200;
1821
        break;
1822
    }
1823

    
1824
    cfsetispeed(&tty, spd);
1825
    cfsetospeed(&tty, spd);
1826

    
1827
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1828
                          |INLCR|IGNCR|ICRNL|IXON);
1829
    tty.c_oflag |= OPOST;
1830
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1831
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1832
    switch(data_bits) {
1833
    default:
1834
    case 8:
1835
        tty.c_cflag |= CS8;
1836
        break;
1837
    case 7:
1838
        tty.c_cflag |= CS7;
1839
        break;
1840
    case 6:
1841
        tty.c_cflag |= CS6;
1842
        break;
1843
    case 5:
1844
        tty.c_cflag |= CS5;
1845
        break;
1846
    }
1847
    switch(parity) {
1848
    default:
1849
    case 'N':
1850
        break;
1851
    case 'E':
1852
        tty.c_cflag |= PARENB;
1853
        break;
1854
    case 'O':
1855
        tty.c_cflag |= PARENB | PARODD;
1856
        break;
1857
    }
1858
    if (stop_bits == 2)
1859
        tty.c_cflag |= CSTOPB;
1860
    
1861
    tcsetattr (fd, TCSANOW, &tty);
1862
}
1863

    
1864
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1865
{
1866
    FDCharDriver *s = chr->opaque;
1867
    
1868
    switch(cmd) {
1869
    case CHR_IOCTL_SERIAL_SET_PARAMS:
1870
        {
1871
            QEMUSerialSetParams *ssp = arg;
1872
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity, 
1873
                            ssp->data_bits, ssp->stop_bits);
1874
        }
1875
        break;
1876
    case CHR_IOCTL_SERIAL_SET_BREAK:
1877
        {
1878
            int enable = *(int *)arg;
1879
            if (enable)
1880
                tcsendbreak(s->fd_in, 1);
1881
        }
1882
        break;
1883
    default:
1884
        return -ENOTSUP;
1885
    }
1886
    return 0;
1887
}
1888

    
1889
static CharDriverState *qemu_chr_open_tty(const char *filename)
1890
{
1891
    CharDriverState *chr;
1892
    int fd;
1893

    
1894
    fd = open(filename, O_RDWR | O_NONBLOCK);
1895
    if (fd < 0)
1896
        return NULL;
1897
    fcntl(fd, F_SETFL, O_NONBLOCK);
1898
    tty_serial_init(fd, 115200, 'N', 8, 1);
1899
    chr = qemu_chr_open_fd(fd, fd);
1900
    if (!chr)
1901
        return NULL;
1902
    chr->chr_ioctl = tty_serial_ioctl;
1903
    qemu_chr_reset(chr);
1904
    return chr;
1905
}
1906

    
1907
typedef struct {
1908
    int fd;
1909
    int mode;
1910
} ParallelCharDriver;
1911

    
1912
static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1913
{
1914
    if (s->mode != mode) {
1915
        int m = mode;
1916
        if (ioctl(s->fd, PPSETMODE, &m) < 0)
1917
            return 0;
1918
        s->mode = mode;
1919
    }
1920
    return 1;
1921
}
1922

    
1923
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1924
{
1925
    ParallelCharDriver *drv = chr->opaque;
1926
    int fd = drv->fd;
1927
    uint8_t b;
1928

    
1929
    switch(cmd) {
1930
    case CHR_IOCTL_PP_READ_DATA:
1931
        if (ioctl(fd, PPRDATA, &b) < 0)
1932
            return -ENOTSUP;
1933
        *(uint8_t *)arg = b;
1934
        break;
1935
    case CHR_IOCTL_PP_WRITE_DATA:
1936
        b = *(uint8_t *)arg;
1937
        if (ioctl(fd, PPWDATA, &b) < 0)
1938
            return -ENOTSUP;
1939
        break;
1940
    case CHR_IOCTL_PP_READ_CONTROL:
1941
        if (ioctl(fd, PPRCONTROL, &b) < 0)
1942
            return -ENOTSUP;
1943
        /* Linux gives only the lowest bits, and no way to know data
1944
           direction! For better compatibility set the fixed upper
1945
           bits. */
1946
        *(uint8_t *)arg = b | 0xc0;
1947
        break;
1948
    case CHR_IOCTL_PP_WRITE_CONTROL:
1949
        b = *(uint8_t *)arg;
1950
        if (ioctl(fd, PPWCONTROL, &b) < 0)
1951
            return -ENOTSUP;
1952
        break;
1953
    case CHR_IOCTL_PP_READ_STATUS:
1954
        if (ioctl(fd, PPRSTATUS, &b) < 0)
1955
            return -ENOTSUP;
1956
        *(uint8_t *)arg = b;
1957
        break;
1958
    case CHR_IOCTL_PP_EPP_READ_ADDR:
1959
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1960
            struct ParallelIOArg *parg = arg;
1961
            int n = read(fd, parg->buffer, parg->count);
1962
            if (n != parg->count) {
1963
                return -EIO;
1964
            }
1965
        }
1966
        break;
1967
    case CHR_IOCTL_PP_EPP_READ:
1968
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1969
            struct ParallelIOArg *parg = arg;
1970
            int n = read(fd, parg->buffer, parg->count);
1971
            if (n != parg->count) {
1972
                return -EIO;
1973
            }
1974
        }
1975
        break;
1976
    case CHR_IOCTL_PP_EPP_WRITE_ADDR:
1977
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP|IEEE1284_ADDR)) {
1978
            struct ParallelIOArg *parg = arg;
1979
            int n = write(fd, parg->buffer, parg->count);
1980
            if (n != parg->count) {
1981
                return -EIO;
1982
            }
1983
        }
1984
        break;
1985
    case CHR_IOCTL_PP_EPP_WRITE:
1986
        if (pp_hw_mode(drv, IEEE1284_MODE_EPP)) {
1987
            struct ParallelIOArg *parg = arg;
1988
            int n = write(fd, parg->buffer, parg->count);
1989
            if (n != parg->count) {
1990
                return -EIO;
1991
            }
1992
        }
1993
        break;
1994
    default:
1995
        return -ENOTSUP;
1996
    }
1997
    return 0;
1998
}
1999

    
2000
static void pp_close(CharDriverState *chr)
2001
{
2002
    ParallelCharDriver *drv = chr->opaque;
2003
    int fd = drv->fd;
2004

    
2005
    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2006
    ioctl(fd, PPRELEASE);
2007
    close(fd);
2008
    qemu_free(drv);
2009
}
2010

    
2011
static CharDriverState *qemu_chr_open_pp(const char *filename)
2012
{
2013
    CharDriverState *chr;
2014
    ParallelCharDriver *drv;
2015
    int fd;
2016

    
2017
    fd = open(filename, O_RDWR);
2018
    if (fd < 0)
2019
        return NULL;
2020

    
2021
    if (ioctl(fd, PPCLAIM) < 0) {
2022
        close(fd);
2023
        return NULL;
2024
    }
2025

    
2026
    drv = qemu_mallocz(sizeof(ParallelCharDriver));
2027
    if (!drv) {
2028
        close(fd);
2029
        return NULL;
2030
    }
2031
    drv->fd = fd;
2032
    drv->mode = IEEE1284_MODE_COMPAT;
2033

    
2034
    chr = qemu_mallocz(sizeof(CharDriverState));
2035
    if (!chr) {
2036
        qemu_free(drv);
2037
        close(fd);
2038
        return NULL;
2039
    }
2040
    chr->chr_write = null_chr_write;
2041
    chr->chr_ioctl = pp_ioctl;
2042
    chr->chr_close = pp_close;
2043
    chr->opaque = drv;
2044

    
2045
    qemu_chr_reset(chr);
2046

    
2047
    return chr;
2048
}
2049

    
2050
#else
2051
static CharDriverState *qemu_chr_open_pty(void)
2052
{
2053
    return NULL;
2054
}
2055
#endif
2056

    
2057
#endif /* !defined(_WIN32) */
2058

    
2059
#ifdef _WIN32
2060
typedef struct {
2061
    int max_size;
2062
    HANDLE hcom, hrecv, hsend;
2063
    OVERLAPPED orecv, osend;
2064
    BOOL fpipe;
2065
    DWORD len;
2066
} WinCharState;
2067

    
2068
#define NSENDBUF 2048
2069
#define NRECVBUF 2048
2070
#define MAXCONNECT 1
2071
#define NTIMEOUT 5000
2072

    
2073
static int win_chr_poll(void *opaque);
2074
static int win_chr_pipe_poll(void *opaque);
2075

    
2076
static void win_chr_close(CharDriverState *chr)
2077
{
2078
    WinCharState *s = chr->opaque;
2079

    
2080
    if (s->hsend) {
2081
        CloseHandle(s->hsend);
2082
        s->hsend = NULL;
2083
    }
2084
    if (s->hrecv) {
2085
        CloseHandle(s->hrecv);
2086
        s->hrecv = NULL;
2087
    }
2088
    if (s->hcom) {
2089
        CloseHandle(s->hcom);
2090
        s->hcom = NULL;
2091
    }
2092
    if (s->fpipe)
2093
        qemu_del_polling_cb(win_chr_pipe_poll, chr);
2094
    else
2095
        qemu_del_polling_cb(win_chr_poll, chr);
2096
}
2097

    
2098
static int win_chr_init(CharDriverState *chr, const char *filename)
2099
{
2100
    WinCharState *s = chr->opaque;
2101
    COMMCONFIG comcfg;
2102
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2103
    COMSTAT comstat;
2104
    DWORD size;
2105
    DWORD err;
2106
    
2107
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2108
    if (!s->hsend) {
2109
        fprintf(stderr, "Failed CreateEvent\n");
2110
        goto fail;
2111
    }
2112
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2113
    if (!s->hrecv) {
2114
        fprintf(stderr, "Failed CreateEvent\n");
2115
        goto fail;
2116
    }
2117

    
2118
    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2119
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2120
    if (s->hcom == INVALID_HANDLE_VALUE) {
2121
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2122
        s->hcom = NULL;
2123
        goto fail;
2124
    }
2125
    
2126
    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2127
        fprintf(stderr, "Failed SetupComm\n");
2128
        goto fail;
2129
    }
2130
    
2131
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2132
    size = sizeof(COMMCONFIG);
2133
    GetDefaultCommConfig(filename, &comcfg, &size);
2134
    comcfg.dcb.DCBlength = sizeof(DCB);
2135
    CommConfigDialog(filename, NULL, &comcfg);
2136

    
2137
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
2138
        fprintf(stderr, "Failed SetCommState\n");
2139
        goto fail;
2140
    }
2141

    
2142
    if (!SetCommMask(s->hcom, EV_ERR)) {
2143
        fprintf(stderr, "Failed SetCommMask\n");
2144
        goto fail;
2145
    }
2146

    
2147
    cto.ReadIntervalTimeout = MAXDWORD;
2148
    if (!SetCommTimeouts(s->hcom, &cto)) {
2149
        fprintf(stderr, "Failed SetCommTimeouts\n");
2150
        goto fail;
2151
    }
2152
    
2153
    if (!ClearCommError(s->hcom, &err, &comstat)) {
2154
        fprintf(stderr, "Failed ClearCommError\n");
2155
        goto fail;
2156
    }
2157
    qemu_add_polling_cb(win_chr_poll, chr);
2158
    return 0;
2159

    
2160
 fail:
2161
    win_chr_close(chr);
2162
    return -1;
2163
}
2164

    
2165
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2166
{
2167
    WinCharState *s = chr->opaque;
2168
    DWORD len, ret, size, err;
2169

    
2170
    len = len1;
2171
    ZeroMemory(&s->osend, sizeof(s->osend));
2172
    s->osend.hEvent = s->hsend;
2173
    while (len > 0) {
2174
        if (s->hsend)
2175
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2176
        else
2177
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
2178
        if (!ret) {
2179
            err = GetLastError();
2180
            if (err == ERROR_IO_PENDING) {
2181
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2182
                if (ret) {
2183
                    buf += size;
2184
                    len -= size;
2185
                } else {
2186
                    break;
2187
                }
2188
            } else {
2189
                break;
2190
            }
2191
        } else {
2192
            buf += size;
2193
            len -= size;
2194
        }
2195
    }
2196
    return len1 - len;
2197
}
2198

    
2199
static int win_chr_read_poll(CharDriverState *chr)
2200
{
2201
    WinCharState *s = chr->opaque;
2202

    
2203
    s->max_size = qemu_chr_can_read(chr);
2204
    return s->max_size;
2205
}
2206

    
2207
static void win_chr_readfile(CharDriverState *chr)
2208
{
2209
    WinCharState *s = chr->opaque;
2210
    int ret, err;
2211
    uint8_t buf[1024];
2212
    DWORD size;
2213
    
2214
    ZeroMemory(&s->orecv, sizeof(s->orecv));
2215
    s->orecv.hEvent = s->hrecv;
2216
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2217
    if (!ret) {
2218
        err = GetLastError();
2219
        if (err == ERROR_IO_PENDING) {
2220
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2221
        }
2222
    }
2223

    
2224
    if (size > 0) {
2225
        qemu_chr_read(chr, buf, size);
2226
    }
2227
}
2228

    
2229
static void win_chr_read(CharDriverState *chr)
2230
{
2231
    WinCharState *s = chr->opaque;
2232

    
2233
    if (s->len > s->max_size)
2234
        s->len = s->max_size;
2235
    if (s->len == 0)
2236
        return;
2237
    
2238
    win_chr_readfile(chr);
2239
}
2240

    
2241
static int win_chr_poll(void *opaque)
2242
{
2243
    CharDriverState *chr = opaque;
2244
    WinCharState *s = chr->opaque;
2245
    COMSTAT status;
2246
    DWORD comerr;
2247
    
2248
    ClearCommError(s->hcom, &comerr, &status);
2249
    if (status.cbInQue > 0) {
2250
        s->len = status.cbInQue;
2251
        win_chr_read_poll(chr);
2252
        win_chr_read(chr);
2253
        return 1;
2254
    }
2255
    return 0;
2256
}
2257

    
2258
static CharDriverState *qemu_chr_open_win(const char *filename)
2259
{
2260
    CharDriverState *chr;
2261
    WinCharState *s;
2262
    
2263
    chr = qemu_mallocz(sizeof(CharDriverState));
2264
    if (!chr)
2265
        return NULL;
2266
    s = qemu_mallocz(sizeof(WinCharState));
2267
    if (!s) {
2268
        free(chr);
2269
        return NULL;
2270
    }
2271
    chr->opaque = s;
2272
    chr->chr_write = win_chr_write;
2273
    chr->chr_close = win_chr_close;
2274

    
2275
    if (win_chr_init(chr, filename) < 0) {
2276
        free(s);
2277
        free(chr);
2278
        return NULL;
2279
    }
2280
    qemu_chr_reset(chr);
2281
    return chr;
2282
}
2283

    
2284
static int win_chr_pipe_poll(void *opaque)
2285
{
2286
    CharDriverState *chr = opaque;
2287
    WinCharState *s = chr->opaque;
2288
    DWORD size;
2289

    
2290
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2291
    if (size > 0) {
2292
        s->len = size;
2293
        win_chr_read_poll(chr);
2294
        win_chr_read(chr);
2295
        return 1;
2296
    }
2297
    return 0;
2298
}
2299

    
2300
static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2301
{
2302
    WinCharState *s = chr->opaque;
2303
    OVERLAPPED ov;
2304
    int ret;
2305
    DWORD size;
2306
    char openname[256];
2307
    
2308
    s->fpipe = TRUE;
2309

    
2310
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2311
    if (!s->hsend) {
2312
        fprintf(stderr, "Failed CreateEvent\n");
2313
        goto fail;
2314
    }
2315
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2316
    if (!s->hrecv) {
2317
        fprintf(stderr, "Failed CreateEvent\n");
2318
        goto fail;
2319
    }
2320
    
2321
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2322
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2323
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2324
                              PIPE_WAIT,
2325
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2326
    if (s->hcom == INVALID_HANDLE_VALUE) {
2327
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2328
        s->hcom = NULL;
2329
        goto fail;
2330
    }
2331

    
2332
    ZeroMemory(&ov, sizeof(ov));
2333
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2334
    ret = ConnectNamedPipe(s->hcom, &ov);
2335
    if (ret) {
2336
        fprintf(stderr, "Failed ConnectNamedPipe\n");
2337
        goto fail;
2338
    }
2339

    
2340
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2341
    if (!ret) {
2342
        fprintf(stderr, "Failed GetOverlappedResult\n");
2343
        if (ov.hEvent) {
2344
            CloseHandle(ov.hEvent);
2345
            ov.hEvent = NULL;
2346
        }
2347
        goto fail;
2348
    }
2349

    
2350
    if (ov.hEvent) {
2351
        CloseHandle(ov.hEvent);
2352
        ov.hEvent = NULL;
2353
    }
2354
    qemu_add_polling_cb(win_chr_pipe_poll, chr);
2355
    return 0;
2356

    
2357
 fail:
2358
    win_chr_close(chr);
2359
    return -1;
2360
}
2361

    
2362

    
2363
static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2364
{
2365
    CharDriverState *chr;
2366
    WinCharState *s;
2367

    
2368
    chr = qemu_mallocz(sizeof(CharDriverState));
2369
    if (!chr)
2370
        return NULL;
2371
    s = qemu_mallocz(sizeof(WinCharState));
2372
    if (!s) {
2373
        free(chr);
2374
        return NULL;
2375
    }
2376
    chr->opaque = s;
2377
    chr->chr_write = win_chr_write;
2378
    chr->chr_close = win_chr_close;
2379
    
2380
    if (win_chr_pipe_init(chr, filename) < 0) {
2381
        free(s);
2382
        free(chr);
2383
        return NULL;
2384
    }
2385
    qemu_chr_reset(chr);
2386
    return chr;
2387
}
2388

    
2389
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2390
{
2391
    CharDriverState *chr;
2392
    WinCharState *s;
2393

    
2394
    chr = qemu_mallocz(sizeof(CharDriverState));
2395
    if (!chr)
2396
        return NULL;
2397
    s = qemu_mallocz(sizeof(WinCharState));
2398
    if (!s) {
2399
        free(chr);
2400
        return NULL;
2401
    }
2402
    s->hcom = fd_out;
2403
    chr->opaque = s;
2404
    chr->chr_write = win_chr_write;
2405
    qemu_chr_reset(chr);
2406
    return chr;
2407
}
2408
    
2409
static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2410
{
2411
    HANDLE fd_out;
2412
    
2413
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2414
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2415
    if (fd_out == INVALID_HANDLE_VALUE)
2416
        return NULL;
2417

    
2418
    return qemu_chr_open_win_file(fd_out);
2419
}
2420
#endif
2421

    
2422
/***********************************************************/
2423
/* UDP Net console */
2424

    
2425
typedef struct {
2426
    int fd;
2427
    struct sockaddr_in daddr;
2428
    char buf[1024];
2429
    int bufcnt;
2430
    int bufptr;
2431
    int max_size;
2432
} NetCharDriver;
2433

    
2434
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2435
{
2436
    NetCharDriver *s = chr->opaque;
2437

    
2438
    return sendto(s->fd, buf, len, 0,
2439
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2440
}
2441

    
2442
static int udp_chr_read_poll(void *opaque)
2443
{
2444
    CharDriverState *chr = opaque;
2445
    NetCharDriver *s = chr->opaque;
2446

    
2447
    s->max_size = qemu_chr_can_read(chr);
2448

    
2449
    /* If there were any stray characters in the queue process them
2450
     * first
2451
     */
2452
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2453
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2454
        s->bufptr++;
2455
        s->max_size = qemu_chr_can_read(chr);
2456
    }
2457
    return s->max_size;
2458
}
2459

    
2460
static void udp_chr_read(void *opaque)
2461
{
2462
    CharDriverState *chr = opaque;
2463
    NetCharDriver *s = chr->opaque;
2464

    
2465
    if (s->max_size == 0)
2466
        return;
2467
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2468
    s->bufptr = s->bufcnt;
2469
    if (s->bufcnt <= 0)
2470
        return;
2471

    
2472
    s->bufptr = 0;
2473
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2474
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2475
        s->bufptr++;
2476
        s->max_size = qemu_chr_can_read(chr);
2477
    }
2478
}
2479

    
2480
static void udp_chr_update_read_handler(CharDriverState *chr)
2481
{
2482
    NetCharDriver *s = chr->opaque;
2483

    
2484
    if (s->fd >= 0) {
2485
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2486
                             udp_chr_read, NULL, chr);
2487
    }
2488
}
2489

    
2490
int parse_host_port(struct sockaddr_in *saddr, const char *str);
2491
#ifndef _WIN32
2492
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2493
#endif
2494
int parse_host_src_port(struct sockaddr_in *haddr,
2495
                        struct sockaddr_in *saddr,
2496
                        const char *str);
2497

    
2498
static CharDriverState *qemu_chr_open_udp(const char *def)
2499
{
2500
    CharDriverState *chr = NULL;
2501
    NetCharDriver *s = NULL;
2502
    int fd = -1;
2503
    struct sockaddr_in saddr;
2504

    
2505
    chr = qemu_mallocz(sizeof(CharDriverState));
2506
    if (!chr)
2507
        goto return_err;
2508
    s = qemu_mallocz(sizeof(NetCharDriver));
2509
    if (!s)
2510
        goto return_err;
2511

    
2512
    fd = socket(PF_INET, SOCK_DGRAM, 0);
2513
    if (fd < 0) {
2514
        perror("socket(PF_INET, SOCK_DGRAM)");
2515
        goto return_err;
2516
    }
2517

    
2518
    if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2519
        printf("Could not parse: %s\n", def);
2520
        goto return_err;
2521
    }
2522

    
2523
    if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2524
    {
2525
        perror("bind");
2526
        goto return_err;
2527
    }
2528

    
2529
    s->fd = fd;
2530
    s->bufcnt = 0;
2531
    s->bufptr = 0;
2532
    chr->opaque = s;
2533
    chr->chr_write = udp_chr_write;
2534
    chr->chr_update_read_handler = udp_chr_update_read_handler;
2535
    return chr;
2536

    
2537
return_err:
2538
    if (chr)
2539
        free(chr);
2540
    if (s)
2541
        free(s);
2542
    if (fd >= 0)
2543
        closesocket(fd);
2544
    return NULL;
2545
}
2546

    
2547
/***********************************************************/
2548
/* TCP Net console */
2549

    
2550
typedef struct {
2551
    int fd, listen_fd;
2552
    int connected;
2553
    int max_size;
2554
    int do_telnetopt;
2555
    int do_nodelay;
2556
    int is_unix;
2557
} TCPCharDriver;
2558

    
2559
static void tcp_chr_accept(void *opaque);
2560

    
2561
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2562
{
2563
    TCPCharDriver *s = chr->opaque;
2564
    if (s->connected) {
2565
        return send_all(s->fd, buf, len);
2566
    } else {
2567
        /* XXX: indicate an error ? */
2568
        return len;
2569
    }
2570
}
2571

    
2572
static int tcp_chr_read_poll(void *opaque)
2573
{
2574
    CharDriverState *chr = opaque;
2575
    TCPCharDriver *s = chr->opaque;
2576
    if (!s->connected)
2577
        return 0;
2578
    s->max_size = qemu_chr_can_read(chr);
2579
    return s->max_size;
2580
}
2581

    
2582
#define IAC 255
2583
#define IAC_BREAK 243
2584
static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2585
                                      TCPCharDriver *s,
2586
                                      char *buf, int *size)
2587
{
2588
    /* Handle any telnet client's basic IAC options to satisfy char by
2589
     * char mode with no echo.  All IAC options will be removed from
2590
     * the buf and the do_telnetopt variable will be used to track the
2591
     * state of the width of the IAC information.
2592
     *
2593
     * IAC commands come in sets of 3 bytes with the exception of the
2594
     * "IAC BREAK" command and the double IAC.
2595
     */
2596

    
2597
    int i;
2598
    int j = 0;
2599

    
2600
    for (i = 0; i < *size; i++) {
2601
        if (s->do_telnetopt > 1) {
2602
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2603
                /* Double IAC means send an IAC */
2604
                if (j != i)
2605
                    buf[j] = buf[i];
2606
                j++;
2607
                s->do_telnetopt = 1;
2608
            } else {
2609
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2610
                    /* Handle IAC break commands by sending a serial break */
2611
                    qemu_chr_event(chr, CHR_EVENT_BREAK);
2612
                    s->do_telnetopt++;
2613
                }
2614
                s->do_telnetopt++;
2615
            }
2616
            if (s->do_telnetopt >= 4) {
2617
                s->do_telnetopt = 1;
2618
            }
2619
        } else {
2620
            if ((unsigned char)buf[i] == IAC) {
2621
                s->do_telnetopt = 2;
2622
            } else {
2623
                if (j != i)
2624
                    buf[j] = buf[i];
2625
                j++;
2626
            }
2627
        }
2628
    }
2629
    *size = j;
2630
}
2631

    
2632
static void tcp_chr_read(void *opaque)
2633
{
2634
    CharDriverState *chr = opaque;
2635
    TCPCharDriver *s = chr->opaque;
2636
    uint8_t buf[1024];
2637
    int len, size;
2638

    
2639
    if (!s->connected || s->max_size <= 0)
2640
        return;
2641
    len = sizeof(buf);
2642
    if (len > s->max_size)
2643
        len = s->max_size;
2644
    size = recv(s->fd, buf, len, 0);
2645
    if (size == 0) {
2646
        /* connection closed */
2647
        s->connected = 0;
2648
        if (s->listen_fd >= 0) {
2649
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2650
        }
2651
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2652
        closesocket(s->fd);
2653
        s->fd = -1;
2654
    } else if (size > 0) {
2655
        if (s->do_telnetopt)
2656
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2657
        if (size > 0)
2658
            qemu_chr_read(chr, buf, size);
2659
    }
2660
}
2661

    
2662
static void tcp_chr_connect(void *opaque)
2663
{
2664
    CharDriverState *chr = opaque;
2665
    TCPCharDriver *s = chr->opaque;
2666

    
2667
    s->connected = 1;
2668
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2669
                         tcp_chr_read, NULL, chr);
2670
    qemu_chr_reset(chr);
2671
}
2672

    
2673
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2674
static void tcp_chr_telnet_init(int fd)
2675
{
2676
    char buf[3];
2677
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2678
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
2679
    send(fd, (char *)buf, 3, 0);
2680
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
2681
    send(fd, (char *)buf, 3, 0);
2682
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
2683
    send(fd, (char *)buf, 3, 0);
2684
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
2685
    send(fd, (char *)buf, 3, 0);
2686
}
2687

    
2688
static void socket_set_nodelay(int fd)
2689
{
2690
    int val = 1;
2691
    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2692
}
2693

    
2694
static void tcp_chr_accept(void *opaque)
2695
{
2696
    CharDriverState *chr = opaque;
2697
    TCPCharDriver *s = chr->opaque;
2698
    struct sockaddr_in saddr;
2699
#ifndef _WIN32
2700
    struct sockaddr_un uaddr;
2701
#endif
2702
    struct sockaddr *addr;
2703
    socklen_t len;
2704
    int fd;
2705

    
2706
    for(;;) {
2707
#ifndef _WIN32
2708
        if (s->is_unix) {
2709
            len = sizeof(uaddr);
2710
            addr = (struct sockaddr *)&uaddr;
2711
        } else
2712
#endif
2713
        {
2714
            len = sizeof(saddr);
2715
            addr = (struct sockaddr *)&saddr;
2716
        }
2717
        fd = accept(s->listen_fd, addr, &len);
2718
        if (fd < 0 && errno != EINTR) {
2719
            return;
2720
        } else if (fd >= 0) {
2721
            if (s->do_telnetopt)
2722
                tcp_chr_telnet_init(fd);
2723
            break;
2724
        }
2725
    }
2726
    socket_set_nonblock(fd);
2727
    if (s->do_nodelay)
2728
        socket_set_nodelay(fd);
2729
    s->fd = fd;
2730
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2731
    tcp_chr_connect(chr);
2732
}
2733

    
2734
static void tcp_chr_close(CharDriverState *chr)
2735
{
2736
    TCPCharDriver *s = chr->opaque;
2737
    if (s->fd >= 0)
2738
        closesocket(s->fd);
2739
    if (s->listen_fd >= 0)
2740
        closesocket(s->listen_fd);
2741
    qemu_free(s);
2742
}
2743

    
2744
static CharDriverState *qemu_chr_open_tcp(const char *host_str, 
2745
                                          int is_telnet,
2746
                                          int is_unix)
2747
{
2748
    CharDriverState *chr = NULL;
2749
    TCPCharDriver *s = NULL;
2750
    int fd = -1, ret, err, val;
2751
    int is_listen = 0;
2752
    int is_waitconnect = 1;
2753
    int do_nodelay = 0;
2754
    const char *ptr;
2755
    struct sockaddr_in saddr;
2756
#ifndef _WIN32
2757
    struct sockaddr_un uaddr;
2758
#endif
2759
    struct sockaddr *addr;
2760
    socklen_t addrlen;
2761

    
2762
#ifndef _WIN32
2763
    if (is_unix) {
2764
        addr = (struct sockaddr *)&uaddr;
2765
        addrlen = sizeof(uaddr);
2766
        if (parse_unix_path(&uaddr, host_str) < 0)
2767
            goto fail;
2768
    } else
2769
#endif
2770
    {
2771
        addr = (struct sockaddr *)&saddr;
2772
        addrlen = sizeof(saddr);
2773
        if (parse_host_port(&saddr, host_str) < 0)
2774
            goto fail;
2775
    }
2776

    
2777
    ptr = host_str;
2778
    while((ptr = strchr(ptr,','))) {
2779
        ptr++;
2780
        if (!strncmp(ptr,"server",6)) {
2781
            is_listen = 1;
2782
        } else if (!strncmp(ptr,"nowait",6)) {
2783
            is_waitconnect = 0;
2784
        } else if (!strncmp(ptr,"nodelay",6)) {
2785
            do_nodelay = 1;
2786
        } else {
2787
            printf("Unknown option: %s\n", ptr);
2788
            goto fail;
2789
        }
2790
    }
2791
    if (!is_listen)
2792
        is_waitconnect = 0;
2793

    
2794
    chr = qemu_mallocz(sizeof(CharDriverState));
2795
    if (!chr)
2796
        goto fail;
2797
    s = qemu_mallocz(sizeof(TCPCharDriver));
2798
    if (!s)
2799
        goto fail;
2800

    
2801
#ifndef _WIN32
2802
    if (is_unix)
2803
        fd = socket(PF_UNIX, SOCK_STREAM, 0);
2804
    else
2805
#endif
2806
        fd = socket(PF_INET, SOCK_STREAM, 0);
2807
        
2808
    if (fd < 0) 
2809
        goto fail;
2810

    
2811
    if (!is_waitconnect)
2812
        socket_set_nonblock(fd);
2813

    
2814
    s->connected = 0;
2815
    s->fd = -1;
2816
    s->listen_fd = -1;
2817
    s->is_unix = is_unix;
2818
    s->do_nodelay = do_nodelay && !is_unix;
2819

    
2820
    chr->opaque = s;
2821
    chr->chr_write = tcp_chr_write;
2822
    chr->chr_close = tcp_chr_close;
2823

    
2824
    if (is_listen) {
2825
        /* allow fast reuse */
2826
#ifndef _WIN32
2827
        if (is_unix) {
2828
            char path[109];
2829
            strncpy(path, uaddr.sun_path, 108);
2830
            path[108] = 0;
2831
            unlink(path);
2832
        } else
2833
#endif
2834
        {
2835
            val = 1;
2836
            setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2837
        }
2838
        
2839
        ret = bind(fd, addr, addrlen);
2840
        if (ret < 0)
2841
            goto fail;
2842

    
2843
        ret = listen(fd, 0);
2844
        if (ret < 0)
2845
            goto fail;
2846

    
2847
        s->listen_fd = fd;
2848
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2849
        if (is_telnet)
2850
            s->do_telnetopt = 1;
2851
    } else {
2852
        for(;;) {
2853
            ret = connect(fd, addr, addrlen);
2854
            if (ret < 0) {
2855
                err = socket_error();
2856
                if (err == EINTR || err == EWOULDBLOCK) {
2857
                } else if (err == EINPROGRESS) {
2858
                    break;
2859
#ifdef _WIN32
2860
                } else if (err == WSAEALREADY) {
2861
                    break;
2862
#endif
2863
                } else {
2864
                    goto fail;
2865
                }
2866
            } else {
2867
                s->connected = 1;
2868
                break;
2869
            }
2870
        }
2871
        s->fd = fd;
2872
        socket_set_nodelay(fd);
2873
        if (s->connected)
2874
            tcp_chr_connect(chr);
2875
        else
2876
            qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2877
    }
2878
    
2879
    if (is_listen && is_waitconnect) {
2880
        printf("QEMU waiting for connection on: %s\n", host_str);
2881
        tcp_chr_accept(chr);
2882
        socket_set_nonblock(s->listen_fd);
2883
    }
2884

    
2885
    return chr;
2886
 fail:
2887
    if (fd >= 0)
2888
        closesocket(fd);
2889
    qemu_free(s);
2890
    qemu_free(chr);
2891
    return NULL;
2892
}
2893

    
2894
CharDriverState *qemu_chr_open(const char *filename)
2895
{
2896
    const char *p;
2897

    
2898
    if (!strcmp(filename, "vc")) {
2899
        return text_console_init(&display_state);
2900
    } else if (!strcmp(filename, "null")) {
2901
        return qemu_chr_open_null();
2902
    } else 
2903
    if (strstart(filename, "tcp:", &p)) {
2904
        return qemu_chr_open_tcp(p, 0, 0);
2905
    } else
2906
    if (strstart(filename, "telnet:", &p)) {
2907
        return qemu_chr_open_tcp(p, 1, 0);
2908
    } else
2909
    if (strstart(filename, "udp:", &p)) {
2910
        return qemu_chr_open_udp(p);
2911
    } else
2912
    if (strstart(filename, "mon:", &p)) {
2913
        CharDriverState *drv = qemu_chr_open(p);
2914
        if (drv) {
2915
            drv = qemu_chr_open_mux(drv);
2916
            monitor_init(drv, !nographic);
2917
            return drv;
2918
        }
2919
        printf("Unable to open driver: %s\n", p);
2920
        return 0;
2921
    } else
2922
#ifndef _WIN32
2923
    if (strstart(filename, "unix:", &p)) {
2924
        return qemu_chr_open_tcp(p, 0, 1);
2925
    } else if (strstart(filename, "file:", &p)) {
2926
        return qemu_chr_open_file_out(p);
2927
    } else if (strstart(filename, "pipe:", &p)) {
2928
        return qemu_chr_open_pipe(p);
2929
    } else if (!strcmp(filename, "pty")) {
2930
        return qemu_chr_open_pty();
2931
    } else if (!strcmp(filename, "stdio")) {
2932
        return qemu_chr_open_stdio();
2933
    } else 
2934
#endif
2935
#if defined(__linux__)
2936
    if (strstart(filename, "/dev/parport", NULL)) {
2937
        return qemu_chr_open_pp(filename);
2938
    } else 
2939
    if (strstart(filename, "/dev/", NULL)) {
2940
        return qemu_chr_open_tty(filename);
2941
    } else 
2942
#endif
2943
#ifdef _WIN32
2944
    if (strstart(filename, "COM", NULL)) {
2945
        return qemu_chr_open_win(filename);
2946
    } else
2947
    if (strstart(filename, "pipe:", &p)) {
2948
        return qemu_chr_open_win_pipe(p);
2949
    } else
2950
    if (strstart(filename, "file:", &p)) {
2951
        return qemu_chr_open_win_file_out(p);
2952
    }
2953
#endif
2954
    {
2955
        return NULL;
2956
    }
2957
}
2958

    
2959
void qemu_chr_close(CharDriverState *chr)
2960
{
2961
    if (chr->chr_close)
2962
        chr->chr_close(chr);
2963
}
2964

    
2965
/***********************************************************/
2966
/* network device redirectors */
2967

    
2968
void hex_dump(FILE *f, const uint8_t *buf, int size)
2969
{
2970
    int len, i, j, c;
2971

    
2972
    for(i=0;i<size;i+=16) {
2973
        len = size - i;
2974
        if (len > 16)
2975
            len = 16;
2976
        fprintf(f, "%08x ", i);
2977
        for(j=0;j<16;j++) {
2978
            if (j < len)
2979
                fprintf(f, " %02x", buf[i+j]);
2980
            else
2981
                fprintf(f, "   ");
2982
        }
2983
        fprintf(f, " ");
2984
        for(j=0;j<len;j++) {
2985
            c = buf[i+j];
2986
            if (c < ' ' || c > '~')
2987
                c = '.';
2988
            fprintf(f, "%c", c);
2989
        }
2990
        fprintf(f, "\n");
2991
    }
2992
}
2993

    
2994
static int parse_macaddr(uint8_t *macaddr, const char *p)
2995
{
2996
    int i;
2997
    for(i = 0; i < 6; i++) {
2998
        macaddr[i] = strtol(p, (char **)&p, 16);
2999
        if (i == 5) {
3000
            if (*p != '\0') 
3001
                return -1;
3002
        } else {
3003
            if (*p != ':') 
3004
                return -1;
3005
            p++;
3006
        }
3007
    }
3008
    return 0;
3009
}
3010

    
3011
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3012
{
3013
    const char *p, *p1;
3014
    int len;
3015
    p = *pp;
3016
    p1 = strchr(p, sep);
3017
    if (!p1)
3018
        return -1;
3019
    len = p1 - p;
3020
    p1++;
3021
    if (buf_size > 0) {
3022
        if (len > buf_size - 1)
3023
            len = buf_size - 1;
3024
        memcpy(buf, p, len);
3025
        buf[len] = '\0';
3026
    }
3027
    *pp = p1;
3028
    return 0;
3029
}
3030

    
3031
int parse_host_src_port(struct sockaddr_in *haddr,
3032
                        struct sockaddr_in *saddr,
3033
                        const char *input_str)
3034
{
3035
    char *str = strdup(input_str);
3036
    char *host_str = str;
3037
    char *src_str;
3038
    char *ptr;
3039

    
3040
    /*
3041
     * Chop off any extra arguments at the end of the string which
3042
     * would start with a comma, then fill in the src port information
3043
     * if it was provided else use the "any address" and "any port".
3044
     */
3045
    if ((ptr = strchr(str,',')))
3046
        *ptr = '\0';
3047

    
3048
    if ((src_str = strchr(input_str,'@'))) {
3049
        *src_str = '\0';
3050
        src_str++;
3051
    }
3052

    
3053
    if (parse_host_port(haddr, host_str) < 0)
3054
        goto fail;
3055

    
3056
    if (!src_str || *src_str == '\0')
3057
        src_str = ":0";
3058

    
3059
    if (parse_host_port(saddr, src_str) < 0)
3060
        goto fail;
3061

    
3062
    free(str);
3063
    return(0);
3064

    
3065
fail:
3066
    free(str);
3067
    return -1;
3068
}
3069

    
3070
int parse_host_port(struct sockaddr_in *saddr, const char *str)
3071
{
3072
    char buf[512];
3073
    struct hostent *he;
3074
    const char *p, *r;
3075
    int port;
3076

    
3077
    p = str;
3078
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3079
        return -1;
3080
    saddr->sin_family = AF_INET;
3081
    if (buf[0] == '\0') {
3082
        saddr->sin_addr.s_addr = 0;
3083
    } else {
3084
        if (isdigit(buf[0])) {
3085
            if (!inet_aton(buf, &saddr->sin_addr))
3086
                return -1;
3087
        } else {
3088
            if ((he = gethostbyname(buf)) == NULL)
3089
                return - 1;
3090
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
3091
        }
3092
    }
3093
    port = strtol(p, (char **)&r, 0);
3094
    if (r == p)
3095
        return -1;
3096
    saddr->sin_port = htons(port);
3097
    return 0;
3098
}
3099

    
3100
#ifndef _WIN32
3101
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3102
{
3103
    const char *p;
3104
    int len;
3105

    
3106
    len = MIN(108, strlen(str));
3107
    p = strchr(str, ',');
3108
    if (p)
3109
        len = MIN(len, p - str);
3110

    
3111
    memset(uaddr, 0, sizeof(*uaddr));
3112

    
3113
    uaddr->sun_family = AF_UNIX;
3114
    memcpy(uaddr->sun_path, str, len);
3115

    
3116
    return 0;
3117
}
3118
#endif
3119

    
3120
/* find or alloc a new VLAN */
3121
VLANState *qemu_find_vlan(int id)
3122
{
3123
    VLANState **pvlan, *vlan;
3124
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3125
        if (vlan->id == id)
3126
            return vlan;
3127
    }
3128
    vlan = qemu_mallocz(sizeof(VLANState));
3129
    if (!vlan)
3130
        return NULL;
3131
    vlan->id = id;
3132
    vlan->next = NULL;
3133
    pvlan = &first_vlan;
3134
    while (*pvlan != NULL)
3135
        pvlan = &(*pvlan)->next;
3136
    *pvlan = vlan;
3137
    return vlan;
3138
}
3139

    
3140
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3141
                                      IOReadHandler *fd_read,
3142
                                      IOCanRWHandler *fd_can_read,
3143
                                      void *opaque)
3144
{
3145
    VLANClientState *vc, **pvc;
3146
    vc = qemu_mallocz(sizeof(VLANClientState));
3147
    if (!vc)
3148
        return NULL;
3149
    vc->fd_read = fd_read;
3150
    vc->fd_can_read = fd_can_read;
3151
    vc->opaque = opaque;
3152
    vc->vlan = vlan;
3153

    
3154
    vc->next = NULL;
3155
    pvc = &vlan->first_client;
3156
    while (*pvc != NULL)
3157
        pvc = &(*pvc)->next;
3158
    *pvc = vc;
3159
    return vc;
3160
}
3161

    
3162
int qemu_can_send_packet(VLANClientState *vc1)
3163
{
3164
    VLANState *vlan = vc1->vlan;
3165
    VLANClientState *vc;
3166

    
3167
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3168
        if (vc != vc1) {
3169
            if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3170
                return 0;
3171
        }
3172
    }
3173
    return 1;
3174
}
3175

    
3176
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3177
{
3178
    VLANState *vlan = vc1->vlan;
3179
    VLANClientState *vc;
3180

    
3181
#if 0
3182
    printf("vlan %d send:\n", vlan->id);
3183
    hex_dump(stdout, buf, size);
3184
#endif
3185
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3186
        if (vc != vc1) {
3187
            vc->fd_read(vc->opaque, buf, size);
3188
        }
3189
    }
3190
}
3191

    
3192
#if defined(CONFIG_SLIRP)
3193

    
3194
/* slirp network adapter */
3195

    
3196
static int slirp_inited;
3197
static VLANClientState *slirp_vc;
3198

    
3199
int slirp_can_output(void)
3200
{
3201
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
3202
}
3203

    
3204
void slirp_output(const uint8_t *pkt, int pkt_len)
3205
{
3206
#if 0
3207
    printf("slirp output:\n");
3208
    hex_dump(stdout, pkt, pkt_len);
3209
#endif
3210
    if (!slirp_vc)
3211
        return;
3212
    qemu_send_packet(slirp_vc, pkt, pkt_len);
3213
}
3214

    
3215
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3216
{
3217
#if 0
3218
    printf("slirp input:\n");
3219
    hex_dump(stdout, buf, size);
3220
#endif
3221
    slirp_input(buf, size);
3222
}
3223

    
3224
static int net_slirp_init(VLANState *vlan)
3225
{
3226
    if (!slirp_inited) {
3227
        slirp_inited = 1;
3228
        slirp_init();
3229
    }
3230
    slirp_vc = qemu_new_vlan_client(vlan, 
3231
                                    slirp_receive, NULL, NULL);
3232
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3233
    return 0;
3234
}
3235

    
3236
static void net_slirp_redir(const char *redir_str)
3237
{
3238
    int is_udp;
3239
    char buf[256], *r;
3240
    const char *p;
3241
    struct in_addr guest_addr;
3242
    int host_port, guest_port;
3243
    
3244
    if (!slirp_inited) {
3245
        slirp_inited = 1;
3246
        slirp_init();
3247
    }
3248

    
3249
    p = redir_str;
3250
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3251
        goto fail;
3252
    if (!strcmp(buf, "tcp")) {
3253
        is_udp = 0;
3254
    } else if (!strcmp(buf, "udp")) {
3255
        is_udp = 1;
3256
    } else {
3257
        goto fail;
3258
    }
3259

    
3260
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3261
        goto fail;
3262
    host_port = strtol(buf, &r, 0);
3263
    if (r == buf)
3264
        goto fail;
3265

    
3266
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3267
        goto fail;
3268
    if (buf[0] == '\0') {
3269
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
3270
    }
3271
    if (!inet_aton(buf, &guest_addr))
3272
        goto fail;
3273
    
3274
    guest_port = strtol(p, &r, 0);
3275
    if (r == p)
3276
        goto fail;
3277
    
3278
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3279
        fprintf(stderr, "qemu: could not set up redirection\n");
3280
        exit(1);
3281
    }
3282
    return;
3283
 fail:
3284
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3285
    exit(1);
3286
}
3287
    
3288
#ifndef _WIN32
3289

    
3290
char smb_dir[1024];
3291

    
3292
static void smb_exit(void)
3293
{
3294
    DIR *d;
3295
    struct dirent *de;
3296
    char filename[1024];
3297

    
3298
    /* erase all the files in the directory */
3299
    d = opendir(smb_dir);
3300
    for(;;) {
3301
        de = readdir(d);
3302
        if (!de)
3303
            break;
3304
        if (strcmp(de->d_name, ".") != 0 &&
3305
            strcmp(de->d_name, "..") != 0) {
3306
            snprintf(filename, sizeof(filename), "%s/%s", 
3307
                     smb_dir, de->d_name);
3308
            unlink(filename);
3309
        }
3310
    }
3311
    closedir(d);
3312
    rmdir(smb_dir);
3313
}
3314

    
3315
/* automatic user mode samba server configuration */
3316
void net_slirp_smb(const char *exported_dir)
3317
{
3318
    char smb_conf[1024];
3319
    char smb_cmdline[1024];
3320
    FILE *f;
3321

    
3322
    if (!slirp_inited) {
3323
        slirp_inited = 1;
3324
        slirp_init();
3325
    }
3326

    
3327
    /* XXX: better tmp dir construction */
3328
    snprintf(smb_dir, sizeof(smb_dir), "/tmp/qemu-smb.%d", getpid());
3329
    if (mkdir(smb_dir, 0700) < 0) {
3330
        fprintf(stderr, "qemu: could not create samba server dir '%s'\n", smb_dir);
3331
        exit(1);
3332
    }
3333
    snprintf(smb_conf, sizeof(smb_conf), "%s/%s", smb_dir, "smb.conf");
3334
    
3335
    f = fopen(smb_conf, "w");
3336
    if (!f) {
3337
        fprintf(stderr, "qemu: could not create samba server configuration file '%s'\n", smb_conf);
3338
        exit(1);
3339
    }
3340
    fprintf(f, 
3341
            "[global]\n"
3342
            "private dir=%s\n"
3343
            "smb ports=0\n"
3344
            "socket address=127.0.0.1\n"
3345
            "pid directory=%s\n"
3346
            "lock directory=%s\n"
3347
            "log file=%s/log.smbd\n"
3348
            "smb passwd file=%s/smbpasswd\n"
3349
            "security = share\n"
3350
            "[qemu]\n"
3351
            "path=%s\n"
3352
            "read only=no\n"
3353
            "guest ok=yes\n",
3354
            smb_dir,
3355
            smb_dir,
3356
            smb_dir,
3357
            smb_dir,
3358
            smb_dir,
3359
            exported_dir
3360
            );
3361
    fclose(f);
3362
    atexit(smb_exit);
3363

    
3364
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3365
             SMBD_COMMAND, smb_conf);
3366
    
3367
    slirp_add_exec(0, smb_cmdline, 4, 139);
3368
}
3369

    
3370
#endif /* !defined(_WIN32) */
3371

    
3372
#endif /* CONFIG_SLIRP */
3373

    
3374
#if !defined(_WIN32)
3375

    
3376
typedef struct TAPState {
3377
    VLANClientState *vc;
3378
    int fd;
3379
} TAPState;
3380

    
3381
static void tap_receive(void *opaque, const uint8_t *buf, int size)
3382
{
3383
    TAPState *s = opaque;
3384
    int ret;
3385
    for(;;) {
3386
        ret = write(s->fd, buf, size);
3387
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3388
        } else {
3389
            break;
3390
        }
3391
    }
3392
}
3393

    
3394
static void tap_send(void *opaque)
3395
{
3396
    TAPState *s = opaque;
3397
    uint8_t buf[4096];
3398
    int size;
3399

    
3400
#ifdef __sun__
3401
    struct strbuf sbuf;
3402
    int f = 0;
3403
    sbuf.maxlen = sizeof(buf);
3404
    sbuf.buf = buf;
3405
    size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3406
#else
3407
    size = read(s->fd, buf, sizeof(buf));
3408
#endif
3409
    if (size > 0) {
3410
        qemu_send_packet(s->vc, buf, size);
3411
    }
3412
}
3413

    
3414
/* fd support */
3415

    
3416
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3417
{
3418
    TAPState *s;
3419

    
3420
    s = qemu_mallocz(sizeof(TAPState));
3421
    if (!s)
3422
        return NULL;
3423
    s->fd = fd;
3424
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3425
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3426
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3427
    return s;
3428
}
3429

    
3430
#ifdef _BSD
3431
static int tap_open(char *ifname, int ifname_size)
3432
{
3433
    int fd;
3434
    char *dev;
3435
    struct stat s;
3436

    
3437
    fd = open("/dev/tap", O_RDWR);
3438
    if (fd < 0) {
3439
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3440
        return -1;
3441
    }
3442

    
3443
    fstat(fd, &s);
3444
    dev = devname(s.st_rdev, S_IFCHR);
3445
    pstrcpy(ifname, ifname_size, dev);
3446

    
3447
    fcntl(fd, F_SETFL, O_NONBLOCK);
3448
    return fd;
3449
}
3450
#elif defined(__sun__)
3451
#define TUNNEWPPA       (('T'<<16) | 0x0001)
3452
/* 
3453
 * Allocate TAP device, returns opened fd. 
3454
 * Stores dev name in the first arg(must be large enough).
3455
 */  
3456
int tap_alloc(char *dev)
3457
{
3458
    int tap_fd, if_fd, ppa = -1;
3459
    static int ip_fd = 0;
3460
    char *ptr;
3461

    
3462
    static int arp_fd = 0;
3463
    int ip_muxid, arp_muxid;
3464
    struct strioctl  strioc_if, strioc_ppa;
3465
    int link_type = I_PLINK;;
3466
    struct lifreq ifr;
3467
    char actual_name[32] = "";
3468

    
3469
    memset(&ifr, 0x0, sizeof(ifr));
3470

    
3471
    if( *dev ){
3472
       ptr = dev;        
3473
       while( *ptr && !isdigit((int)*ptr) ) ptr++; 
3474
       ppa = atoi(ptr);
3475
    }
3476

    
3477
    /* Check if IP device was opened */
3478
    if( ip_fd )
3479
       close(ip_fd);
3480

    
3481
    if( (ip_fd = open("/dev/udp", O_RDWR, 0)) < 0){
3482
       syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3483
       return -1;
3484
    }
3485

    
3486
    if( (tap_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3487
       syslog(LOG_ERR, "Can't open /dev/tap");
3488
       return -1;
3489
    }
3490

    
3491
    /* Assign a new PPA and get its unit number. */
3492
    strioc_ppa.ic_cmd = TUNNEWPPA;
3493
    strioc_ppa.ic_timout = 0;
3494
    strioc_ppa.ic_len = sizeof(ppa);
3495
    strioc_ppa.ic_dp = (char *)&ppa;
3496
    if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3497
       syslog (LOG_ERR, "Can't assign new interface");
3498

    
3499
    if( (if_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3500
       syslog(LOG_ERR, "Can't open /dev/tap (2)");
3501
       return -1;
3502
    }
3503
    if(ioctl(if_fd, I_PUSH, "ip") < 0){
3504
       syslog(LOG_ERR, "Can't push IP module");
3505
       return -1;
3506
    }
3507

    
3508
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3509
        syslog(LOG_ERR, "Can't get flags\n");
3510

    
3511
    snprintf (actual_name, 32, "tap%d", ppa);
3512
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3513

    
3514
    ifr.lifr_ppa = ppa;
3515
    /* Assign ppa according to the unit number returned by tun device */
3516

    
3517
    if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3518
        syslog (LOG_ERR, "Can't set PPA %d", ppa);
3519
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3520
        syslog (LOG_ERR, "Can't get flags\n");
3521
    /* Push arp module to if_fd */
3522
    if (ioctl (if_fd, I_PUSH, "arp") < 0)
3523
        syslog (LOG_ERR, "Can't push ARP module (2)");
3524

    
3525
    /* Push arp module to ip_fd */
3526
    if (ioctl (ip_fd, I_POP, NULL) < 0)
3527
        syslog (LOG_ERR, "I_POP failed\n");
3528
    if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3529
        syslog (LOG_ERR, "Can't push ARP module (3)\n");
3530
    /* Open arp_fd */
3531
    if ((arp_fd = open ("/dev/tap", O_RDWR, 0)) < 0)
3532
       syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3533

    
3534
    /* Set ifname to arp */
3535
    strioc_if.ic_cmd = SIOCSLIFNAME;
3536
    strioc_if.ic_timout = 0;
3537
    strioc_if.ic_len = sizeof(ifr);
3538
    strioc_if.ic_dp = (char *)&ifr;
3539
    if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3540
        syslog (LOG_ERR, "Can't set ifname to arp\n");
3541
    }
3542

    
3543
    if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3544
       syslog(LOG_ERR, "Can't link TAP device to IP");
3545
       return -1;
3546
    }
3547

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

    
3551
    close (if_fd);
3552

    
3553
    memset(&ifr, 0x0, sizeof(ifr));
3554
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3555
    ifr.lifr_ip_muxid  = ip_muxid;
3556
    ifr.lifr_arp_muxid = arp_muxid;
3557

    
3558
    if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3559
    {
3560
      ioctl (ip_fd, I_PUNLINK , arp_muxid);
3561
      ioctl (ip_fd, I_PUNLINK, ip_muxid);
3562
      syslog (LOG_ERR, "Can't set multiplexor id");
3563
    }
3564

    
3565
    sprintf(dev, "tap%d", ppa);
3566
    return tap_fd;
3567
}
3568

    
3569
static int tap_open(char *ifname, int ifname_size)
3570
{
3571
    char  dev[10]="";
3572
    int fd;
3573
    if( (fd = tap_alloc(dev)) < 0 ){
3574
       fprintf(stderr, "Cannot allocate TAP device\n");
3575
       return -1;
3576
    }
3577
    pstrcpy(ifname, ifname_size, dev);
3578
    fcntl(fd, F_SETFL, O_NONBLOCK);
3579
    return fd;
3580
}
3581
#else
3582
static int tap_open(char *ifname, int ifname_size)
3583
{
3584
    struct ifreq ifr;
3585
    int fd, ret;
3586
    
3587
    fd = open("/dev/net/tun", O_RDWR);
3588
    if (fd < 0) {
3589
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
3590
        return -1;
3591
    }
3592
    memset(&ifr, 0, sizeof(ifr));
3593
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
3594
    if (ifname[0] != '\0')
3595
        pstrcpy(ifr.ifr_name, IFNAMSIZ, ifname);
3596
    else
3597
        pstrcpy(ifr.ifr_name, IFNAMSIZ, "tap%d");
3598
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
3599
    if (ret != 0) {
3600
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
3601
        close(fd);
3602
        return -1;
3603
    }
3604
    pstrcpy(ifname, ifname_size, ifr.ifr_name);
3605
    fcntl(fd, F_SETFL, O_NONBLOCK);
3606
    return fd;
3607
}
3608
#endif
3609

    
3610
static int net_tap_init(VLANState *vlan, const char *ifname1,
3611
                        const char *setup_script)
3612
{
3613
    TAPState *s;
3614
    int pid, status, fd;
3615
    char *args[3];
3616
    char **parg;
3617
    char ifname[128];
3618

    
3619
    if (ifname1 != NULL)
3620
        pstrcpy(ifname, sizeof(ifname), ifname1);
3621
    else
3622
        ifname[0] = '\0';
3623
    fd = tap_open(ifname, sizeof(ifname));
3624
    if (fd < 0)
3625
        return -1;
3626

    
3627
    if (!setup_script || !strcmp(setup_script, "no"))
3628
        setup_script = "";
3629
    if (setup_script[0] != '\0') {
3630
        /* try to launch network init script */
3631
        pid = fork();
3632
        if (pid >= 0) {
3633
            if (pid == 0) {
3634
                int open_max = sysconf (_SC_OPEN_MAX), i;
3635
                for (i = 0; i < open_max; i++)
3636
                    if (i != STDIN_FILENO &&
3637
                        i != STDOUT_FILENO &&
3638
                        i != STDERR_FILENO &&
3639
                        i != fd)
3640
                        close(i);
3641

    
3642
                parg = args;
3643
                *parg++ = (char *)setup_script;
3644
                *parg++ = ifname;
3645
                *parg++ = NULL;
3646
                execv(setup_script, args);
3647
                _exit(1);
3648
            }
3649
            while (waitpid(pid, &status, 0) != pid);
3650
            if (!WIFEXITED(status) ||
3651
                WEXITSTATUS(status) != 0) {
3652
                fprintf(stderr, "%s: could not launch network script\n",
3653
                        setup_script);
3654
                return -1;
3655
            }
3656
        }
3657
    }
3658
    s = net_tap_fd_init(vlan, fd);
3659
    if (!s)
3660
        return -1;
3661
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
3662
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
3663
    return 0;
3664
}
3665

    
3666
#endif /* !_WIN32 */
3667

    
3668
/* network connection */
3669
typedef struct NetSocketState {
3670
    VLANClientState *vc;
3671
    int fd;
3672
    int state; /* 0 = getting length, 1 = getting data */
3673
    int index;
3674
    int packet_len;
3675
    uint8_t buf[4096];
3676
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3677
} NetSocketState;
3678

    
3679
typedef struct NetSocketListenState {
3680
    VLANState *vlan;
3681
    int fd;
3682
} NetSocketListenState;
3683

    
3684
/* XXX: we consider we can send the whole packet without blocking */
3685
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3686
{
3687
    NetSocketState *s = opaque;
3688
    uint32_t len;
3689
    len = htonl(size);
3690

    
3691
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3692
    send_all(s->fd, buf, size);
3693
}
3694

    
3695
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3696
{
3697
    NetSocketState *s = opaque;
3698
    sendto(s->fd, buf, size, 0, 
3699
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3700
}
3701

    
3702
static void net_socket_send(void *opaque)
3703
{
3704
    NetSocketState *s = opaque;
3705
    int l, size, err;
3706
    uint8_t buf1[4096];
3707
    const uint8_t *buf;
3708

    
3709
    size = recv(s->fd, buf1, sizeof(buf1), 0);
3710
    if (size < 0) {
3711
        err = socket_error();
3712
        if (err != EWOULDBLOCK) 
3713
            goto eoc;
3714
    } else if (size == 0) {
3715
        /* end of connection */
3716
    eoc:
3717
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3718
        closesocket(s->fd);
3719
        return;
3720
    }
3721
    buf = buf1;
3722
    while (size > 0) {
3723
        /* reassemble a packet from the network */
3724
        switch(s->state) {
3725
        case 0:
3726
            l = 4 - s->index;
3727
            if (l > size)
3728
                l = size;
3729
            memcpy(s->buf + s->index, buf, l);
3730
            buf += l;
3731
            size -= l;
3732
            s->index += l;
3733
            if (s->index == 4) {
3734
                /* got length */
3735
                s->packet_len = ntohl(*(uint32_t *)s->buf);
3736
                s->index = 0;
3737
                s->state = 1;
3738
            }
3739
            break;
3740
        case 1:
3741
            l = s->packet_len - s->index;
3742
            if (l > size)
3743
                l = size;
3744
            memcpy(s->buf + s->index, buf, l);
3745
            s->index += l;
3746
            buf += l;
3747
            size -= l;
3748
            if (s->index >= s->packet_len) {
3749
                qemu_send_packet(s->vc, s->buf, s->packet_len);
3750
                s->index = 0;
3751
                s->state = 0;
3752
            }
3753
            break;
3754
        }
3755
    }
3756
}
3757

    
3758
static void net_socket_send_dgram(void *opaque)
3759
{
3760
    NetSocketState *s = opaque;
3761
    int size;
3762

    
3763
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3764
    if (size < 0) 
3765
        return;
3766
    if (size == 0) {
3767
        /* end of connection */
3768
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3769
        return;
3770
    }
3771
    qemu_send_packet(s->vc, s->buf, size);
3772
}
3773

    
3774
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3775
{
3776
    struct ip_mreq imr;
3777
    int fd;
3778
    int val, ret;
3779
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3780
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3781
                inet_ntoa(mcastaddr->sin_addr), 
3782
                (int)ntohl(mcastaddr->sin_addr.s_addr));
3783
        return -1;
3784

    
3785
    }
3786
    fd = socket(PF_INET, SOCK_DGRAM, 0);
3787
    if (fd < 0) {
3788
        perror("socket(PF_INET, SOCK_DGRAM)");
3789
        return -1;
3790
    }
3791

    
3792
    val = 1;
3793
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, 
3794
                   (const char *)&val, sizeof(val));
3795
    if (ret < 0) {
3796
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3797
        goto fail;
3798
    }
3799

    
3800
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3801
    if (ret < 0) {
3802
        perror("bind");
3803
        goto fail;
3804
    }
3805
    
3806
    /* Add host to multicast group */
3807
    imr.imr_multiaddr = mcastaddr->sin_addr;
3808
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
3809

    
3810
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, 
3811
                     (const char *)&imr, sizeof(struct ip_mreq));
3812
    if (ret < 0) {
3813
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
3814
        goto fail;
3815
    }
3816

    
3817
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3818
    val = 1;
3819
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, 
3820
                   (const char *)&val, sizeof(val));
3821
    if (ret < 0) {
3822
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3823
        goto fail;
3824
    }
3825

    
3826
    socket_set_nonblock(fd);
3827
    return fd;
3828
fail:
3829
    if (fd >= 0) 
3830
        closesocket(fd);
3831
    return -1;
3832
}
3833

    
3834
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd, 
3835
                                          int is_connected)
3836
{
3837
    struct sockaddr_in saddr;
3838
    int newfd;
3839
    socklen_t saddr_len;
3840
    NetSocketState *s;
3841

    
3842
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3843
     * Because this may be "shared" socket from a "master" process, datagrams would be recv() 
3844
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
3845
     */
3846

    
3847
    if (is_connected) {
3848
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3849
            /* must be bound */
3850
            if (saddr.sin_addr.s_addr==0) {
3851
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3852
                        fd);
3853
                return NULL;
3854
            }
3855
            /* clone dgram socket */
3856
            newfd = net_socket_mcast_create(&saddr);
3857
            if (newfd < 0) {
3858
                /* error already reported by net_socket_mcast_create() */
3859
                close(fd);
3860
                return NULL;
3861
            }
3862
            /* clone newfd to fd, close newfd */
3863
            dup2(newfd, fd);
3864
            close(newfd);
3865
        
3866
        } else {
3867
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3868
                    fd, strerror(errno));
3869
            return NULL;
3870
        }
3871
    }
3872

    
3873
    s = qemu_mallocz(sizeof(NetSocketState));
3874
    if (!s)
3875
        return NULL;
3876
    s->fd = fd;
3877

    
3878
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3879
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3880

    
3881
    /* mcast: save bound address as dst */
3882
    if (is_connected) s->dgram_dst=saddr;
3883

    
3884
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3885
            "socket: fd=%d (%s mcast=%s:%d)", 
3886
            fd, is_connected? "cloned" : "",
3887
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3888
    return s;
3889
}
3890

    
3891
static void net_socket_connect(void *opaque)
3892
{
3893
    NetSocketState *s = opaque;
3894
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3895
}
3896

    
3897
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd, 
3898
                                          int is_connected)
3899
{
3900
    NetSocketState *s;
3901
    s = qemu_mallocz(sizeof(NetSocketState));
3902
    if (!s)
3903
        return NULL;
3904
    s->fd = fd;
3905
    s->vc = qemu_new_vlan_client(vlan, 
3906
                                 net_socket_receive, NULL, s);
3907
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3908
             "socket: fd=%d", fd);
3909
    if (is_connected) {
3910
        net_socket_connect(s);
3911
    } else {
3912
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3913
    }
3914
    return s;
3915
}
3916

    
3917
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd, 
3918
                                          int is_connected)
3919
{
3920
    int so_type=-1, optlen=sizeof(so_type);
3921

    
3922
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3923
        fprintf(stderr, "qemu: error: setsockopt(SO_TYPE) for fd=%d failed\n", fd);
3924
        return NULL;
3925
    }
3926
    switch(so_type) {
3927
    case SOCK_DGRAM:
3928
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
3929
    case SOCK_STREAM:
3930
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3931
    default:
3932
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3933
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3934
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3935
    }
3936
    return NULL;
3937
}
3938

    
3939
static void net_socket_accept(void *opaque)
3940
{
3941
    NetSocketListenState *s = opaque;    
3942
    NetSocketState *s1;
3943
    struct sockaddr_in saddr;
3944
    socklen_t len;
3945
    int fd;
3946

    
3947
    for(;;) {
3948
        len = sizeof(saddr);
3949
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3950
        if (fd < 0 && errno != EINTR) {
3951
            return;
3952
        } else if (fd >= 0) {
3953
            break;
3954
        }
3955
    }
3956
    s1 = net_socket_fd_init(s->vlan, fd, 1); 
3957
    if (!s1) {
3958
        closesocket(fd);
3959
    } else {
3960
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3961
                 "socket: connection from %s:%d", 
3962
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3963
    }
3964
}
3965

    
3966
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3967
{
3968
    NetSocketListenState *s;
3969
    int fd, val, ret;
3970
    struct sockaddr_in saddr;
3971

    
3972
    if (parse_host_port(&saddr, host_str) < 0)
3973
        return -1;
3974
    
3975
    s = qemu_mallocz(sizeof(NetSocketListenState));
3976
    if (!s)
3977
        return -1;
3978

    
3979
    fd = socket(PF_INET, SOCK_STREAM, 0);
3980
    if (fd < 0) {
3981
        perror("socket");
3982
        return -1;
3983
    }
3984
    socket_set_nonblock(fd);
3985

    
3986
    /* allow fast reuse */
3987
    val = 1;
3988
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
3989
    
3990
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
3991
    if (ret < 0) {
3992
        perror("bind");
3993
        return -1;
3994
    }
3995
    ret = listen(fd, 0);
3996
    if (ret < 0) {
3997
        perror("listen");
3998
        return -1;
3999
    }
4000
    s->vlan = vlan;
4001
    s->fd = fd;
4002
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4003
    return 0;
4004
}
4005

    
4006
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4007
{
4008
    NetSocketState *s;
4009
    int fd, connected, ret, err;
4010
    struct sockaddr_in saddr;
4011

    
4012
    if (parse_host_port(&saddr, host_str) < 0)
4013
        return -1;
4014

    
4015
    fd = socket(PF_INET, SOCK_STREAM, 0);
4016
    if (fd < 0) {
4017
        perror("socket");
4018
        return -1;
4019
    }
4020
    socket_set_nonblock(fd);
4021

    
4022
    connected = 0;
4023
    for(;;) {
4024
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4025
        if (ret < 0) {
4026
            err = socket_error();
4027
            if (err == EINTR || err == EWOULDBLOCK) {
4028
            } else if (err == EINPROGRESS) {
4029
                break;
4030
#ifdef _WIN32
4031
            } else if (err == WSAEALREADY) {
4032
                break;
4033
#endif
4034
            } else {
4035
                perror("connect");
4036
                closesocket(fd);
4037
                return -1;
4038
            }
4039
        } else {
4040
            connected = 1;
4041
            break;
4042
        }
4043
    }
4044
    s = net_socket_fd_init(vlan, fd, connected);
4045
    if (!s)
4046
        return -1;
4047
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4048
             "socket: connect to %s:%d", 
4049
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4050
    return 0;
4051
}
4052

    
4053
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4054
{
4055
    NetSocketState *s;
4056
    int fd;
4057
    struct sockaddr_in saddr;
4058

    
4059
    if (parse_host_port(&saddr, host_str) < 0)
4060
        return -1;
4061

    
4062

    
4063
    fd = net_socket_mcast_create(&saddr);
4064
    if (fd < 0)
4065
        return -1;
4066

    
4067
    s = net_socket_fd_init(vlan, fd, 0);
4068
    if (!s)
4069
        return -1;
4070

    
4071
    s->dgram_dst = saddr;
4072
    
4073
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4074
             "socket: mcast=%s:%d", 
4075
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4076
    return 0;
4077

    
4078
}
4079

    
4080
static int get_param_value(char *buf, int buf_size,
4081
                           const char *tag, const char *str)
4082
{
4083
    const char *p;
4084
    char *q;
4085
    char option[128];
4086

    
4087
    p = str;
4088
    for(;;) {
4089
        q = option;
4090
        while (*p != '\0' && *p != '=') {
4091
            if ((q - option) < sizeof(option) - 1)
4092
                *q++ = *p;
4093
            p++;
4094
        }
4095
        *q = '\0';
4096
        if (*p != '=')
4097
            break;
4098
        p++;
4099
        if (!strcmp(tag, option)) {
4100
            q = buf;
4101
            while (*p != '\0' && *p != ',') {
4102
                if ((q - buf) < buf_size - 1)
4103
                    *q++ = *p;
4104
                p++;
4105
            }
4106
            *q = '\0';
4107
            return q - buf;
4108
        } else {
4109
            while (*p != '\0' && *p != ',') {
4110
                p++;
4111
            }
4112
        }
4113
        if (*p != ',')
4114
            break;
4115
        p++;
4116
    }
4117
    return 0;
4118
}
4119

    
4120
static int net_client_init(const char *str)
4121
{
4122
    const char *p;
4123
    char *q;
4124
    char device[64];
4125
    char buf[1024];
4126
    int vlan_id, ret;
4127
    VLANState *vlan;
4128

    
4129
    p = str;
4130
    q = device;
4131
    while (*p != '\0' && *p != ',') {
4132
        if ((q - device) < sizeof(device) - 1)
4133
            *q++ = *p;
4134
        p++;
4135
    }
4136
    *q = '\0';
4137
    if (*p == ',')
4138
        p++;
4139
    vlan_id = 0;
4140
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4141
        vlan_id = strtol(buf, NULL, 0);
4142
    }
4143
    vlan = qemu_find_vlan(vlan_id);
4144
    if (!vlan) {
4145
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4146
        return -1;
4147
    }
4148
    if (!strcmp(device, "nic")) {
4149
        NICInfo *nd;
4150
        uint8_t *macaddr;
4151

    
4152
        if (nb_nics >= MAX_NICS) {
4153
            fprintf(stderr, "Too Many NICs\n");
4154
            return -1;
4155
        }
4156
        nd = &nd_table[nb_nics];
4157
        macaddr = nd->macaddr;
4158
        macaddr[0] = 0x52;
4159
        macaddr[1] = 0x54;
4160
        macaddr[2] = 0x00;
4161
        macaddr[3] = 0x12;
4162
        macaddr[4] = 0x34;
4163
        macaddr[5] = 0x56 + nb_nics;
4164

    
4165
        if (get_param_value(buf, sizeof(buf), "macaddr", p)) {
4166
            if (parse_macaddr(macaddr, buf) < 0) {
4167
                fprintf(stderr, "invalid syntax for ethernet address\n");
4168
                return -1;
4169
            }
4170
        }
4171
        if (get_param_value(buf, sizeof(buf), "model", p)) {
4172
            nd->model = strdup(buf);
4173
        }
4174
        nd->vlan = vlan;
4175
        nb_nics++;
4176
        ret = 0;
4177
    } else
4178
    if (!strcmp(device, "none")) {
4179
        /* does nothing. It is needed to signal that no network cards
4180
           are wanted */
4181
        ret = 0;
4182
    } else
4183
#ifdef CONFIG_SLIRP
4184
    if (!strcmp(device, "user")) {
4185
        if (get_param_value(buf, sizeof(buf), "hostname", p)) {
4186
            pstrcpy(slirp_hostname, sizeof(slirp_hostname), buf);
4187
        }
4188
        ret = net_slirp_init(vlan);
4189
    } else
4190
#endif
4191
#ifdef _WIN32
4192
    if (!strcmp(device, "tap")) {
4193
        char ifname[64];
4194
        if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4195
            fprintf(stderr, "tap: no interface name\n");
4196
            return -1;
4197
        }
4198
        ret = tap_win32_init(vlan, ifname);
4199
    } else
4200
#else
4201
    if (!strcmp(device, "tap")) {
4202
        char ifname[64];
4203
        char setup_script[1024];
4204
        int fd;
4205
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4206
            fd = strtol(buf, NULL, 0);
4207
            ret = -1;
4208
            if (net_tap_fd_init(vlan, fd))
4209
                ret = 0;
4210
        } else {
4211
            if (get_param_value(ifname, sizeof(ifname), "ifname", p) <= 0) {
4212
                ifname[0] = '\0';
4213
            }
4214
            if (get_param_value(setup_script, sizeof(setup_script), "script", p) == 0) {
4215
                pstrcpy(setup_script, sizeof(setup_script), DEFAULT_NETWORK_SCRIPT);
4216
            }
4217
            ret = net_tap_init(vlan, ifname, setup_script);
4218
        }
4219
    } else
4220
#endif
4221
    if (!strcmp(device, "socket")) {
4222
        if (get_param_value(buf, sizeof(buf), "fd", p) > 0) {
4223
            int fd;
4224
            fd = strtol(buf, NULL, 0);
4225
            ret = -1;
4226
            if (net_socket_fd_init(vlan, fd, 1))
4227
                ret = 0;
4228
        } else if (get_param_value(buf, sizeof(buf), "listen", p) > 0) {
4229
            ret = net_socket_listen_init(vlan, buf);
4230
        } else if (get_param_value(buf, sizeof(buf), "connect", p) > 0) {
4231
            ret = net_socket_connect_init(vlan, buf);
4232
        } else if (get_param_value(buf, sizeof(buf), "mcast", p) > 0) {
4233
            ret = net_socket_mcast_init(vlan, buf);
4234
        } else {
4235
            fprintf(stderr, "Unknown socket options: %s\n", p);
4236
            return -1;
4237
        }
4238
    } else
4239
    {
4240
        fprintf(stderr, "Unknown network device: %s\n", device);
4241
        return -1;
4242
    }
4243
    if (ret < 0) {
4244
        fprintf(stderr, "Could not initialize device '%s'\n", device);
4245
    }
4246
    
4247
    return ret;
4248
}
4249

    
4250
void do_info_network(void)
4251
{
4252
    VLANState *vlan;
4253
    VLANClientState *vc;
4254

    
4255
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4256
        term_printf("VLAN %d devices:\n", vlan->id);
4257
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4258
            term_printf("  %s\n", vc->info_str);
4259
    }
4260
}
4261

    
4262
/***********************************************************/
4263
/* USB devices */
4264

    
4265
static USBPort *used_usb_ports;
4266
static USBPort *free_usb_ports;
4267

    
4268
/* ??? Maybe change this to register a hub to keep track of the topology.  */
4269
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4270
                            usb_attachfn attach)
4271
{
4272
    port->opaque = opaque;
4273
    port->index = index;
4274
    port->attach = attach;
4275
    port->next = free_usb_ports;
4276
    free_usb_ports = port;
4277
}
4278

    
4279
static int usb_device_add(const char *devname)
4280
{
4281
    const char *p;
4282
    USBDevice *dev;
4283
    USBPort *port;
4284

    
4285
    if (!free_usb_ports)
4286
        return -1;
4287

    
4288
    if (strstart(devname, "host:", &p)) {
4289
        dev = usb_host_device_open(p);
4290
    } else if (!strcmp(devname, "mouse")) {
4291
        dev = usb_mouse_init();
4292
    } else if (!strcmp(devname, "tablet")) {
4293
        dev = usb_tablet_init();
4294
    } else if (strstart(devname, "disk:", &p)) {
4295
        dev = usb_msd_init(p);
4296
    } else {
4297
        return -1;
4298
    }
4299
    if (!dev)
4300
        return -1;
4301

    
4302
    /* Find a USB port to add the device to.  */
4303
    port = free_usb_ports;
4304
    if (!port->next) {
4305
        USBDevice *hub;
4306

    
4307
        /* Create a new hub and chain it on.  */
4308
        free_usb_ports = NULL;
4309
        port->next = used_usb_ports;
4310
        used_usb_ports = port;
4311

    
4312
        hub = usb_hub_init(VM_USB_HUB_SIZE);
4313
        usb_attach(port, hub);
4314
        port = free_usb_ports;
4315
    }
4316

    
4317
    free_usb_ports = port->next;
4318
    port->next = used_usb_ports;
4319
    used_usb_ports = port;
4320
    usb_attach(port, dev);
4321
    return 0;
4322
}
4323

    
4324
static int usb_device_del(const char *devname)
4325
{
4326
    USBPort *port;
4327
    USBPort **lastp;
4328
    USBDevice *dev;
4329
    int bus_num, addr;
4330
    const char *p;
4331

    
4332
    if (!used_usb_ports)
4333
        return -1;
4334

    
4335
    p = strchr(devname, '.');
4336
    if (!p) 
4337
        return -1;
4338
    bus_num = strtoul(devname, NULL, 0);
4339
    addr = strtoul(p + 1, NULL, 0);
4340
    if (bus_num != 0)
4341
        return -1;
4342

    
4343
    lastp = &used_usb_ports;
4344
    port = used_usb_ports;
4345
    while (port && port->dev->addr != addr) {
4346
        lastp = &port->next;
4347
        port = port->next;
4348
    }
4349

    
4350
    if (!port)
4351
        return -1;
4352

    
4353
    dev = port->dev;
4354
    *lastp = port->next;
4355
    usb_attach(port, NULL);
4356
    dev->handle_destroy(dev);
4357
    port->next = free_usb_ports;
4358
    free_usb_ports = port;
4359
    return 0;
4360
}
4361

    
4362
void do_usb_add(const char *devname)
4363
{
4364
    int ret;
4365
    ret = usb_device_add(devname);
4366
    if (ret < 0) 
4367
        term_printf("Could not add USB device '%s'\n", devname);
4368
}
4369

    
4370
void do_usb_del(const char *devname)
4371
{
4372
    int ret;
4373
    ret = usb_device_del(devname);
4374
    if (ret < 0) 
4375
        term_printf("Could not remove USB device '%s'\n", devname);
4376
}
4377

    
4378
void usb_info(void)
4379
{
4380
    USBDevice *dev;
4381
    USBPort *port;
4382
    const char *speed_str;
4383

    
4384
    if (!usb_enabled) {
4385
        term_printf("USB support not enabled\n");
4386
        return;
4387
    }
4388

    
4389
    for (port = used_usb_ports; port; port = port->next) {
4390
        dev = port->dev;
4391
        if (!dev)
4392
            continue;
4393
        switch(dev->speed) {
4394
        case USB_SPEED_LOW: 
4395
            speed_str = "1.5"; 
4396
            break;
4397
        case USB_SPEED_FULL: 
4398
            speed_str = "12"; 
4399
            break;
4400
        case USB_SPEED_HIGH: 
4401
            speed_str = "480"; 
4402
            break;
4403
        default:
4404
            speed_str = "?"; 
4405
            break;
4406
        }
4407
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n", 
4408
                    0, dev->addr, speed_str, dev->devname);
4409
    }
4410
}
4411

    
4412
/***********************************************************/
4413
/* dumb display */
4414

    
4415
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4416
{
4417
}
4418

    
4419
static void dumb_resize(DisplayState *ds, int w, int h)
4420
{
4421
}
4422

    
4423
static void dumb_refresh(DisplayState *ds)
4424
{
4425
    vga_hw_update();
4426
}
4427

    
4428
void dumb_display_init(DisplayState *ds)
4429
{
4430
    ds->data = NULL;
4431
    ds->linesize = 0;
4432
    ds->depth = 0;
4433
    ds->dpy_update = dumb_update;
4434
    ds->dpy_resize = dumb_resize;
4435
    ds->dpy_refresh = dumb_refresh;
4436
}
4437

    
4438
/***********************************************************/
4439
/* I/O handling */
4440

    
4441
#define MAX_IO_HANDLERS 64
4442

    
4443
typedef struct IOHandlerRecord {
4444
    int fd;
4445
    IOCanRWHandler *fd_read_poll;
4446
    IOHandler *fd_read;
4447
    IOHandler *fd_write;
4448
    int deleted;
4449
    void *opaque;
4450
    /* temporary data */
4451
    struct pollfd *ufd;
4452
    struct IOHandlerRecord *next;
4453
} IOHandlerRecord;
4454

    
4455
static IOHandlerRecord *first_io_handler;
4456

    
4457
/* XXX: fd_read_poll should be suppressed, but an API change is
4458
   necessary in the character devices to suppress fd_can_read(). */
4459
int qemu_set_fd_handler2(int fd, 
4460
                         IOCanRWHandler *fd_read_poll, 
4461
                         IOHandler *fd_read, 
4462
                         IOHandler *fd_write, 
4463
                         void *opaque)
4464
{
4465
    IOHandlerRecord **pioh, *ioh;
4466

    
4467
    if (!fd_read && !fd_write) {
4468
        pioh = &first_io_handler;
4469
        for(;;) {
4470
            ioh = *pioh;
4471
            if (ioh == NULL)
4472
                break;
4473
            if (ioh->fd == fd) {
4474
                ioh->deleted = 1;
4475
                break;
4476
            }
4477
            pioh = &ioh->next;
4478
        }
4479
    } else {
4480
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4481
            if (ioh->fd == fd)
4482
                goto found;
4483
        }
4484
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4485
        if (!ioh)
4486
            return -1;
4487
        ioh->next = first_io_handler;
4488
        first_io_handler = ioh;
4489
    found:
4490
        ioh->fd = fd;
4491
        ioh->fd_read_poll = fd_read_poll;
4492
        ioh->fd_read = fd_read;
4493
        ioh->fd_write = fd_write;
4494
        ioh->opaque = opaque;
4495
        ioh->deleted = 0;
4496
    }
4497
    return 0;
4498
}
4499

    
4500
int qemu_set_fd_handler(int fd, 
4501
                        IOHandler *fd_read, 
4502
                        IOHandler *fd_write, 
4503
                        void *opaque)
4504
{
4505
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4506
}
4507

    
4508
/***********************************************************/
4509
/* Polling handling */
4510

    
4511
typedef struct PollingEntry {
4512
    PollingFunc *func;
4513
    void *opaque;
4514
    struct PollingEntry *next;
4515
} PollingEntry;
4516

    
4517
static PollingEntry *first_polling_entry;
4518

    
4519
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4520
{
4521
    PollingEntry **ppe, *pe;
4522
    pe = qemu_mallocz(sizeof(PollingEntry));
4523
    if (!pe)
4524
        return -1;
4525
    pe->func = func;
4526
    pe->opaque = opaque;
4527
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4528
    *ppe = pe;
4529
    return 0;
4530
}
4531

    
4532
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4533
{
4534
    PollingEntry **ppe, *pe;
4535
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4536
        pe = *ppe;
4537
        if (pe->func == func && pe->opaque == opaque) {
4538
            *ppe = pe->next;
4539
            qemu_free(pe);
4540
            break;
4541
        }
4542
    }
4543
}
4544

    
4545
#ifdef _WIN32
4546
/***********************************************************/
4547
/* Wait objects support */
4548
typedef struct WaitObjects {
4549
    int num;
4550
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4551
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4552
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4553
} WaitObjects;
4554

    
4555
static WaitObjects wait_objects = {0};
4556
    
4557
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4558
{
4559
    WaitObjects *w = &wait_objects;
4560

    
4561
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
4562
        return -1;
4563
    w->events[w->num] = handle;
4564
    w->func[w->num] = func;
4565
    w->opaque[w->num] = opaque;
4566
    w->num++;
4567
    return 0;
4568
}
4569

    
4570
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4571
{
4572
    int i, found;
4573
    WaitObjects *w = &wait_objects;
4574

    
4575
    found = 0;
4576
    for (i = 0; i < w->num; i++) {
4577
        if (w->events[i] == handle)
4578
            found = 1;
4579
        if (found) {
4580
            w->events[i] = w->events[i + 1];
4581
            w->func[i] = w->func[i + 1];
4582
            w->opaque[i] = w->opaque[i + 1];
4583
        }            
4584
    }
4585
    if (found)
4586
        w->num--;
4587
}
4588
#endif
4589

    
4590
/***********************************************************/
4591
/* savevm/loadvm support */
4592

    
4593
#define IO_BUF_SIZE 32768
4594

    
4595
struct QEMUFile {
4596
    FILE *outfile;
4597
    BlockDriverState *bs;
4598
    int is_file;
4599
    int is_writable;
4600
    int64_t base_offset;
4601
    int64_t buf_offset; /* start of buffer when writing, end of buffer
4602
                           when reading */
4603
    int buf_index;
4604
    int buf_size; /* 0 when writing */
4605
    uint8_t buf[IO_BUF_SIZE];
4606
};
4607

    
4608
QEMUFile *qemu_fopen(const char *filename, const char *mode)
4609
{
4610
    QEMUFile *f;
4611

    
4612
    f = qemu_mallocz(sizeof(QEMUFile));
4613
    if (!f)
4614
        return NULL;
4615
    if (!strcmp(mode, "wb")) {
4616
        f->is_writable = 1;
4617
    } else if (!strcmp(mode, "rb")) {
4618
        f->is_writable = 0;
4619
    } else {
4620
        goto fail;
4621
    }
4622
    f->outfile = fopen(filename, mode);
4623
    if (!f->outfile)
4624
        goto fail;
4625
    f->is_file = 1;
4626
    return f;
4627
 fail:
4628
    if (f->outfile)
4629
        fclose(f->outfile);
4630
    qemu_free(f);
4631
    return NULL;
4632
}
4633

    
4634
QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4635
{
4636
    QEMUFile *f;
4637

    
4638
    f = qemu_mallocz(sizeof(QEMUFile));
4639
    if (!f)
4640
        return NULL;
4641
    f->is_file = 0;
4642
    f->bs = bs;
4643
    f->is_writable = is_writable;
4644
    f->base_offset = offset;
4645
    return f;
4646
}
4647

    
4648
void qemu_fflush(QEMUFile *f)
4649
{
4650
    if (!f->is_writable)
4651
        return;
4652
    if (f->buf_index > 0) {
4653
        if (f->is_file) {
4654
            fseek(f->outfile, f->buf_offset, SEEK_SET);
4655
            fwrite(f->buf, 1, f->buf_index, f->outfile);
4656
        } else {
4657
            bdrv_pwrite(f->bs, f->base_offset + f->buf_offset, 
4658
                        f->buf, f->buf_index);
4659
        }
4660
        f->buf_offset += f->buf_index;
4661
        f->buf_index = 0;
4662
    }
4663
}
4664

    
4665
static void qemu_fill_buffer(QEMUFile *f)
4666
{
4667
    int len;
4668

    
4669
    if (f->is_writable)
4670
        return;
4671
    if (f->is_file) {
4672
        fseek(f->outfile, f->buf_offset, SEEK_SET);
4673
        len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4674
        if (len < 0)
4675
            len = 0;
4676
    } else {
4677
        len = bdrv_pread(f->bs, f->base_offset + f->buf_offset, 
4678
                         f->buf, IO_BUF_SIZE);
4679
        if (len < 0)
4680
            len = 0;
4681
    }
4682
    f->buf_index = 0;
4683
    f->buf_size = len;
4684
    f->buf_offset += len;
4685
}
4686

    
4687
void qemu_fclose(QEMUFile *f)
4688
{
4689
    if (f->is_writable)
4690
        qemu_fflush(f);
4691
    if (f->is_file) {
4692
        fclose(f->outfile);
4693
    }
4694
    qemu_free(f);
4695
}
4696

    
4697
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4698
{
4699
    int l;
4700
    while (size > 0) {
4701
        l = IO_BUF_SIZE - f->buf_index;
4702
        if (l > size)
4703
            l = size;
4704
        memcpy(f->buf + f->buf_index, buf, l);
4705
        f->buf_index += l;
4706
        buf += l;
4707
        size -= l;
4708
        if (f->buf_index >= IO_BUF_SIZE)
4709
            qemu_fflush(f);
4710
    }
4711
}
4712

    
4713
void qemu_put_byte(QEMUFile *f, int v)
4714
{
4715
    f->buf[f->buf_index++] = v;
4716
    if (f->buf_index >= IO_BUF_SIZE)
4717
        qemu_fflush(f);
4718
}
4719

    
4720
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4721
{
4722
    int size, l;
4723

    
4724
    size = size1;
4725
    while (size > 0) {
4726
        l = f->buf_size - f->buf_index;
4727
        if (l == 0) {
4728
            qemu_fill_buffer(f);
4729
            l = f->buf_size - f->buf_index;
4730
            if (l == 0)
4731
                break;
4732
        }
4733
        if (l > size)
4734
            l = size;
4735
        memcpy(buf, f->buf + f->buf_index, l);
4736
        f->buf_index += l;
4737
        buf += l;
4738
        size -= l;
4739
    }
4740
    return size1 - size;
4741
}
4742

    
4743
int qemu_get_byte(QEMUFile *f)
4744
{
4745
    if (f->buf_index >= f->buf_size) {
4746
        qemu_fill_buffer(f);
4747
        if (f->buf_index >= f->buf_size)
4748
            return 0;
4749
    }
4750
    return f->buf[f->buf_index++];
4751
}
4752

    
4753
int64_t qemu_ftell(QEMUFile *f)
4754
{
4755
    return f->buf_offset - f->buf_size + f->buf_index;
4756
}
4757

    
4758
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4759
{
4760
    if (whence == SEEK_SET) {
4761
        /* nothing to do */
4762
    } else if (whence == SEEK_CUR) {
4763
        pos += qemu_ftell(f);
4764
    } else {
4765
        /* SEEK_END not supported */
4766
        return -1;
4767
    }
4768
    if (f->is_writable) {
4769
        qemu_fflush(f);
4770
        f->buf_offset = pos;
4771
    } else {
4772
        f->buf_offset = pos;
4773
        f->buf_index = 0;
4774
        f->buf_size = 0;
4775
    }
4776
    return pos;
4777
}
4778

    
4779
void qemu_put_be16(QEMUFile *f, unsigned int v)
4780
{
4781
    qemu_put_byte(f, v >> 8);
4782
    qemu_put_byte(f, v);
4783
}
4784

    
4785
void qemu_put_be32(QEMUFile *f, unsigned int v)
4786
{
4787
    qemu_put_byte(f, v >> 24);
4788
    qemu_put_byte(f, v >> 16);
4789
    qemu_put_byte(f, v >> 8);
4790
    qemu_put_byte(f, v);
4791
}
4792

    
4793
void qemu_put_be64(QEMUFile *f, uint64_t v)
4794
{
4795
    qemu_put_be32(f, v >> 32);
4796
    qemu_put_be32(f, v);
4797
}
4798

    
4799
unsigned int qemu_get_be16(QEMUFile *f)
4800
{
4801
    unsigned int v;
4802
    v = qemu_get_byte(f) << 8;
4803
    v |= qemu_get_byte(f);
4804
    return v;
4805
}
4806

    
4807
unsigned int qemu_get_be32(QEMUFile *f)
4808
{
4809
    unsigned int v;
4810
    v = qemu_get_byte(f) << 24;
4811
    v |= qemu_get_byte(f) << 16;
4812
    v |= qemu_get_byte(f) << 8;
4813
    v |= qemu_get_byte(f);
4814
    return v;
4815
}
4816

    
4817
uint64_t qemu_get_be64(QEMUFile *f)
4818
{
4819
    uint64_t v;
4820
    v = (uint64_t)qemu_get_be32(f) << 32;
4821
    v |= qemu_get_be32(f);
4822
    return v;
4823
}
4824

    
4825
typedef struct SaveStateEntry {
4826
    char idstr[256];
4827
    int instance_id;
4828
    int version_id;
4829
    SaveStateHandler *save_state;
4830
    LoadStateHandler *load_state;
4831
    void *opaque;
4832
    struct SaveStateEntry *next;
4833
} SaveStateEntry;
4834

    
4835
static SaveStateEntry *first_se;
4836

    
4837
int register_savevm(const char *idstr, 
4838
                    int instance_id, 
4839
                    int version_id,
4840
                    SaveStateHandler *save_state,
4841
                    LoadStateHandler *load_state,
4842
                    void *opaque)
4843
{
4844
    SaveStateEntry *se, **pse;
4845

    
4846
    se = qemu_malloc(sizeof(SaveStateEntry));
4847
    if (!se)
4848
        return -1;
4849
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4850
    se->instance_id = instance_id;
4851
    se->version_id = version_id;
4852
    se->save_state = save_state;
4853
    se->load_state = load_state;
4854
    se->opaque = opaque;
4855
    se->next = NULL;
4856

    
4857
    /* add at the end of list */
4858
    pse = &first_se;
4859
    while (*pse != NULL)
4860
        pse = &(*pse)->next;
4861
    *pse = se;
4862
    return 0;
4863
}
4864

    
4865
#define QEMU_VM_FILE_MAGIC   0x5145564d
4866
#define QEMU_VM_FILE_VERSION 0x00000002
4867

    
4868
int qemu_savevm_state(QEMUFile *f)
4869
{
4870
    SaveStateEntry *se;
4871
    int len, ret;
4872
    int64_t cur_pos, len_pos, total_len_pos;
4873

    
4874
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4875
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4876
    total_len_pos = qemu_ftell(f);
4877
    qemu_put_be64(f, 0); /* total size */
4878

    
4879
    for(se = first_se; se != NULL; se = se->next) {
4880
        /* ID string */
4881
        len = strlen(se->idstr);
4882
        qemu_put_byte(f, len);
4883
        qemu_put_buffer(f, se->idstr, len);
4884

    
4885
        qemu_put_be32(f, se->instance_id);
4886
        qemu_put_be32(f, se->version_id);
4887

    
4888
        /* record size: filled later */
4889
        len_pos = qemu_ftell(f);
4890
        qemu_put_be32(f, 0);
4891
        
4892
        se->save_state(f, se->opaque);
4893

    
4894
        /* fill record size */
4895
        cur_pos = qemu_ftell(f);
4896
        len = cur_pos - len_pos - 4;
4897
        qemu_fseek(f, len_pos, SEEK_SET);
4898
        qemu_put_be32(f, len);
4899
        qemu_fseek(f, cur_pos, SEEK_SET);
4900
    }
4901
    cur_pos = qemu_ftell(f);
4902
    qemu_fseek(f, total_len_pos, SEEK_SET);
4903
    qemu_put_be64(f, cur_pos - total_len_pos - 8);
4904
    qemu_fseek(f, cur_pos, SEEK_SET);
4905

    
4906
    ret = 0;
4907
    return ret;
4908
}
4909

    
4910
static SaveStateEntry *find_se(const char *idstr, int instance_id)
4911
{
4912
    SaveStateEntry *se;
4913

    
4914
    for(se = first_se; se != NULL; se = se->next) {
4915
        if (!strcmp(se->idstr, idstr) && 
4916
            instance_id == se->instance_id)
4917
            return se;
4918
    }
4919
    return NULL;
4920
}
4921

    
4922
int qemu_loadvm_state(QEMUFile *f)
4923
{
4924
    SaveStateEntry *se;
4925
    int len, ret, instance_id, record_len, version_id;
4926
    int64_t total_len, end_pos, cur_pos;
4927
    unsigned int v;
4928
    char idstr[256];
4929
    
4930
    v = qemu_get_be32(f);
4931
    if (v != QEMU_VM_FILE_MAGIC)
4932
        goto fail;
4933
    v = qemu_get_be32(f);
4934
    if (v != QEMU_VM_FILE_VERSION) {
4935
    fail:
4936
        ret = -1;
4937
        goto the_end;
4938
    }
4939
    total_len = qemu_get_be64(f);
4940
    end_pos = total_len + qemu_ftell(f);
4941
    for(;;) {
4942
        if (qemu_ftell(f) >= end_pos)
4943
            break;
4944
        len = qemu_get_byte(f);
4945
        qemu_get_buffer(f, idstr, len);
4946
        idstr[len] = '\0';
4947
        instance_id = qemu_get_be32(f);
4948
        version_id = qemu_get_be32(f);
4949
        record_len = qemu_get_be32(f);
4950
#if 0
4951
        printf("idstr=%s instance=0x%x version=%d len=%d\n", 
4952
               idstr, instance_id, version_id, record_len);
4953
#endif
4954
        cur_pos = qemu_ftell(f);
4955
        se = find_se(idstr, instance_id);
4956
        if (!se) {
4957
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
4958
                    instance_id, idstr);
4959
        } else {
4960
            ret = se->load_state(f, se->opaque, version_id);
4961
            if (ret < 0) {
4962
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
4963
                        instance_id, idstr);
4964
            }
4965
        }
4966
        /* always seek to exact end of record */
4967
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
4968
    }
4969
    ret = 0;
4970
 the_end:
4971
    return ret;
4972
}
4973

    
4974
/* device can contain snapshots */
4975
static int bdrv_can_snapshot(BlockDriverState *bs)
4976
{
4977
    return (bs &&
4978
            !bdrv_is_removable(bs) &&
4979
            !bdrv_is_read_only(bs));
4980
}
4981

    
4982
/* device must be snapshots in order to have a reliable snapshot */
4983
static int bdrv_has_snapshot(BlockDriverState *bs)
4984
{
4985
    return (bs &&
4986
            !bdrv_is_removable(bs) &&
4987
            !bdrv_is_read_only(bs));
4988
}
4989

    
4990
static BlockDriverState *get_bs_snapshots(void)
4991
{
4992
    BlockDriverState *bs;
4993
    int i;
4994

    
4995
    if (bs_snapshots)
4996
        return bs_snapshots;
4997
    for(i = 0; i <= MAX_DISKS; i++) {
4998
        bs = bs_table[i];
4999
        if (bdrv_can_snapshot(bs))
5000
            goto ok;
5001
    }
5002
    return NULL;
5003
 ok:
5004
    bs_snapshots = bs;
5005
    return bs;
5006
}
5007

    
5008
static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5009
                              const char *name)
5010
{
5011
    QEMUSnapshotInfo *sn_tab, *sn;
5012
    int nb_sns, i, ret;
5013
    
5014
    ret = -ENOENT;
5015
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5016
    if (nb_sns < 0)
5017
        return ret;
5018
    for(i = 0; i < nb_sns; i++) {
5019
        sn = &sn_tab[i];
5020
        if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5021
            *sn_info = *sn;
5022
            ret = 0;
5023
            break;
5024
        }
5025
    }
5026
    qemu_free(sn_tab);
5027
    return ret;
5028
}
5029

    
5030
void do_savevm(const char *name)
5031
{
5032
    BlockDriverState *bs, *bs1;
5033
    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5034
    int must_delete, ret, i;
5035
    BlockDriverInfo bdi1, *bdi = &bdi1;
5036
    QEMUFile *f;
5037
    int saved_vm_running;
5038
#ifdef _WIN32
5039
    struct _timeb tb;
5040
#else
5041
    struct timeval tv;
5042
#endif
5043

    
5044
    bs = get_bs_snapshots();
5045
    if (!bs) {
5046
        term_printf("No block device can accept snapshots\n");
5047
        return;
5048
    }
5049

    
5050
    /* ??? Should this occur after vm_stop?  */
5051
    qemu_aio_flush();
5052

    
5053
    saved_vm_running = vm_running;
5054
    vm_stop(0);
5055
    
5056
    must_delete = 0;
5057
    if (name) {
5058
        ret = bdrv_snapshot_find(bs, old_sn, name);
5059
        if (ret >= 0) {
5060
            must_delete = 1;
5061
        }
5062
    }
5063
    memset(sn, 0, sizeof(*sn));
5064
    if (must_delete) {
5065
        pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5066
        pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5067
    } else {
5068
        if (name)
5069
            pstrcpy(sn->name, sizeof(sn->name), name);
5070
    }
5071

    
5072
    /* fill auxiliary fields */
5073
#ifdef _WIN32
5074
    _ftime(&tb);
5075
    sn->date_sec = tb.time;
5076
    sn->date_nsec = tb.millitm * 1000000;
5077
#else
5078
    gettimeofday(&tv, NULL);
5079
    sn->date_sec = tv.tv_sec;
5080
    sn->date_nsec = tv.tv_usec * 1000;
5081
#endif
5082
    sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5083
    
5084
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5085
        term_printf("Device %s does not support VM state snapshots\n",
5086
                    bdrv_get_device_name(bs));
5087
        goto the_end;
5088
    }
5089
    
5090
    /* save the VM state */
5091
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5092
    if (!f) {
5093
        term_printf("Could not open VM state file\n");
5094
        goto the_end;
5095
    }
5096
    ret = qemu_savevm_state(f);
5097
    sn->vm_state_size = qemu_ftell(f);
5098
    qemu_fclose(f);
5099
    if (ret < 0) {
5100
        term_printf("Error %d while writing VM\n", ret);
5101
        goto the_end;
5102
    }
5103
    
5104
    /* create the snapshots */
5105

    
5106
    for(i = 0; i < MAX_DISKS; i++) {
5107
        bs1 = bs_table[i];
5108
        if (bdrv_has_snapshot(bs1)) {
5109
            if (must_delete) {
5110
                ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5111
                if (ret < 0) {
5112
                    term_printf("Error while deleting snapshot on '%s'\n",
5113
                                bdrv_get_device_name(bs1));
5114
                }
5115
            }
5116
            ret = bdrv_snapshot_create(bs1, sn);
5117
            if (ret < 0) {
5118
                term_printf("Error while creating snapshot on '%s'\n",
5119
                            bdrv_get_device_name(bs1));
5120
            }
5121
        }
5122
    }
5123

    
5124
 the_end:
5125
    if (saved_vm_running)
5126
        vm_start();
5127
}
5128

    
5129
void do_loadvm(const char *name)
5130
{
5131
    BlockDriverState *bs, *bs1;
5132
    BlockDriverInfo bdi1, *bdi = &bdi1;
5133
    QEMUFile *f;
5134
    int i, ret;
5135
    int saved_vm_running;
5136

    
5137
    bs = get_bs_snapshots();
5138
    if (!bs) {
5139
        term_printf("No block device supports snapshots\n");
5140
        return;
5141
    }
5142
    
5143
    /* Flush all IO requests so they don't interfere with the new state.  */
5144
    qemu_aio_flush();
5145

    
5146
    saved_vm_running = vm_running;
5147
    vm_stop(0);
5148

    
5149
    for(i = 0; i <= MAX_DISKS; i++) {
5150
        bs1 = bs_table[i];
5151
        if (bdrv_has_snapshot(bs1)) {
5152
            ret = bdrv_snapshot_goto(bs1, name);
5153
            if (ret < 0) {
5154
                if (bs != bs1)
5155
                    term_printf("Warning: ");
5156
                switch(ret) {
5157
                case -ENOTSUP:
5158
                    term_printf("Snapshots not supported on device '%s'\n",
5159
                                bdrv_get_device_name(bs1));
5160
                    break;
5161
                case -ENOENT:
5162
                    term_printf("Could not find snapshot '%s' on device '%s'\n",
5163
                                name, bdrv_get_device_name(bs1));
5164
                    break;
5165
                default:
5166
                    term_printf("Error %d while activating snapshot on '%s'\n",
5167
                                ret, bdrv_get_device_name(bs1));
5168
                    break;
5169
                }
5170
                /* fatal on snapshot block device */
5171
                if (bs == bs1)
5172
                    goto the_end;
5173
            }
5174
        }
5175
    }
5176

    
5177
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5178
        term_printf("Device %s does not support VM state snapshots\n",
5179
                    bdrv_get_device_name(bs));
5180
        return;
5181
    }
5182
    
5183
    /* restore the VM state */
5184
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5185
    if (!f) {
5186
        term_printf("Could not open VM state file\n");
5187
        goto the_end;
5188
    }
5189
    ret = qemu_loadvm_state(f);
5190
    qemu_fclose(f);
5191
    if (ret < 0) {
5192
        term_printf("Error %d while loading VM state\n", ret);
5193
    }
5194
 the_end:
5195
    if (saved_vm_running)
5196
        vm_start();
5197
}
5198

    
5199
void do_delvm(const char *name)
5200
{
5201
    BlockDriverState *bs, *bs1;
5202
    int i, ret;
5203

    
5204
    bs = get_bs_snapshots();
5205
    if (!bs) {
5206
        term_printf("No block device supports snapshots\n");
5207
        return;
5208
    }
5209
    
5210
    for(i = 0; i <= MAX_DISKS; i++) {
5211
        bs1 = bs_table[i];
5212
        if (bdrv_has_snapshot(bs1)) {
5213
            ret = bdrv_snapshot_delete(bs1, name);
5214
            if (ret < 0) {
5215
                if (ret == -ENOTSUP)
5216
                    term_printf("Snapshots not supported on device '%s'\n",
5217
                                bdrv_get_device_name(bs1));
5218
                else
5219
                    term_printf("Error %d while deleting snapshot on '%s'\n",
5220
                                ret, bdrv_get_device_name(bs1));
5221
            }
5222
        }
5223
    }
5224
}
5225

    
5226
void do_info_snapshots(void)
5227
{
5228
    BlockDriverState *bs, *bs1;
5229
    QEMUSnapshotInfo *sn_tab, *sn;
5230
    int nb_sns, i;
5231
    char buf[256];
5232

    
5233
    bs = get_bs_snapshots();
5234
    if (!bs) {
5235
        term_printf("No available block device supports snapshots\n");
5236
        return;
5237
    }
5238
    term_printf("Snapshot devices:");
5239
    for(i = 0; i <= MAX_DISKS; i++) {
5240
        bs1 = bs_table[i];
5241
        if (bdrv_has_snapshot(bs1)) {
5242
            if (bs == bs1)
5243
                term_printf(" %s", bdrv_get_device_name(bs1));
5244
        }
5245
    }
5246
    term_printf("\n");
5247

    
5248
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5249
    if (nb_sns < 0) {
5250
        term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5251
        return;
5252
    }
5253
    term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5254
    term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5255
    for(i = 0; i < nb_sns; i++) {
5256
        sn = &sn_tab[i];
5257
        term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5258
    }
5259
    qemu_free(sn_tab);
5260
}
5261

    
5262
/***********************************************************/
5263
/* cpu save/restore */
5264

    
5265
#if defined(TARGET_I386)
5266

    
5267
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5268
{
5269
    qemu_put_be32(f, dt->selector);
5270
    qemu_put_betl(f, dt->base);
5271
    qemu_put_be32(f, dt->limit);
5272
    qemu_put_be32(f, dt->flags);
5273
}
5274

    
5275
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5276
{
5277
    dt->selector = qemu_get_be32(f);
5278
    dt->base = qemu_get_betl(f);
5279
    dt->limit = qemu_get_be32(f);
5280
    dt->flags = qemu_get_be32(f);
5281
}
5282

    
5283
void cpu_save(QEMUFile *f, void *opaque)
5284
{
5285
    CPUState *env = opaque;
5286
    uint16_t fptag, fpus, fpuc, fpregs_format;
5287
    uint32_t hflags;
5288
    int i;
5289
    
5290
    for(i = 0; i < CPU_NB_REGS; i++)
5291
        qemu_put_betls(f, &env->regs[i]);
5292
    qemu_put_betls(f, &env->eip);
5293
    qemu_put_betls(f, &env->eflags);
5294
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5295
    qemu_put_be32s(f, &hflags);
5296
    
5297
    /* FPU */
5298
    fpuc = env->fpuc;
5299
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5300
    fptag = 0;
5301
    for(i = 0; i < 8; i++) {
5302
        fptag |= ((!env->fptags[i]) << i);
5303
    }
5304
    
5305
    qemu_put_be16s(f, &fpuc);
5306
    qemu_put_be16s(f, &fpus);
5307
    qemu_put_be16s(f, &fptag);
5308

    
5309
#ifdef USE_X86LDOUBLE
5310
    fpregs_format = 0;
5311
#else
5312
    fpregs_format = 1;
5313
#endif
5314
    qemu_put_be16s(f, &fpregs_format);
5315
    
5316
    for(i = 0; i < 8; i++) {
5317
#ifdef USE_X86LDOUBLE
5318
        {
5319
            uint64_t mant;
5320
            uint16_t exp;
5321
            /* we save the real CPU data (in case of MMX usage only 'mant'
5322
               contains the MMX register */
5323
            cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5324
            qemu_put_be64(f, mant);
5325
            qemu_put_be16(f, exp);
5326
        }
5327
#else
5328
        /* if we use doubles for float emulation, we save the doubles to
5329
           avoid losing information in case of MMX usage. It can give
5330
           problems if the image is restored on a CPU where long
5331
           doubles are used instead. */
5332
        qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5333
#endif
5334
    }
5335

    
5336
    for(i = 0; i < 6; i++)
5337
        cpu_put_seg(f, &env->segs[i]);
5338
    cpu_put_seg(f, &env->ldt);
5339
    cpu_put_seg(f, &env->tr);
5340
    cpu_put_seg(f, &env->gdt);
5341
    cpu_put_seg(f, &env->idt);
5342
    
5343
    qemu_put_be32s(f, &env->sysenter_cs);
5344
    qemu_put_be32s(f, &env->sysenter_esp);
5345
    qemu_put_be32s(f, &env->sysenter_eip);
5346
    
5347
    qemu_put_betls(f, &env->cr[0]);
5348
    qemu_put_betls(f, &env->cr[2]);
5349
    qemu_put_betls(f, &env->cr[3]);
5350
    qemu_put_betls(f, &env->cr[4]);
5351
    
5352
    for(i = 0; i < 8; i++)
5353
        qemu_put_betls(f, &env->dr[i]);
5354

    
5355
    /* MMU */
5356
    qemu_put_be32s(f, &env->a20_mask);
5357

    
5358
    /* XMM */
5359
    qemu_put_be32s(f, &env->mxcsr);
5360
    for(i = 0; i < CPU_NB_REGS; i++) {
5361
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5362
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5363
    }
5364

    
5365
#ifdef TARGET_X86_64
5366
    qemu_put_be64s(f, &env->efer);
5367
    qemu_put_be64s(f, &env->star);
5368
    qemu_put_be64s(f, &env->lstar);
5369
    qemu_put_be64s(f, &env->cstar);
5370
    qemu_put_be64s(f, &env->fmask);
5371
    qemu_put_be64s(f, &env->kernelgsbase);
5372
#endif
5373
    qemu_put_be32s(f, &env->smbase);
5374
}
5375

    
5376
#ifdef USE_X86LDOUBLE
5377
/* XXX: add that in a FPU generic layer */
5378
union x86_longdouble {
5379
    uint64_t mant;
5380
    uint16_t exp;
5381
};
5382

    
5383
#define MANTD1(fp)        (fp & ((1LL << 52) - 1))
5384
#define EXPBIAS1 1023
5385
#define EXPD1(fp)        ((fp >> 52) & 0x7FF)
5386
#define SIGND1(fp)        ((fp >> 32) & 0x80000000)
5387

    
5388
static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5389
{
5390
    int e;
5391
    /* mantissa */
5392
    p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5393
    /* exponent + sign */
5394
    e = EXPD1(temp) - EXPBIAS1 + 16383;
5395
    e |= SIGND1(temp) >> 16;
5396
    p->exp = e;
5397
}
5398
#endif
5399

    
5400
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5401
{
5402
    CPUState *env = opaque;
5403
    int i, guess_mmx;
5404
    uint32_t hflags;
5405
    uint16_t fpus, fpuc, fptag, fpregs_format;
5406

    
5407
    if (version_id != 3 && version_id != 4)
5408
        return -EINVAL;
5409
    for(i = 0; i < CPU_NB_REGS; i++)
5410
        qemu_get_betls(f, &env->regs[i]);
5411
    qemu_get_betls(f, &env->eip);
5412
    qemu_get_betls(f, &env->eflags);
5413
    qemu_get_be32s(f, &hflags);
5414

    
5415
    qemu_get_be16s(f, &fpuc);
5416
    qemu_get_be16s(f, &fpus);
5417
    qemu_get_be16s(f, &fptag);
5418
    qemu_get_be16s(f, &fpregs_format);
5419
    
5420
    /* NOTE: we cannot always restore the FPU state if the image come
5421
       from a host with a different 'USE_X86LDOUBLE' define. We guess
5422
       if we are in an MMX state to restore correctly in that case. */
5423
    guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5424
    for(i = 0; i < 8; i++) {
5425
        uint64_t mant;
5426
        uint16_t exp;
5427
        
5428
        switch(fpregs_format) {
5429
        case 0:
5430
            mant = qemu_get_be64(f);
5431
            exp = qemu_get_be16(f);
5432
#ifdef USE_X86LDOUBLE
5433
            env->fpregs[i].d = cpu_set_fp80(mant, exp);
5434
#else
5435
            /* difficult case */
5436
            if (guess_mmx)
5437
                env->fpregs[i].mmx.MMX_Q(0) = mant;
5438
            else
5439
                env->fpregs[i].d = cpu_set_fp80(mant, exp);
5440
#endif
5441
            break;
5442
        case 1:
5443
            mant = qemu_get_be64(f);
5444
#ifdef USE_X86LDOUBLE
5445
            {
5446
                union x86_longdouble *p;
5447
                /* difficult case */
5448
                p = (void *)&env->fpregs[i];
5449
                if (guess_mmx) {
5450
                    p->mant = mant;
5451
                    p->exp = 0xffff;
5452
                } else {
5453
                    fp64_to_fp80(p, mant);
5454
                }
5455
            }
5456
#else
5457
            env->fpregs[i].mmx.MMX_Q(0) = mant;
5458
#endif            
5459
            break;
5460
        default:
5461
            return -EINVAL;
5462
        }
5463
    }
5464

    
5465
    env->fpuc = fpuc;
5466
    /* XXX: restore FPU round state */
5467
    env->fpstt = (fpus >> 11) & 7;
5468
    env->fpus = fpus & ~0x3800;
5469
    fptag ^= 0xff;
5470
    for(i = 0; i < 8; i++) {
5471
        env->fptags[i] = (fptag >> i) & 1;
5472
    }
5473
    
5474
    for(i = 0; i < 6; i++)
5475
        cpu_get_seg(f, &env->segs[i]);
5476
    cpu_get_seg(f, &env->ldt);
5477
    cpu_get_seg(f, &env->tr);
5478
    cpu_get_seg(f, &env->gdt);
5479
    cpu_get_seg(f, &env->idt);
5480
    
5481
    qemu_get_be32s(f, &env->sysenter_cs);
5482
    qemu_get_be32s(f, &env->sysenter_esp);
5483
    qemu_get_be32s(f, &env->sysenter_eip);
5484
    
5485
    qemu_get_betls(f, &env->cr[0]);
5486
    qemu_get_betls(f, &env->cr[2]);
5487
    qemu_get_betls(f, &env->cr[3]);
5488
    qemu_get_betls(f, &env->cr[4]);
5489
    
5490
    for(i = 0; i < 8; i++)
5491
        qemu_get_betls(f, &env->dr[i]);
5492

    
5493
    /* MMU */
5494
    qemu_get_be32s(f, &env->a20_mask);
5495

    
5496
    qemu_get_be32s(f, &env->mxcsr);
5497
    for(i = 0; i < CPU_NB_REGS; i++) {
5498
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5499
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5500
    }
5501

    
5502
#ifdef TARGET_X86_64
5503
    qemu_get_be64s(f, &env->efer);
5504
    qemu_get_be64s(f, &env->star);
5505
    qemu_get_be64s(f, &env->lstar);
5506
    qemu_get_be64s(f, &env->cstar);
5507
    qemu_get_be64s(f, &env->fmask);
5508
    qemu_get_be64s(f, &env->kernelgsbase);
5509
#endif
5510
    if (version_id >= 4) 
5511
        qemu_get_be32s(f, &env->smbase);
5512

    
5513
    /* XXX: compute hflags from scratch, except for CPL and IIF */
5514
    env->hflags = hflags;
5515
    tlb_flush(env, 1);
5516
    return 0;
5517
}
5518

    
5519
#elif defined(TARGET_PPC)
5520
void cpu_save(QEMUFile *f, void *opaque)
5521
{
5522
}
5523

    
5524
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5525
{
5526
    return 0;
5527
}
5528

    
5529
#elif defined(TARGET_MIPS)
5530
void cpu_save(QEMUFile *f, void *opaque)
5531
{
5532
}
5533

    
5534
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5535
{
5536
    return 0;
5537
}
5538

    
5539
#elif defined(TARGET_SPARC)
5540
void cpu_save(QEMUFile *f, void *opaque)
5541
{
5542
    CPUState *env = opaque;
5543
    int i;
5544
    uint32_t tmp;
5545

    
5546
    for(i = 0; i < 8; i++)
5547
        qemu_put_betls(f, &env->gregs[i]);
5548
    for(i = 0; i < NWINDOWS * 16; i++)
5549
        qemu_put_betls(f, &env->regbase[i]);
5550

    
5551
    /* FPU */
5552
    for(i = 0; i < TARGET_FPREGS; i++) {
5553
        union {
5554
            float32 f;
5555
            uint32_t i;
5556
        } u;
5557
        u.f = env->fpr[i];
5558
        qemu_put_be32(f, u.i);
5559
    }
5560

    
5561
    qemu_put_betls(f, &env->pc);
5562
    qemu_put_betls(f, &env->npc);
5563
    qemu_put_betls(f, &env->y);
5564
    tmp = GET_PSR(env);
5565
    qemu_put_be32(f, tmp);
5566
    qemu_put_betls(f, &env->fsr);
5567
    qemu_put_betls(f, &env->tbr);
5568
#ifndef TARGET_SPARC64
5569
    qemu_put_be32s(f, &env->wim);
5570
    /* MMU */
5571
    for(i = 0; i < 16; i++)
5572
        qemu_put_be32s(f, &env->mmuregs[i]);
5573
#endif
5574
}
5575

    
5576
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5577
{
5578
    CPUState *env = opaque;
5579
    int i;
5580
    uint32_t tmp;
5581

    
5582
    for(i = 0; i < 8; i++)
5583
        qemu_get_betls(f, &env->gregs[i]);
5584
    for(i = 0; i < NWINDOWS * 16; i++)
5585
        qemu_get_betls(f, &env->regbase[i]);
5586

    
5587
    /* FPU */
5588
    for(i = 0; i < TARGET_FPREGS; i++) {
5589
        union {
5590
            float32 f;
5591
            uint32_t i;
5592
        } u;
5593
        u.i = qemu_get_be32(f);
5594
        env->fpr[i] = u.f;
5595
    }
5596

    
5597
    qemu_get_betls(f, &env->pc);
5598
    qemu_get_betls(f, &env->npc);
5599
    qemu_get_betls(f, &env->y);
5600
    tmp = qemu_get_be32(f);
5601
    env->cwp = 0; /* needed to ensure that the wrapping registers are
5602
                     correctly updated */
5603
    PUT_PSR(env, tmp);
5604
    qemu_get_betls(f, &env->fsr);
5605
    qemu_get_betls(f, &env->tbr);
5606
#ifndef TARGET_SPARC64
5607
    qemu_get_be32s(f, &env->wim);
5608
    /* MMU */
5609
    for(i = 0; i < 16; i++)
5610
        qemu_get_be32s(f, &env->mmuregs[i]);
5611
#endif
5612
    tlb_flush(env, 1);
5613
    return 0;
5614
}
5615

    
5616
#elif defined(TARGET_ARM)
5617

    
5618
/* ??? Need to implement these.  */
5619
void cpu_save(QEMUFile *f, void *opaque)
5620
{
5621
}
5622

    
5623
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5624
{
5625
    return 0;
5626
}
5627

    
5628
#else
5629

    
5630
#warning No CPU save/restore functions
5631

    
5632
#endif
5633

    
5634
/***********************************************************/
5635
/* ram save/restore */
5636

    
5637
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5638
{
5639
    int v;
5640

    
5641
    v = qemu_get_byte(f);
5642
    switch(v) {
5643
    case 0:
5644
        if (qemu_get_buffer(f, buf, len) != len)
5645
            return -EIO;
5646
        break;
5647
    case 1:
5648
        v = qemu_get_byte(f);
5649
        memset(buf, v, len);
5650
        break;
5651
    default:
5652
        return -EINVAL;
5653
    }
5654
    return 0;
5655
}
5656

    
5657
static int ram_load_v1(QEMUFile *f, void *opaque)
5658
{
5659
    int i, ret;
5660

    
5661
    if (qemu_get_be32(f) != phys_ram_size)
5662
        return -EINVAL;
5663
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5664
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5665
        if (ret)
5666
            return ret;
5667
    }
5668
    return 0;
5669
}
5670

    
5671
#define BDRV_HASH_BLOCK_SIZE 1024
5672
#define IOBUF_SIZE 4096
5673
#define RAM_CBLOCK_MAGIC 0xfabe
5674

    
5675
typedef struct RamCompressState {
5676
    z_stream zstream;
5677
    QEMUFile *f;
5678
    uint8_t buf[IOBUF_SIZE];
5679
} RamCompressState;
5680

    
5681
static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5682
{
5683
    int ret;
5684
    memset(s, 0, sizeof(*s));
5685
    s->f = f;
5686
    ret = deflateInit2(&s->zstream, 1,
5687
                       Z_DEFLATED, 15, 
5688
                       9, Z_DEFAULT_STRATEGY);
5689
    if (ret != Z_OK)
5690
        return -1;
5691
    s->zstream.avail_out = IOBUF_SIZE;
5692
    s->zstream.next_out = s->buf;
5693
    return 0;
5694
}
5695

    
5696
static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5697
{
5698
    qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5699
    qemu_put_be16(s->f, len);
5700
    qemu_put_buffer(s->f, buf, len);
5701
}
5702

    
5703
static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5704
{
5705
    int ret;
5706

    
5707
    s->zstream.avail_in = len;
5708
    s->zstream.next_in = (uint8_t *)buf;
5709
    while (s->zstream.avail_in > 0) {
5710
        ret = deflate(&s->zstream, Z_NO_FLUSH);
5711
        if (ret != Z_OK)
5712
            return -1;
5713
        if (s->zstream.avail_out == 0) {
5714
            ram_put_cblock(s, s->buf, IOBUF_SIZE);
5715
            s->zstream.avail_out = IOBUF_SIZE;
5716
            s->zstream.next_out = s->buf;
5717
        }
5718
    }
5719
    return 0;
5720
}
5721

    
5722
static void ram_compress_close(RamCompressState *s)
5723
{
5724
    int len, ret;
5725

    
5726
    /* compress last bytes */
5727
    for(;;) {
5728
        ret = deflate(&s->zstream, Z_FINISH);
5729
        if (ret == Z_OK || ret == Z_STREAM_END) {
5730
            len = IOBUF_SIZE - s->zstream.avail_out;
5731
            if (len > 0) {
5732
                ram_put_cblock(s, s->buf, len);
5733
            }
5734
            s->zstream.avail_out = IOBUF_SIZE;
5735
            s->zstream.next_out = s->buf;
5736
            if (ret == Z_STREAM_END)
5737
                break;
5738
        } else {
5739
            goto fail;
5740
        }
5741
    }
5742
fail:
5743
    deflateEnd(&s->zstream);
5744
}
5745

    
5746
typedef struct RamDecompressState {
5747
    z_stream zstream;
5748
    QEMUFile *f;
5749
    uint8_t buf[IOBUF_SIZE];
5750
} RamDecompressState;
5751

    
5752
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5753
{
5754
    int ret;
5755
    memset(s, 0, sizeof(*s));
5756
    s->f = f;
5757
    ret = inflateInit(&s->zstream);
5758
    if (ret != Z_OK)
5759
        return -1;
5760
    return 0;
5761
}
5762

    
5763
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5764
{
5765
    int ret, clen;
5766

    
5767
    s->zstream.avail_out = len;
5768
    s->zstream.next_out = buf;
5769
    while (s->zstream.avail_out > 0) {
5770
        if (s->zstream.avail_in == 0) {
5771
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5772
                return -1;
5773
            clen = qemu_get_be16(s->f);
5774
            if (clen > IOBUF_SIZE)
5775
                return -1;
5776
            qemu_get_buffer(s->f, s->buf, clen);
5777
            s->zstream.avail_in = clen;
5778
            s->zstream.next_in = s->buf;
5779
        }
5780
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5781
        if (ret != Z_OK && ret != Z_STREAM_END) {
5782
            return -1;
5783
        }
5784
    }
5785
    return 0;
5786
}
5787

    
5788
static void ram_decompress_close(RamDecompressState *s)
5789
{
5790
    inflateEnd(&s->zstream);
5791
}
5792

    
5793
static void ram_save(QEMUFile *f, void *opaque)
5794
{
5795
    int i;
5796
    RamCompressState s1, *s = &s1;
5797
    uint8_t buf[10];
5798
    
5799
    qemu_put_be32(f, phys_ram_size);
5800
    if (ram_compress_open(s, f) < 0)
5801
        return;
5802
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5803
#if 0
5804
        if (tight_savevm_enabled) {
5805
            int64_t sector_num;
5806
            int j;
5807

5808
            /* find if the memory block is available on a virtual
5809
               block device */
5810
            sector_num = -1;
5811
            for(j = 0; j < MAX_DISKS; j++) {
5812
                if (bs_table[j]) {
5813
                    sector_num = bdrv_hash_find(bs_table[j], 
5814
                                                phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5815
                    if (sector_num >= 0)
5816
                        break;
5817
                }
5818
            }
5819
            if (j == MAX_DISKS)
5820
                goto normal_compress;
5821
            buf[0] = 1;
5822
            buf[1] = j;
5823
            cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5824
            ram_compress_buf(s, buf, 10);
5825
        } else 
5826
#endif
5827
        {
5828
            //        normal_compress:
5829
            buf[0] = 0;
5830
            ram_compress_buf(s, buf, 1);
5831
            ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5832
        }
5833
    }
5834
    ram_compress_close(s);
5835
}
5836

    
5837
static int ram_load(QEMUFile *f, void *opaque, int version_id)
5838
{
5839
    RamDecompressState s1, *s = &s1;
5840
    uint8_t buf[10];
5841
    int i;
5842

    
5843
    if (version_id == 1)
5844
        return ram_load_v1(f, opaque);
5845
    if (version_id != 2)
5846
        return -EINVAL;
5847
    if (qemu_get_be32(f) != phys_ram_size)
5848
        return -EINVAL;
5849
    if (ram_decompress_open(s, f) < 0)
5850
        return -EINVAL;
5851
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5852
        if (ram_decompress_buf(s, buf, 1) < 0) {
5853
            fprintf(stderr, "Error while reading ram block header\n");
5854
            goto error;
5855
        }
5856
        if (buf[0] == 0) {
5857
            if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5858
                fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5859
                goto error;
5860
            }
5861
        } else 
5862
#if 0
5863
        if (buf[0] == 1) {
5864
            int bs_index;
5865
            int64_t sector_num;
5866

5867
            ram_decompress_buf(s, buf + 1, 9);
5868
            bs_index = buf[1];
5869
            sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5870
            if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5871
                fprintf(stderr, "Invalid block device index %d\n", bs_index);
5872
                goto error;
5873
            }
5874
            if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i, 
5875
                          BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5876
                fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n", 
5877
                        bs_index, sector_num);
5878
                goto error;
5879
            }
5880
        } else 
5881
#endif
5882
        {
5883
        error:
5884
            printf("Error block header\n");
5885
            return -EINVAL;
5886
        }
5887
    }
5888
    ram_decompress_close(s);
5889
    return 0;
5890
}
5891

    
5892
/***********************************************************/
5893
/* bottom halves (can be seen as timers which expire ASAP) */
5894

    
5895
struct QEMUBH {
5896
    QEMUBHFunc *cb;
5897
    void *opaque;
5898
    int scheduled;
5899
    QEMUBH *next;
5900
};
5901

    
5902
static QEMUBH *first_bh = NULL;
5903

    
5904
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5905
{
5906
    QEMUBH *bh;
5907
    bh = qemu_mallocz(sizeof(QEMUBH));
5908
    if (!bh)
5909
        return NULL;
5910
    bh->cb = cb;
5911
    bh->opaque = opaque;
5912
    return bh;
5913
}
5914

    
5915
int qemu_bh_poll(void)
5916
{
5917
    QEMUBH *bh, **pbh;
5918
    int ret;
5919

    
5920
    ret = 0;
5921
    for(;;) {
5922
        pbh = &first_bh;
5923
        bh = *pbh;
5924
        if (!bh)
5925
            break;
5926
        ret = 1;
5927
        *pbh = bh->next;
5928
        bh->scheduled = 0;
5929
        bh->cb(bh->opaque);
5930
    }
5931
    return ret;
5932
}
5933

    
5934
void qemu_bh_schedule(QEMUBH *bh)
5935
{
5936
    CPUState *env = cpu_single_env;
5937
    if (bh->scheduled)
5938
        return;
5939
    bh->scheduled = 1;
5940
    bh->next = first_bh;
5941
    first_bh = bh;
5942

    
5943
    /* stop the currently executing CPU to execute the BH ASAP */
5944
    if (env) {
5945
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
5946
    }
5947
}
5948

    
5949
void qemu_bh_cancel(QEMUBH *bh)
5950
{
5951
    QEMUBH **pbh;
5952
    if (bh->scheduled) {
5953
        pbh = &first_bh;
5954
        while (*pbh != bh)
5955
            pbh = &(*pbh)->next;
5956
        *pbh = bh->next;
5957
        bh->scheduled = 0;
5958
    }
5959
}
5960

    
5961
void qemu_bh_delete(QEMUBH *bh)
5962
{
5963
    qemu_bh_cancel(bh);
5964
    qemu_free(bh);
5965
}
5966

    
5967
/***********************************************************/
5968
/* machine registration */
5969

    
5970
QEMUMachine *first_machine = NULL;
5971

    
5972
int qemu_register_machine(QEMUMachine *m)
5973
{
5974
    QEMUMachine **pm;
5975
    pm = &first_machine;
5976
    while (*pm != NULL)
5977
        pm = &(*pm)->next;
5978
    m->next = NULL;
5979
    *pm = m;
5980
    return 0;
5981
}
5982

    
5983
QEMUMachine *find_machine(const char *name)
5984
{
5985
    QEMUMachine *m;
5986

    
5987
    for(m = first_machine; m != NULL; m = m->next) {
5988
        if (!strcmp(m->name, name))
5989
            return m;
5990
    }
5991
    return NULL;
5992
}
5993

    
5994
/***********************************************************/
5995
/* main execution loop */
5996

    
5997
void gui_update(void *opaque)
5998
{
5999
    display_state.dpy_refresh(&display_state);
6000
    qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6001
}
6002

    
6003
struct vm_change_state_entry {
6004
    VMChangeStateHandler *cb;
6005
    void *opaque;
6006
    LIST_ENTRY (vm_change_state_entry) entries;
6007
};
6008

    
6009
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6010

    
6011
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6012
                                                     void *opaque)
6013
{
6014
    VMChangeStateEntry *e;
6015

    
6016
    e = qemu_mallocz(sizeof (*e));
6017
    if (!e)
6018
        return NULL;
6019

    
6020
    e->cb = cb;
6021
    e->opaque = opaque;
6022
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6023
    return e;
6024
}
6025

    
6026
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6027
{
6028
    LIST_REMOVE (e, entries);
6029
    qemu_free (e);
6030
}
6031

    
6032
static void vm_state_notify(int running)
6033
{
6034
    VMChangeStateEntry *e;
6035

    
6036
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6037
        e->cb(e->opaque, running);
6038
    }
6039
}
6040

    
6041
/* XXX: support several handlers */
6042
static VMStopHandler *vm_stop_cb;
6043
static void *vm_stop_opaque;
6044

    
6045
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6046
{
6047
    vm_stop_cb = cb;
6048
    vm_stop_opaque = opaque;
6049
    return 0;
6050
}
6051

    
6052
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6053
{
6054
    vm_stop_cb = NULL;
6055
}
6056

    
6057
void vm_start(void)
6058
{
6059
    if (!vm_running) {
6060
        cpu_enable_ticks();
6061
        vm_running = 1;
6062
        vm_state_notify(1);
6063
    }
6064
}
6065

    
6066
void vm_stop(int reason) 
6067
{
6068
    if (vm_running) {
6069
        cpu_disable_ticks();
6070
        vm_running = 0;
6071
        if (reason != 0) {
6072
            if (vm_stop_cb) {
6073
                vm_stop_cb(vm_stop_opaque, reason);
6074
            }
6075
        }
6076
        vm_state_notify(0);
6077
    }
6078
}
6079

    
6080
/* reset/shutdown handler */
6081

    
6082
typedef struct QEMUResetEntry {
6083
    QEMUResetHandler *func;
6084
    void *opaque;
6085
    struct QEMUResetEntry *next;
6086
} QEMUResetEntry;
6087

    
6088
static QEMUResetEntry *first_reset_entry;
6089
static int reset_requested;
6090
static int shutdown_requested;
6091
static int powerdown_requested;
6092

    
6093
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6094
{
6095
    QEMUResetEntry **pre, *re;
6096

    
6097
    pre = &first_reset_entry;
6098
    while (*pre != NULL)
6099
        pre = &(*pre)->next;
6100
    re = qemu_mallocz(sizeof(QEMUResetEntry));
6101
    re->func = func;
6102
    re->opaque = opaque;
6103
    re->next = NULL;
6104
    *pre = re;
6105
}
6106

    
6107
static void qemu_system_reset(void)
6108
{
6109
    QEMUResetEntry *re;
6110

    
6111
    /* reset all devices */
6112
    for(re = first_reset_entry; re != NULL; re = re->next) {
6113
        re->func(re->opaque);
6114
    }
6115
}
6116

    
6117
void qemu_system_reset_request(void)
6118
{
6119
    if (no_reboot) {
6120
        shutdown_requested = 1;
6121
    } else {
6122
        reset_requested = 1;
6123
    }
6124
    if (cpu_single_env)
6125
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6126
}
6127

    
6128
void qemu_system_shutdown_request(void)
6129
{
6130
    shutdown_requested = 1;
6131
    if (cpu_single_env)
6132
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6133
}
6134

    
6135
void qemu_system_powerdown_request(void)
6136
{
6137
    powerdown_requested = 1;
6138
    if (cpu_single_env)
6139
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6140
}
6141

    
6142
void main_loop_wait(int timeout)
6143
{
6144
    IOHandlerRecord *ioh;
6145
    fd_set rfds, wfds, xfds;
6146
    int ret, ret2, nfds, i;
6147
    struct timeval tv;
6148
    PollingEntry *pe;
6149

    
6150

    
6151
    /* XXX: need to suppress polling by better using win32 events */
6152
    ret = 0;
6153
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6154
        ret |= pe->func(pe->opaque);
6155
    }
6156
#ifdef _WIN32
6157
    if (ret == 0) {
6158
        int err;
6159
        WaitObjects *w = &wait_objects;
6160
        
6161
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6162
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6163
            if (w->func[ret - WAIT_OBJECT_0])
6164
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6165
                
6166
            /* Check for additional signaled events */ 
6167
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6168
                                
6169
                /* Check if event is signaled */
6170
                ret2 = WaitForSingleObject(w->events[i], 0);
6171
                if(ret2 == WAIT_OBJECT_0) {
6172
                    if (w->func[i])
6173
                        w->func[i](w->opaque[i]);
6174
                } else if (ret2 == WAIT_TIMEOUT) {
6175
                } else {
6176
                    err = GetLastError();
6177
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6178
                }                
6179
            }                 
6180
        } else if (ret == WAIT_TIMEOUT) {
6181
        } else {
6182
            err = GetLastError();
6183
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6184
        }
6185
    }
6186
#endif
6187
    /* poll any events */
6188
    /* XXX: separate device handlers from system ones */
6189
    nfds = -1;
6190
    FD_ZERO(&rfds);
6191
    FD_ZERO(&wfds);
6192
    FD_ZERO(&xfds);
6193
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6194
        if (ioh->deleted)
6195
            continue;
6196
        if (ioh->fd_read &&
6197
            (!ioh->fd_read_poll ||
6198
             ioh->fd_read_poll(ioh->opaque) != 0)) {
6199
            FD_SET(ioh->fd, &rfds);
6200
            if (ioh->fd > nfds)
6201
                nfds = ioh->fd;
6202
        }
6203
        if (ioh->fd_write) {
6204
            FD_SET(ioh->fd, &wfds);
6205
            if (ioh->fd > nfds)
6206
                nfds = ioh->fd;
6207
        }
6208
    }
6209
    
6210
    tv.tv_sec = 0;
6211
#ifdef _WIN32
6212
    tv.tv_usec = 0;
6213
#else
6214
    tv.tv_usec = timeout * 1000;
6215
#endif
6216
#if defined(CONFIG_SLIRP)
6217
    if (slirp_inited) {
6218
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6219
    }
6220
#endif
6221
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6222
    if (ret > 0) {
6223
        IOHandlerRecord **pioh;
6224

    
6225
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6226
            if (ioh->deleted)
6227
                continue;
6228
            if (FD_ISSET(ioh->fd, &rfds)) {
6229
                ioh->fd_read(ioh->opaque);
6230
            }
6231
            if (FD_ISSET(ioh->fd, &wfds)) {
6232
                ioh->fd_write(ioh->opaque);
6233
            }
6234
        }
6235

    
6236
        /* remove deleted IO handlers */
6237
        pioh = &first_io_handler;
6238
        while (*pioh) {
6239
            ioh = *pioh;
6240
            if (ioh->deleted) {
6241
                *pioh = ioh->next;
6242
                qemu_free(ioh);
6243
            } else 
6244
                pioh = &ioh->next;
6245
        }
6246
    }
6247
#if defined(CONFIG_SLIRP)
6248
    if (slirp_inited) {
6249
        if (ret < 0) {
6250
            FD_ZERO(&rfds);
6251
            FD_ZERO(&wfds);
6252
            FD_ZERO(&xfds);
6253
        }
6254
        slirp_select_poll(&rfds, &wfds, &xfds);
6255
    }
6256
#endif
6257
    qemu_aio_poll();
6258
    qemu_bh_poll();
6259

    
6260
    if (vm_running) {
6261
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
6262
                        qemu_get_clock(vm_clock));
6263
        /* run dma transfers, if any */
6264
        DMA_run();
6265
    }
6266
    
6267
    /* real time timers */
6268
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
6269
                    qemu_get_clock(rt_clock));
6270
}
6271

    
6272
static CPUState *cur_cpu;
6273

    
6274
int main_loop(void)
6275
{
6276
    int ret, timeout;
6277
#ifdef CONFIG_PROFILER
6278
    int64_t ti;
6279
#endif
6280
    CPUState *env;
6281

    
6282
    cur_cpu = first_cpu;
6283
    for(;;) {
6284
        if (vm_running) {
6285

    
6286
            env = cur_cpu;
6287
            for(;;) {
6288
                /* get next cpu */
6289
                env = env->next_cpu;
6290
                if (!env)
6291
                    env = first_cpu;
6292
#ifdef CONFIG_PROFILER
6293
                ti = profile_getclock();
6294
#endif
6295
                ret = cpu_exec(env);
6296
#ifdef CONFIG_PROFILER
6297
                qemu_time += profile_getclock() - ti;
6298
#endif
6299
                if (ret == EXCP_HLT) {
6300
                    /* Give the next CPU a chance to run.  */
6301
                    cur_cpu = env;
6302
                    continue;
6303
                }
6304
                if (ret != EXCP_HALTED)
6305
                    break;
6306
                /* all CPUs are halted ? */
6307
                if (env == cur_cpu)
6308
                    break;
6309
            }
6310
            cur_cpu = env;
6311

    
6312
            if (shutdown_requested) {
6313
                ret = EXCP_INTERRUPT;
6314
                break;
6315
            }
6316
            if (reset_requested) {
6317
                reset_requested = 0;
6318
                qemu_system_reset();
6319
                ret = EXCP_INTERRUPT;
6320
            }
6321
            if (powerdown_requested) {
6322
                powerdown_requested = 0;
6323
                qemu_system_powerdown();
6324
                ret = EXCP_INTERRUPT;
6325
            }
6326
            if (ret == EXCP_DEBUG) {
6327
                vm_stop(EXCP_DEBUG);
6328
            }
6329
            /* If all cpus are halted then wait until the next IRQ */
6330
            /* XXX: use timeout computed from timers */
6331
            if (ret == EXCP_HALTED)
6332
                timeout = 10;
6333
            else
6334
                timeout = 0;
6335
        } else {
6336
            timeout = 10;
6337
        }
6338
#ifdef CONFIG_PROFILER
6339
        ti = profile_getclock();
6340
#endif
6341
        main_loop_wait(timeout);
6342
#ifdef CONFIG_PROFILER
6343
        dev_time += profile_getclock() - ti;
6344
#endif
6345
    }
6346
    cpu_disable_ticks();
6347
    return ret;
6348
}
6349

    
6350
void help(void)
6351
{
6352
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6353
           "usage: %s [options] [disk_image]\n"
6354
           "\n"
6355
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6356
           "\n"
6357
           "Standard options:\n"
6358
           "-M machine      select emulated machine (-M ? for list)\n"
6359
           "-cpu cpu        select CPU (-cpu ? for list)\n"
6360
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
6361
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
6362
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
6363
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6364
           "-sd file        use 'file' as SecureDigital card image\n"
6365
           "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6366
           "-snapshot       write to temporary files instead of disk image files\n"
6367
#ifdef CONFIG_SDL
6368
           "-no-frame       open SDL window without a frame and window decorations\n"
6369
           "-no-quit        disable SDL window close capability\n"
6370
#endif
6371
#ifdef TARGET_I386
6372
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
6373
#endif
6374
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
6375
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
6376
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
6377
#ifndef _WIN32
6378
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
6379
#endif
6380
#ifdef HAS_AUDIO
6381
           "-audio-help     print list of audio drivers and their options\n"
6382
           "-soundhw c1,... enable audio support\n"
6383
           "                and only specified sound cards (comma separated list)\n"
6384
           "                use -soundhw ? to get the list of supported cards\n"
6385
           "                use -soundhw all to enable all of them\n"
6386
#endif
6387
           "-localtime      set the real time clock to local time [default=utc]\n"
6388
           "-full-screen    start in full screen\n"
6389
#ifdef TARGET_I386
6390
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
6391
#endif
6392
           "-usb            enable the USB driver (will be the default soon)\n"
6393
           "-usbdevice name add the host or guest USB device 'name'\n"
6394
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
6395
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
6396
#endif
6397
           "-name string    set the name of the guest\n"
6398
           "\n"
6399
           "Network options:\n"
6400
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6401
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
6402
#ifdef CONFIG_SLIRP
6403
           "-net user[,vlan=n][,hostname=host]\n"
6404
           "                connect the user mode network stack to VLAN 'n' and send\n"
6405
           "                hostname 'host' to DHCP clients\n"
6406
#endif
6407
#ifdef _WIN32
6408
           "-net tap[,vlan=n],ifname=name\n"
6409
           "                connect the host TAP network interface to VLAN 'n'\n"
6410
#else
6411
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6412
           "                connect the host TAP network interface to VLAN 'n' and use\n"
6413
           "                the network script 'file' (default=%s);\n"
6414
           "                use 'script=no' to disable script execution;\n"
6415
           "                use 'fd=h' to connect to an already opened TAP interface\n"
6416
#endif
6417
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6418
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
6419
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6420
           "                connect the vlan 'n' to multicast maddr and port\n"
6421
           "-net none       use it alone to have zero network devices; if no -net option\n"
6422
           "                is provided, the default is '-net nic -net user'\n"
6423
           "\n"
6424
#ifdef CONFIG_SLIRP
6425
           "-tftp dir       allow tftp access to files in dir [-net user]\n"
6426
           "-bootp file     advertise file in BOOTP replies\n"
6427
#ifndef _WIN32
6428
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
6429
#endif
6430
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6431
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
6432
#endif
6433
           "\n"
6434
           "Linux boot specific:\n"
6435
           "-kernel bzImage use 'bzImage' as kernel image\n"
6436
           "-append cmdline use 'cmdline' as kernel command line\n"
6437
           "-initrd file    use 'file' as initial ram disk\n"
6438
           "\n"
6439
           "Debug/Expert options:\n"
6440
           "-monitor dev    redirect the monitor to char device 'dev'\n"
6441
           "-serial dev     redirect the serial port to char device 'dev'\n"
6442
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
6443
           "-pidfile file   Write PID to 'file'\n"
6444
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
6445
           "-s              wait gdb connection to port\n"
6446
           "-p port         set gdb connection port [default=%s]\n"
6447
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
6448
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
6449
           "                translation (t=none or lba) (usually qemu can guess them)\n"
6450
           "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
6451
#ifdef USE_KQEMU
6452
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
6453
           "-no-kqemu       disable KQEMU kernel module usage\n"
6454
#endif
6455
#ifdef USE_CODE_COPY
6456
           "-no-code-copy   disable code copy acceleration\n"
6457
#endif
6458
#ifdef TARGET_I386
6459
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
6460
           "                (default is CL-GD5446 PCI VGA)\n"
6461
           "-no-acpi        disable ACPI\n"
6462
#endif
6463
           "-no-reboot      exit instead of rebooting\n"
6464
           "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
6465
           "-vnc display    start a VNC server on display\n"
6466
#ifndef _WIN32
6467
           "-daemonize      daemonize QEMU after initializing\n"
6468
#endif
6469
           "-option-rom rom load a file, rom, into the option ROM space\n"
6470
           "\n"
6471
           "During emulation, the following keys are useful:\n"
6472
           "ctrl-alt-f      toggle full screen\n"
6473
           "ctrl-alt-n      switch to virtual console 'n'\n"
6474
           "ctrl-alt        toggle mouse and keyboard grab\n"
6475
           "\n"
6476
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
6477
           ,
6478
           "qemu",
6479
           DEFAULT_RAM_SIZE,
6480
#ifndef _WIN32
6481
           DEFAULT_NETWORK_SCRIPT,
6482
#endif
6483
           DEFAULT_GDBSTUB_PORT,
6484
           "/tmp/qemu.log");
6485
    exit(1);
6486
}
6487

    
6488
#define HAS_ARG 0x0001
6489

    
6490
enum {
6491
    QEMU_OPTION_h,
6492

    
6493
    QEMU_OPTION_M,
6494
    QEMU_OPTION_cpu,
6495
    QEMU_OPTION_fda,
6496
    QEMU_OPTION_fdb,
6497
    QEMU_OPTION_hda,
6498
    QEMU_OPTION_hdb,
6499
    QEMU_OPTION_hdc,
6500
    QEMU_OPTION_hdd,
6501
    QEMU_OPTION_cdrom,
6502
    QEMU_OPTION_sd,
6503
    QEMU_OPTION_boot,
6504
    QEMU_OPTION_snapshot,
6505
#ifdef TARGET_I386
6506
    QEMU_OPTION_no_fd_bootchk,
6507
#endif
6508
    QEMU_OPTION_m,
6509
    QEMU_OPTION_nographic,
6510
#ifdef HAS_AUDIO
6511
    QEMU_OPTION_audio_help,
6512
    QEMU_OPTION_soundhw,
6513
#endif
6514

    
6515
    QEMU_OPTION_net,
6516
    QEMU_OPTION_tftp,
6517
    QEMU_OPTION_bootp,
6518
    QEMU_OPTION_smb,
6519
    QEMU_OPTION_redir,
6520

    
6521
    QEMU_OPTION_kernel,
6522
    QEMU_OPTION_append,
6523
    QEMU_OPTION_initrd,
6524

    
6525
    QEMU_OPTION_S,
6526
    QEMU_OPTION_s,
6527
    QEMU_OPTION_p,
6528
    QEMU_OPTION_d,
6529
    QEMU_OPTION_hdachs,
6530
    QEMU_OPTION_L,
6531
    QEMU_OPTION_no_code_copy,
6532
    QEMU_OPTION_k,
6533
    QEMU_OPTION_localtime,
6534
    QEMU_OPTION_cirrusvga,
6535
    QEMU_OPTION_vmsvga,
6536
    QEMU_OPTION_g,
6537
    QEMU_OPTION_std_vga,
6538
    QEMU_OPTION_echr,
6539
    QEMU_OPTION_monitor,
6540
    QEMU_OPTION_serial,
6541
    QEMU_OPTION_parallel,
6542
    QEMU_OPTION_loadvm,
6543
    QEMU_OPTION_full_screen,
6544
    QEMU_OPTION_no_frame,
6545
    QEMU_OPTION_no_quit,
6546
    QEMU_OPTION_pidfile,
6547
    QEMU_OPTION_no_kqemu,
6548
    QEMU_OPTION_kernel_kqemu,
6549
    QEMU_OPTION_win2k_hack,
6550
    QEMU_OPTION_usb,
6551
    QEMU_OPTION_usbdevice,
6552
    QEMU_OPTION_smp,
6553
    QEMU_OPTION_vnc,
6554
    QEMU_OPTION_no_acpi,
6555
    QEMU_OPTION_no_reboot,
6556
    QEMU_OPTION_daemonize,
6557
    QEMU_OPTION_option_rom,
6558
    QEMU_OPTION_semihosting,
6559
    QEMU_OPTION_name,
6560
};
6561

    
6562
typedef struct QEMUOption {
6563
    const char *name;
6564
    int flags;
6565
    int index;
6566
} QEMUOption;
6567

    
6568
const QEMUOption qemu_options[] = {
6569
    { "h", 0, QEMU_OPTION_h },
6570
    { "help", 0, QEMU_OPTION_h },
6571

    
6572
    { "M", HAS_ARG, QEMU_OPTION_M },
6573
    { "cpu", HAS_ARG, QEMU_OPTION_cpu },
6574
    { "fda", HAS_ARG, QEMU_OPTION_fda },
6575
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6576
    { "hda", HAS_ARG, QEMU_OPTION_hda },
6577
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6578
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6579
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6580
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6581
    { "sd", HAS_ARG, QEMU_OPTION_sd },
6582
    { "boot", HAS_ARG, QEMU_OPTION_boot },
6583
    { "snapshot", 0, QEMU_OPTION_snapshot },
6584
#ifdef TARGET_I386
6585
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6586
#endif
6587
    { "m", HAS_ARG, QEMU_OPTION_m },
6588
    { "nographic", 0, QEMU_OPTION_nographic },
6589
    { "k", HAS_ARG, QEMU_OPTION_k },
6590
#ifdef HAS_AUDIO
6591
    { "audio-help", 0, QEMU_OPTION_audio_help },
6592
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6593
#endif
6594

    
6595
    { "net", HAS_ARG, QEMU_OPTION_net},
6596
#ifdef CONFIG_SLIRP
6597
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6598
    { "bootp", HAS_ARG, QEMU_OPTION_bootp },
6599
#ifndef _WIN32
6600
    { "smb", HAS_ARG, QEMU_OPTION_smb },
6601
#endif
6602
    { "redir", HAS_ARG, QEMU_OPTION_redir },
6603
#endif
6604

    
6605
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6606
    { "append", HAS_ARG, QEMU_OPTION_append },
6607
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6608

    
6609
    { "S", 0, QEMU_OPTION_S },
6610
    { "s", 0, QEMU_OPTION_s },
6611
    { "p", HAS_ARG, QEMU_OPTION_p },
6612
    { "d", HAS_ARG, QEMU_OPTION_d },
6613
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6614
    { "L", HAS_ARG, QEMU_OPTION_L },
6615
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6616
#ifdef USE_KQEMU
6617
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6618
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6619
#endif
6620
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
6621
    { "g", 1, QEMU_OPTION_g },
6622
#endif
6623
    { "localtime", 0, QEMU_OPTION_localtime },
6624
    { "std-vga", 0, QEMU_OPTION_std_vga },
6625
    { "echr", 1, QEMU_OPTION_echr },
6626
    { "monitor", 1, QEMU_OPTION_monitor },
6627
    { "serial", 1, QEMU_OPTION_serial },
6628
    { "parallel", 1, QEMU_OPTION_parallel },
6629
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6630
    { "full-screen", 0, QEMU_OPTION_full_screen },
6631
#ifdef CONFIG_SDL
6632
    { "no-frame", 0, QEMU_OPTION_no_frame },
6633
    { "no-quit", 0, QEMU_OPTION_no_quit },
6634
#endif
6635
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6636
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6637
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6638
    { "smp", HAS_ARG, QEMU_OPTION_smp },
6639
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6640

    
6641
    /* temporary options */
6642
    { "usb", 0, QEMU_OPTION_usb },
6643
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6644
    { "vmwarevga", 0, QEMU_OPTION_vmsvga },
6645
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
6646
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
6647
    { "daemonize", 0, QEMU_OPTION_daemonize },
6648
    { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6649
#if defined(TARGET_ARM)
6650
    { "semihosting", 0, QEMU_OPTION_semihosting },
6651
#endif
6652
    { "name", HAS_ARG, QEMU_OPTION_name },
6653
    { NULL },
6654
};
6655

    
6656
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
6657

    
6658
/* this stack is only used during signal handling */
6659
#define SIGNAL_STACK_SIZE 32768
6660

    
6661
static uint8_t *signal_stack;
6662

    
6663
#endif
6664

    
6665
/* password input */
6666

    
6667
static BlockDriverState *get_bdrv(int index)
6668
{
6669
    BlockDriverState *bs;
6670

    
6671
    if (index < 4) {
6672
        bs = bs_table[index];
6673
    } else if (index < 6) {
6674
        bs = fd_table[index - 4];
6675
    } else {
6676
        bs = NULL;
6677
    }
6678
    return bs;
6679
}
6680

    
6681
static void read_passwords(void)
6682
{
6683
    BlockDriverState *bs;
6684
    int i, j;
6685
    char password[256];
6686

    
6687
    for(i = 0; i < 6; i++) {
6688
        bs = get_bdrv(i);
6689
        if (bs && bdrv_is_encrypted(bs)) {
6690
            term_printf("%s is encrypted.\n", bdrv_get_device_name(bs));
6691
            for(j = 0; j < 3; j++) {
6692
                monitor_readline("Password: ", 
6693
                                 1, password, sizeof(password));
6694
                if (bdrv_set_key(bs, password) == 0)
6695
                    break;
6696
                term_printf("invalid password\n");
6697
            }
6698
        }
6699
    }
6700
}
6701

    
6702
/* XXX: currently we cannot use simultaneously different CPUs */
6703
void register_machines(void)
6704
{
6705
#if defined(TARGET_I386)
6706
    qemu_register_machine(&pc_machine);
6707
    qemu_register_machine(&isapc_machine);
6708
#elif defined(TARGET_PPC)
6709
    qemu_register_machine(&heathrow_machine);
6710
    qemu_register_machine(&core99_machine);
6711
    qemu_register_machine(&prep_machine);
6712
#elif defined(TARGET_MIPS)
6713
    qemu_register_machine(&mips_machine);
6714
    qemu_register_machine(&mips_malta_machine);
6715
    qemu_register_machine(&mips_pica61_machine);
6716
#elif defined(TARGET_SPARC)
6717
#ifdef TARGET_SPARC64
6718
    qemu_register_machine(&sun4u_machine);
6719
#else
6720
    qemu_register_machine(&ss5_machine);
6721
    qemu_register_machine(&ss10_machine);
6722
#endif
6723
#elif defined(TARGET_ARM)
6724
    qemu_register_machine(&integratorcp_machine);
6725
    qemu_register_machine(&versatilepb_machine);
6726
    qemu_register_machine(&versatileab_machine);
6727
    qemu_register_machine(&realview_machine);
6728
#elif defined(TARGET_SH4)
6729
    qemu_register_machine(&shix_machine);
6730
#elif defined(TARGET_ALPHA)
6731
    /* XXX: TODO */
6732
#else
6733
#error unsupported CPU
6734
#endif
6735
}
6736

    
6737
#ifdef HAS_AUDIO
6738
struct soundhw soundhw[] = {
6739
#ifdef TARGET_I386
6740
    {
6741
        "pcspk",
6742
        "PC speaker",
6743
        0,
6744
        1,
6745
        { .init_isa = pcspk_audio_init }
6746
    },
6747
#endif
6748
    {
6749
        "sb16",
6750
        "Creative Sound Blaster 16",
6751
        0,
6752
        1,
6753
        { .init_isa = SB16_init }
6754
    },
6755

    
6756
#ifdef CONFIG_ADLIB
6757
    {
6758
        "adlib",
6759
#ifdef HAS_YMF262
6760
        "Yamaha YMF262 (OPL3)",
6761
#else
6762
        "Yamaha YM3812 (OPL2)",
6763
#endif
6764
        0,
6765
        1,
6766
        { .init_isa = Adlib_init }
6767
    },
6768
#endif
6769

    
6770
#ifdef CONFIG_GUS
6771
    {
6772
        "gus",
6773
        "Gravis Ultrasound GF1",
6774
        0,
6775
        1,
6776
        { .init_isa = GUS_init }
6777
    },
6778
#endif
6779

    
6780
    {
6781
        "es1370",
6782
        "ENSONIQ AudioPCI ES1370",
6783
        0,
6784
        0,
6785
        { .init_pci = es1370_init }
6786
    },
6787

    
6788
    { NULL, NULL, 0, 0, { NULL } }
6789
};
6790

    
6791
static void select_soundhw (const char *optarg)
6792
{
6793
    struct soundhw *c;
6794

    
6795
    if (*optarg == '?') {
6796
    show_valid_cards:
6797

    
6798
        printf ("Valid sound card names (comma separated):\n");
6799
        for (c = soundhw; c->name; ++c) {
6800
            printf ("%-11s %s\n", c->name, c->descr);
6801
        }
6802
        printf ("\n-soundhw all will enable all of the above\n");
6803
        exit (*optarg != '?');
6804
    }
6805
    else {
6806
        size_t l;
6807
        const char *p;
6808
        char *e;
6809
        int bad_card = 0;
6810

    
6811
        if (!strcmp (optarg, "all")) {
6812
            for (c = soundhw; c->name; ++c) {
6813
                c->enabled = 1;
6814
            }
6815
            return;
6816
        }
6817

    
6818
        p = optarg;
6819
        while (*p) {
6820
            e = strchr (p, ',');
6821
            l = !e ? strlen (p) : (size_t) (e - p);
6822

    
6823
            for (c = soundhw; c->name; ++c) {
6824
                if (!strncmp (c->name, p, l)) {
6825
                    c->enabled = 1;
6826
                    break;
6827
                }
6828
            }
6829

    
6830
            if (!c->name) {
6831
                if (l > 80) {
6832
                    fprintf (stderr,
6833
                             "Unknown sound card name (too big to show)\n");
6834
                }
6835
                else {
6836
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
6837
                             (int) l, p);
6838
                }
6839
                bad_card = 1;
6840
            }
6841
            p += l + (e != NULL);
6842
        }
6843

    
6844
        if (bad_card)
6845
            goto show_valid_cards;
6846
    }
6847
}
6848
#endif
6849

    
6850
#ifdef _WIN32
6851
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6852
{
6853
    exit(STATUS_CONTROL_C_EXIT);
6854
    return TRUE;
6855
}
6856
#endif
6857

    
6858
#define MAX_NET_CLIENTS 32
6859

    
6860
int main(int argc, char **argv)
6861
{
6862
#ifdef CONFIG_GDBSTUB
6863
    int use_gdbstub;
6864
    const char *gdbstub_port;
6865
#endif
6866
    int i, cdrom_index;
6867
    int snapshot, linux_boot;
6868
    const char *initrd_filename;
6869
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6870
    const char *sd_filename;
6871
    const char *kernel_filename, *kernel_cmdline;
6872
    DisplayState *ds = &display_state;
6873
    int cyls, heads, secs, translation;
6874
    char net_clients[MAX_NET_CLIENTS][256];
6875
    int nb_net_clients;
6876
    int optind;
6877
    const char *r, *optarg;
6878
    CharDriverState *monitor_hd;
6879
    char monitor_device[128];
6880
    char serial_devices[MAX_SERIAL_PORTS][128];
6881
    int serial_device_index;
6882
    char parallel_devices[MAX_PARALLEL_PORTS][128];
6883
    int parallel_device_index;
6884
    const char *loadvm = NULL;
6885
    QEMUMachine *machine;
6886
    const char *cpu_model;
6887
    char usb_devices[MAX_USB_CMDLINE][128];
6888
    int usb_devices_index;
6889
    int fds[2];
6890
    const char *pid_file = NULL;
6891

    
6892
    LIST_INIT (&vm_change_state_head);
6893
#ifndef _WIN32
6894
    {
6895
        struct sigaction act;
6896
        sigfillset(&act.sa_mask);
6897
        act.sa_flags = 0;
6898
        act.sa_handler = SIG_IGN;
6899
        sigaction(SIGPIPE, &act, NULL);
6900
    }
6901
#else
6902
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6903
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
6904
       QEMU to run on a single CPU */
6905
    {
6906
        HANDLE h;
6907
        DWORD mask, smask;
6908
        int i;
6909
        h = GetCurrentProcess();
6910
        if (GetProcessAffinityMask(h, &mask, &smask)) {
6911
            for(i = 0; i < 32; i++) {
6912
                if (mask & (1 << i))
6913
                    break;
6914
            }
6915
            if (i != 32) {
6916
                mask = 1 << i;
6917
                SetProcessAffinityMask(h, mask);
6918
            }
6919
        }
6920
    }
6921
#endif
6922

    
6923
    register_machines();
6924
    machine = first_machine;
6925
    cpu_model = NULL;
6926
    initrd_filename = NULL;
6927
    for(i = 0; i < MAX_FD; i++)
6928
        fd_filename[i] = NULL;
6929
    for(i = 0; i < MAX_DISKS; i++)
6930
        hd_filename[i] = NULL;
6931
    sd_filename = NULL;
6932
    ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
6933
    vga_ram_size = VGA_RAM_SIZE;
6934
#ifdef CONFIG_GDBSTUB
6935
    use_gdbstub = 0;
6936
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
6937
#endif
6938
    snapshot = 0;
6939
    nographic = 0;
6940
    kernel_filename = NULL;
6941
    kernel_cmdline = "";
6942
#ifdef TARGET_PPC
6943
    cdrom_index = 1;
6944
#else
6945
    cdrom_index = 2;
6946
#endif
6947
    cyls = heads = secs = 0;
6948
    translation = BIOS_ATA_TRANSLATION_AUTO;
6949
    pstrcpy(monitor_device, sizeof(monitor_device), "vc");
6950

    
6951
    pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
6952
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
6953
        serial_devices[i][0] = '\0';
6954
    serial_device_index = 0;
6955
    
6956
    pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
6957
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
6958
        parallel_devices[i][0] = '\0';
6959
    parallel_device_index = 0;
6960
    
6961
    usb_devices_index = 0;
6962
    
6963
    nb_net_clients = 0;
6964

    
6965
    nb_nics = 0;
6966
    /* default mac address of the first network interface */
6967
    
6968
    optind = 1;
6969
    for(;;) {
6970
        if (optind >= argc)
6971
            break;
6972
        r = argv[optind];
6973
        if (r[0] != '-') {
6974
            hd_filename[0] = argv[optind++];
6975
        } else {
6976
            const QEMUOption *popt;
6977

    
6978
            optind++;
6979
            /* Treat --foo the same as -foo.  */
6980
            if (r[1] == '-')
6981
                r++;
6982
            popt = qemu_options;
6983
            for(;;) {
6984
                if (!popt->name) {
6985
                    fprintf(stderr, "%s: invalid option -- '%s'\n", 
6986
                            argv[0], r);
6987
                    exit(1);
6988
                }
6989
                if (!strcmp(popt->name, r + 1))
6990
                    break;
6991
                popt++;
6992
            }
6993
            if (popt->flags & HAS_ARG) {
6994
                if (optind >= argc) {
6995
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
6996
                            argv[0], r);
6997
                    exit(1);
6998
                }
6999
                optarg = argv[optind++];
7000
            } else {
7001
                optarg = NULL;
7002
            }
7003

    
7004
            switch(popt->index) {
7005
            case QEMU_OPTION_M:
7006
                machine = find_machine(optarg);
7007
                if (!machine) {
7008
                    QEMUMachine *m;
7009
                    printf("Supported machines are:\n");
7010
                    for(m = first_machine; m != NULL; m = m->next) {
7011
                        printf("%-10s %s%s\n",
7012
                               m->name, m->desc, 
7013
                               m == first_machine ? " (default)" : "");
7014
                    }
7015
                    exit(1);
7016
                }
7017
                break;
7018
            case QEMU_OPTION_cpu:
7019
                /* hw initialization will check this */
7020
                if (optarg[0] == '?') {
7021
#if defined(TARGET_PPC)
7022
                    ppc_cpu_list(stdout, &fprintf);
7023
#elif defined(TARGET_ARM)
7024
                    arm_cpu_list();
7025
#elif defined(TARGET_MIPS)
7026
                    mips_cpu_list(stdout, &fprintf);
7027
#elif defined(TARGET_SPARC)
7028
                    sparc_cpu_list(stdout, &fprintf);
7029
#endif
7030
                    exit(1);
7031
                } else {
7032
                    cpu_model = optarg;
7033
                }
7034
                break;
7035
            case QEMU_OPTION_initrd:
7036
                initrd_filename = optarg;
7037
                break;
7038
            case QEMU_OPTION_hda:
7039
            case QEMU_OPTION_hdb:
7040
            case QEMU_OPTION_hdc:
7041
            case QEMU_OPTION_hdd:
7042
                {
7043
                    int hd_index;
7044
                    hd_index = popt->index - QEMU_OPTION_hda;
7045
                    hd_filename[hd_index] = optarg;
7046
                    if (hd_index == cdrom_index)
7047
                        cdrom_index = -1;
7048
                }
7049
                break;
7050
            case QEMU_OPTION_sd:
7051
                sd_filename = optarg;
7052
                break;
7053
            case QEMU_OPTION_snapshot:
7054
                snapshot = 1;
7055
                break;
7056
            case QEMU_OPTION_hdachs:
7057
                {
7058
                    const char *p;
7059
                    p = optarg;
7060
                    cyls = strtol(p, (char **)&p, 0);
7061
                    if (cyls < 1 || cyls > 16383)
7062
                        goto chs_fail;
7063
                    if (*p != ',')
7064
                        goto chs_fail;
7065
                    p++;
7066
                    heads = strtol(p, (char **)&p, 0);
7067
                    if (heads < 1 || heads > 16)
7068
                        goto chs_fail;
7069
                    if (*p != ',')
7070
                        goto chs_fail;
7071
                    p++;
7072
                    secs = strtol(p, (char **)&p, 0);
7073
                    if (secs < 1 || secs > 63)
7074
                        goto chs_fail;
7075
                    if (*p == ',') {
7076
                        p++;
7077
                        if (!strcmp(p, "none"))
7078
                            translation = BIOS_ATA_TRANSLATION_NONE;
7079
                        else if (!strcmp(p, "lba"))
7080
                            translation = BIOS_ATA_TRANSLATION_LBA;
7081
                        else if (!strcmp(p, "auto"))
7082
                            translation = BIOS_ATA_TRANSLATION_AUTO;
7083
                        else
7084
                            goto chs_fail;
7085
                    } else if (*p != '\0') {
7086
                    chs_fail:
7087
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
7088
                        exit(1);
7089
                    }
7090
                }
7091
                break;
7092
            case QEMU_OPTION_nographic:
7093
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7094
                pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7095
                pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7096
                nographic = 1;
7097
                break;
7098
            case QEMU_OPTION_kernel:
7099
                kernel_filename = optarg;
7100
                break;
7101
            case QEMU_OPTION_append:
7102
                kernel_cmdline = optarg;
7103
                break;
7104
            case QEMU_OPTION_cdrom:
7105
                if (cdrom_index >= 0) {
7106
                    hd_filename[cdrom_index] = optarg;
7107
                }
7108
                break;
7109
            case QEMU_OPTION_boot:
7110
                boot_device = optarg[0];
7111
                if (boot_device != 'a' && 
7112
#if defined(TARGET_SPARC) || defined(TARGET_I386)
7113
                    // Network boot
7114
                    boot_device != 'n' &&
7115
#endif
7116
                    boot_device != 'c' && boot_device != 'd') {
7117
                    fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7118
                    exit(1);
7119
                }
7120
                break;
7121
            case QEMU_OPTION_fda:
7122
                fd_filename[0] = optarg;
7123
                break;
7124
            case QEMU_OPTION_fdb:
7125
                fd_filename[1] = optarg;
7126
                break;
7127
#ifdef TARGET_I386
7128
            case QEMU_OPTION_no_fd_bootchk:
7129
                fd_bootchk = 0;
7130
                break;
7131
#endif
7132
            case QEMU_OPTION_no_code_copy:
7133
                code_copy_enabled = 0;
7134
                break;
7135
            case QEMU_OPTION_net:
7136
                if (nb_net_clients >= MAX_NET_CLIENTS) {
7137
                    fprintf(stderr, "qemu: too many network clients\n");
7138
                    exit(1);
7139
                }
7140
                pstrcpy(net_clients[nb_net_clients],
7141
                        sizeof(net_clients[0]),
7142
                        optarg);
7143
                nb_net_clients++;
7144
                break;
7145
#ifdef CONFIG_SLIRP
7146
            case QEMU_OPTION_tftp:
7147
                tftp_prefix = optarg;
7148
                break;
7149
            case QEMU_OPTION_bootp:
7150
                bootp_filename = optarg;
7151
                break;
7152
#ifndef _WIN32
7153
            case QEMU_OPTION_smb:
7154
                net_slirp_smb(optarg);
7155
                break;
7156
#endif
7157
            case QEMU_OPTION_redir:
7158
                net_slirp_redir(optarg);                
7159
                break;
7160
#endif
7161
#ifdef HAS_AUDIO
7162
            case QEMU_OPTION_audio_help:
7163
                AUD_help ();
7164
                exit (0);
7165
                break;
7166
            case QEMU_OPTION_soundhw:
7167
                select_soundhw (optarg);
7168
                break;
7169
#endif
7170
            case QEMU_OPTION_h:
7171
                help();
7172
                break;
7173
            case QEMU_OPTION_m:
7174
                ram_size = atoi(optarg) * 1024 * 1024;
7175
                if (ram_size <= 0)
7176
                    help();
7177
                if (ram_size > PHYS_RAM_MAX_SIZE) {
7178
                    fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7179
                            PHYS_RAM_MAX_SIZE / (1024 * 1024));
7180
                    exit(1);
7181
                }
7182
                break;
7183
            case QEMU_OPTION_d:
7184
                {
7185
                    int mask;
7186
                    CPULogItem *item;
7187
                    
7188
                    mask = cpu_str_to_log_mask(optarg);
7189
                    if (!mask) {
7190
                        printf("Log items (comma separated):\n");
7191
                    for(item = cpu_log_items; item->mask != 0; item++) {
7192
                        printf("%-10s %s\n", item->name, item->help);
7193
                    }
7194
                    exit(1);
7195
                    }
7196
                    cpu_set_log(mask);
7197
                }
7198
                break;
7199
#ifdef CONFIG_GDBSTUB
7200
            case QEMU_OPTION_s:
7201
                use_gdbstub = 1;
7202
                break;
7203
            case QEMU_OPTION_p:
7204
                gdbstub_port = optarg;
7205
                break;
7206
#endif
7207
            case QEMU_OPTION_L:
7208
                bios_dir = optarg;
7209
                break;
7210
            case QEMU_OPTION_S:
7211
                autostart = 0;
7212
                break;
7213
            case QEMU_OPTION_k:
7214
                keyboard_layout = optarg;
7215
                break;
7216
            case QEMU_OPTION_localtime:
7217
                rtc_utc = 0;
7218
                break;
7219
            case QEMU_OPTION_cirrusvga:
7220
                cirrus_vga_enabled = 1;
7221
                vmsvga_enabled = 0;
7222
                break;
7223
            case QEMU_OPTION_vmsvga:
7224
                cirrus_vga_enabled = 0;
7225
                vmsvga_enabled = 1;
7226
                break;
7227
            case QEMU_OPTION_std_vga:
7228
                cirrus_vga_enabled = 0;
7229
                vmsvga_enabled = 0;
7230
                break;
7231
            case QEMU_OPTION_g:
7232
                {
7233
                    const char *p;
7234
                    int w, h, depth;
7235
                    p = optarg;
7236
                    w = strtol(p, (char **)&p, 10);
7237
                    if (w <= 0) {
7238
                    graphic_error:
7239
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
7240
                        exit(1);
7241
                    }
7242
                    if (*p != 'x')
7243
                        goto graphic_error;
7244
                    p++;
7245
                    h = strtol(p, (char **)&p, 10);
7246
                    if (h <= 0)
7247
                        goto graphic_error;
7248
                    if (*p == 'x') {
7249
                        p++;
7250
                        depth = strtol(p, (char **)&p, 10);
7251
                        if (depth != 8 && depth != 15 && depth != 16 && 
7252
                            depth != 24 && depth != 32)
7253
                            goto graphic_error;
7254
                    } else if (*p == '\0') {
7255
                        depth = graphic_depth;
7256
                    } else {
7257
                        goto graphic_error;
7258
                    }
7259
                    
7260
                    graphic_width = w;
7261
                    graphic_height = h;
7262
                    graphic_depth = depth;
7263
                }
7264
                break;
7265
            case QEMU_OPTION_echr:
7266
                {
7267
                    char *r;
7268
                    term_escape_char = strtol(optarg, &r, 0);
7269
                    if (r == optarg)
7270
                        printf("Bad argument to echr\n");
7271
                    break;
7272
                }
7273
            case QEMU_OPTION_monitor:
7274
                pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7275
                break;
7276
            case QEMU_OPTION_serial:
7277
                if (serial_device_index >= MAX_SERIAL_PORTS) {
7278
                    fprintf(stderr, "qemu: too many serial ports\n");
7279
                    exit(1);
7280
                }
7281
                pstrcpy(serial_devices[serial_device_index], 
7282
                        sizeof(serial_devices[0]), optarg);
7283
                serial_device_index++;
7284
                break;
7285
            case QEMU_OPTION_parallel:
7286
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7287
                    fprintf(stderr, "qemu: too many parallel ports\n");
7288
                    exit(1);
7289
                }
7290
                pstrcpy(parallel_devices[parallel_device_index], 
7291
                        sizeof(parallel_devices[0]), optarg);
7292
                parallel_device_index++;
7293
                break;
7294
            case QEMU_OPTION_loadvm:
7295
                loadvm = optarg;
7296
                break;
7297
            case QEMU_OPTION_full_screen:
7298
                full_screen = 1;
7299
                break;
7300
#ifdef CONFIG_SDL
7301
            case QEMU_OPTION_no_frame:
7302
                no_frame = 1;
7303
                break;
7304
            case QEMU_OPTION_no_quit:
7305
                no_quit = 1;
7306
                break;
7307
#endif
7308
            case QEMU_OPTION_pidfile:
7309
                pid_file = optarg;
7310
                break;
7311
#ifdef TARGET_I386
7312
            case QEMU_OPTION_win2k_hack:
7313
                win2k_install_hack = 1;
7314
                break;
7315
#endif
7316
#ifdef USE_KQEMU
7317
            case QEMU_OPTION_no_kqemu:
7318
                kqemu_allowed = 0;
7319
                break;
7320
            case QEMU_OPTION_kernel_kqemu:
7321
                kqemu_allowed = 2;
7322
                break;
7323
#endif
7324
            case QEMU_OPTION_usb:
7325
                usb_enabled = 1;
7326
                break;
7327
            case QEMU_OPTION_usbdevice:
7328
                usb_enabled = 1;
7329
                if (usb_devices_index >= MAX_USB_CMDLINE) {
7330
                    fprintf(stderr, "Too many USB devices\n");
7331
                    exit(1);
7332
                }
7333
                pstrcpy(usb_devices[usb_devices_index],
7334
                        sizeof(usb_devices[usb_devices_index]),
7335
                        optarg);
7336
                usb_devices_index++;
7337
                break;
7338
            case QEMU_OPTION_smp:
7339
                smp_cpus = atoi(optarg);
7340
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7341
                    fprintf(stderr, "Invalid number of CPUs\n");
7342
                    exit(1);
7343
                }
7344
                break;
7345
            case QEMU_OPTION_vnc:
7346
                vnc_display = optarg;
7347
                break;
7348
            case QEMU_OPTION_no_acpi:
7349
                acpi_enabled = 0;
7350
                break;
7351
            case QEMU_OPTION_no_reboot:
7352
                no_reboot = 1;
7353
                break;
7354
            case QEMU_OPTION_daemonize:
7355
                daemonize = 1;
7356
                break;
7357
            case QEMU_OPTION_option_rom:
7358
                if (nb_option_roms >= MAX_OPTION_ROMS) {
7359
                    fprintf(stderr, "Too many option ROMs\n");
7360
                    exit(1);
7361
                }
7362
                option_rom[nb_option_roms] = optarg;
7363
                nb_option_roms++;
7364
                break;
7365
            case QEMU_OPTION_semihosting:
7366
                semihosting_enabled = 1;
7367
                break;
7368
            case QEMU_OPTION_name:
7369
                qemu_name = optarg;
7370
                break;
7371
            }
7372
        }
7373
    }
7374

    
7375
#ifndef _WIN32
7376
    if (daemonize && !nographic && vnc_display == NULL) {
7377
        fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7378
        daemonize = 0;
7379
    }
7380

    
7381
    if (daemonize) {
7382
        pid_t pid;
7383

    
7384
        if (pipe(fds) == -1)
7385
            exit(1);
7386

    
7387
        pid = fork();
7388
        if (pid > 0) {
7389
            uint8_t status;
7390
            ssize_t len;
7391

    
7392
            close(fds[1]);
7393

    
7394
        again:
7395
            len = read(fds[0], &status, 1);
7396
            if (len == -1 && (errno == EINTR))
7397
                goto again;
7398

    
7399
            if (len != 1)
7400
                exit(1);
7401
            else if (status == 1) {
7402
                fprintf(stderr, "Could not acquire pidfile\n");
7403
                exit(1);
7404
            } else
7405
                exit(0);
7406
        } else if (pid < 0)
7407
            exit(1);
7408

    
7409
        setsid();
7410

    
7411
        pid = fork();
7412
        if (pid > 0)
7413
            exit(0);
7414
        else if (pid < 0)
7415
            exit(1);
7416

    
7417
        umask(027);
7418
        chdir("/");
7419

    
7420
        signal(SIGTSTP, SIG_IGN);
7421
        signal(SIGTTOU, SIG_IGN);
7422
        signal(SIGTTIN, SIG_IGN);
7423
    }
7424
#endif
7425

    
7426
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
7427
        if (daemonize) {
7428
            uint8_t status = 1;
7429
            write(fds[1], &status, 1);
7430
        } else
7431
            fprintf(stderr, "Could not acquire pid file\n");
7432
        exit(1);
7433
    }
7434

    
7435
#ifdef USE_KQEMU
7436
    if (smp_cpus > 1)
7437
        kqemu_allowed = 0;
7438
#endif
7439
    linux_boot = (kernel_filename != NULL);
7440

    
7441
    if (!linux_boot &&
7442
        boot_device != 'n' &&
7443
        hd_filename[0] == '\0' && 
7444
        (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7445
        fd_filename[0] == '\0')
7446
        help();
7447

    
7448
    /* boot to floppy or the default cd if no hard disk defined yet */
7449
    if (hd_filename[0] == '\0' && boot_device == 'c') {
7450
        if (fd_filename[0] != '\0')
7451
            boot_device = 'a';
7452
        else
7453
            boot_device = 'd';
7454
    }
7455

    
7456
    setvbuf(stdout, NULL, _IOLBF, 0);
7457
    
7458
    init_timers();
7459
    init_timer_alarm();
7460
    qemu_aio_init();
7461

    
7462
#ifdef _WIN32
7463
    socket_init();
7464
#endif
7465

    
7466
    /* init network clients */
7467
    if (nb_net_clients == 0) {
7468
        /* if no clients, we use a default config */
7469
        pstrcpy(net_clients[0], sizeof(net_clients[0]),
7470
                "nic");
7471
        pstrcpy(net_clients[1], sizeof(net_clients[0]),
7472
                "user");
7473
        nb_net_clients = 2;
7474
    }
7475

    
7476
    for(i = 0;i < nb_net_clients; i++) {
7477
        if (net_client_init(net_clients[i]) < 0)
7478
            exit(1);
7479
    }
7480

    
7481
#ifdef TARGET_I386
7482
    if (boot_device == 'n') {
7483
        for (i = 0; i < nb_nics; i++) {
7484
            const char *model = nd_table[i].model;
7485
            char buf[1024];
7486
            if (model == NULL)
7487
                model = "ne2k_pci";
7488
            snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7489
            if (get_image_size(buf) > 0) {
7490
                option_rom[nb_option_roms] = strdup(buf);
7491
                nb_option_roms++;
7492
                break;
7493
            }
7494
        }
7495
        if (i == nb_nics) {
7496
            fprintf(stderr, "No valid PXE rom found for network device\n");
7497
            exit(1);
7498
        }
7499
        boot_device = 'c'; /* to prevent confusion by the BIOS */
7500
    }
7501
#endif
7502

    
7503
    /* init the memory */
7504
    phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
7505

    
7506
    phys_ram_base = qemu_vmalloc(phys_ram_size);
7507
    if (!phys_ram_base) {
7508
        fprintf(stderr, "Could not allocate physical memory\n");
7509
        exit(1);
7510
    }
7511

    
7512
    /* we always create the cdrom drive, even if no disk is there */
7513
    bdrv_init();
7514
    if (cdrom_index >= 0) {
7515
        bs_table[cdrom_index] = bdrv_new("cdrom");
7516
        bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7517
    }
7518

    
7519
    /* open the virtual block devices */
7520
    for(i = 0; i < MAX_DISKS; i++) {
7521
        if (hd_filename[i]) {
7522
            if (!bs_table[i]) {
7523
                char buf[64];
7524
                snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7525
                bs_table[i] = bdrv_new(buf);
7526
            }
7527
            if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7528
                fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7529
                        hd_filename[i]);
7530
                exit(1);
7531
            }
7532
            if (i == 0 && cyls != 0) {
7533
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7534
                bdrv_set_translation_hint(bs_table[i], translation);
7535
            }
7536
        }
7537
    }
7538

    
7539
    /* we always create at least one floppy disk */
7540
    fd_table[0] = bdrv_new("fda");
7541
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7542

    
7543
    for(i = 0; i < MAX_FD; i++) {
7544
        if (fd_filename[i]) {
7545
            if (!fd_table[i]) {
7546
                char buf[64];
7547
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7548
                fd_table[i] = bdrv_new(buf);
7549
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7550
            }
7551
            if (fd_filename[i][0] != '\0') {
7552
                if (bdrv_open(fd_table[i], fd_filename[i],
7553
                              snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7554
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7555
                            fd_filename[i]);
7556
                    exit(1);
7557
                }
7558
            }
7559
        }
7560
    }
7561

    
7562
    sd_bdrv = bdrv_new ("sd");
7563
    /* FIXME: This isn't really a floppy, but it's a reasonable
7564
       approximation.  */
7565
    bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
7566
    if (sd_filename) {
7567
        if (bdrv_open(sd_bdrv, sd_filename,
7568
                      snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7569
            fprintf(stderr, "qemu: could not open SD card image %s\n",
7570
                    sd_filename);
7571
        }
7572
    }
7573

    
7574
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7575
    register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7576

    
7577
    init_ioports();
7578

    
7579
    /* terminal init */
7580
    if (nographic) {
7581
        dumb_display_init(ds);
7582
    } else if (vnc_display != NULL) {
7583
        vnc_display_init(ds, vnc_display);
7584
    } else {
7585
#if defined(CONFIG_SDL)
7586
        sdl_display_init(ds, full_screen, no_frame);
7587
#elif defined(CONFIG_COCOA)
7588
        cocoa_display_init(ds, full_screen);
7589
#else
7590
        dumb_display_init(ds);
7591
#endif
7592
    }
7593

    
7594
    /* Maintain compatibility with multiple stdio monitors */
7595
    if (!strcmp(monitor_device,"stdio")) {
7596
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
7597
            if (!strcmp(serial_devices[i],"mon:stdio")) {
7598
                monitor_device[0] = '\0';
7599
                break;
7600
            } else if (!strcmp(serial_devices[i],"stdio")) {
7601
                monitor_device[0] = '\0';
7602
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
7603
                break;
7604
            }
7605
        }
7606
    }
7607
    if (monitor_device[0] != '\0') {
7608
        monitor_hd = qemu_chr_open(monitor_device);
7609
        if (!monitor_hd) {
7610
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7611
            exit(1);
7612
        }
7613
        monitor_init(monitor_hd, !nographic);
7614
    }
7615

    
7616
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7617
        const char *devname = serial_devices[i];
7618
        if (devname[0] != '\0' && strcmp(devname, "none")) {
7619
            serial_hds[i] = qemu_chr_open(devname);
7620
            if (!serial_hds[i]) {
7621
                fprintf(stderr, "qemu: could not open serial device '%s'\n", 
7622
                        devname);
7623
                exit(1);
7624
            }
7625
            if (!strcmp(devname, "vc"))
7626
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7627
        }
7628
    }
7629

    
7630
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7631
        const char *devname = parallel_devices[i];
7632
        if (devname[0] != '\0' && strcmp(devname, "none")) {
7633
            parallel_hds[i] = qemu_chr_open(devname);
7634
            if (!parallel_hds[i]) {
7635
                fprintf(stderr, "qemu: could not open parallel device '%s'\n", 
7636
                        devname);
7637
                exit(1);
7638
            }
7639
            if (!strcmp(devname, "vc"))
7640
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7641
        }
7642
    }
7643

    
7644
    machine->init(ram_size, vga_ram_size, boot_device,
7645
                  ds, fd_filename, snapshot,
7646
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
7647

    
7648
    /* init USB devices */
7649
    if (usb_enabled) {
7650
        for(i = 0; i < usb_devices_index; i++) {
7651
            if (usb_device_add(usb_devices[i]) < 0) {
7652
                fprintf(stderr, "Warning: could not add USB device %s\n",
7653
                        usb_devices[i]);
7654
            }
7655
        }
7656
    }
7657

    
7658
    gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7659
    qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7660

    
7661
#ifdef CONFIG_GDBSTUB
7662
    if (use_gdbstub) {
7663
        /* XXX: use standard host:port notation and modify options
7664
           accordingly. */
7665
        if (gdbserver_start(gdbstub_port) < 0) {
7666
            fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
7667
                    gdbstub_port);
7668
            exit(1);
7669
        }
7670
    } else 
7671
#endif
7672
    if (loadvm)
7673
        do_loadvm(loadvm);
7674

    
7675
    {
7676
        /* XXX: simplify init */
7677
        read_passwords();
7678
        if (autostart) {
7679
            vm_start();
7680
        }
7681
    }
7682

    
7683
    if (daemonize) {
7684
        uint8_t status = 0;
7685
        ssize_t len;
7686
        int fd;
7687

    
7688
    again1:
7689
        len = write(fds[1], &status, 1);
7690
        if (len == -1 && (errno == EINTR))
7691
            goto again1;
7692

    
7693
        if (len != 1)
7694
            exit(1);
7695

    
7696
        fd = open("/dev/null", O_RDWR);
7697
        if (fd == -1)
7698
            exit(1);
7699

    
7700
        dup2(fd, 0);
7701
        dup2(fd, 1);
7702
        dup2(fd, 2);
7703

    
7704
        close(fd);
7705
    }
7706

    
7707
    main_loop();
7708
    quit_timers();
7709
    return 0;
7710
}