Statistics
| Branch: | Revision:

root / vl.c @ a171fe39

History | View | Annotate | Download (199.9 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 *pflash_table[MAX_PFLASH];
142
BlockDriverState *sd_bdrv;
143
/* point to the block driver where the snapshots are managed */
144
BlockDriverState *bs_snapshots;
145
int vga_ram_size;
146
static DisplayState display_state;
147
int nographic;
148
const char* keyboard_layout = NULL;
149
int64_t ticks_per_sec;
150
int boot_device = 'c';
151
int ram_size;
152
int pit_min_timer_count = 0;
153
int nb_nics;
154
NICInfo nd_table[MAX_NICS];
155
QEMUTimer *gui_timer;
156
int vm_running;
157
int rtc_utc = 1;
158
int cirrus_vga_enabled = 1;
159
int vmsvga_enabled = 0;
160
#ifdef TARGET_SPARC
161
int graphic_width = 1024;
162
int graphic_height = 768;
163
int graphic_depth = 8;
164
#else
165
int graphic_width = 800;
166
int graphic_height = 600;
167
int graphic_depth = 15;
168
#endif
169
int full_screen = 0;
170
int no_frame = 0;
171
int no_quit = 0;
172
CharDriverState *serial_hds[MAX_SERIAL_PORTS];
173
CharDriverState *parallel_hds[MAX_PARALLEL_PORTS];
174
#ifdef TARGET_I386
175
int win2k_install_hack = 0;
176
#endif
177
int usb_enabled = 0;
178
static VLANState *first_vlan;
179
int smp_cpus = 1;
180
const char *vnc_display;
181
#if defined(TARGET_SPARC)
182
#define MAX_CPUS 16
183
#elif defined(TARGET_I386)
184
#define MAX_CPUS 255
185
#else
186
#define MAX_CPUS 1
187
#endif
188
int acpi_enabled = 1;
189
int fd_bootchk = 1;
190
int no_reboot = 0;
191
int graphic_rotate = 0;
192
int daemonize = 0;
193
const char *option_rom[MAX_OPTION_ROMS];
194
int nb_option_roms;
195
int semihosting_enabled = 0;
196
int autostart = 1;
197
const char *qemu_name;
198

    
199
/***********************************************************/
200
/* x86 ISA bus support */
201

    
202
target_phys_addr_t isa_mem_base = 0;
203
PicState2 *isa_pic;
204

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

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

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

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

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

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

    
252
void init_ioports(void)
253
{
254
    int i;
255

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

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

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

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

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

    
316
void isa_unassign_ioport(int start, int length)
317
{
318
    int i;
319

    
320
    for(i = start; i < start + length; i++) {
321
        ioport_read_table[0][i] = default_ioport_readb;
322
        ioport_read_table[1][i] = default_ioport_readw;
323
        ioport_read_table[2][i] = default_ioport_readl;
324

    
325
        ioport_write_table[0][i] = default_ioport_writeb;
326
        ioport_write_table[1][i] = default_ioport_writew;
327
        ioport_write_table[2][i] = default_ioport_writel;
328
    }
329
}
330

    
331
/***********************************************************/
332

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

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

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

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

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

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

    
417
/***********************************************************/
418
void hw_error(const char *fmt, ...)
419
{
420
    va_list ap;
421
    CPUState *env;
422

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

    
439
/***********************************************************/
440
/* keyboard/mouse */
441

    
442
static QEMUPutKBDEvent *qemu_put_kbd_event;
443
static void *qemu_put_kbd_event_opaque;
444
static QEMUPutMouseEntry *qemu_put_mouse_event_head;
445
static QEMUPutMouseEntry *qemu_put_mouse_event_current;
446

    
447
void qemu_add_kbd_event_handler(QEMUPutKBDEvent *func, void *opaque)
448
{
449
    qemu_put_kbd_event_opaque = opaque;
450
    qemu_put_kbd_event = func;
451
}
452

    
453
QEMUPutMouseEntry *qemu_add_mouse_event_handler(QEMUPutMouseEvent *func,
454
                                                void *opaque, int absolute,
455
                                                const char *name)
456
{
457
    QEMUPutMouseEntry *s, *cursor;
458

    
459
    s = qemu_mallocz(sizeof(QEMUPutMouseEntry));
460
    if (!s)
461
        return NULL;
462

    
463
    s->qemu_put_mouse_event = func;
464
    s->qemu_put_mouse_event_opaque = opaque;
465
    s->qemu_put_mouse_event_absolute = absolute;
466
    s->qemu_put_mouse_event_name = qemu_strdup(name);
467
    s->next = NULL;
468

    
469
    if (!qemu_put_mouse_event_head) {
470
        qemu_put_mouse_event_head = qemu_put_mouse_event_current = s;
471
        return s;
472
    }
473

    
474
    cursor = qemu_put_mouse_event_head;
475
    while (cursor->next != NULL)
476
        cursor = cursor->next;
477

    
478
    cursor->next = s;
479
    qemu_put_mouse_event_current = s;
480

    
481
    return s;
482
}
483

    
484
void qemu_remove_mouse_event_handler(QEMUPutMouseEntry *entry)
485
{
486
    QEMUPutMouseEntry *prev = NULL, *cursor;
487

    
488
    if (!qemu_put_mouse_event_head || entry == NULL)
489
        return;
490

    
491
    cursor = qemu_put_mouse_event_head;
492
    while (cursor != NULL && cursor != entry) {
493
        prev = cursor;
494
        cursor = cursor->next;
495
    }
496

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

    
508
    prev->next = entry->next;
509

    
510
    if (qemu_put_mouse_event_current == entry)
511
        qemu_put_mouse_event_current = prev;
512

    
513
    qemu_free(entry->qemu_put_mouse_event_name);
514
    qemu_free(entry);
515
}
516

    
517
void kbd_put_keycode(int keycode)
518
{
519
    if (qemu_put_kbd_event) {
520
        qemu_put_kbd_event(qemu_put_kbd_event_opaque, keycode);
521
    }
522
}
523

    
524
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
525
{
526
    QEMUPutMouseEvent *mouse_event;
527
    void *mouse_event_opaque;
528
    int width;
529

    
530
    if (!qemu_put_mouse_event_current) {
531
        return;
532
    }
533

    
534
    mouse_event =
535
        qemu_put_mouse_event_current->qemu_put_mouse_event;
536
    mouse_event_opaque =
537
        qemu_put_mouse_event_current->qemu_put_mouse_event_opaque;
538

    
539
    if (mouse_event) {
540
        if (graphic_rotate) {
541
            if (qemu_put_mouse_event_current->qemu_put_mouse_event_absolute)
542
                width = 0x7fff;
543
            else
544
                width = graphic_width;
545
            mouse_event(mouse_event_opaque,
546
                                 width - dy, dx, dz, buttons_state);
547
        } else
548
            mouse_event(mouse_event_opaque,
549
                                 dx, dy, dz, buttons_state);
550
    }
551
}
552

    
553
int kbd_mouse_is_absolute(void)
554
{
555
    if (!qemu_put_mouse_event_current)
556
        return 0;
557

    
558
    return qemu_put_mouse_event_current->qemu_put_mouse_event_absolute;
559
}
560

    
561
void (*kbd_mouse_set)(int x, int y, int on) = NULL;
562
void (*kbd_cursor_define)(int width, int height, int bpp, int hot_x, int hot_y,
563
                          uint8_t *image, uint8_t *mask) = NULL;
564

    
565
void do_info_mice(void)
566
{
567
    QEMUPutMouseEntry *cursor;
568
    int index = 0;
569

    
570
    if (!qemu_put_mouse_event_head) {
571
        term_printf("No mouse devices connected\n");
572
        return;
573
    }
574

    
575
    term_printf("Mouse devices available:\n");
576
    cursor = qemu_put_mouse_event_head;
577
    while (cursor != NULL) {
578
        term_printf("%c Mouse #%d: %s\n",
579
                    (cursor == qemu_put_mouse_event_current ? '*' : ' '),
580
                    index, cursor->qemu_put_mouse_event_name);
581
        index++;
582
        cursor = cursor->next;
583
    }
584
}
585

    
586
void do_mouse_set(int index)
587
{
588
    QEMUPutMouseEntry *cursor;
589
    int i = 0;
590

    
591
    if (!qemu_put_mouse_event_head) {
592
        term_printf("No mouse devices connected\n");
593
        return;
594
    }
595

    
596
    cursor = qemu_put_mouse_event_head;
597
    while (cursor != NULL && index != i) {
598
        i++;
599
        cursor = cursor->next;
600
    }
601

    
602
    if (cursor != NULL)
603
        qemu_put_mouse_event_current = cursor;
604
    else
605
        term_printf("Mouse at given index not found\n");
606
}
607

    
608
/* compute with 96 bit intermediate result: (a*b)/c */
609
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
610
{
611
    union {
612
        uint64_t ll;
613
        struct {
614
#ifdef WORDS_BIGENDIAN
615
            uint32_t high, low;
616
#else
617
            uint32_t low, high;
618
#endif            
619
        } l;
620
    } u, res;
621
    uint64_t rl, rh;
622

    
623
    u.ll = a;
624
    rl = (uint64_t)u.l.low * (uint64_t)b;
625
    rh = (uint64_t)u.l.high * (uint64_t)b;
626
    rh += (rl >> 32);
627
    res.l.high = rh / c;
628
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
629
    return res.ll;
630
}
631

    
632
/***********************************************************/
633
/* real time host monotonic timer */
634

    
635
#define QEMU_TIMER_BASE 1000000000LL
636

    
637
#ifdef WIN32
638

    
639
static int64_t clock_freq;
640

    
641
static void init_get_clock(void)
642
{
643
    LARGE_INTEGER freq;
644
    int ret;
645
    ret = QueryPerformanceFrequency(&freq);
646
    if (ret == 0) {
647
        fprintf(stderr, "Could not calibrate ticks\n");
648
        exit(1);
649
    }
650
    clock_freq = freq.QuadPart;
651
}
652

    
653
static int64_t get_clock(void)
654
{
655
    LARGE_INTEGER ti;
656
    QueryPerformanceCounter(&ti);
657
    return muldiv64(ti.QuadPart, QEMU_TIMER_BASE, clock_freq);
658
}
659

    
660
#else
661

    
662
static int use_rt_clock;
663

    
664
static void init_get_clock(void)
665
{
666
    use_rt_clock = 0;
667
#if defined(__linux__)
668
    {
669
        struct timespec ts;
670
        if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0) {
671
            use_rt_clock = 1;
672
        }
673
    }
674
#endif
675
}
676

    
677
static int64_t get_clock(void)
678
{
679
#if defined(__linux__)
680
    if (use_rt_clock) {
681
        struct timespec ts;
682
        clock_gettime(CLOCK_MONOTONIC, &ts);
683
        return ts.tv_sec * 1000000000LL + ts.tv_nsec;
684
    } else 
685
#endif
686
    {
687
        /* XXX: using gettimeofday leads to problems if the date
688
           changes, so it should be avoided. */
689
        struct timeval tv;
690
        gettimeofday(&tv, NULL);
691
        return tv.tv_sec * 1000000000LL + (tv.tv_usec * 1000);
692
    }
693
}
694

    
695
#endif
696

    
697
/***********************************************************/
698
/* guest cycle counter */
699

    
700
static int64_t cpu_ticks_prev;
701
static int64_t cpu_ticks_offset;
702
static int64_t cpu_clock_offset;
703
static int cpu_ticks_enabled;
704

    
705
/* return the host CPU cycle counter and handle stop/restart */
706
int64_t cpu_get_ticks(void)
707
{
708
    if (!cpu_ticks_enabled) {
709
        return cpu_ticks_offset;
710
    } else {
711
        int64_t ticks;
712
        ticks = cpu_get_real_ticks();
713
        if (cpu_ticks_prev > ticks) {
714
            /* Note: non increasing ticks may happen if the host uses
715
               software suspend */
716
            cpu_ticks_offset += cpu_ticks_prev - ticks;
717
        }
718
        cpu_ticks_prev = ticks;
719
        return ticks + cpu_ticks_offset;
720
    }
721
}
722

    
723
/* return the host CPU monotonic timer and handle stop/restart */
724
static int64_t cpu_get_clock(void)
725
{
726
    int64_t ti;
727
    if (!cpu_ticks_enabled) {
728
        return cpu_clock_offset;
729
    } else {
730
        ti = get_clock();
731
        return ti + cpu_clock_offset;
732
    }
733
}
734

    
735
/* enable cpu_get_ticks() */
736
void cpu_enable_ticks(void)
737
{
738
    if (!cpu_ticks_enabled) {
739
        cpu_ticks_offset -= cpu_get_real_ticks();
740
        cpu_clock_offset -= get_clock();
741
        cpu_ticks_enabled = 1;
742
    }
743
}
744

    
745
/* disable cpu_get_ticks() : the clock is stopped. You must not call
746
   cpu_get_ticks() after that.  */
747
void cpu_disable_ticks(void)
748
{
749
    if (cpu_ticks_enabled) {
750
        cpu_ticks_offset = cpu_get_ticks();
751
        cpu_clock_offset = cpu_get_clock();
752
        cpu_ticks_enabled = 0;
753
    }
754
}
755

    
756
/***********************************************************/
757
/* timers */
758
 
759
#define QEMU_TIMER_REALTIME 0
760
#define QEMU_TIMER_VIRTUAL  1
761

    
762
struct QEMUClock {
763
    int type;
764
    /* XXX: add frequency */
765
};
766

    
767
struct QEMUTimer {
768
    QEMUClock *clock;
769
    int64_t expire_time;
770
    QEMUTimerCB *cb;
771
    void *opaque;
772
    struct QEMUTimer *next;
773
};
774

    
775
QEMUClock *rt_clock;
776
QEMUClock *vm_clock;
777

    
778
static QEMUTimer *active_timers[2];
779
#ifdef _WIN32
780
static MMRESULT timerID;
781
static HANDLE host_alarm = NULL;
782
static unsigned int period = 1;
783
#else
784
/* frequency of the times() clock tick */
785
static int timer_freq;
786
#endif
787

    
788
QEMUClock *qemu_new_clock(int type)
789
{
790
    QEMUClock *clock;
791
    clock = qemu_mallocz(sizeof(QEMUClock));
792
    if (!clock)
793
        return NULL;
794
    clock->type = type;
795
    return clock;
796
}
797

    
798
QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
799
{
800
    QEMUTimer *ts;
801

    
802
    ts = qemu_mallocz(sizeof(QEMUTimer));
803
    ts->clock = clock;
804
    ts->cb = cb;
805
    ts->opaque = opaque;
806
    return ts;
807
}
808

    
809
void qemu_free_timer(QEMUTimer *ts)
810
{
811
    qemu_free(ts);
812
}
813

    
814
/* stop a timer, but do not dealloc it */
815
void qemu_del_timer(QEMUTimer *ts)
816
{
817
    QEMUTimer **pt, *t;
818

    
819
    /* NOTE: this code must be signal safe because
820
       qemu_timer_expired() can be called from a signal. */
821
    pt = &active_timers[ts->clock->type];
822
    for(;;) {
823
        t = *pt;
824
        if (!t)
825
            break;
826
        if (t == ts) {
827
            *pt = t->next;
828
            break;
829
        }
830
        pt = &t->next;
831
    }
832
}
833

    
834
/* modify the current timer so that it will be fired when current_time
835
   >= expire_time. The corresponding callback will be called. */
836
void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
837
{
838
    QEMUTimer **pt, *t;
839

    
840
    qemu_del_timer(ts);
841

    
842
    /* add the timer in the sorted list */
843
    /* NOTE: this code must be signal safe because
844
       qemu_timer_expired() can be called from a signal. */
845
    pt = &active_timers[ts->clock->type];
846
    for(;;) {
847
        t = *pt;
848
        if (!t)
849
            break;
850
        if (t->expire_time > expire_time) 
851
            break;
852
        pt = &t->next;
853
    }
854
    ts->expire_time = expire_time;
855
    ts->next = *pt;
856
    *pt = ts;
857
}
858

    
859
int qemu_timer_pending(QEMUTimer *ts)
860
{
861
    QEMUTimer *t;
862
    for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
863
        if (t == ts)
864
            return 1;
865
    }
866
    return 0;
867
}
868

    
869
static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
870
{
871
    if (!timer_head)
872
        return 0;
873
    return (timer_head->expire_time <= current_time);
874
}
875

    
876
static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
877
{
878
    QEMUTimer *ts;
879
    
880
    for(;;) {
881
        ts = *ptimer_head;
882
        if (!ts || ts->expire_time > current_time)
883
            break;
884
        /* remove timer from the list before calling the callback */
885
        *ptimer_head = ts->next;
886
        ts->next = NULL;
887
        
888
        /* run the callback (the timer list can be modified) */
889
        ts->cb(ts->opaque);
890
    }
891
}
892

    
893
int64_t qemu_get_clock(QEMUClock *clock)
894
{
895
    switch(clock->type) {
896
    case QEMU_TIMER_REALTIME:
897
        return get_clock() / 1000000;
898
    default:
899
    case QEMU_TIMER_VIRTUAL:
900
        return cpu_get_clock();
901
    }
902
}
903

    
904
static void init_timers(void)
905
{
906
    init_get_clock();
907
    ticks_per_sec = QEMU_TIMER_BASE;
908
    rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
909
    vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
910
}
911

    
912
/* save a timer */
913
void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
914
{
915
    uint64_t expire_time;
916

    
917
    if (qemu_timer_pending(ts)) {
918
        expire_time = ts->expire_time;
919
    } else {
920
        expire_time = -1;
921
    }
922
    qemu_put_be64(f, expire_time);
923
}
924

    
925
void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
926
{
927
    uint64_t expire_time;
928

    
929
    expire_time = qemu_get_be64(f);
930
    if (expire_time != -1) {
931
        qemu_mod_timer(ts, expire_time);
932
    } else {
933
        qemu_del_timer(ts);
934
    }
935
}
936

    
937
static void timer_save(QEMUFile *f, void *opaque)
938
{
939
    if (cpu_ticks_enabled) {
940
        hw_error("cannot save state if virtual timers are running");
941
    }
942
    qemu_put_be64s(f, &cpu_ticks_offset);
943
    qemu_put_be64s(f, &ticks_per_sec);
944
    qemu_put_be64s(f, &cpu_clock_offset);
945
}
946

    
947
static int timer_load(QEMUFile *f, void *opaque, int version_id)
948
{
949
    if (version_id != 1 && version_id != 2)
950
        return -EINVAL;
951
    if (cpu_ticks_enabled) {
952
        return -EINVAL;
953
    }
954
    qemu_get_be64s(f, &cpu_ticks_offset);
955
    qemu_get_be64s(f, &ticks_per_sec);
956
    if (version_id == 2) {
957
        qemu_get_be64s(f, &cpu_clock_offset);
958
    }
959
    return 0;
960
}
961

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

    
1018
#ifndef _WIN32
1019

    
1020
#if defined(__linux__)
1021

    
1022
#define RTC_FREQ 1024
1023

    
1024
static int rtc_fd;
1025

    
1026
static int start_rtc_timer(void)
1027
{
1028
    rtc_fd = open("/dev/rtc", O_RDONLY);
1029
    if (rtc_fd < 0)
1030
        return -1;
1031
    if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
1032
        fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
1033
                "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
1034
                "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
1035
        goto fail;
1036
    }
1037
    if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
1038
    fail:
1039
        close(rtc_fd);
1040
        return -1;
1041
    }
1042
    pit_min_timer_count = PIT_FREQ / RTC_FREQ;
1043
    return 0;
1044
}
1045

    
1046
#else
1047

    
1048
static int start_rtc_timer(void)
1049
{
1050
    return -1;
1051
}
1052

    
1053
#endif /* !defined(__linux__) */
1054

    
1055
#endif /* !defined(_WIN32) */
1056

    
1057
static void init_timer_alarm(void)
1058
{
1059
#ifdef _WIN32
1060
    {
1061
        int count=0;
1062
        TIMECAPS tc;
1063

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

    
1103
        itv.it_interval.tv_sec = 0;
1104
        itv.it_interval.tv_usec = 999; /* for i386 kernel 2.6 to get 1 ms */
1105
        itv.it_value.tv_sec = 0;
1106
        itv.it_value.tv_usec = 10 * 1000;
1107
        setitimer(ITIMER_REAL, &itv, NULL);
1108
        /* we probe the tick duration of the kernel to inform the user if
1109
           the emulated kernel requested a too high timer frequency */
1110
        getitimer(ITIMER_REAL, &itv);
1111

    
1112
#if defined(__linux__)
1113
        /* XXX: force /dev/rtc usage because even 2.6 kernels may not
1114
           have timers with 1 ms resolution. The correct solution will
1115
           be to use the POSIX real time timers available in recent
1116
           2.6 kernels */
1117
        if (itv.it_interval.tv_usec > 1000 || 1) {
1118
            /* try to use /dev/rtc to have a faster timer */
1119
            if (start_rtc_timer() < 0)
1120
                goto use_itimer;
1121
            /* disable itimer */
1122
            itv.it_interval.tv_sec = 0;
1123
            itv.it_interval.tv_usec = 0;
1124
            itv.it_value.tv_sec = 0;
1125
            itv.it_value.tv_usec = 0;
1126
            setitimer(ITIMER_REAL, &itv, NULL);
1127

    
1128
            /* use the RTC */
1129
            sigaction(SIGIO, &act, NULL);
1130
            fcntl(rtc_fd, F_SETFL, O_ASYNC);
1131
            fcntl(rtc_fd, F_SETOWN, getpid());
1132
        } else 
1133
#endif /* defined(__linux__) */
1134
        {
1135
        use_itimer:
1136
            pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
1137
                                   PIT_FREQ) / 1000000;
1138
        }
1139
    }
1140
#endif
1141
}
1142

    
1143
void quit_timers(void)
1144
{
1145
#ifdef _WIN32
1146
    timeKillEvent(timerID);
1147
    timeEndPeriod(period);
1148
    if (host_alarm) {
1149
        CloseHandle(host_alarm);
1150
        host_alarm = NULL;
1151
    }
1152
#endif
1153
}
1154

    
1155
/***********************************************************/
1156
/* character device */
1157

    
1158
static void qemu_chr_event(CharDriverState *s, int event)
1159
{
1160
    if (!s->chr_event)
1161
        return;
1162
    s->chr_event(s->handler_opaque, event);
1163
}
1164

    
1165
static void qemu_chr_reset_bh(void *opaque)
1166
{
1167
    CharDriverState *s = opaque;
1168
    qemu_chr_event(s, CHR_EVENT_RESET);
1169
    qemu_bh_delete(s->bh);
1170
    s->bh = NULL;
1171
}
1172

    
1173
void qemu_chr_reset(CharDriverState *s)
1174
{
1175
    if (s->bh == NULL) {
1176
        s->bh = qemu_bh_new(qemu_chr_reset_bh, s);
1177
        qemu_bh_schedule(s->bh);
1178
    }
1179
}
1180

    
1181
int qemu_chr_write(CharDriverState *s, const uint8_t *buf, int len)
1182
{
1183
    return s->chr_write(s, buf, len);
1184
}
1185

    
1186
int qemu_chr_ioctl(CharDriverState *s, int cmd, void *arg)
1187
{
1188
    if (!s->chr_ioctl)
1189
        return -ENOTSUP;
1190
    return s->chr_ioctl(s, cmd, arg);
1191
}
1192

    
1193
int qemu_chr_can_read(CharDriverState *s)
1194
{
1195
    if (!s->chr_can_read)
1196
        return 0;
1197
    return s->chr_can_read(s->handler_opaque);
1198
}
1199

    
1200
void qemu_chr_read(CharDriverState *s, uint8_t *buf, int len)
1201
{
1202
    s->chr_read(s->handler_opaque, buf, len);
1203
}
1204

    
1205

    
1206
void qemu_chr_printf(CharDriverState *s, const char *fmt, ...)
1207
{
1208
    char buf[4096];
1209
    va_list ap;
1210
    va_start(ap, fmt);
1211
    vsnprintf(buf, sizeof(buf), fmt, ap);
1212
    qemu_chr_write(s, buf, strlen(buf));
1213
    va_end(ap);
1214
}
1215

    
1216
void qemu_chr_send_event(CharDriverState *s, int event)
1217
{
1218
    if (s->chr_send_event)
1219
        s->chr_send_event(s, event);
1220
}
1221

    
1222
void qemu_chr_add_handlers(CharDriverState *s, 
1223
                           IOCanRWHandler *fd_can_read, 
1224
                           IOReadHandler *fd_read,
1225
                           IOEventHandler *fd_event,
1226
                           void *opaque)
1227
{
1228
    s->chr_can_read = fd_can_read;
1229
    s->chr_read = fd_read;
1230
    s->chr_event = fd_event;
1231
    s->handler_opaque = opaque;
1232
    if (s->chr_update_read_handler)
1233
        s->chr_update_read_handler(s);
1234
}
1235
             
1236
static int null_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1237
{
1238
    return len;
1239
}
1240

    
1241
static CharDriverState *qemu_chr_open_null(void)
1242
{
1243
    CharDriverState *chr;
1244

    
1245
    chr = qemu_mallocz(sizeof(CharDriverState));
1246
    if (!chr)
1247
        return NULL;
1248
    chr->chr_write = null_chr_write;
1249
    return chr;
1250
}
1251

    
1252
/* MUX driver for serial I/O splitting */
1253
static int term_timestamps;
1254
static int64_t term_timestamps_start;
1255
#define MAX_MUX 4
1256
typedef struct {
1257
    IOCanRWHandler *chr_can_read[MAX_MUX];
1258
    IOReadHandler *chr_read[MAX_MUX];
1259
    IOEventHandler *chr_event[MAX_MUX];
1260
    void *ext_opaque[MAX_MUX];
1261
    CharDriverState *drv;
1262
    int mux_cnt;
1263
    int term_got_escape;
1264
    int max_size;
1265
} MuxDriver;
1266

    
1267

    
1268
static int mux_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1269
{
1270
    MuxDriver *d = chr->opaque;
1271
    int ret;
1272
    if (!term_timestamps) {
1273
        ret = d->drv->chr_write(d->drv, buf, len);
1274
    } else {
1275
        int i;
1276

    
1277
        ret = 0;
1278
        for(i = 0; i < len; i++) {
1279
            ret += d->drv->chr_write(d->drv, buf+i, 1);
1280
            if (buf[i] == '\n') {
1281
                char buf1[64];
1282
                int64_t ti;
1283
                int secs;
1284

    
1285
                ti = get_clock();
1286
                if (term_timestamps_start == -1)
1287
                    term_timestamps_start = ti;
1288
                ti -= term_timestamps_start;
1289
                secs = ti / 1000000000;
1290
                snprintf(buf1, sizeof(buf1),
1291
                         "[%02d:%02d:%02d.%03d] ",
1292
                         secs / 3600,
1293
                         (secs / 60) % 60,
1294
                         secs % 60,
1295
                         (int)((ti / 1000000) % 1000));
1296
                d->drv->chr_write(d->drv, buf1, strlen(buf1));
1297
            }
1298
        }
1299
    }
1300
    return ret;
1301
}
1302

    
1303
static char *mux_help[] = {
1304
    "% h    print this help\n\r",
1305
    "% x    exit emulator\n\r",
1306
    "% s    save disk data back to file (if -snapshot)\n\r",
1307
    "% t    toggle console timestamps\n\r"
1308
    "% b    send break (magic sysrq)\n\r",
1309
    "% c    switch between console and monitor\n\r",
1310
    "% %  sends %\n\r",
1311
    NULL
1312
};
1313

    
1314
static int term_escape_char = 0x01; /* ctrl-a is used for escape */
1315
static void mux_print_help(CharDriverState *chr)
1316
{
1317
    int i, j;
1318
    char ebuf[15] = "Escape-Char";
1319
    char cbuf[50] = "\n\r";
1320

    
1321
    if (term_escape_char > 0 && term_escape_char < 26) {
1322
        sprintf(cbuf,"\n\r");
1323
        sprintf(ebuf,"C-%c", term_escape_char - 1 + 'a');
1324
    } else {
1325
        sprintf(cbuf,"\n\rEscape-Char set to Ascii: 0x%02x\n\r\n\r", term_escape_char);
1326
    }
1327
    chr->chr_write(chr, cbuf, strlen(cbuf));
1328
    for (i = 0; mux_help[i] != NULL; i++) {
1329
        for (j=0; mux_help[i][j] != '\0'; j++) {
1330
            if (mux_help[i][j] == '%')
1331
                chr->chr_write(chr, ebuf, strlen(ebuf));
1332
            else
1333
                chr->chr_write(chr, &mux_help[i][j], 1);
1334
        }
1335
    }
1336
}
1337

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

    
1389
static int mux_chr_can_read(void *opaque)
1390
{
1391
    CharDriverState *chr = opaque;
1392
    MuxDriver *d = chr->opaque;
1393
    if (d->chr_can_read[chr->focus])
1394
       return d->chr_can_read[chr->focus](d->ext_opaque[chr->focus]);
1395
    return 0;
1396
}
1397

    
1398
static void mux_chr_read(void *opaque, const uint8_t *buf, int size)
1399
{
1400
    CharDriverState *chr = opaque;
1401
    MuxDriver *d = chr->opaque;
1402
    int i;
1403
    for(i = 0; i < size; i++)
1404
        if (mux_proc_byte(chr, d, buf[i]))
1405
            d->chr_read[chr->focus](d->ext_opaque[chr->focus], &buf[i], 1);
1406
}
1407

    
1408
static void mux_chr_event(void *opaque, int event)
1409
{
1410
    CharDriverState *chr = opaque;
1411
    MuxDriver *d = chr->opaque;
1412
    int i;
1413

    
1414
    /* Send the event to all registered listeners */
1415
    for (i = 0; i < d->mux_cnt; i++)
1416
        if (d->chr_event[i])
1417
            d->chr_event[i](d->ext_opaque[i], event);
1418
}
1419

    
1420
static void mux_chr_update_read_handler(CharDriverState *chr)
1421
{
1422
    MuxDriver *d = chr->opaque;
1423

    
1424
    if (d->mux_cnt >= MAX_MUX) {
1425
        fprintf(stderr, "Cannot add I/O handlers, MUX array is full\n");
1426
        return;
1427
    }
1428
    d->ext_opaque[d->mux_cnt] = chr->handler_opaque;
1429
    d->chr_can_read[d->mux_cnt] = chr->chr_can_read;
1430
    d->chr_read[d->mux_cnt] = chr->chr_read;
1431
    d->chr_event[d->mux_cnt] = chr->chr_event;
1432
    /* Fix up the real driver with mux routines */
1433
    if (d->mux_cnt == 0) {
1434
        qemu_chr_add_handlers(d->drv, mux_chr_can_read, mux_chr_read,
1435
                              mux_chr_event, chr);
1436
    }
1437
    chr->focus = d->mux_cnt;
1438
    d->mux_cnt++;
1439
}
1440

    
1441
CharDriverState *qemu_chr_open_mux(CharDriverState *drv)
1442
{
1443
    CharDriverState *chr;
1444
    MuxDriver *d;
1445

    
1446
    chr = qemu_mallocz(sizeof(CharDriverState));
1447
    if (!chr)
1448
        return NULL;
1449
    d = qemu_mallocz(sizeof(MuxDriver));
1450
    if (!d) {
1451
        free(chr);
1452
        return NULL;
1453
    }
1454

    
1455
    chr->opaque = d;
1456
    d->drv = drv;
1457
    chr->focus = -1;
1458
    chr->chr_write = mux_chr_write;
1459
    chr->chr_update_read_handler = mux_chr_update_read_handler;
1460
    return chr;
1461
}
1462

    
1463

    
1464
#ifdef _WIN32
1465

    
1466
static void socket_cleanup(void)
1467
{
1468
    WSACleanup();
1469
}
1470

    
1471
static int socket_init(void)
1472
{
1473
    WSADATA Data;
1474
    int ret, err;
1475

    
1476
    ret = WSAStartup(MAKEWORD(2,2), &Data);
1477
    if (ret != 0) {
1478
        err = WSAGetLastError();
1479
        fprintf(stderr, "WSAStartup: %d\n", err);
1480
        return -1;
1481
    }
1482
    atexit(socket_cleanup);
1483
    return 0;
1484
}
1485

    
1486
static int send_all(int fd, const uint8_t *buf, int len1)
1487
{
1488
    int ret, len;
1489
    
1490
    len = len1;
1491
    while (len > 0) {
1492
        ret = send(fd, buf, len, 0);
1493
        if (ret < 0) {
1494
            int errno;
1495
            errno = WSAGetLastError();
1496
            if (errno != WSAEWOULDBLOCK) {
1497
                return -1;
1498
            }
1499
        } else if (ret == 0) {
1500
            break;
1501
        } else {
1502
            buf += ret;
1503
            len -= ret;
1504
        }
1505
    }
1506
    return len1 - len;
1507
}
1508

    
1509
void socket_set_nonblock(int fd)
1510
{
1511
    unsigned long opt = 1;
1512
    ioctlsocket(fd, FIONBIO, &opt);
1513
}
1514

    
1515
#else
1516

    
1517
static int unix_write(int fd, const uint8_t *buf, int len1)
1518
{
1519
    int ret, len;
1520

    
1521
    len = len1;
1522
    while (len > 0) {
1523
        ret = write(fd, buf, len);
1524
        if (ret < 0) {
1525
            if (errno != EINTR && errno != EAGAIN)
1526
                return -1;
1527
        } else if (ret == 0) {
1528
            break;
1529
        } else {
1530
            buf += ret;
1531
            len -= ret;
1532
        }
1533
    }
1534
    return len1 - len;
1535
}
1536

    
1537
static inline int send_all(int fd, const uint8_t *buf, int len1)
1538
{
1539
    return unix_write(fd, buf, len1);
1540
}
1541

    
1542
void socket_set_nonblock(int fd)
1543
{
1544
    fcntl(fd, F_SETFL, O_NONBLOCK);
1545
}
1546
#endif /* !_WIN32 */
1547

    
1548
#ifndef _WIN32
1549

    
1550
typedef struct {
1551
    int fd_in, fd_out;
1552
    int max_size;
1553
} FDCharDriver;
1554

    
1555
#define STDIO_MAX_CLIENTS 1
1556
static int stdio_nb_clients = 0;
1557

    
1558
static int fd_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
1559
{
1560
    FDCharDriver *s = chr->opaque;
1561
    return unix_write(s->fd_out, buf, len);
1562
}
1563

    
1564
static int fd_chr_read_poll(void *opaque)
1565
{
1566
    CharDriverState *chr = opaque;
1567
    FDCharDriver *s = chr->opaque;
1568

    
1569
    s->max_size = qemu_chr_can_read(chr);
1570
    return s->max_size;
1571
}
1572

    
1573
static void fd_chr_read(void *opaque)
1574
{
1575
    CharDriverState *chr = opaque;
1576
    FDCharDriver *s = chr->opaque;
1577
    int size, len;
1578
    uint8_t buf[1024];
1579
    
1580
    len = sizeof(buf);
1581
    if (len > s->max_size)
1582
        len = s->max_size;
1583
    if (len == 0)
1584
        return;
1585
    size = read(s->fd_in, buf, len);
1586
    if (size == 0) {
1587
        /* FD has been closed. Remove it from the active list.  */
1588
        qemu_set_fd_handler2(s->fd_in, NULL, NULL, NULL, NULL);
1589
        return;
1590
    }
1591
    if (size > 0) {
1592
        qemu_chr_read(chr, buf, size);
1593
    }
1594
}
1595

    
1596
static void fd_chr_update_read_handler(CharDriverState *chr)
1597
{
1598
    FDCharDriver *s = chr->opaque;
1599

    
1600
    if (s->fd_in >= 0) {
1601
        if (nographic && s->fd_in == 0) {
1602
        } else {
1603
            qemu_set_fd_handler2(s->fd_in, fd_chr_read_poll, 
1604
                                 fd_chr_read, NULL, chr);
1605
        }
1606
    }
1607
}
1608

    
1609
/* open a character device to a unix fd */
1610
static CharDriverState *qemu_chr_open_fd(int fd_in, int fd_out)
1611
{
1612
    CharDriverState *chr;
1613
    FDCharDriver *s;
1614

    
1615
    chr = qemu_mallocz(sizeof(CharDriverState));
1616
    if (!chr)
1617
        return NULL;
1618
    s = qemu_mallocz(sizeof(FDCharDriver));
1619
    if (!s) {
1620
        free(chr);
1621
        return NULL;
1622
    }
1623
    s->fd_in = fd_in;
1624
    s->fd_out = fd_out;
1625
    chr->opaque = s;
1626
    chr->chr_write = fd_chr_write;
1627
    chr->chr_update_read_handler = fd_chr_update_read_handler;
1628

    
1629
    qemu_chr_reset(chr);
1630

    
1631
    return chr;
1632
}
1633

    
1634
static CharDriverState *qemu_chr_open_file_out(const char *file_out)
1635
{
1636
    int fd_out;
1637

    
1638
    fd_out = open(file_out, O_WRONLY | O_TRUNC | O_CREAT | O_BINARY, 0666);
1639
    if (fd_out < 0)
1640
        return NULL;
1641
    return qemu_chr_open_fd(-1, fd_out);
1642
}
1643

    
1644
static CharDriverState *qemu_chr_open_pipe(const char *filename)
1645
{
1646
    int fd_in, fd_out;
1647
    char filename_in[256], filename_out[256];
1648

    
1649
    snprintf(filename_in, 256, "%s.in", filename);
1650
    snprintf(filename_out, 256, "%s.out", filename);
1651
    fd_in = open(filename_in, O_RDWR | O_BINARY);
1652
    fd_out = open(filename_out, O_RDWR | O_BINARY);
1653
    if (fd_in < 0 || fd_out < 0) {
1654
        if (fd_in >= 0)
1655
            close(fd_in);
1656
        if (fd_out >= 0)
1657
            close(fd_out);
1658
        fd_in = fd_out = open(filename, O_RDWR | O_BINARY);
1659
        if (fd_in < 0)
1660
            return NULL;
1661
    }
1662
    return qemu_chr_open_fd(fd_in, fd_out);
1663
}
1664

    
1665

    
1666
/* for STDIO, we handle the case where several clients use it
1667
   (nographic mode) */
1668

    
1669
#define TERM_FIFO_MAX_SIZE 1
1670

    
1671
static uint8_t term_fifo[TERM_FIFO_MAX_SIZE];
1672
static int term_fifo_size;
1673

    
1674
static int stdio_read_poll(void *opaque)
1675
{
1676
    CharDriverState *chr = opaque;
1677

    
1678
    /* try to flush the queue if needed */
1679
    if (term_fifo_size != 0 && qemu_chr_can_read(chr) > 0) {
1680
        qemu_chr_read(chr, term_fifo, 1);
1681
        term_fifo_size = 0;
1682
    }
1683
    /* see if we can absorb more chars */
1684
    if (term_fifo_size == 0)
1685
        return 1;
1686
    else
1687
        return 0;
1688
}
1689

    
1690
static void stdio_read(void *opaque)
1691
{
1692
    int size;
1693
    uint8_t buf[1];
1694
    CharDriverState *chr = opaque;
1695

    
1696
    size = read(0, buf, 1);
1697
    if (size == 0) {
1698
        /* stdin has been closed. Remove it from the active list.  */
1699
        qemu_set_fd_handler2(0, NULL, NULL, NULL, NULL);
1700
        return;
1701
    }
1702
    if (size > 0) {
1703
        if (qemu_chr_can_read(chr) > 0) {
1704
            qemu_chr_read(chr, buf, 1);
1705
        } else if (term_fifo_size == 0) {
1706
            term_fifo[term_fifo_size++] = buf[0];
1707
        }
1708
    }
1709
}
1710

    
1711
/* init terminal so that we can grab keys */
1712
static struct termios oldtty;
1713
static int old_fd0_flags;
1714

    
1715
static void term_exit(void)
1716
{
1717
    tcsetattr (0, TCSANOW, &oldtty);
1718
    fcntl(0, F_SETFL, old_fd0_flags);
1719
}
1720

    
1721
static void term_init(void)
1722
{
1723
    struct termios tty;
1724

    
1725
    tcgetattr (0, &tty);
1726
    oldtty = tty;
1727
    old_fd0_flags = fcntl(0, F_GETFL);
1728

    
1729
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1730
                          |INLCR|IGNCR|ICRNL|IXON);
1731
    tty.c_oflag |= OPOST;
1732
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1733
    /* if graphical mode, we allow Ctrl-C handling */
1734
    if (nographic)
1735
        tty.c_lflag &= ~ISIG;
1736
    tty.c_cflag &= ~(CSIZE|PARENB);
1737
    tty.c_cflag |= CS8;
1738
    tty.c_cc[VMIN] = 1;
1739
    tty.c_cc[VTIME] = 0;
1740
    
1741
    tcsetattr (0, TCSANOW, &tty);
1742

    
1743
    atexit(term_exit);
1744

    
1745
    fcntl(0, F_SETFL, O_NONBLOCK);
1746
}
1747

    
1748
static CharDriverState *qemu_chr_open_stdio(void)
1749
{
1750
    CharDriverState *chr;
1751

    
1752
    if (stdio_nb_clients >= STDIO_MAX_CLIENTS)
1753
        return NULL;
1754
    chr = qemu_chr_open_fd(0, 1);
1755
    qemu_set_fd_handler2(0, stdio_read_poll, stdio_read, NULL, chr);
1756
    stdio_nb_clients++;
1757
    term_init();
1758

    
1759
    return chr;
1760
}
1761

    
1762
#if defined(__linux__)
1763
static CharDriverState *qemu_chr_open_pty(void)
1764
{
1765
    struct termios tty;
1766
    char slave_name[1024];
1767
    int master_fd, slave_fd;
1768
    
1769
    /* Not satisfying */
1770
    if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
1771
        return NULL;
1772
    }
1773
    
1774
    /* Disabling local echo and line-buffered output */
1775
    tcgetattr (master_fd, &tty);
1776
    tty.c_lflag &= ~(ECHO|ICANON|ISIG);
1777
    tty.c_cc[VMIN] = 1;
1778
    tty.c_cc[VTIME] = 0;
1779
    tcsetattr (master_fd, TCSAFLUSH, &tty);
1780

    
1781
    fprintf(stderr, "char device redirected to %s\n", slave_name);
1782
    return qemu_chr_open_fd(master_fd, master_fd);
1783
}
1784

    
1785
static void tty_serial_init(int fd, int speed, 
1786
                            int parity, int data_bits, int stop_bits)
1787
{
1788
    struct termios tty;
1789
    speed_t spd;
1790

    
1791
#if 0
1792
    printf("tty_serial_init: speed=%d parity=%c data=%d stop=%d\n", 
1793
           speed, parity, data_bits, stop_bits);
1794
#endif
1795
    tcgetattr (fd, &tty);
1796

    
1797
    switch(speed) {
1798
    case 50:
1799
        spd = B50;
1800
        break;
1801
    case 75:
1802
        spd = B75;
1803
        break;
1804
    case 300:
1805
        spd = B300;
1806
        break;
1807
    case 600:
1808
        spd = B600;
1809
        break;
1810
    case 1200:
1811
        spd = B1200;
1812
        break;
1813
    case 2400:
1814
        spd = B2400;
1815
        break;
1816
    case 4800:
1817
        spd = B4800;
1818
        break;
1819
    case 9600:
1820
        spd = B9600;
1821
        break;
1822
    case 19200:
1823
        spd = B19200;
1824
        break;
1825
    case 38400:
1826
        spd = B38400;
1827
        break;
1828
    case 57600:
1829
        spd = B57600;
1830
        break;
1831
    default:
1832
    case 115200:
1833
        spd = B115200;
1834
        break;
1835
    }
1836

    
1837
    cfsetispeed(&tty, spd);
1838
    cfsetospeed(&tty, spd);
1839

    
1840
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1841
                          |INLCR|IGNCR|ICRNL|IXON);
1842
    tty.c_oflag |= OPOST;
1843
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN|ISIG);
1844
    tty.c_cflag &= ~(CSIZE|PARENB|PARODD|CRTSCTS|CSTOPB);
1845
    switch(data_bits) {
1846
    default:
1847
    case 8:
1848
        tty.c_cflag |= CS8;
1849
        break;
1850
    case 7:
1851
        tty.c_cflag |= CS7;
1852
        break;
1853
    case 6:
1854
        tty.c_cflag |= CS6;
1855
        break;
1856
    case 5:
1857
        tty.c_cflag |= CS5;
1858
        break;
1859
    }
1860
    switch(parity) {
1861
    default:
1862
    case 'N':
1863
        break;
1864
    case 'E':
1865
        tty.c_cflag |= PARENB;
1866
        break;
1867
    case 'O':
1868
        tty.c_cflag |= PARENB | PARODD;
1869
        break;
1870
    }
1871
    if (stop_bits == 2)
1872
        tty.c_cflag |= CSTOPB;
1873
    
1874
    tcsetattr (fd, TCSANOW, &tty);
1875
}
1876

    
1877
static int tty_serial_ioctl(CharDriverState *chr, int cmd, void *arg)
1878
{
1879
    FDCharDriver *s = chr->opaque;
1880
    
1881
    switch(cmd) {
1882
    case CHR_IOCTL_SERIAL_SET_PARAMS:
1883
        {
1884
            QEMUSerialSetParams *ssp = arg;
1885
            tty_serial_init(s->fd_in, ssp->speed, ssp->parity, 
1886
                            ssp->data_bits, ssp->stop_bits);
1887
        }
1888
        break;
1889
    case CHR_IOCTL_SERIAL_SET_BREAK:
1890
        {
1891
            int enable = *(int *)arg;
1892
            if (enable)
1893
                tcsendbreak(s->fd_in, 1);
1894
        }
1895
        break;
1896
    default:
1897
        return -ENOTSUP;
1898
    }
1899
    return 0;
1900
}
1901

    
1902
static CharDriverState *qemu_chr_open_tty(const char *filename)
1903
{
1904
    CharDriverState *chr;
1905
    int fd;
1906

    
1907
    fd = open(filename, O_RDWR | O_NONBLOCK);
1908
    if (fd < 0)
1909
        return NULL;
1910
    fcntl(fd, F_SETFL, O_NONBLOCK);
1911
    tty_serial_init(fd, 115200, 'N', 8, 1);
1912
    chr = qemu_chr_open_fd(fd, fd);
1913
    if (!chr)
1914
        return NULL;
1915
    chr->chr_ioctl = tty_serial_ioctl;
1916
    qemu_chr_reset(chr);
1917
    return chr;
1918
}
1919

    
1920
typedef struct {
1921
    int fd;
1922
    int mode;
1923
} ParallelCharDriver;
1924

    
1925
static int pp_hw_mode(ParallelCharDriver *s, uint16_t mode)
1926
{
1927
    if (s->mode != mode) {
1928
        int m = mode;
1929
        if (ioctl(s->fd, PPSETMODE, &m) < 0)
1930
            return 0;
1931
        s->mode = mode;
1932
    }
1933
    return 1;
1934
}
1935

    
1936
static int pp_ioctl(CharDriverState *chr, int cmd, void *arg)
1937
{
1938
    ParallelCharDriver *drv = chr->opaque;
1939
    int fd = drv->fd;
1940
    uint8_t b;
1941

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

    
2013
static void pp_close(CharDriverState *chr)
2014
{
2015
    ParallelCharDriver *drv = chr->opaque;
2016
    int fd = drv->fd;
2017

    
2018
    pp_hw_mode(drv, IEEE1284_MODE_COMPAT);
2019
    ioctl(fd, PPRELEASE);
2020
    close(fd);
2021
    qemu_free(drv);
2022
}
2023

    
2024
static CharDriverState *qemu_chr_open_pp(const char *filename)
2025
{
2026
    CharDriverState *chr;
2027
    ParallelCharDriver *drv;
2028
    int fd;
2029

    
2030
    fd = open(filename, O_RDWR);
2031
    if (fd < 0)
2032
        return NULL;
2033

    
2034
    if (ioctl(fd, PPCLAIM) < 0) {
2035
        close(fd);
2036
        return NULL;
2037
    }
2038

    
2039
    drv = qemu_mallocz(sizeof(ParallelCharDriver));
2040
    if (!drv) {
2041
        close(fd);
2042
        return NULL;
2043
    }
2044
    drv->fd = fd;
2045
    drv->mode = IEEE1284_MODE_COMPAT;
2046

    
2047
    chr = qemu_mallocz(sizeof(CharDriverState));
2048
    if (!chr) {
2049
        qemu_free(drv);
2050
        close(fd);
2051
        return NULL;
2052
    }
2053
    chr->chr_write = null_chr_write;
2054
    chr->chr_ioctl = pp_ioctl;
2055
    chr->chr_close = pp_close;
2056
    chr->opaque = drv;
2057

    
2058
    qemu_chr_reset(chr);
2059

    
2060
    return chr;
2061
}
2062

    
2063
#else
2064
static CharDriverState *qemu_chr_open_pty(void)
2065
{
2066
    return NULL;
2067
}
2068
#endif
2069

    
2070
#endif /* !defined(_WIN32) */
2071

    
2072
#ifdef _WIN32
2073
typedef struct {
2074
    int max_size;
2075
    HANDLE hcom, hrecv, hsend;
2076
    OVERLAPPED orecv, osend;
2077
    BOOL fpipe;
2078
    DWORD len;
2079
} WinCharState;
2080

    
2081
#define NSENDBUF 2048
2082
#define NRECVBUF 2048
2083
#define MAXCONNECT 1
2084
#define NTIMEOUT 5000
2085

    
2086
static int win_chr_poll(void *opaque);
2087
static int win_chr_pipe_poll(void *opaque);
2088

    
2089
static void win_chr_close(CharDriverState *chr)
2090
{
2091
    WinCharState *s = chr->opaque;
2092

    
2093
    if (s->hsend) {
2094
        CloseHandle(s->hsend);
2095
        s->hsend = NULL;
2096
    }
2097
    if (s->hrecv) {
2098
        CloseHandle(s->hrecv);
2099
        s->hrecv = NULL;
2100
    }
2101
    if (s->hcom) {
2102
        CloseHandle(s->hcom);
2103
        s->hcom = NULL;
2104
    }
2105
    if (s->fpipe)
2106
        qemu_del_polling_cb(win_chr_pipe_poll, chr);
2107
    else
2108
        qemu_del_polling_cb(win_chr_poll, chr);
2109
}
2110

    
2111
static int win_chr_init(CharDriverState *chr, const char *filename)
2112
{
2113
    WinCharState *s = chr->opaque;
2114
    COMMCONFIG comcfg;
2115
    COMMTIMEOUTS cto = { 0, 0, 0, 0, 0};
2116
    COMSTAT comstat;
2117
    DWORD size;
2118
    DWORD err;
2119
    
2120
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2121
    if (!s->hsend) {
2122
        fprintf(stderr, "Failed CreateEvent\n");
2123
        goto fail;
2124
    }
2125
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2126
    if (!s->hrecv) {
2127
        fprintf(stderr, "Failed CreateEvent\n");
2128
        goto fail;
2129
    }
2130

    
2131
    s->hcom = CreateFile(filename, GENERIC_READ|GENERIC_WRITE, 0, NULL,
2132
                      OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
2133
    if (s->hcom == INVALID_HANDLE_VALUE) {
2134
        fprintf(stderr, "Failed CreateFile (%lu)\n", GetLastError());
2135
        s->hcom = NULL;
2136
        goto fail;
2137
    }
2138
    
2139
    if (!SetupComm(s->hcom, NRECVBUF, NSENDBUF)) {
2140
        fprintf(stderr, "Failed SetupComm\n");
2141
        goto fail;
2142
    }
2143
    
2144
    ZeroMemory(&comcfg, sizeof(COMMCONFIG));
2145
    size = sizeof(COMMCONFIG);
2146
    GetDefaultCommConfig(filename, &comcfg, &size);
2147
    comcfg.dcb.DCBlength = sizeof(DCB);
2148
    CommConfigDialog(filename, NULL, &comcfg);
2149

    
2150
    if (!SetCommState(s->hcom, &comcfg.dcb)) {
2151
        fprintf(stderr, "Failed SetCommState\n");
2152
        goto fail;
2153
    }
2154

    
2155
    if (!SetCommMask(s->hcom, EV_ERR)) {
2156
        fprintf(stderr, "Failed SetCommMask\n");
2157
        goto fail;
2158
    }
2159

    
2160
    cto.ReadIntervalTimeout = MAXDWORD;
2161
    if (!SetCommTimeouts(s->hcom, &cto)) {
2162
        fprintf(stderr, "Failed SetCommTimeouts\n");
2163
        goto fail;
2164
    }
2165
    
2166
    if (!ClearCommError(s->hcom, &err, &comstat)) {
2167
        fprintf(stderr, "Failed ClearCommError\n");
2168
        goto fail;
2169
    }
2170
    qemu_add_polling_cb(win_chr_poll, chr);
2171
    return 0;
2172

    
2173
 fail:
2174
    win_chr_close(chr);
2175
    return -1;
2176
}
2177

    
2178
static int win_chr_write(CharDriverState *chr, const uint8_t *buf, int len1)
2179
{
2180
    WinCharState *s = chr->opaque;
2181
    DWORD len, ret, size, err;
2182

    
2183
    len = len1;
2184
    ZeroMemory(&s->osend, sizeof(s->osend));
2185
    s->osend.hEvent = s->hsend;
2186
    while (len > 0) {
2187
        if (s->hsend)
2188
            ret = WriteFile(s->hcom, buf, len, &size, &s->osend);
2189
        else
2190
            ret = WriteFile(s->hcom, buf, len, &size, NULL);
2191
        if (!ret) {
2192
            err = GetLastError();
2193
            if (err == ERROR_IO_PENDING) {
2194
                ret = GetOverlappedResult(s->hcom, &s->osend, &size, TRUE);
2195
                if (ret) {
2196
                    buf += size;
2197
                    len -= size;
2198
                } else {
2199
                    break;
2200
                }
2201
            } else {
2202
                break;
2203
            }
2204
        } else {
2205
            buf += size;
2206
            len -= size;
2207
        }
2208
    }
2209
    return len1 - len;
2210
}
2211

    
2212
static int win_chr_read_poll(CharDriverState *chr)
2213
{
2214
    WinCharState *s = chr->opaque;
2215

    
2216
    s->max_size = qemu_chr_can_read(chr);
2217
    return s->max_size;
2218
}
2219

    
2220
static void win_chr_readfile(CharDriverState *chr)
2221
{
2222
    WinCharState *s = chr->opaque;
2223
    int ret, err;
2224
    uint8_t buf[1024];
2225
    DWORD size;
2226
    
2227
    ZeroMemory(&s->orecv, sizeof(s->orecv));
2228
    s->orecv.hEvent = s->hrecv;
2229
    ret = ReadFile(s->hcom, buf, s->len, &size, &s->orecv);
2230
    if (!ret) {
2231
        err = GetLastError();
2232
        if (err == ERROR_IO_PENDING) {
2233
            ret = GetOverlappedResult(s->hcom, &s->orecv, &size, TRUE);
2234
        }
2235
    }
2236

    
2237
    if (size > 0) {
2238
        qemu_chr_read(chr, buf, size);
2239
    }
2240
}
2241

    
2242
static void win_chr_read(CharDriverState *chr)
2243
{
2244
    WinCharState *s = chr->opaque;
2245

    
2246
    if (s->len > s->max_size)
2247
        s->len = s->max_size;
2248
    if (s->len == 0)
2249
        return;
2250
    
2251
    win_chr_readfile(chr);
2252
}
2253

    
2254
static int win_chr_poll(void *opaque)
2255
{
2256
    CharDriverState *chr = opaque;
2257
    WinCharState *s = chr->opaque;
2258
    COMSTAT status;
2259
    DWORD comerr;
2260
    
2261
    ClearCommError(s->hcom, &comerr, &status);
2262
    if (status.cbInQue > 0) {
2263
        s->len = status.cbInQue;
2264
        win_chr_read_poll(chr);
2265
        win_chr_read(chr);
2266
        return 1;
2267
    }
2268
    return 0;
2269
}
2270

    
2271
static CharDriverState *qemu_chr_open_win(const char *filename)
2272
{
2273
    CharDriverState *chr;
2274
    WinCharState *s;
2275
    
2276
    chr = qemu_mallocz(sizeof(CharDriverState));
2277
    if (!chr)
2278
        return NULL;
2279
    s = qemu_mallocz(sizeof(WinCharState));
2280
    if (!s) {
2281
        free(chr);
2282
        return NULL;
2283
    }
2284
    chr->opaque = s;
2285
    chr->chr_write = win_chr_write;
2286
    chr->chr_close = win_chr_close;
2287

    
2288
    if (win_chr_init(chr, filename) < 0) {
2289
        free(s);
2290
        free(chr);
2291
        return NULL;
2292
    }
2293
    qemu_chr_reset(chr);
2294
    return chr;
2295
}
2296

    
2297
static int win_chr_pipe_poll(void *opaque)
2298
{
2299
    CharDriverState *chr = opaque;
2300
    WinCharState *s = chr->opaque;
2301
    DWORD size;
2302

    
2303
    PeekNamedPipe(s->hcom, NULL, 0, NULL, &size, NULL);
2304
    if (size > 0) {
2305
        s->len = size;
2306
        win_chr_read_poll(chr);
2307
        win_chr_read(chr);
2308
        return 1;
2309
    }
2310
    return 0;
2311
}
2312

    
2313
static int win_chr_pipe_init(CharDriverState *chr, const char *filename)
2314
{
2315
    WinCharState *s = chr->opaque;
2316
    OVERLAPPED ov;
2317
    int ret;
2318
    DWORD size;
2319
    char openname[256];
2320
    
2321
    s->fpipe = TRUE;
2322

    
2323
    s->hsend = CreateEvent(NULL, TRUE, FALSE, NULL);
2324
    if (!s->hsend) {
2325
        fprintf(stderr, "Failed CreateEvent\n");
2326
        goto fail;
2327
    }
2328
    s->hrecv = CreateEvent(NULL, TRUE, FALSE, NULL);
2329
    if (!s->hrecv) {
2330
        fprintf(stderr, "Failed CreateEvent\n");
2331
        goto fail;
2332
    }
2333
    
2334
    snprintf(openname, sizeof(openname), "\\\\.\\pipe\\%s", filename);
2335
    s->hcom = CreateNamedPipe(openname, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED,
2336
                              PIPE_TYPE_BYTE | PIPE_READMODE_BYTE |
2337
                              PIPE_WAIT,
2338
                              MAXCONNECT, NSENDBUF, NRECVBUF, NTIMEOUT, NULL);
2339
    if (s->hcom == INVALID_HANDLE_VALUE) {
2340
        fprintf(stderr, "Failed CreateNamedPipe (%lu)\n", GetLastError());
2341
        s->hcom = NULL;
2342
        goto fail;
2343
    }
2344

    
2345
    ZeroMemory(&ov, sizeof(ov));
2346
    ov.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
2347
    ret = ConnectNamedPipe(s->hcom, &ov);
2348
    if (ret) {
2349
        fprintf(stderr, "Failed ConnectNamedPipe\n");
2350
        goto fail;
2351
    }
2352

    
2353
    ret = GetOverlappedResult(s->hcom, &ov, &size, TRUE);
2354
    if (!ret) {
2355
        fprintf(stderr, "Failed GetOverlappedResult\n");
2356
        if (ov.hEvent) {
2357
            CloseHandle(ov.hEvent);
2358
            ov.hEvent = NULL;
2359
        }
2360
        goto fail;
2361
    }
2362

    
2363
    if (ov.hEvent) {
2364
        CloseHandle(ov.hEvent);
2365
        ov.hEvent = NULL;
2366
    }
2367
    qemu_add_polling_cb(win_chr_pipe_poll, chr);
2368
    return 0;
2369

    
2370
 fail:
2371
    win_chr_close(chr);
2372
    return -1;
2373
}
2374

    
2375

    
2376
static CharDriverState *qemu_chr_open_win_pipe(const char *filename)
2377
{
2378
    CharDriverState *chr;
2379
    WinCharState *s;
2380

    
2381
    chr = qemu_mallocz(sizeof(CharDriverState));
2382
    if (!chr)
2383
        return NULL;
2384
    s = qemu_mallocz(sizeof(WinCharState));
2385
    if (!s) {
2386
        free(chr);
2387
        return NULL;
2388
    }
2389
    chr->opaque = s;
2390
    chr->chr_write = win_chr_write;
2391
    chr->chr_close = win_chr_close;
2392
    
2393
    if (win_chr_pipe_init(chr, filename) < 0) {
2394
        free(s);
2395
        free(chr);
2396
        return NULL;
2397
    }
2398
    qemu_chr_reset(chr);
2399
    return chr;
2400
}
2401

    
2402
static CharDriverState *qemu_chr_open_win_file(HANDLE fd_out)
2403
{
2404
    CharDriverState *chr;
2405
    WinCharState *s;
2406

    
2407
    chr = qemu_mallocz(sizeof(CharDriverState));
2408
    if (!chr)
2409
        return NULL;
2410
    s = qemu_mallocz(sizeof(WinCharState));
2411
    if (!s) {
2412
        free(chr);
2413
        return NULL;
2414
    }
2415
    s->hcom = fd_out;
2416
    chr->opaque = s;
2417
    chr->chr_write = win_chr_write;
2418
    qemu_chr_reset(chr);
2419
    return chr;
2420
}
2421
    
2422
static CharDriverState *qemu_chr_open_win_file_out(const char *file_out)
2423
{
2424
    HANDLE fd_out;
2425
    
2426
    fd_out = CreateFile(file_out, GENERIC_WRITE, FILE_SHARE_READ, NULL,
2427
                        OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
2428
    if (fd_out == INVALID_HANDLE_VALUE)
2429
        return NULL;
2430

    
2431
    return qemu_chr_open_win_file(fd_out);
2432
}
2433
#endif
2434

    
2435
/***********************************************************/
2436
/* UDP Net console */
2437

    
2438
typedef struct {
2439
    int fd;
2440
    struct sockaddr_in daddr;
2441
    char buf[1024];
2442
    int bufcnt;
2443
    int bufptr;
2444
    int max_size;
2445
} NetCharDriver;
2446

    
2447
static int udp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2448
{
2449
    NetCharDriver *s = chr->opaque;
2450

    
2451
    return sendto(s->fd, buf, len, 0,
2452
                  (struct sockaddr *)&s->daddr, sizeof(struct sockaddr_in));
2453
}
2454

    
2455
static int udp_chr_read_poll(void *opaque)
2456
{
2457
    CharDriverState *chr = opaque;
2458
    NetCharDriver *s = chr->opaque;
2459

    
2460
    s->max_size = qemu_chr_can_read(chr);
2461

    
2462
    /* If there were any stray characters in the queue process them
2463
     * first
2464
     */
2465
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2466
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2467
        s->bufptr++;
2468
        s->max_size = qemu_chr_can_read(chr);
2469
    }
2470
    return s->max_size;
2471
}
2472

    
2473
static void udp_chr_read(void *opaque)
2474
{
2475
    CharDriverState *chr = opaque;
2476
    NetCharDriver *s = chr->opaque;
2477

    
2478
    if (s->max_size == 0)
2479
        return;
2480
    s->bufcnt = recv(s->fd, s->buf, sizeof(s->buf), 0);
2481
    s->bufptr = s->bufcnt;
2482
    if (s->bufcnt <= 0)
2483
        return;
2484

    
2485
    s->bufptr = 0;
2486
    while (s->max_size > 0 && s->bufptr < s->bufcnt) {
2487
        qemu_chr_read(chr, &s->buf[s->bufptr], 1);
2488
        s->bufptr++;
2489
        s->max_size = qemu_chr_can_read(chr);
2490
    }
2491
}
2492

    
2493
static void udp_chr_update_read_handler(CharDriverState *chr)
2494
{
2495
    NetCharDriver *s = chr->opaque;
2496

    
2497
    if (s->fd >= 0) {
2498
        qemu_set_fd_handler2(s->fd, udp_chr_read_poll,
2499
                             udp_chr_read, NULL, chr);
2500
    }
2501
}
2502

    
2503
int parse_host_port(struct sockaddr_in *saddr, const char *str);
2504
#ifndef _WIN32
2505
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str);
2506
#endif
2507
int parse_host_src_port(struct sockaddr_in *haddr,
2508
                        struct sockaddr_in *saddr,
2509
                        const char *str);
2510

    
2511
static CharDriverState *qemu_chr_open_udp(const char *def)
2512
{
2513
    CharDriverState *chr = NULL;
2514
    NetCharDriver *s = NULL;
2515
    int fd = -1;
2516
    struct sockaddr_in saddr;
2517

    
2518
    chr = qemu_mallocz(sizeof(CharDriverState));
2519
    if (!chr)
2520
        goto return_err;
2521
    s = qemu_mallocz(sizeof(NetCharDriver));
2522
    if (!s)
2523
        goto return_err;
2524

    
2525
    fd = socket(PF_INET, SOCK_DGRAM, 0);
2526
    if (fd < 0) {
2527
        perror("socket(PF_INET, SOCK_DGRAM)");
2528
        goto return_err;
2529
    }
2530

    
2531
    if (parse_host_src_port(&s->daddr, &saddr, def) < 0) {
2532
        printf("Could not parse: %s\n", def);
2533
        goto return_err;
2534
    }
2535

    
2536
    if (bind(fd, (struct sockaddr *)&saddr, sizeof(saddr)) < 0)
2537
    {
2538
        perror("bind");
2539
        goto return_err;
2540
    }
2541

    
2542
    s->fd = fd;
2543
    s->bufcnt = 0;
2544
    s->bufptr = 0;
2545
    chr->opaque = s;
2546
    chr->chr_write = udp_chr_write;
2547
    chr->chr_update_read_handler = udp_chr_update_read_handler;
2548
    return chr;
2549

    
2550
return_err:
2551
    if (chr)
2552
        free(chr);
2553
    if (s)
2554
        free(s);
2555
    if (fd >= 0)
2556
        closesocket(fd);
2557
    return NULL;
2558
}
2559

    
2560
/***********************************************************/
2561
/* TCP Net console */
2562

    
2563
typedef struct {
2564
    int fd, listen_fd;
2565
    int connected;
2566
    int max_size;
2567
    int do_telnetopt;
2568
    int do_nodelay;
2569
    int is_unix;
2570
} TCPCharDriver;
2571

    
2572
static void tcp_chr_accept(void *opaque);
2573

    
2574
static int tcp_chr_write(CharDriverState *chr, const uint8_t *buf, int len)
2575
{
2576
    TCPCharDriver *s = chr->opaque;
2577
    if (s->connected) {
2578
        return send_all(s->fd, buf, len);
2579
    } else {
2580
        /* XXX: indicate an error ? */
2581
        return len;
2582
    }
2583
}
2584

    
2585
static int tcp_chr_read_poll(void *opaque)
2586
{
2587
    CharDriverState *chr = opaque;
2588
    TCPCharDriver *s = chr->opaque;
2589
    if (!s->connected)
2590
        return 0;
2591
    s->max_size = qemu_chr_can_read(chr);
2592
    return s->max_size;
2593
}
2594

    
2595
#define IAC 255
2596
#define IAC_BREAK 243
2597
static void tcp_chr_process_IAC_bytes(CharDriverState *chr,
2598
                                      TCPCharDriver *s,
2599
                                      char *buf, int *size)
2600
{
2601
    /* Handle any telnet client's basic IAC options to satisfy char by
2602
     * char mode with no echo.  All IAC options will be removed from
2603
     * the buf and the do_telnetopt variable will be used to track the
2604
     * state of the width of the IAC information.
2605
     *
2606
     * IAC commands come in sets of 3 bytes with the exception of the
2607
     * "IAC BREAK" command and the double IAC.
2608
     */
2609

    
2610
    int i;
2611
    int j = 0;
2612

    
2613
    for (i = 0; i < *size; i++) {
2614
        if (s->do_telnetopt > 1) {
2615
            if ((unsigned char)buf[i] == IAC && s->do_telnetopt == 2) {
2616
                /* Double IAC means send an IAC */
2617
                if (j != i)
2618
                    buf[j] = buf[i];
2619
                j++;
2620
                s->do_telnetopt = 1;
2621
            } else {
2622
                if ((unsigned char)buf[i] == IAC_BREAK && s->do_telnetopt == 2) {
2623
                    /* Handle IAC break commands by sending a serial break */
2624
                    qemu_chr_event(chr, CHR_EVENT_BREAK);
2625
                    s->do_telnetopt++;
2626
                }
2627
                s->do_telnetopt++;
2628
            }
2629
            if (s->do_telnetopt >= 4) {
2630
                s->do_telnetopt = 1;
2631
            }
2632
        } else {
2633
            if ((unsigned char)buf[i] == IAC) {
2634
                s->do_telnetopt = 2;
2635
            } else {
2636
                if (j != i)
2637
                    buf[j] = buf[i];
2638
                j++;
2639
            }
2640
        }
2641
    }
2642
    *size = j;
2643
}
2644

    
2645
static void tcp_chr_read(void *opaque)
2646
{
2647
    CharDriverState *chr = opaque;
2648
    TCPCharDriver *s = chr->opaque;
2649
    uint8_t buf[1024];
2650
    int len, size;
2651

    
2652
    if (!s->connected || s->max_size <= 0)
2653
        return;
2654
    len = sizeof(buf);
2655
    if (len > s->max_size)
2656
        len = s->max_size;
2657
    size = recv(s->fd, buf, len, 0);
2658
    if (size == 0) {
2659
        /* connection closed */
2660
        s->connected = 0;
2661
        if (s->listen_fd >= 0) {
2662
            qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2663
        }
2664
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
2665
        closesocket(s->fd);
2666
        s->fd = -1;
2667
    } else if (size > 0) {
2668
        if (s->do_telnetopt)
2669
            tcp_chr_process_IAC_bytes(chr, s, buf, &size);
2670
        if (size > 0)
2671
            qemu_chr_read(chr, buf, size);
2672
    }
2673
}
2674

    
2675
static void tcp_chr_connect(void *opaque)
2676
{
2677
    CharDriverState *chr = opaque;
2678
    TCPCharDriver *s = chr->opaque;
2679

    
2680
    s->connected = 1;
2681
    qemu_set_fd_handler2(s->fd, tcp_chr_read_poll,
2682
                         tcp_chr_read, NULL, chr);
2683
    qemu_chr_reset(chr);
2684
}
2685

    
2686
#define IACSET(x,a,b,c) x[0] = a; x[1] = b; x[2] = c;
2687
static void tcp_chr_telnet_init(int fd)
2688
{
2689
    char buf[3];
2690
    /* Send the telnet negotion to put telnet in binary, no echo, single char mode */
2691
    IACSET(buf, 0xff, 0xfb, 0x01);  /* IAC WILL ECHO */
2692
    send(fd, (char *)buf, 3, 0);
2693
    IACSET(buf, 0xff, 0xfb, 0x03);  /* IAC WILL Suppress go ahead */
2694
    send(fd, (char *)buf, 3, 0);
2695
    IACSET(buf, 0xff, 0xfb, 0x00);  /* IAC WILL Binary */
2696
    send(fd, (char *)buf, 3, 0);
2697
    IACSET(buf, 0xff, 0xfd, 0x00);  /* IAC DO Binary */
2698
    send(fd, (char *)buf, 3, 0);
2699
}
2700

    
2701
static void socket_set_nodelay(int fd)
2702
{
2703
    int val = 1;
2704
    setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, (char *)&val, sizeof(val));
2705
}
2706

    
2707
static void tcp_chr_accept(void *opaque)
2708
{
2709
    CharDriverState *chr = opaque;
2710
    TCPCharDriver *s = chr->opaque;
2711
    struct sockaddr_in saddr;
2712
#ifndef _WIN32
2713
    struct sockaddr_un uaddr;
2714
#endif
2715
    struct sockaddr *addr;
2716
    socklen_t len;
2717
    int fd;
2718

    
2719
    for(;;) {
2720
#ifndef _WIN32
2721
        if (s->is_unix) {
2722
            len = sizeof(uaddr);
2723
            addr = (struct sockaddr *)&uaddr;
2724
        } else
2725
#endif
2726
        {
2727
            len = sizeof(saddr);
2728
            addr = (struct sockaddr *)&saddr;
2729
        }
2730
        fd = accept(s->listen_fd, addr, &len);
2731
        if (fd < 0 && errno != EINTR) {
2732
            return;
2733
        } else if (fd >= 0) {
2734
            if (s->do_telnetopt)
2735
                tcp_chr_telnet_init(fd);
2736
            break;
2737
        }
2738
    }
2739
    socket_set_nonblock(fd);
2740
    if (s->do_nodelay)
2741
        socket_set_nodelay(fd);
2742
    s->fd = fd;
2743
    qemu_set_fd_handler(s->listen_fd, NULL, NULL, NULL);
2744
    tcp_chr_connect(chr);
2745
}
2746

    
2747
static void tcp_chr_close(CharDriverState *chr)
2748
{
2749
    TCPCharDriver *s = chr->opaque;
2750
    if (s->fd >= 0)
2751
        closesocket(s->fd);
2752
    if (s->listen_fd >= 0)
2753
        closesocket(s->listen_fd);
2754
    qemu_free(s);
2755
}
2756

    
2757
static CharDriverState *qemu_chr_open_tcp(const char *host_str, 
2758
                                          int is_telnet,
2759
                                          int is_unix)
2760
{
2761
    CharDriverState *chr = NULL;
2762
    TCPCharDriver *s = NULL;
2763
    int fd = -1, ret, err, val;
2764
    int is_listen = 0;
2765
    int is_waitconnect = 1;
2766
    int do_nodelay = 0;
2767
    const char *ptr;
2768
    struct sockaddr_in saddr;
2769
#ifndef _WIN32
2770
    struct sockaddr_un uaddr;
2771
#endif
2772
    struct sockaddr *addr;
2773
    socklen_t addrlen;
2774

    
2775
#ifndef _WIN32
2776
    if (is_unix) {
2777
        addr = (struct sockaddr *)&uaddr;
2778
        addrlen = sizeof(uaddr);
2779
        if (parse_unix_path(&uaddr, host_str) < 0)
2780
            goto fail;
2781
    } else
2782
#endif
2783
    {
2784
        addr = (struct sockaddr *)&saddr;
2785
        addrlen = sizeof(saddr);
2786
        if (parse_host_port(&saddr, host_str) < 0)
2787
            goto fail;
2788
    }
2789

    
2790
    ptr = host_str;
2791
    while((ptr = strchr(ptr,','))) {
2792
        ptr++;
2793
        if (!strncmp(ptr,"server",6)) {
2794
            is_listen = 1;
2795
        } else if (!strncmp(ptr,"nowait",6)) {
2796
            is_waitconnect = 0;
2797
        } else if (!strncmp(ptr,"nodelay",6)) {
2798
            do_nodelay = 1;
2799
        } else {
2800
            printf("Unknown option: %s\n", ptr);
2801
            goto fail;
2802
        }
2803
    }
2804
    if (!is_listen)
2805
        is_waitconnect = 0;
2806

    
2807
    chr = qemu_mallocz(sizeof(CharDriverState));
2808
    if (!chr)
2809
        goto fail;
2810
    s = qemu_mallocz(sizeof(TCPCharDriver));
2811
    if (!s)
2812
        goto fail;
2813

    
2814
#ifndef _WIN32
2815
    if (is_unix)
2816
        fd = socket(PF_UNIX, SOCK_STREAM, 0);
2817
    else
2818
#endif
2819
        fd = socket(PF_INET, SOCK_STREAM, 0);
2820
        
2821
    if (fd < 0) 
2822
        goto fail;
2823

    
2824
    if (!is_waitconnect)
2825
        socket_set_nonblock(fd);
2826

    
2827
    s->connected = 0;
2828
    s->fd = -1;
2829
    s->listen_fd = -1;
2830
    s->is_unix = is_unix;
2831
    s->do_nodelay = do_nodelay && !is_unix;
2832

    
2833
    chr->opaque = s;
2834
    chr->chr_write = tcp_chr_write;
2835
    chr->chr_close = tcp_chr_close;
2836

    
2837
    if (is_listen) {
2838
        /* allow fast reuse */
2839
#ifndef _WIN32
2840
        if (is_unix) {
2841
            char path[109];
2842
            strncpy(path, uaddr.sun_path, 108);
2843
            path[108] = 0;
2844
            unlink(path);
2845
        } else
2846
#endif
2847
        {
2848
            val = 1;
2849
            setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
2850
        }
2851
        
2852
        ret = bind(fd, addr, addrlen);
2853
        if (ret < 0)
2854
            goto fail;
2855

    
2856
        ret = listen(fd, 0);
2857
        if (ret < 0)
2858
            goto fail;
2859

    
2860
        s->listen_fd = fd;
2861
        qemu_set_fd_handler(s->listen_fd, tcp_chr_accept, NULL, chr);
2862
        if (is_telnet)
2863
            s->do_telnetopt = 1;
2864
    } else {
2865
        for(;;) {
2866
            ret = connect(fd, addr, addrlen);
2867
            if (ret < 0) {
2868
                err = socket_error();
2869
                if (err == EINTR || err == EWOULDBLOCK) {
2870
                } else if (err == EINPROGRESS) {
2871
                    break;
2872
#ifdef _WIN32
2873
                } else if (err == WSAEALREADY) {
2874
                    break;
2875
#endif
2876
                } else {
2877
                    goto fail;
2878
                }
2879
            } else {
2880
                s->connected = 1;
2881
                break;
2882
            }
2883
        }
2884
        s->fd = fd;
2885
        socket_set_nodelay(fd);
2886
        if (s->connected)
2887
            tcp_chr_connect(chr);
2888
        else
2889
            qemu_set_fd_handler(s->fd, NULL, tcp_chr_connect, chr);
2890
    }
2891
    
2892
    if (is_listen && is_waitconnect) {
2893
        printf("QEMU waiting for connection on: %s\n", host_str);
2894
        tcp_chr_accept(chr);
2895
        socket_set_nonblock(s->listen_fd);
2896
    }
2897

    
2898
    return chr;
2899
 fail:
2900
    if (fd >= 0)
2901
        closesocket(fd);
2902
    qemu_free(s);
2903
    qemu_free(chr);
2904
    return NULL;
2905
}
2906

    
2907
CharDriverState *qemu_chr_open(const char *filename)
2908
{
2909
    const char *p;
2910

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

    
2972
void qemu_chr_close(CharDriverState *chr)
2973
{
2974
    if (chr->chr_close)
2975
        chr->chr_close(chr);
2976
}
2977

    
2978
/***********************************************************/
2979
/* network device redirectors */
2980

    
2981
void hex_dump(FILE *f, const uint8_t *buf, int size)
2982
{
2983
    int len, i, j, c;
2984

    
2985
    for(i=0;i<size;i+=16) {
2986
        len = size - i;
2987
        if (len > 16)
2988
            len = 16;
2989
        fprintf(f, "%08x ", i);
2990
        for(j=0;j<16;j++) {
2991
            if (j < len)
2992
                fprintf(f, " %02x", buf[i+j]);
2993
            else
2994
                fprintf(f, "   ");
2995
        }
2996
        fprintf(f, " ");
2997
        for(j=0;j<len;j++) {
2998
            c = buf[i+j];
2999
            if (c < ' ' || c > '~')
3000
                c = '.';
3001
            fprintf(f, "%c", c);
3002
        }
3003
        fprintf(f, "\n");
3004
    }
3005
}
3006

    
3007
static int parse_macaddr(uint8_t *macaddr, const char *p)
3008
{
3009
    int i;
3010
    for(i = 0; i < 6; i++) {
3011
        macaddr[i] = strtol(p, (char **)&p, 16);
3012
        if (i == 5) {
3013
            if (*p != '\0') 
3014
                return -1;
3015
        } else {
3016
            if (*p != ':') 
3017
                return -1;
3018
            p++;
3019
        }
3020
    }
3021
    return 0;
3022
}
3023

    
3024
static int get_str_sep(char *buf, int buf_size, const char **pp, int sep)
3025
{
3026
    const char *p, *p1;
3027
    int len;
3028
    p = *pp;
3029
    p1 = strchr(p, sep);
3030
    if (!p1)
3031
        return -1;
3032
    len = p1 - p;
3033
    p1++;
3034
    if (buf_size > 0) {
3035
        if (len > buf_size - 1)
3036
            len = buf_size - 1;
3037
        memcpy(buf, p, len);
3038
        buf[len] = '\0';
3039
    }
3040
    *pp = p1;
3041
    return 0;
3042
}
3043

    
3044
int parse_host_src_port(struct sockaddr_in *haddr,
3045
                        struct sockaddr_in *saddr,
3046
                        const char *input_str)
3047
{
3048
    char *str = strdup(input_str);
3049
    char *host_str = str;
3050
    char *src_str;
3051
    char *ptr;
3052

    
3053
    /*
3054
     * Chop off any extra arguments at the end of the string which
3055
     * would start with a comma, then fill in the src port information
3056
     * if it was provided else use the "any address" and "any port".
3057
     */
3058
    if ((ptr = strchr(str,',')))
3059
        *ptr = '\0';
3060

    
3061
    if ((src_str = strchr(input_str,'@'))) {
3062
        *src_str = '\0';
3063
        src_str++;
3064
    }
3065

    
3066
    if (parse_host_port(haddr, host_str) < 0)
3067
        goto fail;
3068

    
3069
    if (!src_str || *src_str == '\0')
3070
        src_str = ":0";
3071

    
3072
    if (parse_host_port(saddr, src_str) < 0)
3073
        goto fail;
3074

    
3075
    free(str);
3076
    return(0);
3077

    
3078
fail:
3079
    free(str);
3080
    return -1;
3081
}
3082

    
3083
int parse_host_port(struct sockaddr_in *saddr, const char *str)
3084
{
3085
    char buf[512];
3086
    struct hostent *he;
3087
    const char *p, *r;
3088
    int port;
3089

    
3090
    p = str;
3091
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3092
        return -1;
3093
    saddr->sin_family = AF_INET;
3094
    if (buf[0] == '\0') {
3095
        saddr->sin_addr.s_addr = 0;
3096
    } else {
3097
        if (isdigit(buf[0])) {
3098
            if (!inet_aton(buf, &saddr->sin_addr))
3099
                return -1;
3100
        } else {
3101
            if ((he = gethostbyname(buf)) == NULL)
3102
                return - 1;
3103
            saddr->sin_addr = *(struct in_addr *)he->h_addr;
3104
        }
3105
    }
3106
    port = strtol(p, (char **)&r, 0);
3107
    if (r == p)
3108
        return -1;
3109
    saddr->sin_port = htons(port);
3110
    return 0;
3111
}
3112

    
3113
#ifndef _WIN32
3114
static int parse_unix_path(struct sockaddr_un *uaddr, const char *str)
3115
{
3116
    const char *p;
3117
    int len;
3118

    
3119
    len = MIN(108, strlen(str));
3120
    p = strchr(str, ',');
3121
    if (p)
3122
        len = MIN(len, p - str);
3123

    
3124
    memset(uaddr, 0, sizeof(*uaddr));
3125

    
3126
    uaddr->sun_family = AF_UNIX;
3127
    memcpy(uaddr->sun_path, str, len);
3128

    
3129
    return 0;
3130
}
3131
#endif
3132

    
3133
/* find or alloc a new VLAN */
3134
VLANState *qemu_find_vlan(int id)
3135
{
3136
    VLANState **pvlan, *vlan;
3137
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
3138
        if (vlan->id == id)
3139
            return vlan;
3140
    }
3141
    vlan = qemu_mallocz(sizeof(VLANState));
3142
    if (!vlan)
3143
        return NULL;
3144
    vlan->id = id;
3145
    vlan->next = NULL;
3146
    pvlan = &first_vlan;
3147
    while (*pvlan != NULL)
3148
        pvlan = &(*pvlan)->next;
3149
    *pvlan = vlan;
3150
    return vlan;
3151
}
3152

    
3153
VLANClientState *qemu_new_vlan_client(VLANState *vlan,
3154
                                      IOReadHandler *fd_read,
3155
                                      IOCanRWHandler *fd_can_read,
3156
                                      void *opaque)
3157
{
3158
    VLANClientState *vc, **pvc;
3159
    vc = qemu_mallocz(sizeof(VLANClientState));
3160
    if (!vc)
3161
        return NULL;
3162
    vc->fd_read = fd_read;
3163
    vc->fd_can_read = fd_can_read;
3164
    vc->opaque = opaque;
3165
    vc->vlan = vlan;
3166

    
3167
    vc->next = NULL;
3168
    pvc = &vlan->first_client;
3169
    while (*pvc != NULL)
3170
        pvc = &(*pvc)->next;
3171
    *pvc = vc;
3172
    return vc;
3173
}
3174

    
3175
int qemu_can_send_packet(VLANClientState *vc1)
3176
{
3177
    VLANState *vlan = vc1->vlan;
3178
    VLANClientState *vc;
3179

    
3180
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3181
        if (vc != vc1) {
3182
            if (vc->fd_can_read && !vc->fd_can_read(vc->opaque))
3183
                return 0;
3184
        }
3185
    }
3186
    return 1;
3187
}
3188

    
3189
void qemu_send_packet(VLANClientState *vc1, const uint8_t *buf, int size)
3190
{
3191
    VLANState *vlan = vc1->vlan;
3192
    VLANClientState *vc;
3193

    
3194
#if 0
3195
    printf("vlan %d send:\n", vlan->id);
3196
    hex_dump(stdout, buf, size);
3197
#endif
3198
    for(vc = vlan->first_client; vc != NULL; vc = vc->next) {
3199
        if (vc != vc1) {
3200
            vc->fd_read(vc->opaque, buf, size);
3201
        }
3202
    }
3203
}
3204

    
3205
#if defined(CONFIG_SLIRP)
3206

    
3207
/* slirp network adapter */
3208

    
3209
static int slirp_inited;
3210
static VLANClientState *slirp_vc;
3211

    
3212
int slirp_can_output(void)
3213
{
3214
    return !slirp_vc || qemu_can_send_packet(slirp_vc);
3215
}
3216

    
3217
void slirp_output(const uint8_t *pkt, int pkt_len)
3218
{
3219
#if 0
3220
    printf("slirp output:\n");
3221
    hex_dump(stdout, pkt, pkt_len);
3222
#endif
3223
    if (!slirp_vc)
3224
        return;
3225
    qemu_send_packet(slirp_vc, pkt, pkt_len);
3226
}
3227

    
3228
static void slirp_receive(void *opaque, const uint8_t *buf, int size)
3229
{
3230
#if 0
3231
    printf("slirp input:\n");
3232
    hex_dump(stdout, buf, size);
3233
#endif
3234
    slirp_input(buf, size);
3235
}
3236

    
3237
static int net_slirp_init(VLANState *vlan)
3238
{
3239
    if (!slirp_inited) {
3240
        slirp_inited = 1;
3241
        slirp_init();
3242
    }
3243
    slirp_vc = qemu_new_vlan_client(vlan, 
3244
                                    slirp_receive, NULL, NULL);
3245
    snprintf(slirp_vc->info_str, sizeof(slirp_vc->info_str), "user redirector");
3246
    return 0;
3247
}
3248

    
3249
static void net_slirp_redir(const char *redir_str)
3250
{
3251
    int is_udp;
3252
    char buf[256], *r;
3253
    const char *p;
3254
    struct in_addr guest_addr;
3255
    int host_port, guest_port;
3256
    
3257
    if (!slirp_inited) {
3258
        slirp_inited = 1;
3259
        slirp_init();
3260
    }
3261

    
3262
    p = redir_str;
3263
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3264
        goto fail;
3265
    if (!strcmp(buf, "tcp")) {
3266
        is_udp = 0;
3267
    } else if (!strcmp(buf, "udp")) {
3268
        is_udp = 1;
3269
    } else {
3270
        goto fail;
3271
    }
3272

    
3273
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3274
        goto fail;
3275
    host_port = strtol(buf, &r, 0);
3276
    if (r == buf)
3277
        goto fail;
3278

    
3279
    if (get_str_sep(buf, sizeof(buf), &p, ':') < 0)
3280
        goto fail;
3281
    if (buf[0] == '\0') {
3282
        pstrcpy(buf, sizeof(buf), "10.0.2.15");
3283
    }
3284
    if (!inet_aton(buf, &guest_addr))
3285
        goto fail;
3286
    
3287
    guest_port = strtol(p, &r, 0);
3288
    if (r == p)
3289
        goto fail;
3290
    
3291
    if (slirp_redir(is_udp, host_port, guest_addr, guest_port) < 0) {
3292
        fprintf(stderr, "qemu: could not set up redirection\n");
3293
        exit(1);
3294
    }
3295
    return;
3296
 fail:
3297
    fprintf(stderr, "qemu: syntax: -redir [tcp|udp]:host-port:[guest-host]:guest-port\n");
3298
    exit(1);
3299
}
3300
    
3301
#ifndef _WIN32
3302

    
3303
char smb_dir[1024];
3304

    
3305
static void smb_exit(void)
3306
{
3307
    DIR *d;
3308
    struct dirent *de;
3309
    char filename[1024];
3310

    
3311
    /* erase all the files in the directory */
3312
    d = opendir(smb_dir);
3313
    for(;;) {
3314
        de = readdir(d);
3315
        if (!de)
3316
            break;
3317
        if (strcmp(de->d_name, ".") != 0 &&
3318
            strcmp(de->d_name, "..") != 0) {
3319
            snprintf(filename, sizeof(filename), "%s/%s", 
3320
                     smb_dir, de->d_name);
3321
            unlink(filename);
3322
        }
3323
    }
3324
    closedir(d);
3325
    rmdir(smb_dir);
3326
}
3327

    
3328
/* automatic user mode samba server configuration */
3329
void net_slirp_smb(const char *exported_dir)
3330
{
3331
    char smb_conf[1024];
3332
    char smb_cmdline[1024];
3333
    FILE *f;
3334

    
3335
    if (!slirp_inited) {
3336
        slirp_inited = 1;
3337
        slirp_init();
3338
    }
3339

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

    
3377
    snprintf(smb_cmdline, sizeof(smb_cmdline), "%s -s %s",
3378
             SMBD_COMMAND, smb_conf);
3379
    
3380
    slirp_add_exec(0, smb_cmdline, 4, 139);
3381
}
3382

    
3383
#endif /* !defined(_WIN32) */
3384

    
3385
#endif /* CONFIG_SLIRP */
3386

    
3387
#if !defined(_WIN32)
3388

    
3389
typedef struct TAPState {
3390
    VLANClientState *vc;
3391
    int fd;
3392
} TAPState;
3393

    
3394
static void tap_receive(void *opaque, const uint8_t *buf, int size)
3395
{
3396
    TAPState *s = opaque;
3397
    int ret;
3398
    for(;;) {
3399
        ret = write(s->fd, buf, size);
3400
        if (ret < 0 && (errno == EINTR || errno == EAGAIN)) {
3401
        } else {
3402
            break;
3403
        }
3404
    }
3405
}
3406

    
3407
static void tap_send(void *opaque)
3408
{
3409
    TAPState *s = opaque;
3410
    uint8_t buf[4096];
3411
    int size;
3412

    
3413
#ifdef __sun__
3414
    struct strbuf sbuf;
3415
    int f = 0;
3416
    sbuf.maxlen = sizeof(buf);
3417
    sbuf.buf = buf;
3418
    size = getmsg(s->fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
3419
#else
3420
    size = read(s->fd, buf, sizeof(buf));
3421
#endif
3422
    if (size > 0) {
3423
        qemu_send_packet(s->vc, buf, size);
3424
    }
3425
}
3426

    
3427
/* fd support */
3428

    
3429
static TAPState *net_tap_fd_init(VLANState *vlan, int fd)
3430
{
3431
    TAPState *s;
3432

    
3433
    s = qemu_mallocz(sizeof(TAPState));
3434
    if (!s)
3435
        return NULL;
3436
    s->fd = fd;
3437
    s->vc = qemu_new_vlan_client(vlan, tap_receive, NULL, s);
3438
    qemu_set_fd_handler(s->fd, tap_send, NULL, s);
3439
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), "tap: fd=%d", fd);
3440
    return s;
3441
}
3442

    
3443
#ifdef _BSD
3444
static int tap_open(char *ifname, int ifname_size)
3445
{
3446
    int fd;
3447
    char *dev;
3448
    struct stat s;
3449

    
3450
    fd = open("/dev/tap", O_RDWR);
3451
    if (fd < 0) {
3452
        fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
3453
        return -1;
3454
    }
3455

    
3456
    fstat(fd, &s);
3457
    dev = devname(s.st_rdev, S_IFCHR);
3458
    pstrcpy(ifname, ifname_size, dev);
3459

    
3460
    fcntl(fd, F_SETFL, O_NONBLOCK);
3461
    return fd;
3462
}
3463
#elif defined(__sun__)
3464
#define TUNNEWPPA       (('T'<<16) | 0x0001)
3465
/* 
3466
 * Allocate TAP device, returns opened fd. 
3467
 * Stores dev name in the first arg(must be large enough).
3468
 */  
3469
int tap_alloc(char *dev)
3470
{
3471
    int tap_fd, if_fd, ppa = -1;
3472
    static int ip_fd = 0;
3473
    char *ptr;
3474

    
3475
    static int arp_fd = 0;
3476
    int ip_muxid, arp_muxid;
3477
    struct strioctl  strioc_if, strioc_ppa;
3478
    int link_type = I_PLINK;;
3479
    struct lifreq ifr;
3480
    char actual_name[32] = "";
3481

    
3482
    memset(&ifr, 0x0, sizeof(ifr));
3483

    
3484
    if( *dev ){
3485
       ptr = dev;        
3486
       while( *ptr && !isdigit((int)*ptr) ) ptr++; 
3487
       ppa = atoi(ptr);
3488
    }
3489

    
3490
    /* Check if IP device was opened */
3491
    if( ip_fd )
3492
       close(ip_fd);
3493

    
3494
    if( (ip_fd = open("/dev/udp", O_RDWR, 0)) < 0){
3495
       syslog(LOG_ERR, "Can't open /dev/ip (actually /dev/udp)");
3496
       return -1;
3497
    }
3498

    
3499
    if( (tap_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3500
       syslog(LOG_ERR, "Can't open /dev/tap");
3501
       return -1;
3502
    }
3503

    
3504
    /* Assign a new PPA and get its unit number. */
3505
    strioc_ppa.ic_cmd = TUNNEWPPA;
3506
    strioc_ppa.ic_timout = 0;
3507
    strioc_ppa.ic_len = sizeof(ppa);
3508
    strioc_ppa.ic_dp = (char *)&ppa;
3509
    if ((ppa = ioctl (tap_fd, I_STR, &strioc_ppa)) < 0)
3510
       syslog (LOG_ERR, "Can't assign new interface");
3511

    
3512
    if( (if_fd = open("/dev/tap", O_RDWR, 0)) < 0){
3513
       syslog(LOG_ERR, "Can't open /dev/tap (2)");
3514
       return -1;
3515
    }
3516
    if(ioctl(if_fd, I_PUSH, "ip") < 0){
3517
       syslog(LOG_ERR, "Can't push IP module");
3518
       return -1;
3519
    }
3520

    
3521
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) < 0)
3522
        syslog(LOG_ERR, "Can't get flags\n");
3523

    
3524
    snprintf (actual_name, 32, "tap%d", ppa);
3525
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3526

    
3527
    ifr.lifr_ppa = ppa;
3528
    /* Assign ppa according to the unit number returned by tun device */
3529

    
3530
    if (ioctl (if_fd, SIOCSLIFNAME, &ifr) < 0)
3531
        syslog (LOG_ERR, "Can't set PPA %d", ppa);
3532
    if (ioctl(if_fd, SIOCGLIFFLAGS, &ifr) <0)
3533
        syslog (LOG_ERR, "Can't get flags\n");
3534
    /* Push arp module to if_fd */
3535
    if (ioctl (if_fd, I_PUSH, "arp") < 0)
3536
        syslog (LOG_ERR, "Can't push ARP module (2)");
3537

    
3538
    /* Push arp module to ip_fd */
3539
    if (ioctl (ip_fd, I_POP, NULL) < 0)
3540
        syslog (LOG_ERR, "I_POP failed\n");
3541
    if (ioctl (ip_fd, I_PUSH, "arp") < 0)
3542
        syslog (LOG_ERR, "Can't push ARP module (3)\n");
3543
    /* Open arp_fd */
3544
    if ((arp_fd = open ("/dev/tap", O_RDWR, 0)) < 0)
3545
       syslog (LOG_ERR, "Can't open %s\n", "/dev/tap");
3546

    
3547
    /* Set ifname to arp */
3548
    strioc_if.ic_cmd = SIOCSLIFNAME;
3549
    strioc_if.ic_timout = 0;
3550
    strioc_if.ic_len = sizeof(ifr);
3551
    strioc_if.ic_dp = (char *)&ifr;
3552
    if (ioctl(arp_fd, I_STR, &strioc_if) < 0){
3553
        syslog (LOG_ERR, "Can't set ifname to arp\n");
3554
    }
3555

    
3556
    if((ip_muxid = ioctl(ip_fd, I_LINK, if_fd)) < 0){
3557
       syslog(LOG_ERR, "Can't link TAP device to IP");
3558
       return -1;
3559
    }
3560

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

    
3564
    close (if_fd);
3565

    
3566
    memset(&ifr, 0x0, sizeof(ifr));
3567
    strncpy (ifr.lifr_name, actual_name, sizeof (ifr.lifr_name));
3568
    ifr.lifr_ip_muxid  = ip_muxid;
3569
    ifr.lifr_arp_muxid = arp_muxid;
3570

    
3571
    if (ioctl (ip_fd, SIOCSLIFMUXID, &ifr) < 0)
3572
    {
3573
      ioctl (ip_fd, I_PUNLINK , arp_muxid);
3574
      ioctl (ip_fd, I_PUNLINK, ip_muxid);
3575
      syslog (LOG_ERR, "Can't set multiplexor id");
3576
    }
3577

    
3578
    sprintf(dev, "tap%d", ppa);
3579
    return tap_fd;
3580
}
3581

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

    
3623
static int net_tap_init(VLANState *vlan, const char *ifname1,
3624
                        const char *setup_script)
3625
{
3626
    TAPState *s;
3627
    int pid, status, fd;
3628
    char *args[3];
3629
    char **parg;
3630
    char ifname[128];
3631

    
3632
    if (ifname1 != NULL)
3633
        pstrcpy(ifname, sizeof(ifname), ifname1);
3634
    else
3635
        ifname[0] = '\0';
3636
    fd = tap_open(ifname, sizeof(ifname));
3637
    if (fd < 0)
3638
        return -1;
3639

    
3640
    if (!setup_script || !strcmp(setup_script, "no"))
3641
        setup_script = "";
3642
    if (setup_script[0] != '\0') {
3643
        /* try to launch network init script */
3644
        pid = fork();
3645
        if (pid >= 0) {
3646
            if (pid == 0) {
3647
                int open_max = sysconf (_SC_OPEN_MAX), i;
3648
                for (i = 0; i < open_max; i++)
3649
                    if (i != STDIN_FILENO &&
3650
                        i != STDOUT_FILENO &&
3651
                        i != STDERR_FILENO &&
3652
                        i != fd)
3653
                        close(i);
3654

    
3655
                parg = args;
3656
                *parg++ = (char *)setup_script;
3657
                *parg++ = ifname;
3658
                *parg++ = NULL;
3659
                execv(setup_script, args);
3660
                _exit(1);
3661
            }
3662
            while (waitpid(pid, &status, 0) != pid);
3663
            if (!WIFEXITED(status) ||
3664
                WEXITSTATUS(status) != 0) {
3665
                fprintf(stderr, "%s: could not launch network script\n",
3666
                        setup_script);
3667
                return -1;
3668
            }
3669
        }
3670
    }
3671
    s = net_tap_fd_init(vlan, fd);
3672
    if (!s)
3673
        return -1;
3674
    snprintf(s->vc->info_str, sizeof(s->vc->info_str), 
3675
             "tap: ifname=%s setup_script=%s", ifname, setup_script);
3676
    return 0;
3677
}
3678

    
3679
#endif /* !_WIN32 */
3680

    
3681
/* network connection */
3682
typedef struct NetSocketState {
3683
    VLANClientState *vc;
3684
    int fd;
3685
    int state; /* 0 = getting length, 1 = getting data */
3686
    int index;
3687
    int packet_len;
3688
    uint8_t buf[4096];
3689
    struct sockaddr_in dgram_dst; /* contains inet host and port destination iff connectionless (SOCK_DGRAM) */
3690
} NetSocketState;
3691

    
3692
typedef struct NetSocketListenState {
3693
    VLANState *vlan;
3694
    int fd;
3695
} NetSocketListenState;
3696

    
3697
/* XXX: we consider we can send the whole packet without blocking */
3698
static void net_socket_receive(void *opaque, const uint8_t *buf, int size)
3699
{
3700
    NetSocketState *s = opaque;
3701
    uint32_t len;
3702
    len = htonl(size);
3703

    
3704
    send_all(s->fd, (const uint8_t *)&len, sizeof(len));
3705
    send_all(s->fd, buf, size);
3706
}
3707

    
3708
static void net_socket_receive_dgram(void *opaque, const uint8_t *buf, int size)
3709
{
3710
    NetSocketState *s = opaque;
3711
    sendto(s->fd, buf, size, 0, 
3712
           (struct sockaddr *)&s->dgram_dst, sizeof(s->dgram_dst));
3713
}
3714

    
3715
static void net_socket_send(void *opaque)
3716
{
3717
    NetSocketState *s = opaque;
3718
    int l, size, err;
3719
    uint8_t buf1[4096];
3720
    const uint8_t *buf;
3721

    
3722
    size = recv(s->fd, buf1, sizeof(buf1), 0);
3723
    if (size < 0) {
3724
        err = socket_error();
3725
        if (err != EWOULDBLOCK) 
3726
            goto eoc;
3727
    } else if (size == 0) {
3728
        /* end of connection */
3729
    eoc:
3730
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3731
        closesocket(s->fd);
3732
        return;
3733
    }
3734
    buf = buf1;
3735
    while (size > 0) {
3736
        /* reassemble a packet from the network */
3737
        switch(s->state) {
3738
        case 0:
3739
            l = 4 - s->index;
3740
            if (l > size)
3741
                l = size;
3742
            memcpy(s->buf + s->index, buf, l);
3743
            buf += l;
3744
            size -= l;
3745
            s->index += l;
3746
            if (s->index == 4) {
3747
                /* got length */
3748
                s->packet_len = ntohl(*(uint32_t *)s->buf);
3749
                s->index = 0;
3750
                s->state = 1;
3751
            }
3752
            break;
3753
        case 1:
3754
            l = s->packet_len - s->index;
3755
            if (l > size)
3756
                l = size;
3757
            memcpy(s->buf + s->index, buf, l);
3758
            s->index += l;
3759
            buf += l;
3760
            size -= l;
3761
            if (s->index >= s->packet_len) {
3762
                qemu_send_packet(s->vc, s->buf, s->packet_len);
3763
                s->index = 0;
3764
                s->state = 0;
3765
            }
3766
            break;
3767
        }
3768
    }
3769
}
3770

    
3771
static void net_socket_send_dgram(void *opaque)
3772
{
3773
    NetSocketState *s = opaque;
3774
    int size;
3775

    
3776
    size = recv(s->fd, s->buf, sizeof(s->buf), 0);
3777
    if (size < 0) 
3778
        return;
3779
    if (size == 0) {
3780
        /* end of connection */
3781
        qemu_set_fd_handler(s->fd, NULL, NULL, NULL);
3782
        return;
3783
    }
3784
    qemu_send_packet(s->vc, s->buf, size);
3785
}
3786

    
3787
static int net_socket_mcast_create(struct sockaddr_in *mcastaddr)
3788
{
3789
    struct ip_mreq imr;
3790
    int fd;
3791
    int val, ret;
3792
    if (!IN_MULTICAST(ntohl(mcastaddr->sin_addr.s_addr))) {
3793
        fprintf(stderr, "qemu: error: specified mcastaddr \"%s\" (0x%08x) does not contain a multicast address\n",
3794
                inet_ntoa(mcastaddr->sin_addr), 
3795
                (int)ntohl(mcastaddr->sin_addr.s_addr));
3796
        return -1;
3797

    
3798
    }
3799
    fd = socket(PF_INET, SOCK_DGRAM, 0);
3800
    if (fd < 0) {
3801
        perror("socket(PF_INET, SOCK_DGRAM)");
3802
        return -1;
3803
    }
3804

    
3805
    val = 1;
3806
    ret=setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, 
3807
                   (const char *)&val, sizeof(val));
3808
    if (ret < 0) {
3809
        perror("setsockopt(SOL_SOCKET, SO_REUSEADDR)");
3810
        goto fail;
3811
    }
3812

    
3813
    ret = bind(fd, (struct sockaddr *)mcastaddr, sizeof(*mcastaddr));
3814
    if (ret < 0) {
3815
        perror("bind");
3816
        goto fail;
3817
    }
3818
    
3819
    /* Add host to multicast group */
3820
    imr.imr_multiaddr = mcastaddr->sin_addr;
3821
    imr.imr_interface.s_addr = htonl(INADDR_ANY);
3822

    
3823
    ret = setsockopt(fd, IPPROTO_IP, IP_ADD_MEMBERSHIP, 
3824
                     (const char *)&imr, sizeof(struct ip_mreq));
3825
    if (ret < 0) {
3826
        perror("setsockopt(IP_ADD_MEMBERSHIP)");
3827
        goto fail;
3828
    }
3829

    
3830
    /* Force mcast msgs to loopback (eg. several QEMUs in same host */
3831
    val = 1;
3832
    ret=setsockopt(fd, IPPROTO_IP, IP_MULTICAST_LOOP, 
3833
                   (const char *)&val, sizeof(val));
3834
    if (ret < 0) {
3835
        perror("setsockopt(SOL_IP, IP_MULTICAST_LOOP)");
3836
        goto fail;
3837
    }
3838

    
3839
    socket_set_nonblock(fd);
3840
    return fd;
3841
fail:
3842
    if (fd >= 0) 
3843
        closesocket(fd);
3844
    return -1;
3845
}
3846

    
3847
static NetSocketState *net_socket_fd_init_dgram(VLANState *vlan, int fd, 
3848
                                          int is_connected)
3849
{
3850
    struct sockaddr_in saddr;
3851
    int newfd;
3852
    socklen_t saddr_len;
3853
    NetSocketState *s;
3854

    
3855
    /* fd passed: multicast: "learn" dgram_dst address from bound address and save it
3856
     * Because this may be "shared" socket from a "master" process, datagrams would be recv() 
3857
     * by ONLY ONE process: we must "clone" this dgram socket --jjo
3858
     */
3859

    
3860
    if (is_connected) {
3861
        if (getsockname(fd, (struct sockaddr *) &saddr, &saddr_len) == 0) {
3862
            /* must be bound */
3863
            if (saddr.sin_addr.s_addr==0) {
3864
                fprintf(stderr, "qemu: error: init_dgram: fd=%d unbound, cannot setup multicast dst addr\n",
3865
                        fd);
3866
                return NULL;
3867
            }
3868
            /* clone dgram socket */
3869
            newfd = net_socket_mcast_create(&saddr);
3870
            if (newfd < 0) {
3871
                /* error already reported by net_socket_mcast_create() */
3872
                close(fd);
3873
                return NULL;
3874
            }
3875
            /* clone newfd to fd, close newfd */
3876
            dup2(newfd, fd);
3877
            close(newfd);
3878
        
3879
        } else {
3880
            fprintf(stderr, "qemu: error: init_dgram: fd=%d failed getsockname(): %s\n",
3881
                    fd, strerror(errno));
3882
            return NULL;
3883
        }
3884
    }
3885

    
3886
    s = qemu_mallocz(sizeof(NetSocketState));
3887
    if (!s)
3888
        return NULL;
3889
    s->fd = fd;
3890

    
3891
    s->vc = qemu_new_vlan_client(vlan, net_socket_receive_dgram, NULL, s);
3892
    qemu_set_fd_handler(s->fd, net_socket_send_dgram, NULL, s);
3893

    
3894
    /* mcast: save bound address as dst */
3895
    if (is_connected) s->dgram_dst=saddr;
3896

    
3897
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3898
            "socket: fd=%d (%s mcast=%s:%d)", 
3899
            fd, is_connected? "cloned" : "",
3900
            inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3901
    return s;
3902
}
3903

    
3904
static void net_socket_connect(void *opaque)
3905
{
3906
    NetSocketState *s = opaque;
3907
    qemu_set_fd_handler(s->fd, net_socket_send, NULL, s);
3908
}
3909

    
3910
static NetSocketState *net_socket_fd_init_stream(VLANState *vlan, int fd, 
3911
                                          int is_connected)
3912
{
3913
    NetSocketState *s;
3914
    s = qemu_mallocz(sizeof(NetSocketState));
3915
    if (!s)
3916
        return NULL;
3917
    s->fd = fd;
3918
    s->vc = qemu_new_vlan_client(vlan, 
3919
                                 net_socket_receive, NULL, s);
3920
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
3921
             "socket: fd=%d", fd);
3922
    if (is_connected) {
3923
        net_socket_connect(s);
3924
    } else {
3925
        qemu_set_fd_handler(s->fd, NULL, net_socket_connect, s);
3926
    }
3927
    return s;
3928
}
3929

    
3930
static NetSocketState *net_socket_fd_init(VLANState *vlan, int fd, 
3931
                                          int is_connected)
3932
{
3933
    int so_type=-1, optlen=sizeof(so_type);
3934

    
3935
    if(getsockopt(fd, SOL_SOCKET, SO_TYPE, (char *)&so_type, &optlen)< 0) {
3936
        fprintf(stderr, "qemu: error: getsockopt(SO_TYPE) for fd=%d failed\n", fd);
3937
        return NULL;
3938
    }
3939
    switch(so_type) {
3940
    case SOCK_DGRAM:
3941
        return net_socket_fd_init_dgram(vlan, fd, is_connected);
3942
    case SOCK_STREAM:
3943
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3944
    default:
3945
        /* who knows ... this could be a eg. a pty, do warn and continue as stream */
3946
        fprintf(stderr, "qemu: warning: socket type=%d for fd=%d is not SOCK_DGRAM or SOCK_STREAM\n", so_type, fd);
3947
        return net_socket_fd_init_stream(vlan, fd, is_connected);
3948
    }
3949
    return NULL;
3950
}
3951

    
3952
static void net_socket_accept(void *opaque)
3953
{
3954
    NetSocketListenState *s = opaque;    
3955
    NetSocketState *s1;
3956
    struct sockaddr_in saddr;
3957
    socklen_t len;
3958
    int fd;
3959

    
3960
    for(;;) {
3961
        len = sizeof(saddr);
3962
        fd = accept(s->fd, (struct sockaddr *)&saddr, &len);
3963
        if (fd < 0 && errno != EINTR) {
3964
            return;
3965
        } else if (fd >= 0) {
3966
            break;
3967
        }
3968
    }
3969
    s1 = net_socket_fd_init(s->vlan, fd, 1); 
3970
    if (!s1) {
3971
        closesocket(fd);
3972
    } else {
3973
        snprintf(s1->vc->info_str, sizeof(s1->vc->info_str),
3974
                 "socket: connection from %s:%d", 
3975
                 inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
3976
    }
3977
}
3978

    
3979
static int net_socket_listen_init(VLANState *vlan, const char *host_str)
3980
{
3981
    NetSocketListenState *s;
3982
    int fd, val, ret;
3983
    struct sockaddr_in saddr;
3984

    
3985
    if (parse_host_port(&saddr, host_str) < 0)
3986
        return -1;
3987
    
3988
    s = qemu_mallocz(sizeof(NetSocketListenState));
3989
    if (!s)
3990
        return -1;
3991

    
3992
    fd = socket(PF_INET, SOCK_STREAM, 0);
3993
    if (fd < 0) {
3994
        perror("socket");
3995
        return -1;
3996
    }
3997
    socket_set_nonblock(fd);
3998

    
3999
    /* allow fast reuse */
4000
    val = 1;
4001
    setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (const char *)&val, sizeof(val));
4002
    
4003
    ret = bind(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4004
    if (ret < 0) {
4005
        perror("bind");
4006
        return -1;
4007
    }
4008
    ret = listen(fd, 0);
4009
    if (ret < 0) {
4010
        perror("listen");
4011
        return -1;
4012
    }
4013
    s->vlan = vlan;
4014
    s->fd = fd;
4015
    qemu_set_fd_handler(fd, net_socket_accept, NULL, s);
4016
    return 0;
4017
}
4018

    
4019
static int net_socket_connect_init(VLANState *vlan, const char *host_str)
4020
{
4021
    NetSocketState *s;
4022
    int fd, connected, ret, err;
4023
    struct sockaddr_in saddr;
4024

    
4025
    if (parse_host_port(&saddr, host_str) < 0)
4026
        return -1;
4027

    
4028
    fd = socket(PF_INET, SOCK_STREAM, 0);
4029
    if (fd < 0) {
4030
        perror("socket");
4031
        return -1;
4032
    }
4033
    socket_set_nonblock(fd);
4034

    
4035
    connected = 0;
4036
    for(;;) {
4037
        ret = connect(fd, (struct sockaddr *)&saddr, sizeof(saddr));
4038
        if (ret < 0) {
4039
            err = socket_error();
4040
            if (err == EINTR || err == EWOULDBLOCK) {
4041
            } else if (err == EINPROGRESS) {
4042
                break;
4043
#ifdef _WIN32
4044
            } else if (err == WSAEALREADY) {
4045
                break;
4046
#endif
4047
            } else {
4048
                perror("connect");
4049
                closesocket(fd);
4050
                return -1;
4051
            }
4052
        } else {
4053
            connected = 1;
4054
            break;
4055
        }
4056
    }
4057
    s = net_socket_fd_init(vlan, fd, connected);
4058
    if (!s)
4059
        return -1;
4060
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4061
             "socket: connect to %s:%d", 
4062
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4063
    return 0;
4064
}
4065

    
4066
static int net_socket_mcast_init(VLANState *vlan, const char *host_str)
4067
{
4068
    NetSocketState *s;
4069
    int fd;
4070
    struct sockaddr_in saddr;
4071

    
4072
    if (parse_host_port(&saddr, host_str) < 0)
4073
        return -1;
4074

    
4075

    
4076
    fd = net_socket_mcast_create(&saddr);
4077
    if (fd < 0)
4078
        return -1;
4079

    
4080
    s = net_socket_fd_init(vlan, fd, 0);
4081
    if (!s)
4082
        return -1;
4083

    
4084
    s->dgram_dst = saddr;
4085
    
4086
    snprintf(s->vc->info_str, sizeof(s->vc->info_str),
4087
             "socket: mcast=%s:%d", 
4088
             inet_ntoa(saddr.sin_addr), ntohs(saddr.sin_port));
4089
    return 0;
4090

    
4091
}
4092

    
4093
static int get_param_value(char *buf, int buf_size,
4094
                           const char *tag, const char *str)
4095
{
4096
    const char *p;
4097
    char *q;
4098
    char option[128];
4099

    
4100
    p = str;
4101
    for(;;) {
4102
        q = option;
4103
        while (*p != '\0' && *p != '=') {
4104
            if ((q - option) < sizeof(option) - 1)
4105
                *q++ = *p;
4106
            p++;
4107
        }
4108
        *q = '\0';
4109
        if (*p != '=')
4110
            break;
4111
        p++;
4112
        if (!strcmp(tag, option)) {
4113
            q = buf;
4114
            while (*p != '\0' && *p != ',') {
4115
                if ((q - buf) < buf_size - 1)
4116
                    *q++ = *p;
4117
                p++;
4118
            }
4119
            *q = '\0';
4120
            return q - buf;
4121
        } else {
4122
            while (*p != '\0' && *p != ',') {
4123
                p++;
4124
            }
4125
        }
4126
        if (*p != ',')
4127
            break;
4128
        p++;
4129
    }
4130
    return 0;
4131
}
4132

    
4133
static int net_client_init(const char *str)
4134
{
4135
    const char *p;
4136
    char *q;
4137
    char device[64];
4138
    char buf[1024];
4139
    int vlan_id, ret;
4140
    VLANState *vlan;
4141

    
4142
    p = str;
4143
    q = device;
4144
    while (*p != '\0' && *p != ',') {
4145
        if ((q - device) < sizeof(device) - 1)
4146
            *q++ = *p;
4147
        p++;
4148
    }
4149
    *q = '\0';
4150
    if (*p == ',')
4151
        p++;
4152
    vlan_id = 0;
4153
    if (get_param_value(buf, sizeof(buf), "vlan", p)) {
4154
        vlan_id = strtol(buf, NULL, 0);
4155
    }
4156
    vlan = qemu_find_vlan(vlan_id);
4157
    if (!vlan) {
4158
        fprintf(stderr, "Could not create vlan %d\n", vlan_id);
4159
        return -1;
4160
    }
4161
    if (!strcmp(device, "nic")) {
4162
        NICInfo *nd;
4163
        uint8_t *macaddr;
4164

    
4165
        if (nb_nics >= MAX_NICS) {
4166
            fprintf(stderr, "Too Many NICs\n");
4167
            return -1;
4168
        }
4169
        nd = &nd_table[nb_nics];
4170
        macaddr = nd->macaddr;
4171
        macaddr[0] = 0x52;
4172
        macaddr[1] = 0x54;
4173
        macaddr[2] = 0x00;
4174
        macaddr[3] = 0x12;
4175
        macaddr[4] = 0x34;
4176
        macaddr[5] = 0x56 + nb_nics;
4177

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

    
4263
void do_info_network(void)
4264
{
4265
    VLANState *vlan;
4266
    VLANClientState *vc;
4267

    
4268
    for(vlan = first_vlan; vlan != NULL; vlan = vlan->next) {
4269
        term_printf("VLAN %d devices:\n", vlan->id);
4270
        for(vc = vlan->first_client; vc != NULL; vc = vc->next)
4271
            term_printf("  %s\n", vc->info_str);
4272
    }
4273
}
4274

    
4275
/***********************************************************/
4276
/* USB devices */
4277

    
4278
static USBPort *used_usb_ports;
4279
static USBPort *free_usb_ports;
4280

    
4281
/* ??? Maybe change this to register a hub to keep track of the topology.  */
4282
void qemu_register_usb_port(USBPort *port, void *opaque, int index,
4283
                            usb_attachfn attach)
4284
{
4285
    port->opaque = opaque;
4286
    port->index = index;
4287
    port->attach = attach;
4288
    port->next = free_usb_ports;
4289
    free_usb_ports = port;
4290
}
4291

    
4292
static int usb_device_add(const char *devname)
4293
{
4294
    const char *p;
4295
    USBDevice *dev;
4296
    USBPort *port;
4297

    
4298
    if (!free_usb_ports)
4299
        return -1;
4300

    
4301
    if (strstart(devname, "host:", &p)) {
4302
        dev = usb_host_device_open(p);
4303
    } else if (!strcmp(devname, "mouse")) {
4304
        dev = usb_mouse_init();
4305
    } else if (!strcmp(devname, "tablet")) {
4306
        dev = usb_tablet_init();
4307
    } else if (strstart(devname, "disk:", &p)) {
4308
        dev = usb_msd_init(p);
4309
    } else {
4310
        return -1;
4311
    }
4312
    if (!dev)
4313
        return -1;
4314

    
4315
    /* Find a USB port to add the device to.  */
4316
    port = free_usb_ports;
4317
    if (!port->next) {
4318
        USBDevice *hub;
4319

    
4320
        /* Create a new hub and chain it on.  */
4321
        free_usb_ports = NULL;
4322
        port->next = used_usb_ports;
4323
        used_usb_ports = port;
4324

    
4325
        hub = usb_hub_init(VM_USB_HUB_SIZE);
4326
        usb_attach(port, hub);
4327
        port = free_usb_ports;
4328
    }
4329

    
4330
    free_usb_ports = port->next;
4331
    port->next = used_usb_ports;
4332
    used_usb_ports = port;
4333
    usb_attach(port, dev);
4334
    return 0;
4335
}
4336

    
4337
static int usb_device_del(const char *devname)
4338
{
4339
    USBPort *port;
4340
    USBPort **lastp;
4341
    USBDevice *dev;
4342
    int bus_num, addr;
4343
    const char *p;
4344

    
4345
    if (!used_usb_ports)
4346
        return -1;
4347

    
4348
    p = strchr(devname, '.');
4349
    if (!p) 
4350
        return -1;
4351
    bus_num = strtoul(devname, NULL, 0);
4352
    addr = strtoul(p + 1, NULL, 0);
4353
    if (bus_num != 0)
4354
        return -1;
4355

    
4356
    lastp = &used_usb_ports;
4357
    port = used_usb_ports;
4358
    while (port && port->dev->addr != addr) {
4359
        lastp = &port->next;
4360
        port = port->next;
4361
    }
4362

    
4363
    if (!port)
4364
        return -1;
4365

    
4366
    dev = port->dev;
4367
    *lastp = port->next;
4368
    usb_attach(port, NULL);
4369
    dev->handle_destroy(dev);
4370
    port->next = free_usb_ports;
4371
    free_usb_ports = port;
4372
    return 0;
4373
}
4374

    
4375
void do_usb_add(const char *devname)
4376
{
4377
    int ret;
4378
    ret = usb_device_add(devname);
4379
    if (ret < 0) 
4380
        term_printf("Could not add USB device '%s'\n", devname);
4381
}
4382

    
4383
void do_usb_del(const char *devname)
4384
{
4385
    int ret;
4386
    ret = usb_device_del(devname);
4387
    if (ret < 0) 
4388
        term_printf("Could not remove USB device '%s'\n", devname);
4389
}
4390

    
4391
void usb_info(void)
4392
{
4393
    USBDevice *dev;
4394
    USBPort *port;
4395
    const char *speed_str;
4396

    
4397
    if (!usb_enabled) {
4398
        term_printf("USB support not enabled\n");
4399
        return;
4400
    }
4401

    
4402
    for (port = used_usb_ports; port; port = port->next) {
4403
        dev = port->dev;
4404
        if (!dev)
4405
            continue;
4406
        switch(dev->speed) {
4407
        case USB_SPEED_LOW: 
4408
            speed_str = "1.5"; 
4409
            break;
4410
        case USB_SPEED_FULL: 
4411
            speed_str = "12"; 
4412
            break;
4413
        case USB_SPEED_HIGH: 
4414
            speed_str = "480"; 
4415
            break;
4416
        default:
4417
            speed_str = "?"; 
4418
            break;
4419
        }
4420
        term_printf("  Device %d.%d, Speed %s Mb/s, Product %s\n", 
4421
                    0, dev->addr, speed_str, dev->devname);
4422
    }
4423
}
4424

    
4425
/***********************************************************/
4426
/* PCMCIA/Cardbus */
4427

    
4428
static struct pcmcia_socket_entry_s {
4429
    struct pcmcia_socket_s *socket;
4430
    struct pcmcia_socket_entry_s *next;
4431
} *pcmcia_sockets = 0;
4432

    
4433
void pcmcia_socket_register(struct pcmcia_socket_s *socket)
4434
{
4435
    struct pcmcia_socket_entry_s *entry;
4436

    
4437
    entry = qemu_malloc(sizeof(struct pcmcia_socket_entry_s));
4438
    entry->socket = socket;
4439
    entry->next = pcmcia_sockets;
4440
    pcmcia_sockets = entry;
4441
}
4442

    
4443
void pcmcia_socket_unregister(struct pcmcia_socket_s *socket)
4444
{
4445
    struct pcmcia_socket_entry_s *entry, **ptr;
4446

    
4447
    ptr = &pcmcia_sockets;
4448
    for (entry = *ptr; entry; ptr = &entry->next, entry = *ptr)
4449
        if (entry->socket == socket) {
4450
            *ptr = entry->next;
4451
            qemu_free(entry);
4452
        }
4453
}
4454

    
4455
void pcmcia_info(void)
4456
{
4457
    struct pcmcia_socket_entry_s *iter;
4458
    if (!pcmcia_sockets)
4459
        term_printf("No PCMCIA sockets\n");
4460

    
4461
    for (iter = pcmcia_sockets; iter; iter = iter->next)
4462
        term_printf("%s: %s\n", iter->socket->slot_string,
4463
                    iter->socket->attached ? iter->socket->card_string :
4464
                    "Empty");
4465
}
4466

    
4467
/***********************************************************/
4468
/* dumb display */
4469

    
4470
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
4471
{
4472
}
4473

    
4474
static void dumb_resize(DisplayState *ds, int w, int h)
4475
{
4476
}
4477

    
4478
static void dumb_refresh(DisplayState *ds)
4479
{
4480
    vga_hw_update();
4481
}
4482

    
4483
void dumb_display_init(DisplayState *ds)
4484
{
4485
    ds->data = NULL;
4486
    ds->linesize = 0;
4487
    ds->depth = 0;
4488
    ds->dpy_update = dumb_update;
4489
    ds->dpy_resize = dumb_resize;
4490
    ds->dpy_refresh = dumb_refresh;
4491
}
4492

    
4493
/***********************************************************/
4494
/* I/O handling */
4495

    
4496
#define MAX_IO_HANDLERS 64
4497

    
4498
typedef struct IOHandlerRecord {
4499
    int fd;
4500
    IOCanRWHandler *fd_read_poll;
4501
    IOHandler *fd_read;
4502
    IOHandler *fd_write;
4503
    int deleted;
4504
    void *opaque;
4505
    /* temporary data */
4506
    struct pollfd *ufd;
4507
    struct IOHandlerRecord *next;
4508
} IOHandlerRecord;
4509

    
4510
static IOHandlerRecord *first_io_handler;
4511

    
4512
/* XXX: fd_read_poll should be suppressed, but an API change is
4513
   necessary in the character devices to suppress fd_can_read(). */
4514
int qemu_set_fd_handler2(int fd, 
4515
                         IOCanRWHandler *fd_read_poll, 
4516
                         IOHandler *fd_read, 
4517
                         IOHandler *fd_write, 
4518
                         void *opaque)
4519
{
4520
    IOHandlerRecord **pioh, *ioh;
4521

    
4522
    if (!fd_read && !fd_write) {
4523
        pioh = &first_io_handler;
4524
        for(;;) {
4525
            ioh = *pioh;
4526
            if (ioh == NULL)
4527
                break;
4528
            if (ioh->fd == fd) {
4529
                ioh->deleted = 1;
4530
                break;
4531
            }
4532
            pioh = &ioh->next;
4533
        }
4534
    } else {
4535
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
4536
            if (ioh->fd == fd)
4537
                goto found;
4538
        }
4539
        ioh = qemu_mallocz(sizeof(IOHandlerRecord));
4540
        if (!ioh)
4541
            return -1;
4542
        ioh->next = first_io_handler;
4543
        first_io_handler = ioh;
4544
    found:
4545
        ioh->fd = fd;
4546
        ioh->fd_read_poll = fd_read_poll;
4547
        ioh->fd_read = fd_read;
4548
        ioh->fd_write = fd_write;
4549
        ioh->opaque = opaque;
4550
        ioh->deleted = 0;
4551
    }
4552
    return 0;
4553
}
4554

    
4555
int qemu_set_fd_handler(int fd, 
4556
                        IOHandler *fd_read, 
4557
                        IOHandler *fd_write, 
4558
                        void *opaque)
4559
{
4560
    return qemu_set_fd_handler2(fd, NULL, fd_read, fd_write, opaque);
4561
}
4562

    
4563
/***********************************************************/
4564
/* Polling handling */
4565

    
4566
typedef struct PollingEntry {
4567
    PollingFunc *func;
4568
    void *opaque;
4569
    struct PollingEntry *next;
4570
} PollingEntry;
4571

    
4572
static PollingEntry *first_polling_entry;
4573

    
4574
int qemu_add_polling_cb(PollingFunc *func, void *opaque)
4575
{
4576
    PollingEntry **ppe, *pe;
4577
    pe = qemu_mallocz(sizeof(PollingEntry));
4578
    if (!pe)
4579
        return -1;
4580
    pe->func = func;
4581
    pe->opaque = opaque;
4582
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next);
4583
    *ppe = pe;
4584
    return 0;
4585
}
4586

    
4587
void qemu_del_polling_cb(PollingFunc *func, void *opaque)
4588
{
4589
    PollingEntry **ppe, *pe;
4590
    for(ppe = &first_polling_entry; *ppe != NULL; ppe = &(*ppe)->next) {
4591
        pe = *ppe;
4592
        if (pe->func == func && pe->opaque == opaque) {
4593
            *ppe = pe->next;
4594
            qemu_free(pe);
4595
            break;
4596
        }
4597
    }
4598
}
4599

    
4600
#ifdef _WIN32
4601
/***********************************************************/
4602
/* Wait objects support */
4603
typedef struct WaitObjects {
4604
    int num;
4605
    HANDLE events[MAXIMUM_WAIT_OBJECTS + 1];
4606
    WaitObjectFunc *func[MAXIMUM_WAIT_OBJECTS + 1];
4607
    void *opaque[MAXIMUM_WAIT_OBJECTS + 1];
4608
} WaitObjects;
4609

    
4610
static WaitObjects wait_objects = {0};
4611
    
4612
int qemu_add_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4613
{
4614
    WaitObjects *w = &wait_objects;
4615

    
4616
    if (w->num >= MAXIMUM_WAIT_OBJECTS)
4617
        return -1;
4618
    w->events[w->num] = handle;
4619
    w->func[w->num] = func;
4620
    w->opaque[w->num] = opaque;
4621
    w->num++;
4622
    return 0;
4623
}
4624

    
4625
void qemu_del_wait_object(HANDLE handle, WaitObjectFunc *func, void *opaque)
4626
{
4627
    int i, found;
4628
    WaitObjects *w = &wait_objects;
4629

    
4630
    found = 0;
4631
    for (i = 0; i < w->num; i++) {
4632
        if (w->events[i] == handle)
4633
            found = 1;
4634
        if (found) {
4635
            w->events[i] = w->events[i + 1];
4636
            w->func[i] = w->func[i + 1];
4637
            w->opaque[i] = w->opaque[i + 1];
4638
        }            
4639
    }
4640
    if (found)
4641
        w->num--;
4642
}
4643
#endif
4644

    
4645
/***********************************************************/
4646
/* savevm/loadvm support */
4647

    
4648
#define IO_BUF_SIZE 32768
4649

    
4650
struct QEMUFile {
4651
    FILE *outfile;
4652
    BlockDriverState *bs;
4653
    int is_file;
4654
    int is_writable;
4655
    int64_t base_offset;
4656
    int64_t buf_offset; /* start of buffer when writing, end of buffer
4657
                           when reading */
4658
    int buf_index;
4659
    int buf_size; /* 0 when writing */
4660
    uint8_t buf[IO_BUF_SIZE];
4661
};
4662

    
4663
QEMUFile *qemu_fopen(const char *filename, const char *mode)
4664
{
4665
    QEMUFile *f;
4666

    
4667
    f = qemu_mallocz(sizeof(QEMUFile));
4668
    if (!f)
4669
        return NULL;
4670
    if (!strcmp(mode, "wb")) {
4671
        f->is_writable = 1;
4672
    } else if (!strcmp(mode, "rb")) {
4673
        f->is_writable = 0;
4674
    } else {
4675
        goto fail;
4676
    }
4677
    f->outfile = fopen(filename, mode);
4678
    if (!f->outfile)
4679
        goto fail;
4680
    f->is_file = 1;
4681
    return f;
4682
 fail:
4683
    if (f->outfile)
4684
        fclose(f->outfile);
4685
    qemu_free(f);
4686
    return NULL;
4687
}
4688

    
4689
QEMUFile *qemu_fopen_bdrv(BlockDriverState *bs, int64_t offset, int is_writable)
4690
{
4691
    QEMUFile *f;
4692

    
4693
    f = qemu_mallocz(sizeof(QEMUFile));
4694
    if (!f)
4695
        return NULL;
4696
    f->is_file = 0;
4697
    f->bs = bs;
4698
    f->is_writable = is_writable;
4699
    f->base_offset = offset;
4700
    return f;
4701
}
4702

    
4703
void qemu_fflush(QEMUFile *f)
4704
{
4705
    if (!f->is_writable)
4706
        return;
4707
    if (f->buf_index > 0) {
4708
        if (f->is_file) {
4709
            fseek(f->outfile, f->buf_offset, SEEK_SET);
4710
            fwrite(f->buf, 1, f->buf_index, f->outfile);
4711
        } else {
4712
            bdrv_pwrite(f->bs, f->base_offset + f->buf_offset, 
4713
                        f->buf, f->buf_index);
4714
        }
4715
        f->buf_offset += f->buf_index;
4716
        f->buf_index = 0;
4717
    }
4718
}
4719

    
4720
static void qemu_fill_buffer(QEMUFile *f)
4721
{
4722
    int len;
4723

    
4724
    if (f->is_writable)
4725
        return;
4726
    if (f->is_file) {
4727
        fseek(f->outfile, f->buf_offset, SEEK_SET);
4728
        len = fread(f->buf, 1, IO_BUF_SIZE, f->outfile);
4729
        if (len < 0)
4730
            len = 0;
4731
    } else {
4732
        len = bdrv_pread(f->bs, f->base_offset + f->buf_offset, 
4733
                         f->buf, IO_BUF_SIZE);
4734
        if (len < 0)
4735
            len = 0;
4736
    }
4737
    f->buf_index = 0;
4738
    f->buf_size = len;
4739
    f->buf_offset += len;
4740
}
4741

    
4742
void qemu_fclose(QEMUFile *f)
4743
{
4744
    if (f->is_writable)
4745
        qemu_fflush(f);
4746
    if (f->is_file) {
4747
        fclose(f->outfile);
4748
    }
4749
    qemu_free(f);
4750
}
4751

    
4752
void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
4753
{
4754
    int l;
4755
    while (size > 0) {
4756
        l = IO_BUF_SIZE - f->buf_index;
4757
        if (l > size)
4758
            l = size;
4759
        memcpy(f->buf + f->buf_index, buf, l);
4760
        f->buf_index += l;
4761
        buf += l;
4762
        size -= l;
4763
        if (f->buf_index >= IO_BUF_SIZE)
4764
            qemu_fflush(f);
4765
    }
4766
}
4767

    
4768
void qemu_put_byte(QEMUFile *f, int v)
4769
{
4770
    f->buf[f->buf_index++] = v;
4771
    if (f->buf_index >= IO_BUF_SIZE)
4772
        qemu_fflush(f);
4773
}
4774

    
4775
int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size1)
4776
{
4777
    int size, l;
4778

    
4779
    size = size1;
4780
    while (size > 0) {
4781
        l = f->buf_size - f->buf_index;
4782
        if (l == 0) {
4783
            qemu_fill_buffer(f);
4784
            l = f->buf_size - f->buf_index;
4785
            if (l == 0)
4786
                break;
4787
        }
4788
        if (l > size)
4789
            l = size;
4790
        memcpy(buf, f->buf + f->buf_index, l);
4791
        f->buf_index += l;
4792
        buf += l;
4793
        size -= l;
4794
    }
4795
    return size1 - size;
4796
}
4797

    
4798
int qemu_get_byte(QEMUFile *f)
4799
{
4800
    if (f->buf_index >= f->buf_size) {
4801
        qemu_fill_buffer(f);
4802
        if (f->buf_index >= f->buf_size)
4803
            return 0;
4804
    }
4805
    return f->buf[f->buf_index++];
4806
}
4807

    
4808
int64_t qemu_ftell(QEMUFile *f)
4809
{
4810
    return f->buf_offset - f->buf_size + f->buf_index;
4811
}
4812

    
4813
int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
4814
{
4815
    if (whence == SEEK_SET) {
4816
        /* nothing to do */
4817
    } else if (whence == SEEK_CUR) {
4818
        pos += qemu_ftell(f);
4819
    } else {
4820
        /* SEEK_END not supported */
4821
        return -1;
4822
    }
4823
    if (f->is_writable) {
4824
        qemu_fflush(f);
4825
        f->buf_offset = pos;
4826
    } else {
4827
        f->buf_offset = pos;
4828
        f->buf_index = 0;
4829
        f->buf_size = 0;
4830
    }
4831
    return pos;
4832
}
4833

    
4834
void qemu_put_be16(QEMUFile *f, unsigned int v)
4835
{
4836
    qemu_put_byte(f, v >> 8);
4837
    qemu_put_byte(f, v);
4838
}
4839

    
4840
void qemu_put_be32(QEMUFile *f, unsigned int v)
4841
{
4842
    qemu_put_byte(f, v >> 24);
4843
    qemu_put_byte(f, v >> 16);
4844
    qemu_put_byte(f, v >> 8);
4845
    qemu_put_byte(f, v);
4846
}
4847

    
4848
void qemu_put_be64(QEMUFile *f, uint64_t v)
4849
{
4850
    qemu_put_be32(f, v >> 32);
4851
    qemu_put_be32(f, v);
4852
}
4853

    
4854
unsigned int qemu_get_be16(QEMUFile *f)
4855
{
4856
    unsigned int v;
4857
    v = qemu_get_byte(f) << 8;
4858
    v |= qemu_get_byte(f);
4859
    return v;
4860
}
4861

    
4862
unsigned int qemu_get_be32(QEMUFile *f)
4863
{
4864
    unsigned int v;
4865
    v = qemu_get_byte(f) << 24;
4866
    v |= qemu_get_byte(f) << 16;
4867
    v |= qemu_get_byte(f) << 8;
4868
    v |= qemu_get_byte(f);
4869
    return v;
4870
}
4871

    
4872
uint64_t qemu_get_be64(QEMUFile *f)
4873
{
4874
    uint64_t v;
4875
    v = (uint64_t)qemu_get_be32(f) << 32;
4876
    v |= qemu_get_be32(f);
4877
    return v;
4878
}
4879

    
4880
typedef struct SaveStateEntry {
4881
    char idstr[256];
4882
    int instance_id;
4883
    int version_id;
4884
    SaveStateHandler *save_state;
4885
    LoadStateHandler *load_state;
4886
    void *opaque;
4887
    struct SaveStateEntry *next;
4888
} SaveStateEntry;
4889

    
4890
static SaveStateEntry *first_se;
4891

    
4892
int register_savevm(const char *idstr, 
4893
                    int instance_id, 
4894
                    int version_id,
4895
                    SaveStateHandler *save_state,
4896
                    LoadStateHandler *load_state,
4897
                    void *opaque)
4898
{
4899
    SaveStateEntry *se, **pse;
4900

    
4901
    se = qemu_malloc(sizeof(SaveStateEntry));
4902
    if (!se)
4903
        return -1;
4904
    pstrcpy(se->idstr, sizeof(se->idstr), idstr);
4905
    se->instance_id = instance_id;
4906
    se->version_id = version_id;
4907
    se->save_state = save_state;
4908
    se->load_state = load_state;
4909
    se->opaque = opaque;
4910
    se->next = NULL;
4911

    
4912
    /* add at the end of list */
4913
    pse = &first_se;
4914
    while (*pse != NULL)
4915
        pse = &(*pse)->next;
4916
    *pse = se;
4917
    return 0;
4918
}
4919

    
4920
#define QEMU_VM_FILE_MAGIC   0x5145564d
4921
#define QEMU_VM_FILE_VERSION 0x00000002
4922

    
4923
int qemu_savevm_state(QEMUFile *f)
4924
{
4925
    SaveStateEntry *se;
4926
    int len, ret;
4927
    int64_t cur_pos, len_pos, total_len_pos;
4928

    
4929
    qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
4930
    qemu_put_be32(f, QEMU_VM_FILE_VERSION);
4931
    total_len_pos = qemu_ftell(f);
4932
    qemu_put_be64(f, 0); /* total size */
4933

    
4934
    for(se = first_se; se != NULL; se = se->next) {
4935
        /* ID string */
4936
        len = strlen(se->idstr);
4937
        qemu_put_byte(f, len);
4938
        qemu_put_buffer(f, se->idstr, len);
4939

    
4940
        qemu_put_be32(f, se->instance_id);
4941
        qemu_put_be32(f, se->version_id);
4942

    
4943
        /* record size: filled later */
4944
        len_pos = qemu_ftell(f);
4945
        qemu_put_be32(f, 0);
4946
        
4947
        se->save_state(f, se->opaque);
4948

    
4949
        /* fill record size */
4950
        cur_pos = qemu_ftell(f);
4951
        len = cur_pos - len_pos - 4;
4952
        qemu_fseek(f, len_pos, SEEK_SET);
4953
        qemu_put_be32(f, len);
4954
        qemu_fseek(f, cur_pos, SEEK_SET);
4955
    }
4956
    cur_pos = qemu_ftell(f);
4957
    qemu_fseek(f, total_len_pos, SEEK_SET);
4958
    qemu_put_be64(f, cur_pos - total_len_pos - 8);
4959
    qemu_fseek(f, cur_pos, SEEK_SET);
4960

    
4961
    ret = 0;
4962
    return ret;
4963
}
4964

    
4965
static SaveStateEntry *find_se(const char *idstr, int instance_id)
4966
{
4967
    SaveStateEntry *se;
4968

    
4969
    for(se = first_se; se != NULL; se = se->next) {
4970
        if (!strcmp(se->idstr, idstr) && 
4971
            instance_id == se->instance_id)
4972
            return se;
4973
    }
4974
    return NULL;
4975
}
4976

    
4977
int qemu_loadvm_state(QEMUFile *f)
4978
{
4979
    SaveStateEntry *se;
4980
    int len, ret, instance_id, record_len, version_id;
4981
    int64_t total_len, end_pos, cur_pos;
4982
    unsigned int v;
4983
    char idstr[256];
4984
    
4985
    v = qemu_get_be32(f);
4986
    if (v != QEMU_VM_FILE_MAGIC)
4987
        goto fail;
4988
    v = qemu_get_be32(f);
4989
    if (v != QEMU_VM_FILE_VERSION) {
4990
    fail:
4991
        ret = -1;
4992
        goto the_end;
4993
    }
4994
    total_len = qemu_get_be64(f);
4995
    end_pos = total_len + qemu_ftell(f);
4996
    for(;;) {
4997
        if (qemu_ftell(f) >= end_pos)
4998
            break;
4999
        len = qemu_get_byte(f);
5000
        qemu_get_buffer(f, idstr, len);
5001
        idstr[len] = '\0';
5002
        instance_id = qemu_get_be32(f);
5003
        version_id = qemu_get_be32(f);
5004
        record_len = qemu_get_be32(f);
5005
#if 0
5006
        printf("idstr=%s instance=0x%x version=%d len=%d\n", 
5007
               idstr, instance_id, version_id, record_len);
5008
#endif
5009
        cur_pos = qemu_ftell(f);
5010
        se = find_se(idstr, instance_id);
5011
        if (!se) {
5012
            fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
5013
                    instance_id, idstr);
5014
        } else {
5015
            ret = se->load_state(f, se->opaque, version_id);
5016
            if (ret < 0) {
5017
                fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
5018
                        instance_id, idstr);
5019
            }
5020
        }
5021
        /* always seek to exact end of record */
5022
        qemu_fseek(f, cur_pos + record_len, SEEK_SET);
5023
    }
5024
    ret = 0;
5025
 the_end:
5026
    return ret;
5027
}
5028

    
5029
/* device can contain snapshots */
5030
static int bdrv_can_snapshot(BlockDriverState *bs)
5031
{
5032
    return (bs &&
5033
            !bdrv_is_removable(bs) &&
5034
            !bdrv_is_read_only(bs));
5035
}
5036

    
5037
/* device must be snapshots in order to have a reliable snapshot */
5038
static int bdrv_has_snapshot(BlockDriverState *bs)
5039
{
5040
    return (bs &&
5041
            !bdrv_is_removable(bs) &&
5042
            !bdrv_is_read_only(bs));
5043
}
5044

    
5045
static BlockDriverState *get_bs_snapshots(void)
5046
{
5047
    BlockDriverState *bs;
5048
    int i;
5049

    
5050
    if (bs_snapshots)
5051
        return bs_snapshots;
5052
    for(i = 0; i <= MAX_DISKS; i++) {
5053
        bs = bs_table[i];
5054
        if (bdrv_can_snapshot(bs))
5055
            goto ok;
5056
    }
5057
    return NULL;
5058
 ok:
5059
    bs_snapshots = bs;
5060
    return bs;
5061
}
5062

    
5063
static int bdrv_snapshot_find(BlockDriverState *bs, QEMUSnapshotInfo *sn_info,
5064
                              const char *name)
5065
{
5066
    QEMUSnapshotInfo *sn_tab, *sn;
5067
    int nb_sns, i, ret;
5068
    
5069
    ret = -ENOENT;
5070
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5071
    if (nb_sns < 0)
5072
        return ret;
5073
    for(i = 0; i < nb_sns; i++) {
5074
        sn = &sn_tab[i];
5075
        if (!strcmp(sn->id_str, name) || !strcmp(sn->name, name)) {
5076
            *sn_info = *sn;
5077
            ret = 0;
5078
            break;
5079
        }
5080
    }
5081
    qemu_free(sn_tab);
5082
    return ret;
5083
}
5084

    
5085
void do_savevm(const char *name)
5086
{
5087
    BlockDriverState *bs, *bs1;
5088
    QEMUSnapshotInfo sn1, *sn = &sn1, old_sn1, *old_sn = &old_sn1;
5089
    int must_delete, ret, i;
5090
    BlockDriverInfo bdi1, *bdi = &bdi1;
5091
    QEMUFile *f;
5092
    int saved_vm_running;
5093
#ifdef _WIN32
5094
    struct _timeb tb;
5095
#else
5096
    struct timeval tv;
5097
#endif
5098

    
5099
    bs = get_bs_snapshots();
5100
    if (!bs) {
5101
        term_printf("No block device can accept snapshots\n");
5102
        return;
5103
    }
5104

    
5105
    /* ??? Should this occur after vm_stop?  */
5106
    qemu_aio_flush();
5107

    
5108
    saved_vm_running = vm_running;
5109
    vm_stop(0);
5110
    
5111
    must_delete = 0;
5112
    if (name) {
5113
        ret = bdrv_snapshot_find(bs, old_sn, name);
5114
        if (ret >= 0) {
5115
            must_delete = 1;
5116
        }
5117
    }
5118
    memset(sn, 0, sizeof(*sn));
5119
    if (must_delete) {
5120
        pstrcpy(sn->name, sizeof(sn->name), old_sn->name);
5121
        pstrcpy(sn->id_str, sizeof(sn->id_str), old_sn->id_str);
5122
    } else {
5123
        if (name)
5124
            pstrcpy(sn->name, sizeof(sn->name), name);
5125
    }
5126

    
5127
    /* fill auxiliary fields */
5128
#ifdef _WIN32
5129
    _ftime(&tb);
5130
    sn->date_sec = tb.time;
5131
    sn->date_nsec = tb.millitm * 1000000;
5132
#else
5133
    gettimeofday(&tv, NULL);
5134
    sn->date_sec = tv.tv_sec;
5135
    sn->date_nsec = tv.tv_usec * 1000;
5136
#endif
5137
    sn->vm_clock_nsec = qemu_get_clock(vm_clock);
5138
    
5139
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5140
        term_printf("Device %s does not support VM state snapshots\n",
5141
                    bdrv_get_device_name(bs));
5142
        goto the_end;
5143
    }
5144
    
5145
    /* save the VM state */
5146
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 1);
5147
    if (!f) {
5148
        term_printf("Could not open VM state file\n");
5149
        goto the_end;
5150
    }
5151
    ret = qemu_savevm_state(f);
5152
    sn->vm_state_size = qemu_ftell(f);
5153
    qemu_fclose(f);
5154
    if (ret < 0) {
5155
        term_printf("Error %d while writing VM\n", ret);
5156
        goto the_end;
5157
    }
5158
    
5159
    /* create the snapshots */
5160

    
5161
    for(i = 0; i < MAX_DISKS; i++) {
5162
        bs1 = bs_table[i];
5163
        if (bdrv_has_snapshot(bs1)) {
5164
            if (must_delete) {
5165
                ret = bdrv_snapshot_delete(bs1, old_sn->id_str);
5166
                if (ret < 0) {
5167
                    term_printf("Error while deleting snapshot on '%s'\n",
5168
                                bdrv_get_device_name(bs1));
5169
                }
5170
            }
5171
            ret = bdrv_snapshot_create(bs1, sn);
5172
            if (ret < 0) {
5173
                term_printf("Error while creating snapshot on '%s'\n",
5174
                            bdrv_get_device_name(bs1));
5175
            }
5176
        }
5177
    }
5178

    
5179
 the_end:
5180
    if (saved_vm_running)
5181
        vm_start();
5182
}
5183

    
5184
void do_loadvm(const char *name)
5185
{
5186
    BlockDriverState *bs, *bs1;
5187
    BlockDriverInfo bdi1, *bdi = &bdi1;
5188
    QEMUFile *f;
5189
    int i, ret;
5190
    int saved_vm_running;
5191

    
5192
    bs = get_bs_snapshots();
5193
    if (!bs) {
5194
        term_printf("No block device supports snapshots\n");
5195
        return;
5196
    }
5197
    
5198
    /* Flush all IO requests so they don't interfere with the new state.  */
5199
    qemu_aio_flush();
5200

    
5201
    saved_vm_running = vm_running;
5202
    vm_stop(0);
5203

    
5204
    for(i = 0; i <= MAX_DISKS; i++) {
5205
        bs1 = bs_table[i];
5206
        if (bdrv_has_snapshot(bs1)) {
5207
            ret = bdrv_snapshot_goto(bs1, name);
5208
            if (ret < 0) {
5209
                if (bs != bs1)
5210
                    term_printf("Warning: ");
5211
                switch(ret) {
5212
                case -ENOTSUP:
5213
                    term_printf("Snapshots not supported on device '%s'\n",
5214
                                bdrv_get_device_name(bs1));
5215
                    break;
5216
                case -ENOENT:
5217
                    term_printf("Could not find snapshot '%s' on device '%s'\n",
5218
                                name, bdrv_get_device_name(bs1));
5219
                    break;
5220
                default:
5221
                    term_printf("Error %d while activating snapshot on '%s'\n",
5222
                                ret, bdrv_get_device_name(bs1));
5223
                    break;
5224
                }
5225
                /* fatal on snapshot block device */
5226
                if (bs == bs1)
5227
                    goto the_end;
5228
            }
5229
        }
5230
    }
5231

    
5232
    if (bdrv_get_info(bs, bdi) < 0 || bdi->vm_state_offset <= 0) {
5233
        term_printf("Device %s does not support VM state snapshots\n",
5234
                    bdrv_get_device_name(bs));
5235
        return;
5236
    }
5237
    
5238
    /* restore the VM state */
5239
    f = qemu_fopen_bdrv(bs, bdi->vm_state_offset, 0);
5240
    if (!f) {
5241
        term_printf("Could not open VM state file\n");
5242
        goto the_end;
5243
    }
5244
    ret = qemu_loadvm_state(f);
5245
    qemu_fclose(f);
5246
    if (ret < 0) {
5247
        term_printf("Error %d while loading VM state\n", ret);
5248
    }
5249
 the_end:
5250
    if (saved_vm_running)
5251
        vm_start();
5252
}
5253

    
5254
void do_delvm(const char *name)
5255
{
5256
    BlockDriverState *bs, *bs1;
5257
    int i, ret;
5258

    
5259
    bs = get_bs_snapshots();
5260
    if (!bs) {
5261
        term_printf("No block device supports snapshots\n");
5262
        return;
5263
    }
5264
    
5265
    for(i = 0; i <= MAX_DISKS; i++) {
5266
        bs1 = bs_table[i];
5267
        if (bdrv_has_snapshot(bs1)) {
5268
            ret = bdrv_snapshot_delete(bs1, name);
5269
            if (ret < 0) {
5270
                if (ret == -ENOTSUP)
5271
                    term_printf("Snapshots not supported on device '%s'\n",
5272
                                bdrv_get_device_name(bs1));
5273
                else
5274
                    term_printf("Error %d while deleting snapshot on '%s'\n",
5275
                                ret, bdrv_get_device_name(bs1));
5276
            }
5277
        }
5278
    }
5279
}
5280

    
5281
void do_info_snapshots(void)
5282
{
5283
    BlockDriverState *bs, *bs1;
5284
    QEMUSnapshotInfo *sn_tab, *sn;
5285
    int nb_sns, i;
5286
    char buf[256];
5287

    
5288
    bs = get_bs_snapshots();
5289
    if (!bs) {
5290
        term_printf("No available block device supports snapshots\n");
5291
        return;
5292
    }
5293
    term_printf("Snapshot devices:");
5294
    for(i = 0; i <= MAX_DISKS; i++) {
5295
        bs1 = bs_table[i];
5296
        if (bdrv_has_snapshot(bs1)) {
5297
            if (bs == bs1)
5298
                term_printf(" %s", bdrv_get_device_name(bs1));
5299
        }
5300
    }
5301
    term_printf("\n");
5302

    
5303
    nb_sns = bdrv_snapshot_list(bs, &sn_tab);
5304
    if (nb_sns < 0) {
5305
        term_printf("bdrv_snapshot_list: error %d\n", nb_sns);
5306
        return;
5307
    }
5308
    term_printf("Snapshot list (from %s):\n", bdrv_get_device_name(bs));
5309
    term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), NULL));
5310
    for(i = 0; i < nb_sns; i++) {
5311
        sn = &sn_tab[i];
5312
        term_printf("%s\n", bdrv_snapshot_dump(buf, sizeof(buf), sn));
5313
    }
5314
    qemu_free(sn_tab);
5315
}
5316

    
5317
/***********************************************************/
5318
/* cpu save/restore */
5319

    
5320
#if defined(TARGET_I386)
5321

    
5322
static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
5323
{
5324
    qemu_put_be32(f, dt->selector);
5325
    qemu_put_betl(f, dt->base);
5326
    qemu_put_be32(f, dt->limit);
5327
    qemu_put_be32(f, dt->flags);
5328
}
5329

    
5330
static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
5331
{
5332
    dt->selector = qemu_get_be32(f);
5333
    dt->base = qemu_get_betl(f);
5334
    dt->limit = qemu_get_be32(f);
5335
    dt->flags = qemu_get_be32(f);
5336
}
5337

    
5338
void cpu_save(QEMUFile *f, void *opaque)
5339
{
5340
    CPUState *env = opaque;
5341
    uint16_t fptag, fpus, fpuc, fpregs_format;
5342
    uint32_t hflags;
5343
    int i;
5344
    
5345
    for(i = 0; i < CPU_NB_REGS; i++)
5346
        qemu_put_betls(f, &env->regs[i]);
5347
    qemu_put_betls(f, &env->eip);
5348
    qemu_put_betls(f, &env->eflags);
5349
    hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
5350
    qemu_put_be32s(f, &hflags);
5351
    
5352
    /* FPU */
5353
    fpuc = env->fpuc;
5354
    fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
5355
    fptag = 0;
5356
    for(i = 0; i < 8; i++) {
5357
        fptag |= ((!env->fptags[i]) << i);
5358
    }
5359
    
5360
    qemu_put_be16s(f, &fpuc);
5361
    qemu_put_be16s(f, &fpus);
5362
    qemu_put_be16s(f, &fptag);
5363

    
5364
#ifdef USE_X86LDOUBLE
5365
    fpregs_format = 0;
5366
#else
5367
    fpregs_format = 1;
5368
#endif
5369
    qemu_put_be16s(f, &fpregs_format);
5370
    
5371
    for(i = 0; i < 8; i++) {
5372
#ifdef USE_X86LDOUBLE
5373
        {
5374
            uint64_t mant;
5375
            uint16_t exp;
5376
            /* we save the real CPU data (in case of MMX usage only 'mant'
5377
               contains the MMX register */
5378
            cpu_get_fp80(&mant, &exp, env->fpregs[i].d);
5379
            qemu_put_be64(f, mant);
5380
            qemu_put_be16(f, exp);
5381
        }
5382
#else
5383
        /* if we use doubles for float emulation, we save the doubles to
5384
           avoid losing information in case of MMX usage. It can give
5385
           problems if the image is restored on a CPU where long
5386
           doubles are used instead. */
5387
        qemu_put_be64(f, env->fpregs[i].mmx.MMX_Q(0));
5388
#endif
5389
    }
5390

    
5391
    for(i = 0; i < 6; i++)
5392
        cpu_put_seg(f, &env->segs[i]);
5393
    cpu_put_seg(f, &env->ldt);
5394
    cpu_put_seg(f, &env->tr);
5395
    cpu_put_seg(f, &env->gdt);
5396
    cpu_put_seg(f, &env->idt);
5397
    
5398
    qemu_put_be32s(f, &env->sysenter_cs);
5399
    qemu_put_be32s(f, &env->sysenter_esp);
5400
    qemu_put_be32s(f, &env->sysenter_eip);
5401
    
5402
    qemu_put_betls(f, &env->cr[0]);
5403
    qemu_put_betls(f, &env->cr[2]);
5404
    qemu_put_betls(f, &env->cr[3]);
5405
    qemu_put_betls(f, &env->cr[4]);
5406
    
5407
    for(i = 0; i < 8; i++)
5408
        qemu_put_betls(f, &env->dr[i]);
5409

    
5410
    /* MMU */
5411
    qemu_put_be32s(f, &env->a20_mask);
5412

    
5413
    /* XMM */
5414
    qemu_put_be32s(f, &env->mxcsr);
5415
    for(i = 0; i < CPU_NB_REGS; i++) {
5416
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5417
        qemu_put_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5418
    }
5419

    
5420
#ifdef TARGET_X86_64
5421
    qemu_put_be64s(f, &env->efer);
5422
    qemu_put_be64s(f, &env->star);
5423
    qemu_put_be64s(f, &env->lstar);
5424
    qemu_put_be64s(f, &env->cstar);
5425
    qemu_put_be64s(f, &env->fmask);
5426
    qemu_put_be64s(f, &env->kernelgsbase);
5427
#endif
5428
    qemu_put_be32s(f, &env->smbase);
5429
}
5430

    
5431
#ifdef USE_X86LDOUBLE
5432
/* XXX: add that in a FPU generic layer */
5433
union x86_longdouble {
5434
    uint64_t mant;
5435
    uint16_t exp;
5436
};
5437

    
5438
#define MANTD1(fp)        (fp & ((1LL << 52) - 1))
5439
#define EXPBIAS1 1023
5440
#define EXPD1(fp)        ((fp >> 52) & 0x7FF)
5441
#define SIGND1(fp)        ((fp >> 32) & 0x80000000)
5442

    
5443
static void fp64_to_fp80(union x86_longdouble *p, uint64_t temp)
5444
{
5445
    int e;
5446
    /* mantissa */
5447
    p->mant = (MANTD1(temp) << 11) | (1LL << 63);
5448
    /* exponent + sign */
5449
    e = EXPD1(temp) - EXPBIAS1 + 16383;
5450
    e |= SIGND1(temp) >> 16;
5451
    p->exp = e;
5452
}
5453
#endif
5454

    
5455
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5456
{
5457
    CPUState *env = opaque;
5458
    int i, guess_mmx;
5459
    uint32_t hflags;
5460
    uint16_t fpus, fpuc, fptag, fpregs_format;
5461

    
5462
    if (version_id != 3 && version_id != 4)
5463
        return -EINVAL;
5464
    for(i = 0; i < CPU_NB_REGS; i++)
5465
        qemu_get_betls(f, &env->regs[i]);
5466
    qemu_get_betls(f, &env->eip);
5467
    qemu_get_betls(f, &env->eflags);
5468
    qemu_get_be32s(f, &hflags);
5469

    
5470
    qemu_get_be16s(f, &fpuc);
5471
    qemu_get_be16s(f, &fpus);
5472
    qemu_get_be16s(f, &fptag);
5473
    qemu_get_be16s(f, &fpregs_format);
5474
    
5475
    /* NOTE: we cannot always restore the FPU state if the image come
5476
       from a host with a different 'USE_X86LDOUBLE' define. We guess
5477
       if we are in an MMX state to restore correctly in that case. */
5478
    guess_mmx = ((fptag == 0xff) && (fpus & 0x3800) == 0);
5479
    for(i = 0; i < 8; i++) {
5480
        uint64_t mant;
5481
        uint16_t exp;
5482
        
5483
        switch(fpregs_format) {
5484
        case 0:
5485
            mant = qemu_get_be64(f);
5486
            exp = qemu_get_be16(f);
5487
#ifdef USE_X86LDOUBLE
5488
            env->fpregs[i].d = cpu_set_fp80(mant, exp);
5489
#else
5490
            /* difficult case */
5491
            if (guess_mmx)
5492
                env->fpregs[i].mmx.MMX_Q(0) = mant;
5493
            else
5494
                env->fpregs[i].d = cpu_set_fp80(mant, exp);
5495
#endif
5496
            break;
5497
        case 1:
5498
            mant = qemu_get_be64(f);
5499
#ifdef USE_X86LDOUBLE
5500
            {
5501
                union x86_longdouble *p;
5502
                /* difficult case */
5503
                p = (void *)&env->fpregs[i];
5504
                if (guess_mmx) {
5505
                    p->mant = mant;
5506
                    p->exp = 0xffff;
5507
                } else {
5508
                    fp64_to_fp80(p, mant);
5509
                }
5510
            }
5511
#else
5512
            env->fpregs[i].mmx.MMX_Q(0) = mant;
5513
#endif            
5514
            break;
5515
        default:
5516
            return -EINVAL;
5517
        }
5518
    }
5519

    
5520
    env->fpuc = fpuc;
5521
    /* XXX: restore FPU round state */
5522
    env->fpstt = (fpus >> 11) & 7;
5523
    env->fpus = fpus & ~0x3800;
5524
    fptag ^= 0xff;
5525
    for(i = 0; i < 8; i++) {
5526
        env->fptags[i] = (fptag >> i) & 1;
5527
    }
5528
    
5529
    for(i = 0; i < 6; i++)
5530
        cpu_get_seg(f, &env->segs[i]);
5531
    cpu_get_seg(f, &env->ldt);
5532
    cpu_get_seg(f, &env->tr);
5533
    cpu_get_seg(f, &env->gdt);
5534
    cpu_get_seg(f, &env->idt);
5535
    
5536
    qemu_get_be32s(f, &env->sysenter_cs);
5537
    qemu_get_be32s(f, &env->sysenter_esp);
5538
    qemu_get_be32s(f, &env->sysenter_eip);
5539
    
5540
    qemu_get_betls(f, &env->cr[0]);
5541
    qemu_get_betls(f, &env->cr[2]);
5542
    qemu_get_betls(f, &env->cr[3]);
5543
    qemu_get_betls(f, &env->cr[4]);
5544
    
5545
    for(i = 0; i < 8; i++)
5546
        qemu_get_betls(f, &env->dr[i]);
5547

    
5548
    /* MMU */
5549
    qemu_get_be32s(f, &env->a20_mask);
5550

    
5551
    qemu_get_be32s(f, &env->mxcsr);
5552
    for(i = 0; i < CPU_NB_REGS; i++) {
5553
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(0));
5554
        qemu_get_be64s(f, &env->xmm_regs[i].XMM_Q(1));
5555
    }
5556

    
5557
#ifdef TARGET_X86_64
5558
    qemu_get_be64s(f, &env->efer);
5559
    qemu_get_be64s(f, &env->star);
5560
    qemu_get_be64s(f, &env->lstar);
5561
    qemu_get_be64s(f, &env->cstar);
5562
    qemu_get_be64s(f, &env->fmask);
5563
    qemu_get_be64s(f, &env->kernelgsbase);
5564
#endif
5565
    if (version_id >= 4) 
5566
        qemu_get_be32s(f, &env->smbase);
5567

    
5568
    /* XXX: compute hflags from scratch, except for CPL and IIF */
5569
    env->hflags = hflags;
5570
    tlb_flush(env, 1);
5571
    return 0;
5572
}
5573

    
5574
#elif defined(TARGET_PPC)
5575
void cpu_save(QEMUFile *f, void *opaque)
5576
{
5577
}
5578

    
5579
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5580
{
5581
    return 0;
5582
}
5583

    
5584
#elif defined(TARGET_MIPS)
5585
void cpu_save(QEMUFile *f, void *opaque)
5586
{
5587
}
5588

    
5589
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5590
{
5591
    return 0;
5592
}
5593

    
5594
#elif defined(TARGET_SPARC)
5595
void cpu_save(QEMUFile *f, void *opaque)
5596
{
5597
    CPUState *env = opaque;
5598
    int i;
5599
    uint32_t tmp;
5600

    
5601
    for(i = 0; i < 8; i++)
5602
        qemu_put_betls(f, &env->gregs[i]);
5603
    for(i = 0; i < NWINDOWS * 16; i++)
5604
        qemu_put_betls(f, &env->regbase[i]);
5605

    
5606
    /* FPU */
5607
    for(i = 0; i < TARGET_FPREGS; i++) {
5608
        union {
5609
            float32 f;
5610
            uint32_t i;
5611
        } u;
5612
        u.f = env->fpr[i];
5613
        qemu_put_be32(f, u.i);
5614
    }
5615

    
5616
    qemu_put_betls(f, &env->pc);
5617
    qemu_put_betls(f, &env->npc);
5618
    qemu_put_betls(f, &env->y);
5619
    tmp = GET_PSR(env);
5620
    qemu_put_be32(f, tmp);
5621
    qemu_put_betls(f, &env->fsr);
5622
    qemu_put_betls(f, &env->tbr);
5623
#ifndef TARGET_SPARC64
5624
    qemu_put_be32s(f, &env->wim);
5625
    /* MMU */
5626
    for(i = 0; i < 16; i++)
5627
        qemu_put_be32s(f, &env->mmuregs[i]);
5628
#endif
5629
}
5630

    
5631
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5632
{
5633
    CPUState *env = opaque;
5634
    int i;
5635
    uint32_t tmp;
5636

    
5637
    for(i = 0; i < 8; i++)
5638
        qemu_get_betls(f, &env->gregs[i]);
5639
    for(i = 0; i < NWINDOWS * 16; i++)
5640
        qemu_get_betls(f, &env->regbase[i]);
5641

    
5642
    /* FPU */
5643
    for(i = 0; i < TARGET_FPREGS; i++) {
5644
        union {
5645
            float32 f;
5646
            uint32_t i;
5647
        } u;
5648
        u.i = qemu_get_be32(f);
5649
        env->fpr[i] = u.f;
5650
    }
5651

    
5652
    qemu_get_betls(f, &env->pc);
5653
    qemu_get_betls(f, &env->npc);
5654
    qemu_get_betls(f, &env->y);
5655
    tmp = qemu_get_be32(f);
5656
    env->cwp = 0; /* needed to ensure that the wrapping registers are
5657
                     correctly updated */
5658
    PUT_PSR(env, tmp);
5659
    qemu_get_betls(f, &env->fsr);
5660
    qemu_get_betls(f, &env->tbr);
5661
#ifndef TARGET_SPARC64
5662
    qemu_get_be32s(f, &env->wim);
5663
    /* MMU */
5664
    for(i = 0; i < 16; i++)
5665
        qemu_get_be32s(f, &env->mmuregs[i]);
5666
#endif
5667
    tlb_flush(env, 1);
5668
    return 0;
5669
}
5670

    
5671
#elif defined(TARGET_ARM)
5672

    
5673
/* ??? Need to implement these.  */
5674
void cpu_save(QEMUFile *f, void *opaque)
5675
{
5676
}
5677

    
5678
int cpu_load(QEMUFile *f, void *opaque, int version_id)
5679
{
5680
    return 0;
5681
}
5682

    
5683
#else
5684

    
5685
#warning No CPU save/restore functions
5686

    
5687
#endif
5688

    
5689
/***********************************************************/
5690
/* ram save/restore */
5691

    
5692
static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
5693
{
5694
    int v;
5695

    
5696
    v = qemu_get_byte(f);
5697
    switch(v) {
5698
    case 0:
5699
        if (qemu_get_buffer(f, buf, len) != len)
5700
            return -EIO;
5701
        break;
5702
    case 1:
5703
        v = qemu_get_byte(f);
5704
        memset(buf, v, len);
5705
        break;
5706
    default:
5707
        return -EINVAL;
5708
    }
5709
    return 0;
5710
}
5711

    
5712
static int ram_load_v1(QEMUFile *f, void *opaque)
5713
{
5714
    int i, ret;
5715

    
5716
    if (qemu_get_be32(f) != phys_ram_size)
5717
        return -EINVAL;
5718
    for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
5719
        ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
5720
        if (ret)
5721
            return ret;
5722
    }
5723
    return 0;
5724
}
5725

    
5726
#define BDRV_HASH_BLOCK_SIZE 1024
5727
#define IOBUF_SIZE 4096
5728
#define RAM_CBLOCK_MAGIC 0xfabe
5729

    
5730
typedef struct RamCompressState {
5731
    z_stream zstream;
5732
    QEMUFile *f;
5733
    uint8_t buf[IOBUF_SIZE];
5734
} RamCompressState;
5735

    
5736
static int ram_compress_open(RamCompressState *s, QEMUFile *f)
5737
{
5738
    int ret;
5739
    memset(s, 0, sizeof(*s));
5740
    s->f = f;
5741
    ret = deflateInit2(&s->zstream, 1,
5742
                       Z_DEFLATED, 15, 
5743
                       9, Z_DEFAULT_STRATEGY);
5744
    if (ret != Z_OK)
5745
        return -1;
5746
    s->zstream.avail_out = IOBUF_SIZE;
5747
    s->zstream.next_out = s->buf;
5748
    return 0;
5749
}
5750

    
5751
static void ram_put_cblock(RamCompressState *s, const uint8_t *buf, int len)
5752
{
5753
    qemu_put_be16(s->f, RAM_CBLOCK_MAGIC);
5754
    qemu_put_be16(s->f, len);
5755
    qemu_put_buffer(s->f, buf, len);
5756
}
5757

    
5758
static int ram_compress_buf(RamCompressState *s, const uint8_t *buf, int len)
5759
{
5760
    int ret;
5761

    
5762
    s->zstream.avail_in = len;
5763
    s->zstream.next_in = (uint8_t *)buf;
5764
    while (s->zstream.avail_in > 0) {
5765
        ret = deflate(&s->zstream, Z_NO_FLUSH);
5766
        if (ret != Z_OK)
5767
            return -1;
5768
        if (s->zstream.avail_out == 0) {
5769
            ram_put_cblock(s, s->buf, IOBUF_SIZE);
5770
            s->zstream.avail_out = IOBUF_SIZE;
5771
            s->zstream.next_out = s->buf;
5772
        }
5773
    }
5774
    return 0;
5775
}
5776

    
5777
static void ram_compress_close(RamCompressState *s)
5778
{
5779
    int len, ret;
5780

    
5781
    /* compress last bytes */
5782
    for(;;) {
5783
        ret = deflate(&s->zstream, Z_FINISH);
5784
        if (ret == Z_OK || ret == Z_STREAM_END) {
5785
            len = IOBUF_SIZE - s->zstream.avail_out;
5786
            if (len > 0) {
5787
                ram_put_cblock(s, s->buf, len);
5788
            }
5789
            s->zstream.avail_out = IOBUF_SIZE;
5790
            s->zstream.next_out = s->buf;
5791
            if (ret == Z_STREAM_END)
5792
                break;
5793
        } else {
5794
            goto fail;
5795
        }
5796
    }
5797
fail:
5798
    deflateEnd(&s->zstream);
5799
}
5800

    
5801
typedef struct RamDecompressState {
5802
    z_stream zstream;
5803
    QEMUFile *f;
5804
    uint8_t buf[IOBUF_SIZE];
5805
} RamDecompressState;
5806

    
5807
static int ram_decompress_open(RamDecompressState *s, QEMUFile *f)
5808
{
5809
    int ret;
5810
    memset(s, 0, sizeof(*s));
5811
    s->f = f;
5812
    ret = inflateInit(&s->zstream);
5813
    if (ret != Z_OK)
5814
        return -1;
5815
    return 0;
5816
}
5817

    
5818
static int ram_decompress_buf(RamDecompressState *s, uint8_t *buf, int len)
5819
{
5820
    int ret, clen;
5821

    
5822
    s->zstream.avail_out = len;
5823
    s->zstream.next_out = buf;
5824
    while (s->zstream.avail_out > 0) {
5825
        if (s->zstream.avail_in == 0) {
5826
            if (qemu_get_be16(s->f) != RAM_CBLOCK_MAGIC)
5827
                return -1;
5828
            clen = qemu_get_be16(s->f);
5829
            if (clen > IOBUF_SIZE)
5830
                return -1;
5831
            qemu_get_buffer(s->f, s->buf, clen);
5832
            s->zstream.avail_in = clen;
5833
            s->zstream.next_in = s->buf;
5834
        }
5835
        ret = inflate(&s->zstream, Z_PARTIAL_FLUSH);
5836
        if (ret != Z_OK && ret != Z_STREAM_END) {
5837
            return -1;
5838
        }
5839
    }
5840
    return 0;
5841
}
5842

    
5843
static void ram_decompress_close(RamDecompressState *s)
5844
{
5845
    inflateEnd(&s->zstream);
5846
}
5847

    
5848
static void ram_save(QEMUFile *f, void *opaque)
5849
{
5850
    int i;
5851
    RamCompressState s1, *s = &s1;
5852
    uint8_t buf[10];
5853
    
5854
    qemu_put_be32(f, phys_ram_size);
5855
    if (ram_compress_open(s, f) < 0)
5856
        return;
5857
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5858
#if 0
5859
        if (tight_savevm_enabled) {
5860
            int64_t sector_num;
5861
            int j;
5862

5863
            /* find if the memory block is available on a virtual
5864
               block device */
5865
            sector_num = -1;
5866
            for(j = 0; j < MAX_DISKS; j++) {
5867
                if (bs_table[j]) {
5868
                    sector_num = bdrv_hash_find(bs_table[j], 
5869
                                                phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5870
                    if (sector_num >= 0)
5871
                        break;
5872
                }
5873
            }
5874
            if (j == MAX_DISKS)
5875
                goto normal_compress;
5876
            buf[0] = 1;
5877
            buf[1] = j;
5878
            cpu_to_be64wu((uint64_t *)(buf + 2), sector_num);
5879
            ram_compress_buf(s, buf, 10);
5880
        } else 
5881
#endif
5882
        {
5883
            //        normal_compress:
5884
            buf[0] = 0;
5885
            ram_compress_buf(s, buf, 1);
5886
            ram_compress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE);
5887
        }
5888
    }
5889
    ram_compress_close(s);
5890
}
5891

    
5892
static int ram_load(QEMUFile *f, void *opaque, int version_id)
5893
{
5894
    RamDecompressState s1, *s = &s1;
5895
    uint8_t buf[10];
5896
    int i;
5897

    
5898
    if (version_id == 1)
5899
        return ram_load_v1(f, opaque);
5900
    if (version_id != 2)
5901
        return -EINVAL;
5902
    if (qemu_get_be32(f) != phys_ram_size)
5903
        return -EINVAL;
5904
    if (ram_decompress_open(s, f) < 0)
5905
        return -EINVAL;
5906
    for(i = 0; i < phys_ram_size; i+= BDRV_HASH_BLOCK_SIZE) {
5907
        if (ram_decompress_buf(s, buf, 1) < 0) {
5908
            fprintf(stderr, "Error while reading ram block header\n");
5909
            goto error;
5910
        }
5911
        if (buf[0] == 0) {
5912
            if (ram_decompress_buf(s, phys_ram_base + i, BDRV_HASH_BLOCK_SIZE) < 0) {
5913
                fprintf(stderr, "Error while reading ram block address=0x%08x", i);
5914
                goto error;
5915
            }
5916
        } else 
5917
#if 0
5918
        if (buf[0] == 1) {
5919
            int bs_index;
5920
            int64_t sector_num;
5921

5922
            ram_decompress_buf(s, buf + 1, 9);
5923
            bs_index = buf[1];
5924
            sector_num = be64_to_cpupu((const uint64_t *)(buf + 2));
5925
            if (bs_index >= MAX_DISKS || bs_table[bs_index] == NULL) {
5926
                fprintf(stderr, "Invalid block device index %d\n", bs_index);
5927
                goto error;
5928
            }
5929
            if (bdrv_read(bs_table[bs_index], sector_num, phys_ram_base + i, 
5930
                          BDRV_HASH_BLOCK_SIZE / 512) < 0) {
5931
                fprintf(stderr, "Error while reading sector %d:%" PRId64 "\n", 
5932
                        bs_index, sector_num);
5933
                goto error;
5934
            }
5935
        } else 
5936
#endif
5937
        {
5938
        error:
5939
            printf("Error block header\n");
5940
            return -EINVAL;
5941
        }
5942
    }
5943
    ram_decompress_close(s);
5944
    return 0;
5945
}
5946

    
5947
/***********************************************************/
5948
/* bottom halves (can be seen as timers which expire ASAP) */
5949

    
5950
struct QEMUBH {
5951
    QEMUBHFunc *cb;
5952
    void *opaque;
5953
    int scheduled;
5954
    QEMUBH *next;
5955
};
5956

    
5957
static QEMUBH *first_bh = NULL;
5958

    
5959
QEMUBH *qemu_bh_new(QEMUBHFunc *cb, void *opaque)
5960
{
5961
    QEMUBH *bh;
5962
    bh = qemu_mallocz(sizeof(QEMUBH));
5963
    if (!bh)
5964
        return NULL;
5965
    bh->cb = cb;
5966
    bh->opaque = opaque;
5967
    return bh;
5968
}
5969

    
5970
int qemu_bh_poll(void)
5971
{
5972
    QEMUBH *bh, **pbh;
5973
    int ret;
5974

    
5975
    ret = 0;
5976
    for(;;) {
5977
        pbh = &first_bh;
5978
        bh = *pbh;
5979
        if (!bh)
5980
            break;
5981
        ret = 1;
5982
        *pbh = bh->next;
5983
        bh->scheduled = 0;
5984
        bh->cb(bh->opaque);
5985
    }
5986
    return ret;
5987
}
5988

    
5989
void qemu_bh_schedule(QEMUBH *bh)
5990
{
5991
    CPUState *env = cpu_single_env;
5992
    if (bh->scheduled)
5993
        return;
5994
    bh->scheduled = 1;
5995
    bh->next = first_bh;
5996
    first_bh = bh;
5997

    
5998
    /* stop the currently executing CPU to execute the BH ASAP */
5999
    if (env) {
6000
        cpu_interrupt(env, CPU_INTERRUPT_EXIT);
6001
    }
6002
}
6003

    
6004
void qemu_bh_cancel(QEMUBH *bh)
6005
{
6006
    QEMUBH **pbh;
6007
    if (bh->scheduled) {
6008
        pbh = &first_bh;
6009
        while (*pbh != bh)
6010
            pbh = &(*pbh)->next;
6011
        *pbh = bh->next;
6012
        bh->scheduled = 0;
6013
    }
6014
}
6015

    
6016
void qemu_bh_delete(QEMUBH *bh)
6017
{
6018
    qemu_bh_cancel(bh);
6019
    qemu_free(bh);
6020
}
6021

    
6022
/***********************************************************/
6023
/* machine registration */
6024

    
6025
QEMUMachine *first_machine = NULL;
6026

    
6027
int qemu_register_machine(QEMUMachine *m)
6028
{
6029
    QEMUMachine **pm;
6030
    pm = &first_machine;
6031
    while (*pm != NULL)
6032
        pm = &(*pm)->next;
6033
    m->next = NULL;
6034
    *pm = m;
6035
    return 0;
6036
}
6037

    
6038
QEMUMachine *find_machine(const char *name)
6039
{
6040
    QEMUMachine *m;
6041

    
6042
    for(m = first_machine; m != NULL; m = m->next) {
6043
        if (!strcmp(m->name, name))
6044
            return m;
6045
    }
6046
    return NULL;
6047
}
6048

    
6049
/***********************************************************/
6050
/* main execution loop */
6051

    
6052
void gui_update(void *opaque)
6053
{
6054
    display_state.dpy_refresh(&display_state);
6055
    qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
6056
}
6057

    
6058
struct vm_change_state_entry {
6059
    VMChangeStateHandler *cb;
6060
    void *opaque;
6061
    LIST_ENTRY (vm_change_state_entry) entries;
6062
};
6063

    
6064
static LIST_HEAD(vm_change_state_head, vm_change_state_entry) vm_change_state_head;
6065

    
6066
VMChangeStateEntry *qemu_add_vm_change_state_handler(VMChangeStateHandler *cb,
6067
                                                     void *opaque)
6068
{
6069
    VMChangeStateEntry *e;
6070

    
6071
    e = qemu_mallocz(sizeof (*e));
6072
    if (!e)
6073
        return NULL;
6074

    
6075
    e->cb = cb;
6076
    e->opaque = opaque;
6077
    LIST_INSERT_HEAD(&vm_change_state_head, e, entries);
6078
    return e;
6079
}
6080

    
6081
void qemu_del_vm_change_state_handler(VMChangeStateEntry *e)
6082
{
6083
    LIST_REMOVE (e, entries);
6084
    qemu_free (e);
6085
}
6086

    
6087
static void vm_state_notify(int running)
6088
{
6089
    VMChangeStateEntry *e;
6090

    
6091
    for (e = vm_change_state_head.lh_first; e; e = e->entries.le_next) {
6092
        e->cb(e->opaque, running);
6093
    }
6094
}
6095

    
6096
/* XXX: support several handlers */
6097
static VMStopHandler *vm_stop_cb;
6098
static void *vm_stop_opaque;
6099

    
6100
int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
6101
{
6102
    vm_stop_cb = cb;
6103
    vm_stop_opaque = opaque;
6104
    return 0;
6105
}
6106

    
6107
void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
6108
{
6109
    vm_stop_cb = NULL;
6110
}
6111

    
6112
void vm_start(void)
6113
{
6114
    if (!vm_running) {
6115
        cpu_enable_ticks();
6116
        vm_running = 1;
6117
        vm_state_notify(1);
6118
    }
6119
}
6120

    
6121
void vm_stop(int reason) 
6122
{
6123
    if (vm_running) {
6124
        cpu_disable_ticks();
6125
        vm_running = 0;
6126
        if (reason != 0) {
6127
            if (vm_stop_cb) {
6128
                vm_stop_cb(vm_stop_opaque, reason);
6129
            }
6130
        }
6131
        vm_state_notify(0);
6132
    }
6133
}
6134

    
6135
/* reset/shutdown handler */
6136

    
6137
typedef struct QEMUResetEntry {
6138
    QEMUResetHandler *func;
6139
    void *opaque;
6140
    struct QEMUResetEntry *next;
6141
} QEMUResetEntry;
6142

    
6143
static QEMUResetEntry *first_reset_entry;
6144
static int reset_requested;
6145
static int shutdown_requested;
6146
static int powerdown_requested;
6147

    
6148
void qemu_register_reset(QEMUResetHandler *func, void *opaque)
6149
{
6150
    QEMUResetEntry **pre, *re;
6151

    
6152
    pre = &first_reset_entry;
6153
    while (*pre != NULL)
6154
        pre = &(*pre)->next;
6155
    re = qemu_mallocz(sizeof(QEMUResetEntry));
6156
    re->func = func;
6157
    re->opaque = opaque;
6158
    re->next = NULL;
6159
    *pre = re;
6160
}
6161

    
6162
static void qemu_system_reset(void)
6163
{
6164
    QEMUResetEntry *re;
6165

    
6166
    /* reset all devices */
6167
    for(re = first_reset_entry; re != NULL; re = re->next) {
6168
        re->func(re->opaque);
6169
    }
6170
}
6171

    
6172
void qemu_system_reset_request(void)
6173
{
6174
    if (no_reboot) {
6175
        shutdown_requested = 1;
6176
    } else {
6177
        reset_requested = 1;
6178
    }
6179
    if (cpu_single_env)
6180
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6181
}
6182

    
6183
void qemu_system_shutdown_request(void)
6184
{
6185
    shutdown_requested = 1;
6186
    if (cpu_single_env)
6187
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6188
}
6189

    
6190
void qemu_system_powerdown_request(void)
6191
{
6192
    powerdown_requested = 1;
6193
    if (cpu_single_env)
6194
        cpu_interrupt(cpu_single_env, CPU_INTERRUPT_EXIT);
6195
}
6196

    
6197
void main_loop_wait(int timeout)
6198
{
6199
    IOHandlerRecord *ioh;
6200
    fd_set rfds, wfds, xfds;
6201
    int ret, nfds;
6202
#ifdef _WIN32
6203
    int ret2, i;
6204
#endif
6205
    struct timeval tv;
6206
    PollingEntry *pe;
6207

    
6208

    
6209
    /* XXX: need to suppress polling by better using win32 events */
6210
    ret = 0;
6211
    for(pe = first_polling_entry; pe != NULL; pe = pe->next) {
6212
        ret |= pe->func(pe->opaque);
6213
    }
6214
#ifdef _WIN32
6215
    if (ret == 0) {
6216
        int err;
6217
        WaitObjects *w = &wait_objects;
6218
        
6219
        ret = WaitForMultipleObjects(w->num, w->events, FALSE, timeout);
6220
        if (WAIT_OBJECT_0 + 0 <= ret && ret <= WAIT_OBJECT_0 + w->num - 1) {
6221
            if (w->func[ret - WAIT_OBJECT_0])
6222
                w->func[ret - WAIT_OBJECT_0](w->opaque[ret - WAIT_OBJECT_0]);
6223
                
6224
            /* Check for additional signaled events */ 
6225
            for(i = (ret - WAIT_OBJECT_0 + 1); i < w->num; i++) {
6226
                                
6227
                /* Check if event is signaled */
6228
                ret2 = WaitForSingleObject(w->events[i], 0);
6229
                if(ret2 == WAIT_OBJECT_0) {
6230
                    if (w->func[i])
6231
                        w->func[i](w->opaque[i]);
6232
                } else if (ret2 == WAIT_TIMEOUT) {
6233
                } else {
6234
                    err = GetLastError();
6235
                    fprintf(stderr, "WaitForSingleObject error %d %d\n", i, err);
6236
                }                
6237
            }                 
6238
        } else if (ret == WAIT_TIMEOUT) {
6239
        } else {
6240
            err = GetLastError();
6241
            fprintf(stderr, "WaitForMultipleObjects error %d %d\n", ret, err);
6242
        }
6243
    }
6244
#endif
6245
    /* poll any events */
6246
    /* XXX: separate device handlers from system ones */
6247
    nfds = -1;
6248
    FD_ZERO(&rfds);
6249
    FD_ZERO(&wfds);
6250
    FD_ZERO(&xfds);
6251
    for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6252
        if (ioh->deleted)
6253
            continue;
6254
        if (ioh->fd_read &&
6255
            (!ioh->fd_read_poll ||
6256
             ioh->fd_read_poll(ioh->opaque) != 0)) {
6257
            FD_SET(ioh->fd, &rfds);
6258
            if (ioh->fd > nfds)
6259
                nfds = ioh->fd;
6260
        }
6261
        if (ioh->fd_write) {
6262
            FD_SET(ioh->fd, &wfds);
6263
            if (ioh->fd > nfds)
6264
                nfds = ioh->fd;
6265
        }
6266
    }
6267
    
6268
    tv.tv_sec = 0;
6269
#ifdef _WIN32
6270
    tv.tv_usec = 0;
6271
#else
6272
    tv.tv_usec = timeout * 1000;
6273
#endif
6274
#if defined(CONFIG_SLIRP)
6275
    if (slirp_inited) {
6276
        slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
6277
    }
6278
#endif
6279
    ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
6280
    if (ret > 0) {
6281
        IOHandlerRecord **pioh;
6282

    
6283
        for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
6284
            if (ioh->deleted)
6285
                continue;
6286
            if (FD_ISSET(ioh->fd, &rfds)) {
6287
                ioh->fd_read(ioh->opaque);
6288
            }
6289
            if (FD_ISSET(ioh->fd, &wfds)) {
6290
                ioh->fd_write(ioh->opaque);
6291
            }
6292
        }
6293

    
6294
        /* remove deleted IO handlers */
6295
        pioh = &first_io_handler;
6296
        while (*pioh) {
6297
            ioh = *pioh;
6298
            if (ioh->deleted) {
6299
                *pioh = ioh->next;
6300
                qemu_free(ioh);
6301
            } else 
6302
                pioh = &ioh->next;
6303
        }
6304
    }
6305
#if defined(CONFIG_SLIRP)
6306
    if (slirp_inited) {
6307
        if (ret < 0) {
6308
            FD_ZERO(&rfds);
6309
            FD_ZERO(&wfds);
6310
            FD_ZERO(&xfds);
6311
        }
6312
        slirp_select_poll(&rfds, &wfds, &xfds);
6313
    }
6314
#endif
6315
    qemu_aio_poll();
6316
    qemu_bh_poll();
6317

    
6318
    if (vm_running) {
6319
        qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
6320
                        qemu_get_clock(vm_clock));
6321
        /* run dma transfers, if any */
6322
        DMA_run();
6323
    }
6324
    
6325
    /* real time timers */
6326
    qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
6327
                    qemu_get_clock(rt_clock));
6328
}
6329

    
6330
static CPUState *cur_cpu;
6331

    
6332
int main_loop(void)
6333
{
6334
    int ret, timeout;
6335
#ifdef CONFIG_PROFILER
6336
    int64_t ti;
6337
#endif
6338
    CPUState *env;
6339

    
6340
    cur_cpu = first_cpu;
6341
    for(;;) {
6342
        if (vm_running) {
6343

    
6344
            env = cur_cpu;
6345
            for(;;) {
6346
                /* get next cpu */
6347
                env = env->next_cpu;
6348
                if (!env)
6349
                    env = first_cpu;
6350
#ifdef CONFIG_PROFILER
6351
                ti = profile_getclock();
6352
#endif
6353
                ret = cpu_exec(env);
6354
#ifdef CONFIG_PROFILER
6355
                qemu_time += profile_getclock() - ti;
6356
#endif
6357
                if (ret == EXCP_HLT) {
6358
                    /* Give the next CPU a chance to run.  */
6359
                    cur_cpu = env;
6360
                    continue;
6361
                }
6362
                if (ret != EXCP_HALTED)
6363
                    break;
6364
                /* all CPUs are halted ? */
6365
                if (env == cur_cpu)
6366
                    break;
6367
            }
6368
            cur_cpu = env;
6369

    
6370
            if (shutdown_requested) {
6371
                ret = EXCP_INTERRUPT;
6372
                break;
6373
            }
6374
            if (reset_requested) {
6375
                reset_requested = 0;
6376
                qemu_system_reset();
6377
                ret = EXCP_INTERRUPT;
6378
            }
6379
            if (powerdown_requested) {
6380
                powerdown_requested = 0;
6381
                qemu_system_powerdown();
6382
                ret = EXCP_INTERRUPT;
6383
            }
6384
            if (ret == EXCP_DEBUG) {
6385
                vm_stop(EXCP_DEBUG);
6386
            }
6387
            /* If all cpus are halted then wait until the next IRQ */
6388
            /* XXX: use timeout computed from timers */
6389
            if (ret == EXCP_HALTED)
6390
                timeout = 10;
6391
            else
6392
                timeout = 0;
6393
        } else {
6394
            timeout = 10;
6395
        }
6396
#ifdef CONFIG_PROFILER
6397
        ti = profile_getclock();
6398
#endif
6399
        main_loop_wait(timeout);
6400
#ifdef CONFIG_PROFILER
6401
        dev_time += profile_getclock() - ti;
6402
#endif
6403
    }
6404
    cpu_disable_ticks();
6405
    return ret;
6406
}
6407

    
6408
void help(void)
6409
{
6410
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2007 Fabrice Bellard\n"
6411
           "usage: %s [options] [disk_image]\n"
6412
           "\n"
6413
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
6414
           "\n"
6415
           "Standard options:\n"
6416
           "-M machine      select emulated machine (-M ? for list)\n"
6417
           "-cpu cpu        select CPU (-cpu ? for list)\n"
6418
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
6419
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
6420
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
6421
           "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
6422
           "-sd file        use 'file' as SecureDigital card image\n"
6423
           "-pflash file    use 'file' as a parallel flash image\n"
6424
           "-boot [a|c|d|n] boot on floppy (a), hard disk (c), CD-ROM (d), or network (n)\n"
6425
           "-snapshot       write to temporary files instead of disk image files\n"
6426
#ifdef CONFIG_SDL
6427
           "-no-frame       open SDL window without a frame and window decorations\n"
6428
           "-no-quit        disable SDL window close capability\n"
6429
#endif
6430
#ifdef TARGET_I386
6431
           "-no-fd-bootchk  disable boot signature checking for floppy disks\n"
6432
#endif
6433
           "-m megs         set virtual RAM size to megs MB [default=%d]\n"
6434
           "-smp n          set the number of CPUs to 'n' [default=1]\n"
6435
           "-nographic      disable graphical output and redirect serial I/Os to console\n"
6436
           "-portrait       rotate graphical output 90 deg left (only PXA LCD)\n"
6437
#ifndef _WIN32
6438
           "-k language     use keyboard layout (for example \"fr\" for French)\n"
6439
#endif
6440
#ifdef HAS_AUDIO
6441
           "-audio-help     print list of audio drivers and their options\n"
6442
           "-soundhw c1,... enable audio support\n"
6443
           "                and only specified sound cards (comma separated list)\n"
6444
           "                use -soundhw ? to get the list of supported cards\n"
6445
           "                use -soundhw all to enable all of them\n"
6446
#endif
6447
           "-localtime      set the real time clock to local time [default=utc]\n"
6448
           "-full-screen    start in full screen\n"
6449
#ifdef TARGET_I386
6450
           "-win2k-hack     use it when installing Windows 2000 to avoid a disk full bug\n"
6451
#endif
6452
           "-usb            enable the USB driver (will be the default soon)\n"
6453
           "-usbdevice name add the host or guest USB device 'name'\n"
6454
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
6455
           "-g WxH[xDEPTH]  Set the initial graphical resolution and depth\n"
6456
#endif
6457
           "-name string    set the name of the guest\n"
6458
           "\n"
6459
           "Network options:\n"
6460
           "-net nic[,vlan=n][,macaddr=addr][,model=type]\n"
6461
           "                create a new Network Interface Card and connect it to VLAN 'n'\n"
6462
#ifdef CONFIG_SLIRP
6463
           "-net user[,vlan=n][,hostname=host]\n"
6464
           "                connect the user mode network stack to VLAN 'n' and send\n"
6465
           "                hostname 'host' to DHCP clients\n"
6466
#endif
6467
#ifdef _WIN32
6468
           "-net tap[,vlan=n],ifname=name\n"
6469
           "                connect the host TAP network interface to VLAN 'n'\n"
6470
#else
6471
           "-net tap[,vlan=n][,fd=h][,ifname=name][,script=file]\n"
6472
           "                connect the host TAP network interface to VLAN 'n' and use\n"
6473
           "                the network script 'file' (default=%s);\n"
6474
           "                use 'script=no' to disable script execution;\n"
6475
           "                use 'fd=h' to connect to an already opened TAP interface\n"
6476
#endif
6477
           "-net socket[,vlan=n][,fd=h][,listen=[host]:port][,connect=host:port]\n"
6478
           "                connect the vlan 'n' to another VLAN using a socket connection\n"
6479
           "-net socket[,vlan=n][,fd=h][,mcast=maddr:port]\n"
6480
           "                connect the vlan 'n' to multicast maddr and port\n"
6481
           "-net none       use it alone to have zero network devices; if no -net option\n"
6482
           "                is provided, the default is '-net nic -net user'\n"
6483
           "\n"
6484
#ifdef CONFIG_SLIRP
6485
           "-tftp dir       allow tftp access to files in dir [-net user]\n"
6486
           "-bootp file     advertise file in BOOTP replies\n"
6487
#ifndef _WIN32
6488
           "-smb dir        allow SMB access to files in 'dir' [-net user]\n"
6489
#endif
6490
           "-redir [tcp|udp]:host-port:[guest-host]:guest-port\n"
6491
           "                redirect TCP or UDP connections from host to guest [-net user]\n"
6492
#endif
6493
           "\n"
6494
           "Linux boot specific:\n"
6495
           "-kernel bzImage use 'bzImage' as kernel image\n"
6496
           "-append cmdline use 'cmdline' as kernel command line\n"
6497
           "-initrd file    use 'file' as initial ram disk\n"
6498
           "\n"
6499
           "Debug/Expert options:\n"
6500
           "-monitor dev    redirect the monitor to char device 'dev'\n"
6501
           "-serial dev     redirect the serial port to char device 'dev'\n"
6502
           "-parallel dev   redirect the parallel port to char device 'dev'\n"
6503
           "-pidfile file   Write PID to 'file'\n"
6504
           "-S              freeze CPU at startup (use 'c' to start execution)\n"
6505
           "-s              wait gdb connection to port\n"
6506
           "-p port         set gdb connection port [default=%s]\n"
6507
           "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
6508
           "-hdachs c,h,s[,t]  force hard disk 0 physical geometry and the optional BIOS\n"
6509
           "                translation (t=none or lba) (usually qemu can guess them)\n"
6510
           "-L path         set the directory for the BIOS, VGA BIOS and keymaps\n"
6511
#ifdef USE_KQEMU
6512
           "-kernel-kqemu   enable KQEMU full virtualization (default is user mode only)\n"
6513
           "-no-kqemu       disable KQEMU kernel module usage\n"
6514
#endif
6515
#ifdef USE_CODE_COPY
6516
           "-no-code-copy   disable code copy acceleration\n"
6517
#endif
6518
#ifdef TARGET_I386
6519
           "-std-vga        simulate a standard VGA card with VESA Bochs Extensions\n"
6520
           "                (default is CL-GD5446 PCI VGA)\n"
6521
           "-no-acpi        disable ACPI\n"
6522
#endif
6523
           "-no-reboot      exit instead of rebooting\n"
6524
           "-loadvm file    start right away with a saved state (loadvm in monitor)\n"
6525
           "-vnc display    start a VNC server on display\n"
6526
#ifndef _WIN32
6527
           "-daemonize      daemonize QEMU after initializing\n"
6528
#endif
6529
           "-option-rom rom load a file, rom, into the option ROM space\n"
6530
           "\n"
6531
           "During emulation, the following keys are useful:\n"
6532
           "ctrl-alt-f      toggle full screen\n"
6533
           "ctrl-alt-n      switch to virtual console 'n'\n"
6534
           "ctrl-alt        toggle mouse and keyboard grab\n"
6535
           "\n"
6536
           "When using -nographic, press 'ctrl-a h' to get some help.\n"
6537
           ,
6538
           "qemu",
6539
           DEFAULT_RAM_SIZE,
6540
#ifndef _WIN32
6541
           DEFAULT_NETWORK_SCRIPT,
6542
#endif
6543
           DEFAULT_GDBSTUB_PORT,
6544
           "/tmp/qemu.log");
6545
    exit(1);
6546
}
6547

    
6548
#define HAS_ARG 0x0001
6549

    
6550
enum {
6551
    QEMU_OPTION_h,
6552

    
6553
    QEMU_OPTION_M,
6554
    QEMU_OPTION_cpu,
6555
    QEMU_OPTION_fda,
6556
    QEMU_OPTION_fdb,
6557
    QEMU_OPTION_hda,
6558
    QEMU_OPTION_hdb,
6559
    QEMU_OPTION_hdc,
6560
    QEMU_OPTION_hdd,
6561
    QEMU_OPTION_cdrom,
6562
    QEMU_OPTION_sd,
6563
    QEMU_OPTION_pflash,
6564
    QEMU_OPTION_boot,
6565
    QEMU_OPTION_snapshot,
6566
#ifdef TARGET_I386
6567
    QEMU_OPTION_no_fd_bootchk,
6568
#endif
6569
    QEMU_OPTION_m,
6570
    QEMU_OPTION_nographic,
6571
    QEMU_OPTION_portrait,
6572
#ifdef HAS_AUDIO
6573
    QEMU_OPTION_audio_help,
6574
    QEMU_OPTION_soundhw,
6575
#endif
6576

    
6577
    QEMU_OPTION_net,
6578
    QEMU_OPTION_tftp,
6579
    QEMU_OPTION_bootp,
6580
    QEMU_OPTION_smb,
6581
    QEMU_OPTION_redir,
6582

    
6583
    QEMU_OPTION_kernel,
6584
    QEMU_OPTION_append,
6585
    QEMU_OPTION_initrd,
6586

    
6587
    QEMU_OPTION_S,
6588
    QEMU_OPTION_s,
6589
    QEMU_OPTION_p,
6590
    QEMU_OPTION_d,
6591
    QEMU_OPTION_hdachs,
6592
    QEMU_OPTION_L,
6593
    QEMU_OPTION_no_code_copy,
6594
    QEMU_OPTION_k,
6595
    QEMU_OPTION_localtime,
6596
    QEMU_OPTION_cirrusvga,
6597
    QEMU_OPTION_vmsvga,
6598
    QEMU_OPTION_g,
6599
    QEMU_OPTION_std_vga,
6600
    QEMU_OPTION_echr,
6601
    QEMU_OPTION_monitor,
6602
    QEMU_OPTION_serial,
6603
    QEMU_OPTION_parallel,
6604
    QEMU_OPTION_loadvm,
6605
    QEMU_OPTION_full_screen,
6606
    QEMU_OPTION_no_frame,
6607
    QEMU_OPTION_no_quit,
6608
    QEMU_OPTION_pidfile,
6609
    QEMU_OPTION_no_kqemu,
6610
    QEMU_OPTION_kernel_kqemu,
6611
    QEMU_OPTION_win2k_hack,
6612
    QEMU_OPTION_usb,
6613
    QEMU_OPTION_usbdevice,
6614
    QEMU_OPTION_smp,
6615
    QEMU_OPTION_vnc,
6616
    QEMU_OPTION_no_acpi,
6617
    QEMU_OPTION_no_reboot,
6618
    QEMU_OPTION_daemonize,
6619
    QEMU_OPTION_option_rom,
6620
    QEMU_OPTION_semihosting,
6621
    QEMU_OPTION_name,
6622
};
6623

    
6624
typedef struct QEMUOption {
6625
    const char *name;
6626
    int flags;
6627
    int index;
6628
} QEMUOption;
6629

    
6630
const QEMUOption qemu_options[] = {
6631
    { "h", 0, QEMU_OPTION_h },
6632
    { "help", 0, QEMU_OPTION_h },
6633

    
6634
    { "M", HAS_ARG, QEMU_OPTION_M },
6635
    { "cpu", HAS_ARG, QEMU_OPTION_cpu },
6636
    { "fda", HAS_ARG, QEMU_OPTION_fda },
6637
    { "fdb", HAS_ARG, QEMU_OPTION_fdb },
6638
    { "hda", HAS_ARG, QEMU_OPTION_hda },
6639
    { "hdb", HAS_ARG, QEMU_OPTION_hdb },
6640
    { "hdc", HAS_ARG, QEMU_OPTION_hdc },
6641
    { "hdd", HAS_ARG, QEMU_OPTION_hdd },
6642
    { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
6643
    { "sd", HAS_ARG, QEMU_OPTION_sd },
6644
    { "pflash", HAS_ARG, QEMU_OPTION_pflash },
6645
    { "boot", HAS_ARG, QEMU_OPTION_boot },
6646
    { "snapshot", 0, QEMU_OPTION_snapshot },
6647
#ifdef TARGET_I386
6648
    { "no-fd-bootchk", 0, QEMU_OPTION_no_fd_bootchk },
6649
#endif
6650
    { "m", HAS_ARG, QEMU_OPTION_m },
6651
    { "nographic", 0, QEMU_OPTION_nographic },
6652
    { "portrait", 0, QEMU_OPTION_portrait },
6653
    { "k", HAS_ARG, QEMU_OPTION_k },
6654
#ifdef HAS_AUDIO
6655
    { "audio-help", 0, QEMU_OPTION_audio_help },
6656
    { "soundhw", HAS_ARG, QEMU_OPTION_soundhw },
6657
#endif
6658

    
6659
    { "net", HAS_ARG, QEMU_OPTION_net},
6660
#ifdef CONFIG_SLIRP
6661
    { "tftp", HAS_ARG, QEMU_OPTION_tftp },
6662
    { "bootp", HAS_ARG, QEMU_OPTION_bootp },
6663
#ifndef _WIN32
6664
    { "smb", HAS_ARG, QEMU_OPTION_smb },
6665
#endif
6666
    { "redir", HAS_ARG, QEMU_OPTION_redir },
6667
#endif
6668

    
6669
    { "kernel", HAS_ARG, QEMU_OPTION_kernel },
6670
    { "append", HAS_ARG, QEMU_OPTION_append },
6671
    { "initrd", HAS_ARG, QEMU_OPTION_initrd },
6672

    
6673
    { "S", 0, QEMU_OPTION_S },
6674
    { "s", 0, QEMU_OPTION_s },
6675
    { "p", HAS_ARG, QEMU_OPTION_p },
6676
    { "d", HAS_ARG, QEMU_OPTION_d },
6677
    { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
6678
    { "L", HAS_ARG, QEMU_OPTION_L },
6679
    { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
6680
#ifdef USE_KQEMU
6681
    { "no-kqemu", 0, QEMU_OPTION_no_kqemu },
6682
    { "kernel-kqemu", 0, QEMU_OPTION_kernel_kqemu },
6683
#endif
6684
#if defined(TARGET_PPC) || defined(TARGET_SPARC)
6685
    { "g", 1, QEMU_OPTION_g },
6686
#endif
6687
    { "localtime", 0, QEMU_OPTION_localtime },
6688
    { "std-vga", 0, QEMU_OPTION_std_vga },
6689
    { "echr", 1, QEMU_OPTION_echr },
6690
    { "monitor", 1, QEMU_OPTION_monitor },
6691
    { "serial", 1, QEMU_OPTION_serial },
6692
    { "parallel", 1, QEMU_OPTION_parallel },
6693
    { "loadvm", HAS_ARG, QEMU_OPTION_loadvm },
6694
    { "full-screen", 0, QEMU_OPTION_full_screen },
6695
#ifdef CONFIG_SDL
6696
    { "no-frame", 0, QEMU_OPTION_no_frame },
6697
    { "no-quit", 0, QEMU_OPTION_no_quit },
6698
#endif
6699
    { "pidfile", HAS_ARG, QEMU_OPTION_pidfile },
6700
    { "win2k-hack", 0, QEMU_OPTION_win2k_hack },
6701
    { "usbdevice", HAS_ARG, QEMU_OPTION_usbdevice },
6702
    { "smp", HAS_ARG, QEMU_OPTION_smp },
6703
    { "vnc", HAS_ARG, QEMU_OPTION_vnc },
6704

    
6705
    /* temporary options */
6706
    { "usb", 0, QEMU_OPTION_usb },
6707
    { "cirrusvga", 0, QEMU_OPTION_cirrusvga },
6708
    { "vmwarevga", 0, QEMU_OPTION_vmsvga },
6709
    { "no-acpi", 0, QEMU_OPTION_no_acpi },
6710
    { "no-reboot", 0, QEMU_OPTION_no_reboot },
6711
    { "daemonize", 0, QEMU_OPTION_daemonize },
6712
    { "option-rom", HAS_ARG, QEMU_OPTION_option_rom },
6713
#if defined(TARGET_ARM)
6714
    { "semihosting", 0, QEMU_OPTION_semihosting },
6715
#endif
6716
    { "name", HAS_ARG, QEMU_OPTION_name },
6717
    { NULL },
6718
};
6719

    
6720
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
6721

    
6722
/* this stack is only used during signal handling */
6723
#define SIGNAL_STACK_SIZE 32768
6724

    
6725
static uint8_t *signal_stack;
6726

    
6727
#endif
6728

    
6729
/* password input */
6730

    
6731
int qemu_key_check(BlockDriverState *bs, const char *name)
6732
{
6733
    char password[256];
6734
    int i;
6735

    
6736
    if (!bdrv_is_encrypted(bs))
6737
        return 0;
6738

    
6739
    term_printf("%s is encrypted.\n", name);
6740
    for(i = 0; i < 3; i++) {
6741
        monitor_readline("Password: ", 1, password, sizeof(password));
6742
        if (bdrv_set_key(bs, password) == 0)
6743
            return 0;
6744
        term_printf("invalid password\n");
6745
    }
6746
    return -EPERM;
6747
}
6748

    
6749
static BlockDriverState *get_bdrv(int index)
6750
{
6751
    BlockDriverState *bs;
6752

    
6753
    if (index < 4) {
6754
        bs = bs_table[index];
6755
    } else if (index < 6) {
6756
        bs = fd_table[index - 4];
6757
    } else {
6758
        bs = NULL;
6759
    }
6760
    return bs;
6761
}
6762

    
6763
static void read_passwords(void)
6764
{
6765
    BlockDriverState *bs;
6766
    int i;
6767

    
6768
    for(i = 0; i < 6; i++) {
6769
        bs = get_bdrv(i);
6770
        if (bs)
6771
            qemu_key_check(bs, bdrv_get_device_name(bs));
6772
    }
6773
}
6774

    
6775
/* XXX: currently we cannot use simultaneously different CPUs */
6776
void register_machines(void)
6777
{
6778
#if defined(TARGET_I386)
6779
    qemu_register_machine(&pc_machine);
6780
    qemu_register_machine(&isapc_machine);
6781
#elif defined(TARGET_PPC)
6782
    qemu_register_machine(&heathrow_machine);
6783
    qemu_register_machine(&core99_machine);
6784
    qemu_register_machine(&prep_machine);
6785
    qemu_register_machine(&ref405ep_machine);
6786
    qemu_register_machine(&taihu_machine);
6787
#elif defined(TARGET_MIPS)
6788
    qemu_register_machine(&mips_machine);
6789
    qemu_register_machine(&mips_malta_machine);
6790
    qemu_register_machine(&mips_pica61_machine);
6791
#elif defined(TARGET_SPARC)
6792
#ifdef TARGET_SPARC64
6793
    qemu_register_machine(&sun4u_machine);
6794
#else
6795
    qemu_register_machine(&ss5_machine);
6796
    qemu_register_machine(&ss10_machine);
6797
#endif
6798
#elif defined(TARGET_ARM)
6799
    qemu_register_machine(&integratorcp_machine);
6800
    qemu_register_machine(&versatilepb_machine);
6801
    qemu_register_machine(&versatileab_machine);
6802
    qemu_register_machine(&realview_machine);
6803
#elif defined(TARGET_SH4)
6804
    qemu_register_machine(&shix_machine);
6805
#elif defined(TARGET_ALPHA)
6806
    /* XXX: TODO */
6807
#else
6808
#error unsupported CPU
6809
#endif
6810
}
6811

    
6812
#ifdef HAS_AUDIO
6813
struct soundhw soundhw[] = {
6814
#ifdef TARGET_I386
6815
    {
6816
        "pcspk",
6817
        "PC speaker",
6818
        0,
6819
        1,
6820
        { .init_isa = pcspk_audio_init }
6821
    },
6822
#endif
6823
    {
6824
        "sb16",
6825
        "Creative Sound Blaster 16",
6826
        0,
6827
        1,
6828
        { .init_isa = SB16_init }
6829
    },
6830

    
6831
#ifdef CONFIG_ADLIB
6832
    {
6833
        "adlib",
6834
#ifdef HAS_YMF262
6835
        "Yamaha YMF262 (OPL3)",
6836
#else
6837
        "Yamaha YM3812 (OPL2)",
6838
#endif
6839
        0,
6840
        1,
6841
        { .init_isa = Adlib_init }
6842
    },
6843
#endif
6844

    
6845
#ifdef CONFIG_GUS
6846
    {
6847
        "gus",
6848
        "Gravis Ultrasound GF1",
6849
        0,
6850
        1,
6851
        { .init_isa = GUS_init }
6852
    },
6853
#endif
6854

    
6855
    {
6856
        "es1370",
6857
        "ENSONIQ AudioPCI ES1370",
6858
        0,
6859
        0,
6860
        { .init_pci = es1370_init }
6861
    },
6862

    
6863
    { NULL, NULL, 0, 0, { NULL } }
6864
};
6865

    
6866
static void select_soundhw (const char *optarg)
6867
{
6868
    struct soundhw *c;
6869

    
6870
    if (*optarg == '?') {
6871
    show_valid_cards:
6872

    
6873
        printf ("Valid sound card names (comma separated):\n");
6874
        for (c = soundhw; c->name; ++c) {
6875
            printf ("%-11s %s\n", c->name, c->descr);
6876
        }
6877
        printf ("\n-soundhw all will enable all of the above\n");
6878
        exit (*optarg != '?');
6879
    }
6880
    else {
6881
        size_t l;
6882
        const char *p;
6883
        char *e;
6884
        int bad_card = 0;
6885

    
6886
        if (!strcmp (optarg, "all")) {
6887
            for (c = soundhw; c->name; ++c) {
6888
                c->enabled = 1;
6889
            }
6890
            return;
6891
        }
6892

    
6893
        p = optarg;
6894
        while (*p) {
6895
            e = strchr (p, ',');
6896
            l = !e ? strlen (p) : (size_t) (e - p);
6897

    
6898
            for (c = soundhw; c->name; ++c) {
6899
                if (!strncmp (c->name, p, l)) {
6900
                    c->enabled = 1;
6901
                    break;
6902
                }
6903
            }
6904

    
6905
            if (!c->name) {
6906
                if (l > 80) {
6907
                    fprintf (stderr,
6908
                             "Unknown sound card name (too big to show)\n");
6909
                }
6910
                else {
6911
                    fprintf (stderr, "Unknown sound card name `%.*s'\n",
6912
                             (int) l, p);
6913
                }
6914
                bad_card = 1;
6915
            }
6916
            p += l + (e != NULL);
6917
        }
6918

    
6919
        if (bad_card)
6920
            goto show_valid_cards;
6921
    }
6922
}
6923
#endif
6924

    
6925
#ifdef _WIN32
6926
static BOOL WINAPI qemu_ctrl_handler(DWORD type)
6927
{
6928
    exit(STATUS_CONTROL_C_EXIT);
6929
    return TRUE;
6930
}
6931
#endif
6932

    
6933
#define MAX_NET_CLIENTS 32
6934

    
6935
int main(int argc, char **argv)
6936
{
6937
#ifdef CONFIG_GDBSTUB
6938
    int use_gdbstub;
6939
    const char *gdbstub_port;
6940
#endif
6941
    int i, cdrom_index, pflash_index;
6942
    int snapshot, linux_boot;
6943
    const char *initrd_filename;
6944
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
6945
    const char *pflash_filename[MAX_PFLASH];
6946
    const char *sd_filename;
6947
    const char *kernel_filename, *kernel_cmdline;
6948
    DisplayState *ds = &display_state;
6949
    int cyls, heads, secs, translation;
6950
    char net_clients[MAX_NET_CLIENTS][256];
6951
    int nb_net_clients;
6952
    int optind;
6953
    const char *r, *optarg;
6954
    CharDriverState *monitor_hd;
6955
    char monitor_device[128];
6956
    char serial_devices[MAX_SERIAL_PORTS][128];
6957
    int serial_device_index;
6958
    char parallel_devices[MAX_PARALLEL_PORTS][128];
6959
    int parallel_device_index;
6960
    const char *loadvm = NULL;
6961
    QEMUMachine *machine;
6962
    const char *cpu_model;
6963
    char usb_devices[MAX_USB_CMDLINE][128];
6964
    int usb_devices_index;
6965
    int fds[2];
6966
    const char *pid_file = NULL;
6967

    
6968
    LIST_INIT (&vm_change_state_head);
6969
#ifndef _WIN32
6970
    {
6971
        struct sigaction act;
6972
        sigfillset(&act.sa_mask);
6973
        act.sa_flags = 0;
6974
        act.sa_handler = SIG_IGN;
6975
        sigaction(SIGPIPE, &act, NULL);
6976
    }
6977
#else
6978
    SetConsoleCtrlHandler(qemu_ctrl_handler, TRUE);
6979
    /* Note: cpu_interrupt() is currently not SMP safe, so we force
6980
       QEMU to run on a single CPU */
6981
    {
6982
        HANDLE h;
6983
        DWORD mask, smask;
6984
        int i;
6985
        h = GetCurrentProcess();
6986
        if (GetProcessAffinityMask(h, &mask, &smask)) {
6987
            for(i = 0; i < 32; i++) {
6988
                if (mask & (1 << i))
6989
                    break;
6990
            }
6991
            if (i != 32) {
6992
                mask = 1 << i;
6993
                SetProcessAffinityMask(h, mask);
6994
            }
6995
        }
6996
    }
6997
#endif
6998

    
6999
    register_machines();
7000
    machine = first_machine;
7001
    cpu_model = NULL;
7002
    initrd_filename = NULL;
7003
    for(i = 0; i < MAX_FD; i++)
7004
        fd_filename[i] = NULL;
7005
    for(i = 0; i < MAX_DISKS; i++)
7006
        hd_filename[i] = NULL;
7007
    for(i = 0; i < MAX_PFLASH; i++)
7008
        pflash_filename[i] = NULL;
7009
    pflash_index = 0;
7010
    sd_filename = NULL;
7011
    ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
7012
    vga_ram_size = VGA_RAM_SIZE;
7013
#ifdef CONFIG_GDBSTUB
7014
    use_gdbstub = 0;
7015
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
7016
#endif
7017
    snapshot = 0;
7018
    nographic = 0;
7019
    kernel_filename = NULL;
7020
    kernel_cmdline = "";
7021
#ifdef TARGET_PPC
7022
    cdrom_index = 1;
7023
#else
7024
    cdrom_index = 2;
7025
#endif
7026
    cyls = heads = secs = 0;
7027
    translation = BIOS_ATA_TRANSLATION_AUTO;
7028
    pstrcpy(monitor_device, sizeof(monitor_device), "vc");
7029

    
7030
    pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "vc");
7031
    for(i = 1; i < MAX_SERIAL_PORTS; i++)
7032
        serial_devices[i][0] = '\0';
7033
    serial_device_index = 0;
7034
    
7035
    pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "vc");
7036
    for(i = 1; i < MAX_PARALLEL_PORTS; i++)
7037
        parallel_devices[i][0] = '\0';
7038
    parallel_device_index = 0;
7039
    
7040
    usb_devices_index = 0;
7041
    
7042
    nb_net_clients = 0;
7043

    
7044
    nb_nics = 0;
7045
    /* default mac address of the first network interface */
7046
    
7047
    optind = 1;
7048
    for(;;) {
7049
        if (optind >= argc)
7050
            break;
7051
        r = argv[optind];
7052
        if (r[0] != '-') {
7053
            hd_filename[0] = argv[optind++];
7054
        } else {
7055
            const QEMUOption *popt;
7056

    
7057
            optind++;
7058
            /* Treat --foo the same as -foo.  */
7059
            if (r[1] == '-')
7060
                r++;
7061
            popt = qemu_options;
7062
            for(;;) {
7063
                if (!popt->name) {
7064
                    fprintf(stderr, "%s: invalid option -- '%s'\n", 
7065
                            argv[0], r);
7066
                    exit(1);
7067
                }
7068
                if (!strcmp(popt->name, r + 1))
7069
                    break;
7070
                popt++;
7071
            }
7072
            if (popt->flags & HAS_ARG) {
7073
                if (optind >= argc) {
7074
                    fprintf(stderr, "%s: option '%s' requires an argument\n",
7075
                            argv[0], r);
7076
                    exit(1);
7077
                }
7078
                optarg = argv[optind++];
7079
            } else {
7080
                optarg = NULL;
7081
            }
7082

    
7083
            switch(popt->index) {
7084
            case QEMU_OPTION_M:
7085
                machine = find_machine(optarg);
7086
                if (!machine) {
7087
                    QEMUMachine *m;
7088
                    printf("Supported machines are:\n");
7089
                    for(m = first_machine; m != NULL; m = m->next) {
7090
                        printf("%-10s %s%s\n",
7091
                               m->name, m->desc, 
7092
                               m == first_machine ? " (default)" : "");
7093
                    }
7094
                    exit(1);
7095
                }
7096
                break;
7097
            case QEMU_OPTION_cpu:
7098
                /* hw initialization will check this */
7099
                if (optarg[0] == '?') {
7100
#if defined(TARGET_PPC)
7101
                    ppc_cpu_list(stdout, &fprintf);
7102
#elif defined(TARGET_ARM)
7103
                    arm_cpu_list();
7104
#elif defined(TARGET_MIPS)
7105
                    mips_cpu_list(stdout, &fprintf);
7106
#elif defined(TARGET_SPARC)
7107
                    sparc_cpu_list(stdout, &fprintf);
7108
#endif
7109
                    exit(1);
7110
                } else {
7111
                    cpu_model = optarg;
7112
                }
7113
                break;
7114
            case QEMU_OPTION_initrd:
7115
                initrd_filename = optarg;
7116
                break;
7117
            case QEMU_OPTION_hda:
7118
            case QEMU_OPTION_hdb:
7119
            case QEMU_OPTION_hdc:
7120
            case QEMU_OPTION_hdd:
7121
                {
7122
                    int hd_index;
7123
                    hd_index = popt->index - QEMU_OPTION_hda;
7124
                    hd_filename[hd_index] = optarg;
7125
                    if (hd_index == cdrom_index)
7126
                        cdrom_index = -1;
7127
                }
7128
                break;
7129
            case QEMU_OPTION_sd:
7130
                sd_filename = optarg;
7131
                break;
7132
            case QEMU_OPTION_pflash:
7133
                if (pflash_index >= MAX_PFLASH) {
7134
                    fprintf(stderr, "qemu: too many parallel flash images\n");
7135
                    exit(1);
7136
                }
7137
                pflash_filename[pflash_index++] = optarg;
7138
                break;
7139
            case QEMU_OPTION_snapshot:
7140
                snapshot = 1;
7141
                break;
7142
            case QEMU_OPTION_hdachs:
7143
                {
7144
                    const char *p;
7145
                    p = optarg;
7146
                    cyls = strtol(p, (char **)&p, 0);
7147
                    if (cyls < 1 || cyls > 16383)
7148
                        goto chs_fail;
7149
                    if (*p != ',')
7150
                        goto chs_fail;
7151
                    p++;
7152
                    heads = strtol(p, (char **)&p, 0);
7153
                    if (heads < 1 || heads > 16)
7154
                        goto chs_fail;
7155
                    if (*p != ',')
7156
                        goto chs_fail;
7157
                    p++;
7158
                    secs = strtol(p, (char **)&p, 0);
7159
                    if (secs < 1 || secs > 63)
7160
                        goto chs_fail;
7161
                    if (*p == ',') {
7162
                        p++;
7163
                        if (!strcmp(p, "none"))
7164
                            translation = BIOS_ATA_TRANSLATION_NONE;
7165
                        else if (!strcmp(p, "lba"))
7166
                            translation = BIOS_ATA_TRANSLATION_LBA;
7167
                        else if (!strcmp(p, "auto"))
7168
                            translation = BIOS_ATA_TRANSLATION_AUTO;
7169
                        else
7170
                            goto chs_fail;
7171
                    } else if (*p != '\0') {
7172
                    chs_fail:
7173
                        fprintf(stderr, "qemu: invalid physical CHS format\n");
7174
                        exit(1);
7175
                    }
7176
                }
7177
                break;
7178
            case QEMU_OPTION_nographic:
7179
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "stdio");
7180
                pstrcpy(parallel_devices[0], sizeof(parallel_devices[0]), "null");
7181
                pstrcpy(monitor_device, sizeof(monitor_device), "stdio");
7182
                nographic = 1;
7183
                break;
7184
            case QEMU_OPTION_portrait:
7185
                graphic_rotate = 1;
7186
                break;
7187
            case QEMU_OPTION_kernel:
7188
                kernel_filename = optarg;
7189
                break;
7190
            case QEMU_OPTION_append:
7191
                kernel_cmdline = optarg;
7192
                break;
7193
            case QEMU_OPTION_cdrom:
7194
                if (cdrom_index >= 0) {
7195
                    hd_filename[cdrom_index] = optarg;
7196
                }
7197
                break;
7198
            case QEMU_OPTION_boot:
7199
                boot_device = optarg[0];
7200
                if (boot_device != 'a' && 
7201
#if defined(TARGET_SPARC) || defined(TARGET_I386)
7202
                    // Network boot
7203
                    boot_device != 'n' &&
7204
#endif
7205
                    boot_device != 'c' && boot_device != 'd') {
7206
                    fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
7207
                    exit(1);
7208
                }
7209
                break;
7210
            case QEMU_OPTION_fda:
7211
                fd_filename[0] = optarg;
7212
                break;
7213
            case QEMU_OPTION_fdb:
7214
                fd_filename[1] = optarg;
7215
                break;
7216
#ifdef TARGET_I386
7217
            case QEMU_OPTION_no_fd_bootchk:
7218
                fd_bootchk = 0;
7219
                break;
7220
#endif
7221
            case QEMU_OPTION_no_code_copy:
7222
                code_copy_enabled = 0;
7223
                break;
7224
            case QEMU_OPTION_net:
7225
                if (nb_net_clients >= MAX_NET_CLIENTS) {
7226
                    fprintf(stderr, "qemu: too many network clients\n");
7227
                    exit(1);
7228
                }
7229
                pstrcpy(net_clients[nb_net_clients],
7230
                        sizeof(net_clients[0]),
7231
                        optarg);
7232
                nb_net_clients++;
7233
                break;
7234
#ifdef CONFIG_SLIRP
7235
            case QEMU_OPTION_tftp:
7236
                tftp_prefix = optarg;
7237
                break;
7238
            case QEMU_OPTION_bootp:
7239
                bootp_filename = optarg;
7240
                break;
7241
#ifndef _WIN32
7242
            case QEMU_OPTION_smb:
7243
                net_slirp_smb(optarg);
7244
                break;
7245
#endif
7246
            case QEMU_OPTION_redir:
7247
                net_slirp_redir(optarg);                
7248
                break;
7249
#endif
7250
#ifdef HAS_AUDIO
7251
            case QEMU_OPTION_audio_help:
7252
                AUD_help ();
7253
                exit (0);
7254
                break;
7255
            case QEMU_OPTION_soundhw:
7256
                select_soundhw (optarg);
7257
                break;
7258
#endif
7259
            case QEMU_OPTION_h:
7260
                help();
7261
                break;
7262
            case QEMU_OPTION_m:
7263
                ram_size = atoi(optarg) * 1024 * 1024;
7264
                if (ram_size <= 0)
7265
                    help();
7266
                if (ram_size > PHYS_RAM_MAX_SIZE) {
7267
                    fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
7268
                            PHYS_RAM_MAX_SIZE / (1024 * 1024));
7269
                    exit(1);
7270
                }
7271
                break;
7272
            case QEMU_OPTION_d:
7273
                {
7274
                    int mask;
7275
                    CPULogItem *item;
7276
                    
7277
                    mask = cpu_str_to_log_mask(optarg);
7278
                    if (!mask) {
7279
                        printf("Log items (comma separated):\n");
7280
                    for(item = cpu_log_items; item->mask != 0; item++) {
7281
                        printf("%-10s %s\n", item->name, item->help);
7282
                    }
7283
                    exit(1);
7284
                    }
7285
                    cpu_set_log(mask);
7286
                }
7287
                break;
7288
#ifdef CONFIG_GDBSTUB
7289
            case QEMU_OPTION_s:
7290
                use_gdbstub = 1;
7291
                break;
7292
            case QEMU_OPTION_p:
7293
                gdbstub_port = optarg;
7294
                break;
7295
#endif
7296
            case QEMU_OPTION_L:
7297
                bios_dir = optarg;
7298
                break;
7299
            case QEMU_OPTION_S:
7300
                autostart = 0;
7301
                break;
7302
            case QEMU_OPTION_k:
7303
                keyboard_layout = optarg;
7304
                break;
7305
            case QEMU_OPTION_localtime:
7306
                rtc_utc = 0;
7307
                break;
7308
            case QEMU_OPTION_cirrusvga:
7309
                cirrus_vga_enabled = 1;
7310
                vmsvga_enabled = 0;
7311
                break;
7312
            case QEMU_OPTION_vmsvga:
7313
                cirrus_vga_enabled = 0;
7314
                vmsvga_enabled = 1;
7315
                break;
7316
            case QEMU_OPTION_std_vga:
7317
                cirrus_vga_enabled = 0;
7318
                vmsvga_enabled = 0;
7319
                break;
7320
            case QEMU_OPTION_g:
7321
                {
7322
                    const char *p;
7323
                    int w, h, depth;
7324
                    p = optarg;
7325
                    w = strtol(p, (char **)&p, 10);
7326
                    if (w <= 0) {
7327
                    graphic_error:
7328
                        fprintf(stderr, "qemu: invalid resolution or depth\n");
7329
                        exit(1);
7330
                    }
7331
                    if (*p != 'x')
7332
                        goto graphic_error;
7333
                    p++;
7334
                    h = strtol(p, (char **)&p, 10);
7335
                    if (h <= 0)
7336
                        goto graphic_error;
7337
                    if (*p == 'x') {
7338
                        p++;
7339
                        depth = strtol(p, (char **)&p, 10);
7340
                        if (depth != 8 && depth != 15 && depth != 16 && 
7341
                            depth != 24 && depth != 32)
7342
                            goto graphic_error;
7343
                    } else if (*p == '\0') {
7344
                        depth = graphic_depth;
7345
                    } else {
7346
                        goto graphic_error;
7347
                    }
7348
                    
7349
                    graphic_width = w;
7350
                    graphic_height = h;
7351
                    graphic_depth = depth;
7352
                }
7353
                break;
7354
            case QEMU_OPTION_echr:
7355
                {
7356
                    char *r;
7357
                    term_escape_char = strtol(optarg, &r, 0);
7358
                    if (r == optarg)
7359
                        printf("Bad argument to echr\n");
7360
                    break;
7361
                }
7362
            case QEMU_OPTION_monitor:
7363
                pstrcpy(monitor_device, sizeof(monitor_device), optarg);
7364
                break;
7365
            case QEMU_OPTION_serial:
7366
                if (serial_device_index >= MAX_SERIAL_PORTS) {
7367
                    fprintf(stderr, "qemu: too many serial ports\n");
7368
                    exit(1);
7369
                }
7370
                pstrcpy(serial_devices[serial_device_index], 
7371
                        sizeof(serial_devices[0]), optarg);
7372
                serial_device_index++;
7373
                break;
7374
            case QEMU_OPTION_parallel:
7375
                if (parallel_device_index >= MAX_PARALLEL_PORTS) {
7376
                    fprintf(stderr, "qemu: too many parallel ports\n");
7377
                    exit(1);
7378
                }
7379
                pstrcpy(parallel_devices[parallel_device_index], 
7380
                        sizeof(parallel_devices[0]), optarg);
7381
                parallel_device_index++;
7382
                break;
7383
            case QEMU_OPTION_loadvm:
7384
                loadvm = optarg;
7385
                break;
7386
            case QEMU_OPTION_full_screen:
7387
                full_screen = 1;
7388
                break;
7389
#ifdef CONFIG_SDL
7390
            case QEMU_OPTION_no_frame:
7391
                no_frame = 1;
7392
                break;
7393
            case QEMU_OPTION_no_quit:
7394
                no_quit = 1;
7395
                break;
7396
#endif
7397
            case QEMU_OPTION_pidfile:
7398
                pid_file = optarg;
7399
                break;
7400
#ifdef TARGET_I386
7401
            case QEMU_OPTION_win2k_hack:
7402
                win2k_install_hack = 1;
7403
                break;
7404
#endif
7405
#ifdef USE_KQEMU
7406
            case QEMU_OPTION_no_kqemu:
7407
                kqemu_allowed = 0;
7408
                break;
7409
            case QEMU_OPTION_kernel_kqemu:
7410
                kqemu_allowed = 2;
7411
                break;
7412
#endif
7413
            case QEMU_OPTION_usb:
7414
                usb_enabled = 1;
7415
                break;
7416
            case QEMU_OPTION_usbdevice:
7417
                usb_enabled = 1;
7418
                if (usb_devices_index >= MAX_USB_CMDLINE) {
7419
                    fprintf(stderr, "Too many USB devices\n");
7420
                    exit(1);
7421
                }
7422
                pstrcpy(usb_devices[usb_devices_index],
7423
                        sizeof(usb_devices[usb_devices_index]),
7424
                        optarg);
7425
                usb_devices_index++;
7426
                break;
7427
            case QEMU_OPTION_smp:
7428
                smp_cpus = atoi(optarg);
7429
                if (smp_cpus < 1 || smp_cpus > MAX_CPUS) {
7430
                    fprintf(stderr, "Invalid number of CPUs\n");
7431
                    exit(1);
7432
                }
7433
                break;
7434
            case QEMU_OPTION_vnc:
7435
                vnc_display = optarg;
7436
                break;
7437
            case QEMU_OPTION_no_acpi:
7438
                acpi_enabled = 0;
7439
                break;
7440
            case QEMU_OPTION_no_reboot:
7441
                no_reboot = 1;
7442
                break;
7443
            case QEMU_OPTION_daemonize:
7444
                daemonize = 1;
7445
                break;
7446
            case QEMU_OPTION_option_rom:
7447
                if (nb_option_roms >= MAX_OPTION_ROMS) {
7448
                    fprintf(stderr, "Too many option ROMs\n");
7449
                    exit(1);
7450
                }
7451
                option_rom[nb_option_roms] = optarg;
7452
                nb_option_roms++;
7453
                break;
7454
            case QEMU_OPTION_semihosting:
7455
                semihosting_enabled = 1;
7456
                break;
7457
            case QEMU_OPTION_name:
7458
                qemu_name = optarg;
7459
                break;
7460
            }
7461
        }
7462
    }
7463

    
7464
#ifndef _WIN32
7465
    if (daemonize && !nographic && vnc_display == NULL) {
7466
        fprintf(stderr, "Can only daemonize if using -nographic or -vnc\n");
7467
        daemonize = 0;
7468
    }
7469

    
7470
    if (daemonize) {
7471
        pid_t pid;
7472

    
7473
        if (pipe(fds) == -1)
7474
            exit(1);
7475

    
7476
        pid = fork();
7477
        if (pid > 0) {
7478
            uint8_t status;
7479
            ssize_t len;
7480

    
7481
            close(fds[1]);
7482

    
7483
        again:
7484
            len = read(fds[0], &status, 1);
7485
            if (len == -1 && (errno == EINTR))
7486
                goto again;
7487

    
7488
            if (len != 1)
7489
                exit(1);
7490
            else if (status == 1) {
7491
                fprintf(stderr, "Could not acquire pidfile\n");
7492
                exit(1);
7493
            } else
7494
                exit(0);
7495
        } else if (pid < 0)
7496
            exit(1);
7497

    
7498
        setsid();
7499

    
7500
        pid = fork();
7501
        if (pid > 0)
7502
            exit(0);
7503
        else if (pid < 0)
7504
            exit(1);
7505

    
7506
        umask(027);
7507
        chdir("/");
7508

    
7509
        signal(SIGTSTP, SIG_IGN);
7510
        signal(SIGTTOU, SIG_IGN);
7511
        signal(SIGTTIN, SIG_IGN);
7512
    }
7513
#endif
7514

    
7515
    if (pid_file && qemu_create_pidfile(pid_file) != 0) {
7516
        if (daemonize) {
7517
            uint8_t status = 1;
7518
            write(fds[1], &status, 1);
7519
        } else
7520
            fprintf(stderr, "Could not acquire pid file\n");
7521
        exit(1);
7522
    }
7523

    
7524
#ifdef USE_KQEMU
7525
    if (smp_cpus > 1)
7526
        kqemu_allowed = 0;
7527
#endif
7528
    linux_boot = (kernel_filename != NULL);
7529

    
7530
    if (!linux_boot &&
7531
        boot_device != 'n' &&
7532
        hd_filename[0] == '\0' && 
7533
        (cdrom_index >= 0 && hd_filename[cdrom_index] == '\0') &&
7534
        fd_filename[0] == '\0')
7535
        help();
7536

    
7537
    /* boot to floppy or the default cd if no hard disk defined yet */
7538
    if (hd_filename[0] == '\0' && boot_device == 'c') {
7539
        if (fd_filename[0] != '\0')
7540
            boot_device = 'a';
7541
        else
7542
            boot_device = 'd';
7543
    }
7544

    
7545
    setvbuf(stdout, NULL, _IOLBF, 0);
7546
    
7547
    init_timers();
7548
    init_timer_alarm();
7549
    qemu_aio_init();
7550

    
7551
#ifdef _WIN32
7552
    socket_init();
7553
#endif
7554

    
7555
    /* init network clients */
7556
    if (nb_net_clients == 0) {
7557
        /* if no clients, we use a default config */
7558
        pstrcpy(net_clients[0], sizeof(net_clients[0]),
7559
                "nic");
7560
        pstrcpy(net_clients[1], sizeof(net_clients[0]),
7561
                "user");
7562
        nb_net_clients = 2;
7563
    }
7564

    
7565
    for(i = 0;i < nb_net_clients; i++) {
7566
        if (net_client_init(net_clients[i]) < 0)
7567
            exit(1);
7568
    }
7569

    
7570
#ifdef TARGET_I386
7571
    if (boot_device == 'n') {
7572
        for (i = 0; i < nb_nics; i++) {
7573
            const char *model = nd_table[i].model;
7574
            char buf[1024];
7575
            if (model == NULL)
7576
                model = "ne2k_pci";
7577
            snprintf(buf, sizeof(buf), "%s/pxe-%s.bin", bios_dir, model);
7578
            if (get_image_size(buf) > 0) {
7579
                option_rom[nb_option_roms] = strdup(buf);
7580
                nb_option_roms++;
7581
                break;
7582
            }
7583
        }
7584
        if (i == nb_nics) {
7585
            fprintf(stderr, "No valid PXE rom found for network device\n");
7586
            exit(1);
7587
        }
7588
        boot_device = 'c'; /* to prevent confusion by the BIOS */
7589
    }
7590
#endif
7591

    
7592
    /* init the memory */
7593
    phys_ram_size = ram_size + vga_ram_size + MAX_BIOS_SIZE;
7594

    
7595
    phys_ram_base = qemu_vmalloc(phys_ram_size);
7596
    if (!phys_ram_base) {
7597
        fprintf(stderr, "Could not allocate physical memory\n");
7598
        exit(1);
7599
    }
7600

    
7601
    /* we always create the cdrom drive, even if no disk is there */
7602
    bdrv_init();
7603
    if (cdrom_index >= 0) {
7604
        bs_table[cdrom_index] = bdrv_new("cdrom");
7605
        bdrv_set_type_hint(bs_table[cdrom_index], BDRV_TYPE_CDROM);
7606
    }
7607

    
7608
    /* open the virtual block devices */
7609
    for(i = 0; i < MAX_DISKS; i++) {
7610
        if (hd_filename[i]) {
7611
            if (!bs_table[i]) {
7612
                char buf[64];
7613
                snprintf(buf, sizeof(buf), "hd%c", i + 'a');
7614
                bs_table[i] = bdrv_new(buf);
7615
            }
7616
            if (bdrv_open(bs_table[i], hd_filename[i], snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7617
                fprintf(stderr, "qemu: could not open hard disk image '%s'\n",
7618
                        hd_filename[i]);
7619
                exit(1);
7620
            }
7621
            if (i == 0 && cyls != 0) {
7622
                bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
7623
                bdrv_set_translation_hint(bs_table[i], translation);
7624
            }
7625
        }
7626
    }
7627

    
7628
    /* we always create at least one floppy disk */
7629
    fd_table[0] = bdrv_new("fda");
7630
    bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
7631

    
7632
    for(i = 0; i < MAX_FD; i++) {
7633
        if (fd_filename[i]) {
7634
            if (!fd_table[i]) {
7635
                char buf[64];
7636
                snprintf(buf, sizeof(buf), "fd%c", i + 'a');
7637
                fd_table[i] = bdrv_new(buf);
7638
                bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
7639
            }
7640
            if (fd_filename[i][0] != '\0') {
7641
                if (bdrv_open(fd_table[i], fd_filename[i],
7642
                              snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7643
                    fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
7644
                            fd_filename[i]);
7645
                    exit(1);
7646
                }
7647
            }
7648
        }
7649
    }
7650

    
7651
    /* Open the virtual parallel flash block devices */
7652
    for(i = 0; i < MAX_PFLASH; i++) {
7653
        if (pflash_filename[i]) {
7654
            if (!pflash_table[i]) {
7655
                char buf[64];
7656
                snprintf(buf, sizeof(buf), "fl%c", i + 'a');
7657
                pflash_table[i] = bdrv_new(buf);
7658
            }
7659
            if (bdrv_open(pflash_table[i], pflash_filename[i],
7660
                          snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7661
                fprintf(stderr, "qemu: could not open flash image '%s'\n",
7662
                        pflash_filename[i]);
7663
                exit(1);
7664
            }
7665
        }
7666
    }
7667

    
7668
    sd_bdrv = bdrv_new ("sd");
7669
    /* FIXME: This isn't really a floppy, but it's a reasonable
7670
       approximation.  */
7671
    bdrv_set_type_hint(sd_bdrv, BDRV_TYPE_FLOPPY);
7672
    if (sd_filename) {
7673
        if (bdrv_open(sd_bdrv, sd_filename,
7674
                      snapshot ? BDRV_O_SNAPSHOT : 0) < 0) {
7675
            fprintf(stderr, "qemu: could not open SD card image %s\n",
7676
                    sd_filename);
7677
        } else
7678
            qemu_key_check(sd_bdrv, sd_filename);
7679
    }
7680

    
7681
    register_savevm("timer", 0, 2, timer_save, timer_load, NULL);
7682
    register_savevm("ram", 0, 2, ram_save, ram_load, NULL);
7683

    
7684
    init_ioports();
7685

    
7686
    /* terminal init */
7687
    if (nographic) {
7688
        dumb_display_init(ds);
7689
    } else if (vnc_display != NULL) {
7690
        vnc_display_init(ds, vnc_display);
7691
    } else {
7692
#if defined(CONFIG_SDL)
7693
        sdl_display_init(ds, full_screen, no_frame);
7694
#elif defined(CONFIG_COCOA)
7695
        cocoa_display_init(ds, full_screen);
7696
#else
7697
        dumb_display_init(ds);
7698
#endif
7699
    }
7700

    
7701
    /* Maintain compatibility with multiple stdio monitors */
7702
    if (!strcmp(monitor_device,"stdio")) {
7703
        for (i = 0; i < MAX_SERIAL_PORTS; i++) {
7704
            if (!strcmp(serial_devices[i],"mon:stdio")) {
7705
                monitor_device[0] = '\0';
7706
                break;
7707
            } else if (!strcmp(serial_devices[i],"stdio")) {
7708
                monitor_device[0] = '\0';
7709
                pstrcpy(serial_devices[0], sizeof(serial_devices[0]), "mon:stdio");
7710
                break;
7711
            }
7712
        }
7713
    }
7714
    if (monitor_device[0] != '\0') {
7715
        monitor_hd = qemu_chr_open(monitor_device);
7716
        if (!monitor_hd) {
7717
            fprintf(stderr, "qemu: could not open monitor device '%s'\n", monitor_device);
7718
            exit(1);
7719
        }
7720
        monitor_init(monitor_hd, !nographic);
7721
    }
7722

    
7723
    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
7724
        const char *devname = serial_devices[i];
7725
        if (devname[0] != '\0' && strcmp(devname, "none")) {
7726
            serial_hds[i] = qemu_chr_open(devname);
7727
            if (!serial_hds[i]) {
7728
                fprintf(stderr, "qemu: could not open serial device '%s'\n", 
7729
                        devname);
7730
                exit(1);
7731
            }
7732
            if (!strcmp(devname, "vc"))
7733
                qemu_chr_printf(serial_hds[i], "serial%d console\r\n", i);
7734
        }
7735
    }
7736

    
7737
    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
7738
        const char *devname = parallel_devices[i];
7739
        if (devname[0] != '\0' && strcmp(devname, "none")) {
7740
            parallel_hds[i] = qemu_chr_open(devname);
7741
            if (!parallel_hds[i]) {
7742
                fprintf(stderr, "qemu: could not open parallel device '%s'\n", 
7743
                        devname);
7744
                exit(1);
7745
            }
7746
            if (!strcmp(devname, "vc"))
7747
                qemu_chr_printf(parallel_hds[i], "parallel%d console\r\n", i);
7748
        }
7749
    }
7750

    
7751
    machine->init(ram_size, vga_ram_size, boot_device,
7752
                  ds, fd_filename, snapshot,
7753
                  kernel_filename, kernel_cmdline, initrd_filename, cpu_model);
7754

    
7755
    /* init USB devices */
7756
    if (usb_enabled) {
7757
        for(i = 0; i < usb_devices_index; i++) {
7758
            if (usb_device_add(usb_devices[i]) < 0) {
7759
                fprintf(stderr, "Warning: could not add USB device %s\n",
7760
                        usb_devices[i]);
7761
            }
7762
        }
7763
    }
7764

    
7765
    gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
7766
    qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
7767

    
7768
#ifdef CONFIG_GDBSTUB
7769
    if (use_gdbstub) {
7770
        /* XXX: use standard host:port notation and modify options
7771
           accordingly. */
7772
        if (gdbserver_start(gdbstub_port) < 0) {
7773
            fprintf(stderr, "qemu: could not open gdbstub device on port '%s'\n",
7774
                    gdbstub_port);
7775
            exit(1);
7776
        }
7777
    } else 
7778
#endif
7779
    if (loadvm)
7780
        do_loadvm(loadvm);
7781

    
7782
    {
7783
        /* XXX: simplify init */
7784
        read_passwords();
7785
        if (autostart) {
7786
            vm_start();
7787
        }
7788
    }
7789

    
7790
    if (daemonize) {
7791
        uint8_t status = 0;
7792
        ssize_t len;
7793
        int fd;
7794

    
7795
    again1:
7796
        len = write(fds[1], &status, 1);
7797
        if (len == -1 && (errno == EINTR))
7798
            goto again1;
7799

    
7800
        if (len != 1)
7801
            exit(1);
7802

    
7803
        fd = open("/dev/null", O_RDWR);
7804
        if (fd == -1)
7805
            exit(1);
7806

    
7807
        dup2(fd, 0);
7808
        dup2(fd, 1);
7809
        dup2(fd, 2);
7810

    
7811
        close(fd);
7812
    }
7813

    
7814
    main_loop();
7815
    quit_timers();
7816
    return 0;
7817
}