Statistics
| Branch: | Revision:

root / vl.c @ 80cabfad

History | View | Annotate | Download (33.1 kB)

1
/*
2
 * QEMU System Emulator
3
 * 
4
 * Copyright (c) 2003-2004 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 <stdlib.h>
25
#include <stdio.h>
26
#include <stdarg.h>
27
#include <string.h>
28
#include <ctype.h>
29
#include <getopt.h>
30
#include <inttypes.h>
31
#include <unistd.h>
32
#include <sys/mman.h>
33
#include <fcntl.h>
34
#include <signal.h>
35
#include <time.h>
36
#include <sys/time.h>
37
#include <malloc.h>
38
#include <termios.h>
39
#include <sys/poll.h>
40
#include <errno.h>
41
#include <sys/wait.h>
42

    
43
#include <sys/ioctl.h>
44
#include <sys/socket.h>
45
#include <linux/if.h>
46
#include <linux/if_tun.h>
47

    
48
#include "disas.h"
49
#include "thunk.h"
50

    
51
#include "vl.h"
52

    
53
#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
54

    
55
//#define DEBUG_UNUSED_IOPORT
56

    
57
#if !defined(CONFIG_SOFTMMU)
58
#define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
59
#else
60
#define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
61
#endif
62

    
63
#if defined (TARGET_I386)
64
#elif defined (TARGET_PPC)
65
//#define USE_OPEN_FIRMWARE
66
#if !defined (USE_OPEN_FIRMWARE)
67
#define KERNEL_LOAD_ADDR    0x01000000
68
#define KERNEL_STACK_ADDR   0x01200000
69
#else
70
#define KERNEL_LOAD_ADDR    0x00000000
71
#define KERNEL_STACK_ADDR   0x00400000
72
#endif
73
#endif
74

    
75
#define GUI_REFRESH_INTERVAL 30 
76

    
77
/* XXX: use a two level table to limit memory usage */
78
#define MAX_IOPORTS 65536
79

    
80
const char *bios_dir = CONFIG_QEMU_SHAREDIR;
81
char phys_ram_file[1024];
82
CPUState *global_env;
83
CPUState *cpu_single_env;
84
IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
85
IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
86
BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
87
int vga_ram_size;
88
static DisplayState display_state;
89
int nographic;
90
int term_inited;
91
int64_t ticks_per_sec;
92
int boot_device = 'c';
93
static int ram_size;
94
static char network_script[1024];
95
int pit_min_timer_count = 0;
96

    
97
/***********************************************************/
98
/* x86 io ports */
99

    
100
uint32_t default_ioport_readb(CPUState *env, uint32_t address)
101
{
102
#ifdef DEBUG_UNUSED_IOPORT
103
    fprintf(stderr, "inb: port=0x%04x\n", address);
104
#endif
105
    return 0xff;
106
}
107

    
108
void default_ioport_writeb(CPUState *env, uint32_t address, uint32_t data)
109
{
110
#ifdef DEBUG_UNUSED_IOPORT
111
    fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
112
#endif
113
}
114

    
115
/* default is to make two byte accesses */
116
uint32_t default_ioport_readw(CPUState *env, uint32_t address)
117
{
118
    uint32_t data;
119
    data = ioport_read_table[0][address & (MAX_IOPORTS - 1)](env, address);
120
    data |= ioport_read_table[0][(address + 1) & (MAX_IOPORTS - 1)](env, address + 1) << 8;
121
    return data;
122
}
123

    
124
void default_ioport_writew(CPUState *env, uint32_t address, uint32_t data)
125
{
126
    ioport_write_table[0][address & (MAX_IOPORTS - 1)](env, address, data & 0xff);
127
    ioport_write_table[0][(address + 1) & (MAX_IOPORTS - 1)](env, address + 1, (data >> 8) & 0xff);
128
}
129

    
130
uint32_t default_ioport_readl(CPUState *env, uint32_t address)
131
{
132
#ifdef DEBUG_UNUSED_IOPORT
133
    fprintf(stderr, "inl: port=0x%04x\n", address);
134
#endif
135
    return 0xffffffff;
136
}
137

    
138
void default_ioport_writel(CPUState *env, uint32_t address, uint32_t data)
139
{
140
#ifdef DEBUG_UNUSED_IOPORT
141
    fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
142
#endif
143
}
144

    
145
void init_ioports(void)
146
{
147
    int i;
148

    
149
    for(i = 0; i < MAX_IOPORTS; i++) {
150
        ioport_read_table[0][i] = default_ioport_readb;
151
        ioport_write_table[0][i] = default_ioport_writeb;
152
        ioport_read_table[1][i] = default_ioport_readw;
153
        ioport_write_table[1][i] = default_ioport_writew;
154
        ioport_read_table[2][i] = default_ioport_readl;
155
        ioport_write_table[2][i] = default_ioport_writel;
156
    }
157
}
158

    
159
/* size is the word size in byte */
160
int register_ioport_read(int start, int length, IOPortReadFunc *func, int size)
161
{
162
    int i, bsize;
163

    
164
    if (size == 1)
165
        bsize = 0;
166
    else if (size == 2)
167
        bsize = 1;
168
    else if (size == 4)
169
        bsize = 2;
170
    else
171
        return -1;
172
    for(i = start; i < start + length; i += size)
173
        ioport_read_table[bsize][i] = func;
174
    return 0;
175
}
176

    
177
/* size is the word size in byte */
178
int register_ioport_write(int start, int length, IOPortWriteFunc *func, int size)
179
{
180
    int i, bsize;
181

    
182
    if (size == 1)
183
        bsize = 0;
184
    else if (size == 2)
185
        bsize = 1;
186
    else if (size == 4)
187
        bsize = 2;
188
    else
189
        return -1;
190
    for(i = start; i < start + length; i += size)
191
        ioport_write_table[bsize][i] = func;
192
    return 0;
193
}
194

    
195
void pstrcpy(char *buf, int buf_size, const char *str)
196
{
197
    int c;
198
    char *q = buf;
199

    
200
    if (buf_size <= 0)
201
        return;
202

    
203
    for(;;) {
204
        c = *str++;
205
        if (c == 0 || q >= buf + buf_size - 1)
206
            break;
207
        *q++ = c;
208
    }
209
    *q = '\0';
210
}
211

    
212
/* strcat and truncate. */
213
char *pstrcat(char *buf, int buf_size, const char *s)
214
{
215
    int len;
216
    len = strlen(buf);
217
    if (len < buf_size) 
218
        pstrcpy(buf + len, buf_size - len, s);
219
    return buf;
220
}
221

    
222
/* return the size or -1 if error */
223
int load_image(const char *filename, uint8_t *addr)
224
{
225
    int fd, size;
226
    fd = open(filename, O_RDONLY);
227
    if (fd < 0)
228
        return -1;
229
    size = lseek(fd, 0, SEEK_END);
230
    lseek(fd, 0, SEEK_SET);
231
    if (read(fd, addr, size) != size) {
232
        close(fd);
233
        return -1;
234
    }
235
    close(fd);
236
    return size;
237
}
238

    
239
void cpu_outb(CPUState *env, int addr, int val)
240
{
241
    ioport_write_table[0][addr & (MAX_IOPORTS - 1)](env, addr, val);
242
}
243

    
244
void cpu_outw(CPUState *env, int addr, int val)
245
{
246
    ioport_write_table[1][addr & (MAX_IOPORTS - 1)](env, addr, val);
247
}
248

    
249
void cpu_outl(CPUState *env, int addr, int val)
250
{
251
    ioport_write_table[2][addr & (MAX_IOPORTS - 1)](env, addr, val);
252
}
253

    
254
int cpu_inb(CPUState *env, int addr)
255
{
256
    return ioport_read_table[0][addr & (MAX_IOPORTS - 1)](env, addr);
257
}
258

    
259
int cpu_inw(CPUState *env, int addr)
260
{
261
    return ioport_read_table[1][addr & (MAX_IOPORTS - 1)](env, addr);
262
}
263

    
264
int cpu_inl(CPUState *env, int addr)
265
{
266
    return ioport_read_table[2][addr & (MAX_IOPORTS - 1)](env, addr);
267
}
268

    
269
/***********************************************************/
270
void hw_error(const char *fmt, ...)
271
{
272
    va_list ap;
273

    
274
    va_start(ap, fmt);
275
    fprintf(stderr, "qemu: hardware error: ");
276
    vfprintf(stderr, fmt, ap);
277
    fprintf(stderr, "\n");
278
#ifdef TARGET_I386
279
    cpu_x86_dump_state(global_env, stderr, X86_DUMP_FPU | X86_DUMP_CCOP);
280
#else
281
    cpu_dump_state(global_env, stderr, 0);
282
#endif
283
    va_end(ap);
284
    abort();
285
}
286

    
287
#if defined(__powerpc__)
288

    
289
static inline uint32_t get_tbl(void) 
290
{
291
    uint32_t tbl;
292
    asm volatile("mftb %0" : "=r" (tbl));
293
    return tbl;
294
}
295

    
296
static inline uint32_t get_tbu(void) 
297
{
298
        uint32_t tbl;
299
        asm volatile("mftbu %0" : "=r" (tbl));
300
        return tbl;
301
}
302

    
303
int64_t cpu_get_real_ticks(void)
304
{
305
    uint32_t l, h, h1;
306
    /* NOTE: we test if wrapping has occurred */
307
    do {
308
        h = get_tbu();
309
        l = get_tbl();
310
        h1 = get_tbu();
311
    } while (h != h1);
312
    return ((int64_t)h << 32) | l;
313
}
314

    
315
#elif defined(__i386__)
316

    
317
int64_t cpu_get_real_ticks(void)
318
{
319
    int64_t val;
320
    asm("rdtsc" : "=A" (val));
321
    return val;
322
}
323

    
324
#else
325
#error unsupported CPU
326
#endif
327

    
328
static int64_t cpu_ticks_offset;
329
static int64_t cpu_ticks_last;
330

    
331
int64_t cpu_get_ticks(void)
332
{
333
    return cpu_get_real_ticks() + cpu_ticks_offset;
334
}
335

    
336
/* enable cpu_get_ticks() */
337
void cpu_enable_ticks(void)
338
{
339
    cpu_ticks_offset = cpu_ticks_last - cpu_get_real_ticks();
340
}
341

    
342
/* disable cpu_get_ticks() : the clock is stopped. You must not call
343
   cpu_get_ticks() after that.  */
344
void cpu_disable_ticks(void)
345
{
346
    cpu_ticks_last = cpu_get_ticks();
347
}
348

    
349
int64_t get_clock(void)
350
{
351
    struct timeval tv;
352
    gettimeofday(&tv, NULL);
353
    return tv.tv_sec * 1000000LL + tv.tv_usec;
354
}
355

    
356
void cpu_calibrate_ticks(void)
357
{
358
    int64_t usec, ticks;
359

    
360
    usec = get_clock();
361
    ticks = cpu_get_ticks();
362
    usleep(50 * 1000);
363
    usec = get_clock() - usec;
364
    ticks = cpu_get_ticks() - ticks;
365
    ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
366
}
367

    
368
/* compute with 96 bit intermediate result: (a*b)/c */
369
uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
370
{
371
    union {
372
        uint64_t ll;
373
        struct {
374
#ifdef WORDS_BIGENDIAN
375
            uint32_t high, low;
376
#else
377
            uint32_t low, high;
378
#endif            
379
        } l;
380
    } u, res;
381
    uint64_t rl, rh;
382

    
383
    u.ll = a;
384
    rl = (uint64_t)u.l.low * (uint64_t)b;
385
    rh = (uint64_t)u.l.high * (uint64_t)b;
386
    rh += (rl >> 32);
387
    res.l.high = rh / c;
388
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
389
    return res.ll;
390
}
391

    
392
#define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
393
static int term_got_escape, term_command;
394
static unsigned char term_cmd_buf[128];
395

    
396
typedef struct term_cmd_t {
397
    const unsigned char *name;
398
    void (*handler)(unsigned char *params);
399
} term_cmd_t;
400

    
401
static void do_change_cdrom (unsigned char *params);
402
static void do_change_fd0 (unsigned char *params);
403
static void do_change_fd1 (unsigned char *params);
404

    
405
static term_cmd_t term_cmds[] = {
406
    { "changecd", &do_change_cdrom, },
407
    { "changefd0", &do_change_fd0, },
408
    { "changefd1", &do_change_fd1, },
409
    { NULL, NULL, },
410
};
411

    
412
void term_print_help(void)
413
{
414
    printf("\n"
415
           "C-a h    print this help\n"
416
           "C-a x    exit emulatior\n"
417
           "C-a d    switch on/off debug log\n"
418
           "C-a s    save disk data back to file (if -snapshot)\n"
419
           "C-a b    send break (magic sysrq)\n"
420
           "C-a c    send qemu internal command\n"
421
           "C-a C-a  send C-a\n"
422
           );
423
}
424

    
425
static void do_change_cdrom (unsigned char *params)
426
{
427
    /* Dunno how to do it... */
428
}
429

    
430
static void do_change_fd (int fd, unsigned char *params)
431
{
432
    unsigned char *name_start, *name_end, *ros;
433
    int ro;
434

    
435
    for (name_start = params;
436
         isspace(*name_start); name_start++)
437
        continue;
438
    if (*name_start == '\0')
439
        return;
440
    for (name_end = name_start;
441
         !isspace(*name_end) && *name_end != '\0'; name_end++)
442
        continue;
443
    for (ros = name_end + 1; isspace(*ros); ros++)
444
        continue;
445
    if (ros[0] == 'r' && ros[1] == 'o')
446
        ro = 1;
447
    else
448
        ro = 0;
449
    *name_end = '\0';
450
    printf("Change fd %d to %s (%s)\n", fd, name_start, params);
451
    fdctrl_disk_change(fd, name_start, ro);
452
}
453

    
454
static void do_change_fd0 (unsigned char *params)
455
{
456
    do_change_fd(0, params);
457
}
458

    
459
static void do_change_fd1 (unsigned char *params)
460
{
461
    do_change_fd(1, params);
462
}
463

    
464
static void term_treat_command(void)
465
{
466
    unsigned char *cmd_start, *cmd_end;
467
    int i;
468

    
469
    for (cmd_start = term_cmd_buf; isspace(*cmd_start); cmd_start++)
470
        continue;
471
    for (cmd_end = cmd_start;
472
         !isspace(*cmd_end) && *cmd_end != '\0'; cmd_end++)
473
        continue;
474
    for (i = 0; term_cmds[i].name != NULL; i++) {
475
        if (strlen(term_cmds[i].name) == (cmd_end - cmd_start) &&
476
            memcmp(term_cmds[i].name, cmd_start, cmd_end - cmd_start) == 0) {
477
            (*term_cmds[i].handler)(cmd_end + 1);
478
            return;
479
        }
480
    }
481
    *cmd_end = '\0';
482
    printf("Unknown term command: %s\n", cmd_start);
483
}
484

    
485
extern FILE *logfile;
486

    
487
/* called when a char is received */
488
void term_received_byte(int ch)
489
{
490
    if (term_command) {
491
        if (ch == '\n' || ch == '\r' || term_command == 127) {
492
            printf("\n");
493
            term_treat_command();
494
            term_command = 0;
495
        } else {
496
            if (ch == 0x7F || ch == 0x08) {
497
                if (term_command > 1) {
498
                    term_cmd_buf[--term_command - 1] = '\0';
499
                    printf("\r                                               "
500
                           "                               ");
501
                    printf("\r> %s", term_cmd_buf);
502
                }
503
            } else if (ch > 0x1f) {
504
                term_cmd_buf[term_command++ - 1] = ch;
505
                term_cmd_buf[term_command - 1] = '\0';
506
                printf("\r> %s", term_cmd_buf);
507
            }
508
            fflush(stdout);
509
        }
510
    } else if (term_got_escape) {
511
        term_got_escape = 0;
512
        switch(ch) {
513
        case 'h':
514
            term_print_help();
515
            break;
516
        case 'x':
517
            exit(0);
518
            break;
519
        case 's': 
520
            {
521
                int i;
522
                for (i = 0; i < MAX_DISKS; i++) {
523
                    if (bs_table[i])
524
                        bdrv_commit(bs_table[i]);
525
                }
526
            }
527
            break;
528
        case 'b':
529
            serial_receive_break();
530
            break;
531
        case 'c':
532
            printf("> ");
533
            fflush(stdout);
534
            term_command = 1;
535
            break;
536
        case 'd':
537
            cpu_set_log(CPU_LOG_ALL);
538
            break;
539
        case TERM_ESCAPE:
540
            goto send_char;
541
        }
542
    } else if (ch == TERM_ESCAPE) {
543
        term_got_escape = 1;
544
    } else {
545
    send_char:
546
        serial_receive_byte(ch);
547
    }
548
}
549

    
550
/***********************************************************/
551
/* Linux network device redirector */
552

    
553
int net_init(void)
554
{
555
    struct ifreq ifr;
556
    int fd, ret, pid, status;
557
    
558
    fd = open("/dev/net/tun", O_RDWR);
559
    if (fd < 0) {
560
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
561
        return -1;
562
    }
563
    memset(&ifr, 0, sizeof(ifr));
564
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
565
    pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
566
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
567
    if (ret != 0) {
568
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
569
        close(fd);
570
        return -1;
571
    }
572
    printf("Connected to host network interface: %s\n", ifr.ifr_name);
573
    fcntl(fd, F_SETFL, O_NONBLOCK);
574
    net_fd = fd;
575

    
576
    /* try to launch network init script */
577
    pid = fork();
578
    if (pid >= 0) {
579
        if (pid == 0) {
580
            execl(network_script, network_script, ifr.ifr_name, NULL);
581
            exit(1);
582
        }
583
        while (waitpid(pid, &status, 0) != pid);
584
        if (!WIFEXITED(status) ||
585
            WEXITSTATUS(status) != 0) {
586
            fprintf(stderr, "%s: could not launch network script for '%s'\n",
587
                    network_script, ifr.ifr_name);
588
        }
589
    }
590
    return 0;
591
}
592

    
593
void net_send_packet(int net_fd, const uint8_t *buf, int size)
594
{
595
#ifdef DEBUG_NE2000
596
    printf("NE2000: sending packet size=%d\n", size);
597
#endif
598
    write(net_fd, buf, size);
599
}
600

    
601
/***********************************************************/
602
/* dumb display */
603

    
604
/* init terminal so that we can grab keys */
605
static struct termios oldtty;
606

    
607
static void term_exit(void)
608
{
609
    tcsetattr (0, TCSANOW, &oldtty);
610
}
611

    
612
static void term_init(void)
613
{
614
    struct termios tty;
615

    
616
    tcgetattr (0, &tty);
617
    oldtty = tty;
618

    
619
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
620
                          |INLCR|IGNCR|ICRNL|IXON);
621
    tty.c_oflag |= OPOST;
622
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
623
    /* if graphical mode, we allow Ctrl-C handling */
624
    if (nographic)
625
        tty.c_lflag &= ~ISIG;
626
    tty.c_cflag &= ~(CSIZE|PARENB);
627
    tty.c_cflag |= CS8;
628
    tty.c_cc[VMIN] = 1;
629
    tty.c_cc[VTIME] = 0;
630
    
631
    tcsetattr (0, TCSANOW, &tty);
632

    
633
    atexit(term_exit);
634

    
635
    fcntl(0, F_SETFL, O_NONBLOCK);
636
}
637

    
638
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
639
{
640
}
641

    
642
static void dumb_resize(DisplayState *ds, int w, int h)
643
{
644
}
645

    
646
static void dumb_refresh(DisplayState *ds)
647
{
648
    vga_update_display();
649
}
650

    
651
void dumb_display_init(DisplayState *ds)
652
{
653
    ds->data = NULL;
654
    ds->linesize = 0;
655
    ds->depth = 0;
656
    ds->dpy_update = dumb_update;
657
    ds->dpy_resize = dumb_resize;
658
    ds->dpy_refresh = dumb_refresh;
659
}
660

    
661
#if !defined(CONFIG_SOFTMMU)
662
/***********************************************************/
663
/* cpu signal handler */
664
static void host_segv_handler(int host_signum, siginfo_t *info, 
665
                              void *puc)
666
{
667
    if (cpu_signal_handler(host_signum, info, puc))
668
        return;
669
    term_exit();
670
    abort();
671
}
672
#endif
673

    
674
static int timer_irq_pending;
675
static int timer_irq_count;
676

    
677
static int timer_ms;
678
static int gui_refresh_pending, gui_refresh_count;
679

    
680
static void host_alarm_handler(int host_signum, siginfo_t *info, 
681
                               void *puc)
682
{
683
    /* NOTE: since usually the OS asks a 100 Hz clock, there can be
684
       some drift between cpu_get_ticks() and the interrupt time. So
685
       we queue some interrupts to avoid missing some */
686
    timer_irq_count += pit_get_out_edges(&pit_channels[0]);
687
    if (timer_irq_count) {
688
        if (timer_irq_count > 2)
689
            timer_irq_count = 2;
690
        timer_irq_count--;
691
        timer_irq_pending = 1;
692
    }
693
    gui_refresh_count += timer_ms;
694
    if (gui_refresh_count >= GUI_REFRESH_INTERVAL) {
695
        gui_refresh_count = 0;
696
        gui_refresh_pending = 1;
697
    }
698

    
699
    if (gui_refresh_pending || timer_irq_pending) {
700
        /* just exit from the cpu to have a chance to handle timers */
701
        cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
702
    }
703
}
704

    
705
/* main execution loop */
706

    
707
CPUState *cpu_gdbstub_get_env(void *opaque)
708
{
709
    return global_env;
710
}
711

    
712
int main_loop(void *opaque)
713
{
714
    struct pollfd ufds[3], *pf, *serial_ufd, *gdb_ufd;
715
#if defined (TARGET_I386)
716
    struct pollfd *net_ufd;
717
#endif
718
    int ret, n, timeout, serial_ok;
719
    uint8_t ch;
720
    CPUState *env = global_env;
721

    
722
    if (!term_inited) {
723
        /* initialize terminal only there so that the user has a
724
           chance to stop QEMU with Ctrl-C before the gdb connection
725
           is launched */
726
        term_inited = 1;
727
        term_init();
728
    }
729

    
730
    serial_ok = 1;
731
    cpu_enable_ticks();
732
    for(;;) {
733
#if defined (DO_TB_FLUSH)
734
        tb_flush();
735
#endif
736
        ret = cpu_exec(env);
737
        if (reset_requested) {
738
            ret = EXCP_INTERRUPT; 
739
            break;
740
        }
741
        if (ret == EXCP_DEBUG) {
742
            ret = EXCP_DEBUG;
743
            break;
744
        }
745
        /* if hlt instruction, we wait until the next IRQ */
746
        if (ret == EXCP_HLT) 
747
            timeout = 10;
748
        else
749
            timeout = 0;
750
        /* poll any events */
751
        serial_ufd = NULL;
752
        pf = ufds;
753
        if (serial_ok && serial_can_receive()) {
754
            serial_ufd = pf;
755
            pf->fd = 0;
756
            pf->events = POLLIN;
757
            pf++;
758
        }
759
#if defined (TARGET_I386)
760
        net_ufd = NULL;
761
        if (net_fd > 0 && ne2000_can_receive()) {
762
            net_ufd = pf;
763
            pf->fd = net_fd;
764
            pf->events = POLLIN;
765
            pf++;
766
        }
767
#endif
768
        gdb_ufd = NULL;
769
        if (gdbstub_fd > 0) {
770
            gdb_ufd = pf;
771
            pf->fd = gdbstub_fd;
772
            pf->events = POLLIN;
773
            pf++;
774
        }
775

    
776
        ret = poll(ufds, pf - ufds, timeout);
777
        if (ret > 0) {
778
            if (serial_ufd && (serial_ufd->revents & POLLIN)) {
779
                n = read(0, &ch, 1);
780
                if (n == 1) {
781
                    term_received_byte(ch);
782
                } else {
783
                    /* Closed, stop polling. */
784
                    serial_ok = 0;
785
                }
786
            }
787
#if defined (TARGET_I386)
788
            if (net_ufd && (net_ufd->revents & POLLIN)) {
789
                uint8_t buf[MAX_ETH_FRAME_SIZE];
790

    
791
                n = read(net_fd, buf, MAX_ETH_FRAME_SIZE);
792
                if (n > 0) {
793
                    if (n < 60) {
794
                        memset(buf + n, 0, 60 - n);
795
                        n = 60;
796
                    }
797
                    ne2000_receive(buf, n);
798
                }
799
            }
800
#endif
801
            if (gdb_ufd && (gdb_ufd->revents & POLLIN)) {
802
                uint8_t buf[1];
803
                /* stop emulation if requested by gdb */
804
                n = read(gdbstub_fd, buf, 1);
805
                if (n == 1) {
806
                    ret = EXCP_INTERRUPT; 
807
                    break;
808
                }
809
            }
810
        }
811

    
812
        /* timer IRQ */
813
        if (timer_irq_pending) {
814
#if defined (TARGET_I386)
815
            pic_set_irq(0, 1);
816
            pic_set_irq(0, 0);
817
            timer_irq_pending = 0;
818
            rtc_timer();
819
#endif
820
        }
821
        /* XXX: add explicit timer */
822
        SB16_run();
823

    
824
        /* run dma transfers, if any */
825
        DMA_run();
826

    
827
        /* VGA */
828
        if (gui_refresh_pending) {
829
            display_state.dpy_refresh(&display_state);
830
            gui_refresh_pending = 0;
831
        }
832
    }
833
    cpu_disable_ticks();
834
    return ret;
835
}
836

    
837
void help(void)
838
{
839
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003 Fabrice Bellard\n"
840
           "usage: %s [options] [disk_image]\n"
841
           "\n"
842
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
843
           "\n"
844
           "Standard options:\n"
845
           "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
846
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
847
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
848
           "-cdrom file     use 'file' as IDE cdrom 2 image\n"
849
           "-boot [a|b|c|d] boot on floppy (a, b), hard disk (c) or CD-ROM (d)\n"
850
           "-snapshot       write to temporary files instead of disk image files\n"
851
           "-m megs         set virtual RAM size to megs MB\n"
852
           "-n script       set network init script [default=%s]\n"
853
           "-tun-fd fd      this fd talks to tap/tun, use it.\n"
854
           "-nographic      disable graphical output\n"
855
           "\n"
856
           "Linux boot specific (does not require PC BIOS):\n"
857
           "-kernel bzImage use 'bzImage' as kernel image\n"
858
           "-append cmdline use 'cmdline' as kernel command line\n"
859
           "-initrd file    use 'file' as initial ram disk\n"
860
           "\n"
861
           "Debug/Expert options:\n"
862
           "-s              wait gdb connection to port %d\n"
863
           "-p port         change gdb connection port\n"
864
           "-d              output log to %s\n"
865
           "-hdachs c,h,s   force hard disk 0 geometry (usually qemu can guess it)\n"
866
           "-L path         set the directory for the BIOS and VGA BIOS\n"
867
#ifdef USE_CODE_COPY
868
           "-no-code-copy   disable code copy acceleration\n"
869
#endif
870

    
871
           "\n"
872
           "During emulation, use C-a h to get terminal commands:\n",
873
#ifdef CONFIG_SOFTMMU
874
           "qemu",
875
#else
876
           "qemu-fast",
877
#endif
878
           DEFAULT_NETWORK_SCRIPT, 
879
           DEFAULT_GDBSTUB_PORT,
880
           "/tmp/qemu.log");
881
    term_print_help();
882
#ifndef CONFIG_SOFTMMU
883
    printf("\n"
884
           "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
885
           "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
886
           "PC emulation.\n");
887
#endif
888
    exit(1);
889
}
890

    
891
struct option long_options[] = {
892
    { "initrd", 1, NULL, 0, },
893
    { "hda", 1, NULL, 0, },
894
    { "hdb", 1, NULL, 0, },
895
    { "snapshot", 0, NULL, 0, },
896
    { "hdachs", 1, NULL, 0, },
897
    { "nographic", 0, NULL, 0, },
898
    { "kernel", 1, NULL, 0, },
899
    { "append", 1, NULL, 0, },
900
    { "tun-fd", 1, NULL, 0, },
901
    { "hdc", 1, NULL, 0, },
902
    { "hdd", 1, NULL, 0, },
903
    { "cdrom", 1, NULL, 0, },
904
    { "boot", 1, NULL, 0, },
905
    { "fda", 1, NULL, 0, },
906
    { "fdb", 1, NULL, 0, },
907
    { "no-code-copy", 0, NULL, 0},
908
    { NULL, 0, NULL, 0 },
909
};
910

    
911
#ifdef CONFIG_SDL
912
/* SDL use the pthreads and they modify sigaction. We don't
913
   want that. */
914
#if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2)
915
extern void __libc_sigaction();
916
#define sigaction(sig, act, oact) __libc_sigaction(sig, act, oact)
917
#else
918
extern void __sigaction();
919
#define sigaction(sig, act, oact) __sigaction(sig, act, oact)
920
#endif
921
#endif /* CONFIG_SDL */
922

    
923
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
924

    
925
/* this stack is only used during signal handling */
926
#define SIGNAL_STACK_SIZE 32768
927

    
928
static uint8_t *signal_stack;
929

    
930
#endif
931

    
932
int main(int argc, char **argv)
933
{
934
    int c, i, use_gdbstub, gdbstub_port, long_index;
935
    int snapshot, linux_boot;
936
    struct sigaction act;
937
    struct itimerval itv;
938
    CPUState *env;
939
    const char *initrd_filename;
940
    const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
941
    const char *kernel_filename, *kernel_cmdline;
942
    DisplayState *ds = &display_state;
943

    
944
    /* we never want that malloc() uses mmap() */
945
    mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
946
    initrd_filename = NULL;
947
    for(i = 0; i < MAX_FD; i++)
948
        fd_filename[i] = NULL;
949
    for(i = 0; i < MAX_DISKS; i++)
950
        hd_filename[i] = NULL;
951
    ram_size = 32 * 1024 * 1024;
952
    vga_ram_size = VGA_RAM_SIZE;
953
#if defined (TARGET_I386)
954
    pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
955
#endif
956
    use_gdbstub = 0;
957
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
958
    snapshot = 0;
959
    nographic = 0;
960
    kernel_filename = NULL;
961
    kernel_cmdline = "";
962
    for(;;) {
963
        c = getopt_long_only(argc, argv, "hm:dn:sp:L:", long_options, &long_index);
964
        if (c == -1)
965
            break;
966
        switch(c) {
967
        case 0:
968
            switch(long_index) {
969
            case 0:
970
                initrd_filename = optarg;
971
                break;
972
            case 1:
973
                hd_filename[0] = optarg;
974
                break;
975
            case 2:
976
                hd_filename[1] = optarg;
977
                break;
978
            case 3:
979
                snapshot = 1;
980
                break;
981
            case 4:
982
                {
983
                    int cyls, heads, secs;
984
                    const char *p;
985
                    p = optarg;
986
                    cyls = strtol(p, (char **)&p, 0);
987
                    if (*p != ',')
988
                        goto chs_fail;
989
                    p++;
990
                    heads = strtol(p, (char **)&p, 0);
991
                    if (*p != ',')
992
                        goto chs_fail;
993
                    p++;
994
                    secs = strtol(p, (char **)&p, 0);
995
                    if (*p != '\0')
996
                        goto chs_fail;
997
                    ide_set_geometry(0, cyls, heads, secs);
998
                chs_fail: ;
999
                }
1000
                break;
1001
            case 5:
1002
                nographic = 1;
1003
                break;
1004
            case 6:
1005
                kernel_filename = optarg;
1006
                break;
1007
            case 7:
1008
                kernel_cmdline = optarg;
1009
                break;
1010
#if defined (TARGET_I386)
1011
            case 8:
1012
                net_fd = atoi(optarg);
1013
                break;
1014
#endif
1015
            case 9:
1016
                hd_filename[2] = optarg;
1017
                break;
1018
            case 10:
1019
                hd_filename[3] = optarg;
1020
                break;
1021
            case 11:
1022
                hd_filename[2] = optarg;
1023
                ide_set_cdrom(2, 1);
1024
                break;
1025
            case 12:
1026
                boot_device = optarg[0];
1027
                if (boot_device != 'a' && boot_device != 'b' &&
1028
                    boot_device != 'c' && boot_device != 'd') {
1029
                    fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
1030
                    exit(1);
1031
                }
1032
                break;
1033
            case 13:
1034
                fd_filename[0] = optarg;
1035
                break;
1036
            case 14:
1037
                fd_filename[1] = optarg;
1038
                break;
1039
            case 15:
1040
                code_copy_enabled = 0;
1041
                break;
1042
            }
1043
            break;
1044
        case 'h':
1045
            help();
1046
            break;
1047
        case 'm':
1048
            ram_size = atoi(optarg) * 1024 * 1024;
1049
            if (ram_size <= 0)
1050
                help();
1051
            if (ram_size > PHYS_RAM_MAX_SIZE) {
1052
                fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
1053
                        PHYS_RAM_MAX_SIZE / (1024 * 1024));
1054
                exit(1);
1055
            }
1056
            break;
1057
        case 'd':
1058
            cpu_set_log(CPU_LOG_ALL);
1059
            break;
1060
#if defined (TARGET_I386)
1061
        case 'n':
1062
            pstrcpy(network_script, sizeof(network_script), optarg);
1063
            break;
1064
#endif
1065
        case 's':
1066
            use_gdbstub = 1;
1067
            break;
1068
        case 'p':
1069
            gdbstub_port = atoi(optarg);
1070
            break;
1071
        case 'L':
1072
            bios_dir = optarg;
1073
            break;
1074
        }
1075
    }
1076

    
1077
    if (optind < argc) {
1078
        hd_filename[0] = argv[optind++];
1079
    }
1080

    
1081
    linux_boot = (kernel_filename != NULL);
1082
        
1083
    if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
1084
        fd_filename[0] == '\0')
1085
        help();
1086
    
1087
    /* boot to cd by default if no hard disk */
1088
    if (hd_filename[0] == '\0' && boot_device == 'c') {
1089
        if (fd_filename[0] != '\0')
1090
            boot_device = 'a';
1091
        else
1092
            boot_device = 'd';
1093
    }
1094

    
1095
#if !defined(CONFIG_SOFTMMU)
1096
    /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
1097
    {
1098
        static uint8_t stdout_buf[4096];
1099
        setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
1100
    }
1101
#else
1102
    setvbuf(stdout, NULL, _IOLBF, 0);
1103
#endif
1104

    
1105
    /* init network tun interface */
1106
#if defined (TARGET_I386)
1107
    if (net_fd < 0)
1108
        net_init();
1109
#endif
1110

    
1111
    /* init the memory */
1112
    phys_ram_size = ram_size + vga_ram_size;
1113

    
1114
#ifdef CONFIG_SOFTMMU
1115
    phys_ram_base = memalign(TARGET_PAGE_SIZE, phys_ram_size);
1116
    if (!phys_ram_base) {
1117
        fprintf(stderr, "Could not allocate physical memory\n");
1118
        exit(1);
1119
    }
1120
#else
1121
    /* as we must map the same page at several addresses, we must use
1122
       a fd */
1123
    {
1124
        const char *tmpdir;
1125

    
1126
        tmpdir = getenv("QEMU_TMPDIR");
1127
        if (!tmpdir)
1128
            tmpdir = "/tmp";
1129
        snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
1130
        if (mkstemp(phys_ram_file) < 0) {
1131
            fprintf(stderr, "Could not create temporary memory file '%s'\n", 
1132
                    phys_ram_file);
1133
            exit(1);
1134
        }
1135
        phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
1136
        if (phys_ram_fd < 0) {
1137
            fprintf(stderr, "Could not open temporary memory file '%s'\n", 
1138
                    phys_ram_file);
1139
            exit(1);
1140
        }
1141
        ftruncate(phys_ram_fd, phys_ram_size);
1142
        unlink(phys_ram_file);
1143
        phys_ram_base = mmap(get_mmap_addr(phys_ram_size), 
1144
                             phys_ram_size, 
1145
                             PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
1146
                             phys_ram_fd, 0);
1147
        if (phys_ram_base == MAP_FAILED) {
1148
            fprintf(stderr, "Could not map physical memory\n");
1149
            exit(1);
1150
        }
1151
    }
1152
#endif
1153

    
1154
    /* open the virtual block devices */
1155
    for(i = 0; i < MAX_DISKS; i++) {
1156
        if (hd_filename[i]) {
1157
            bs_table[i] = bdrv_open(hd_filename[i], snapshot);
1158
            if (!bs_table[i]) {
1159
                fprintf(stderr, "qemu: could not open hard disk image '%s\n",
1160
                        hd_filename[i]);
1161
                exit(1);
1162
            }
1163
        }
1164
    }
1165

    
1166
    /* init CPU state */
1167
    env = cpu_init();
1168
    global_env = env;
1169
    cpu_single_env = env;
1170

    
1171
    init_ioports();
1172
    cpu_calibrate_ticks();
1173

    
1174
    /* terminal init */
1175
    if (nographic) {
1176
        dumb_display_init(ds);
1177
    } else {
1178
#ifdef CONFIG_SDL
1179
        sdl_display_init(ds);
1180
#else
1181
        dumb_display_init(ds);
1182
#endif
1183
    }
1184

    
1185
#if defined(TARGET_I386)
1186
    pc_init(ram_size, vga_ram_size, boot_device,
1187
            ds, fd_filename, snapshot,
1188
            kernel_filename, kernel_cmdline, initrd_filename);
1189
#elif defined(TARGET_PPC)
1190
    ppc_init();
1191
#endif
1192

    
1193
    /* setup cpu signal handlers for MMU / self modifying code handling */
1194
#if !defined(CONFIG_SOFTMMU)
1195

    
1196
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
1197
    {
1198
        stack_t stk;
1199
        signal_stack = malloc(SIGNAL_STACK_SIZE);
1200
        stk.ss_sp = signal_stack;
1201
        stk.ss_size = SIGNAL_STACK_SIZE;
1202
        stk.ss_flags = 0;
1203

    
1204
        if (sigaltstack(&stk, NULL) < 0) {
1205
            perror("sigaltstack");
1206
            exit(1);
1207
        }
1208
    }
1209
#endif
1210
        
1211
    sigfillset(&act.sa_mask);
1212
    act.sa_flags = SA_SIGINFO;
1213
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
1214
    act.sa_flags |= SA_ONSTACK;
1215
#endif
1216
    act.sa_sigaction = host_segv_handler;
1217
    sigaction(SIGSEGV, &act, NULL);
1218
    sigaction(SIGBUS, &act, NULL);
1219
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
1220
    sigaction(SIGFPE, &act, NULL);
1221
#endif
1222
#endif
1223

    
1224
    /* timer signal */
1225
    sigfillset(&act.sa_mask);
1226
    act.sa_flags = SA_SIGINFO;
1227
#if defined (TARGET_I386) && defined(USE_CODE_COPY)
1228
    act.sa_flags |= SA_ONSTACK;
1229
#endif
1230
    act.sa_sigaction = host_alarm_handler;
1231
    sigaction(SIGALRM, &act, NULL);
1232

    
1233
    itv.it_interval.tv_sec = 0;
1234
    itv.it_interval.tv_usec = 1000;
1235
    itv.it_value.tv_sec = 0;
1236
    itv.it_value.tv_usec = 10 * 1000;
1237
    setitimer(ITIMER_REAL, &itv, NULL);
1238
    /* we probe the tick duration of the kernel to inform the user if
1239
       the emulated kernel requested a too high timer frequency */
1240
    getitimer(ITIMER_REAL, &itv);
1241
    timer_ms = itv.it_interval.tv_usec / 1000;
1242
    pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * PIT_FREQ) / 
1243
        1000000;
1244

    
1245
    if (use_gdbstub) {
1246
        cpu_gdbstub(NULL, main_loop, gdbstub_port);
1247
    } else {
1248
        main_loop(NULL);
1249
    }
1250
    return 0;
1251
}