write to both IDE drives - return 0 for not present drives
[qemu] / vl.c
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 #include <pty.h>
43
44 #include <sys/ioctl.h>
45 #include <sys/socket.h>
46 #include <linux/if.h>
47 #include <linux/if_tun.h>
48
49 #include "disas.h"
50 #include "thunk.h"
51
52 #include "vl.h"
53
54 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
55
56 //#define DEBUG_UNUSED_IOPORT
57
58 #if !defined(CONFIG_SOFTMMU)
59 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
60 #else
61 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
62 #endif
63
64 #if defined (TARGET_I386)
65 #elif defined (TARGET_PPC)
66 //#define USE_OPEN_FIRMWARE
67 #if !defined (USE_OPEN_FIRMWARE)
68 #define KERNEL_LOAD_ADDR    0x01000000
69 #define KERNEL_STACK_ADDR   0x01200000
70 #else
71 #define KERNEL_LOAD_ADDR    0x00000000
72 #define KERNEL_STACK_ADDR   0x00400000
73 #endif
74 #endif
75
76 #define GUI_REFRESH_INTERVAL 30 
77
78 /* XXX: use a two level table to limit memory usage */
79 #define MAX_IOPORTS 65536
80
81 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
82 char phys_ram_file[1024];
83 CPUState *global_env;
84 CPUState *cpu_single_env;
85 void *ioport_opaque[MAX_IOPORTS];
86 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
87 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
88 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
89 int vga_ram_size;
90 static DisplayState display_state;
91 int nographic;
92 int term_inited;
93 int64_t ticks_per_sec;
94 int boot_device = 'c';
95 static int ram_size;
96 static char network_script[1024];
97 int pit_min_timer_count = 0;
98 int nb_nics;
99 NetDriverState nd_table[MAX_NICS];
100 SerialState *serial_console;
101
102 /***********************************************************/
103 /* x86 io ports */
104
105 uint32_t default_ioport_readb(void *opaque, uint32_t address)
106 {
107 #ifdef DEBUG_UNUSED_IOPORT
108     fprintf(stderr, "inb: port=0x%04x\n", address);
109 #endif
110     return 0xff;
111 }
112
113 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
114 {
115 #ifdef DEBUG_UNUSED_IOPORT
116     fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
117 #endif
118 }
119
120 /* default is to make two byte accesses */
121 uint32_t default_ioport_readw(void *opaque, uint32_t address)
122 {
123     uint32_t data;
124     data = ioport_read_table[0][address & (MAX_IOPORTS - 1)](opaque, address);
125     data |= ioport_read_table[0][(address + 1) & (MAX_IOPORTS - 1)](opaque, address + 1) << 8;
126     return data;
127 }
128
129 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
130 {
131     ioport_write_table[0][address & (MAX_IOPORTS - 1)](opaque, address, data & 0xff);
132     ioport_write_table[0][(address + 1) & (MAX_IOPORTS - 1)](opaque, address + 1, (data >> 8) & 0xff);
133 }
134
135 uint32_t default_ioport_readl(void *opaque, uint32_t address)
136 {
137 #ifdef DEBUG_UNUSED_IOPORT
138     fprintf(stderr, "inl: port=0x%04x\n", address);
139 #endif
140     return 0xffffffff;
141 }
142
143 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
144 {
145 #ifdef DEBUG_UNUSED_IOPORT
146     fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
147 #endif
148 }
149
150 void init_ioports(void)
151 {
152     int i;
153
154     for(i = 0; i < MAX_IOPORTS; i++) {
155         ioport_read_table[0][i] = default_ioport_readb;
156         ioport_write_table[0][i] = default_ioport_writeb;
157         ioport_read_table[1][i] = default_ioport_readw;
158         ioport_write_table[1][i] = default_ioport_writew;
159         ioport_read_table[2][i] = default_ioport_readl;
160         ioport_write_table[2][i] = default_ioport_writel;
161     }
162 }
163
164 /* size is the word size in byte */
165 int register_ioport_read(int start, int length, int size, 
166                          IOPortReadFunc *func, void *opaque)
167 {
168     int i, bsize;
169
170     if (size == 1) {
171         bsize = 0;
172     } else if (size == 2) {
173         bsize = 1;
174     } else if (size == 4) {
175         bsize = 2;
176     } else {
177         hw_error("register_ioport_read: invalid size");
178         return -1;
179     }
180     for(i = start; i < start + length; i += size) {
181         ioport_read_table[bsize][i] = func;
182         if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
183             hw_error("register_ioport_read: invalid opaque");
184         ioport_opaque[i] = opaque;
185     }
186     return 0;
187 }
188
189 /* size is the word size in byte */
190 int register_ioport_write(int start, int length, int size, 
191                           IOPortWriteFunc *func, void *opaque)
192 {
193     int i, bsize;
194
195     if (size == 1) {
196         bsize = 0;
197     } else if (size == 2) {
198         bsize = 1;
199     } else if (size == 4) {
200         bsize = 2;
201     } else {
202         hw_error("register_ioport_write: invalid size");
203         return -1;
204     }
205     for(i = start; i < start + length; i += size) {
206         ioport_write_table[bsize][i] = func;
207         if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
208             hw_error("register_ioport_read: invalid opaque");
209         ioport_opaque[i] = opaque;
210     }
211     return 0;
212 }
213
214 void pstrcpy(char *buf, int buf_size, const char *str)
215 {
216     int c;
217     char *q = buf;
218
219     if (buf_size <= 0)
220         return;
221
222     for(;;) {
223         c = *str++;
224         if (c == 0 || q >= buf + buf_size - 1)
225             break;
226         *q++ = c;
227     }
228     *q = '\0';
229 }
230
231 /* strcat and truncate. */
232 char *pstrcat(char *buf, int buf_size, const char *s)
233 {
234     int len;
235     len = strlen(buf);
236     if (len < buf_size) 
237         pstrcpy(buf + len, buf_size - len, s);
238     return buf;
239 }
240
241 /* return the size or -1 if error */
242 int load_image(const char *filename, uint8_t *addr)
243 {
244     int fd, size;
245     fd = open(filename, O_RDONLY);
246     if (fd < 0)
247         return -1;
248     size = lseek(fd, 0, SEEK_END);
249     lseek(fd, 0, SEEK_SET);
250     if (read(fd, addr, size) != size) {
251         close(fd);
252         return -1;
253     }
254     close(fd);
255     return size;
256 }
257
258 void cpu_outb(CPUState *env, int addr, int val)
259 {
260     addr &= (MAX_IOPORTS - 1);
261     ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
262 }
263
264 void cpu_outw(CPUState *env, int addr, int val)
265 {
266     addr &= (MAX_IOPORTS - 1);
267     ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
268 }
269
270 void cpu_outl(CPUState *env, int addr, int val)
271 {
272     addr &= (MAX_IOPORTS - 1);
273     ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
274 }
275
276 int cpu_inb(CPUState *env, int addr)
277 {
278     addr &= (MAX_IOPORTS - 1);
279     return ioport_read_table[0][addr](ioport_opaque[addr], addr);
280 }
281
282 int cpu_inw(CPUState *env, int addr)
283 {
284     addr &= (MAX_IOPORTS - 1);
285     return ioport_read_table[1][addr](ioport_opaque[addr], addr);
286 }
287
288 int cpu_inl(CPUState *env, int addr)
289 {
290     addr &= (MAX_IOPORTS - 1);
291     return ioport_read_table[2][addr](ioport_opaque[addr], addr);
292 }
293
294 /***********************************************************/
295 void hw_error(const char *fmt, ...)
296 {
297     va_list ap;
298
299     va_start(ap, fmt);
300     fprintf(stderr, "qemu: hardware error: ");
301     vfprintf(stderr, fmt, ap);
302     fprintf(stderr, "\n");
303 #ifdef TARGET_I386
304     cpu_x86_dump_state(global_env, stderr, X86_DUMP_FPU | X86_DUMP_CCOP);
305 #else
306     cpu_dump_state(global_env, stderr, 0);
307 #endif
308     va_end(ap);
309     abort();
310 }
311
312 #if defined(__powerpc__)
313
314 static inline uint32_t get_tbl(void) 
315 {
316     uint32_t tbl;
317     asm volatile("mftb %0" : "=r" (tbl));
318     return tbl;
319 }
320
321 static inline uint32_t get_tbu(void) 
322 {
323         uint32_t tbl;
324         asm volatile("mftbu %0" : "=r" (tbl));
325         return tbl;
326 }
327
328 int64_t cpu_get_real_ticks(void)
329 {
330     uint32_t l, h, h1;
331     /* NOTE: we test if wrapping has occurred */
332     do {
333         h = get_tbu();
334         l = get_tbl();
335         h1 = get_tbu();
336     } while (h != h1);
337     return ((int64_t)h << 32) | l;
338 }
339
340 #elif defined(__i386__)
341
342 int64_t cpu_get_real_ticks(void)
343 {
344     int64_t val;
345     asm("rdtsc" : "=A" (val));
346     return val;
347 }
348
349 #else
350 #error unsupported CPU
351 #endif
352
353 static int64_t cpu_ticks_offset;
354 static int64_t cpu_ticks_last;
355
356 int64_t cpu_get_ticks(void)
357 {
358     return cpu_get_real_ticks() + cpu_ticks_offset;
359 }
360
361 /* enable cpu_get_ticks() */
362 void cpu_enable_ticks(void)
363 {
364     cpu_ticks_offset = cpu_ticks_last - cpu_get_real_ticks();
365 }
366
367 /* disable cpu_get_ticks() : the clock is stopped. You must not call
368    cpu_get_ticks() after that.  */
369 void cpu_disable_ticks(void)
370 {
371     cpu_ticks_last = cpu_get_ticks();
372 }
373
374 int64_t get_clock(void)
375 {
376     struct timeval tv;
377     gettimeofday(&tv, NULL);
378     return tv.tv_sec * 1000000LL + tv.tv_usec;
379 }
380
381 void cpu_calibrate_ticks(void)
382 {
383     int64_t usec, ticks;
384
385     usec = get_clock();
386     ticks = cpu_get_ticks();
387     usleep(50 * 1000);
388     usec = get_clock() - usec;
389     ticks = cpu_get_ticks() - ticks;
390     ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
391 }
392
393 /* compute with 96 bit intermediate result: (a*b)/c */
394 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
395 {
396     union {
397         uint64_t ll;
398         struct {
399 #ifdef WORDS_BIGENDIAN
400             uint32_t high, low;
401 #else
402             uint32_t low, high;
403 #endif            
404         } l;
405     } u, res;
406     uint64_t rl, rh;
407
408     u.ll = a;
409     rl = (uint64_t)u.l.low * (uint64_t)b;
410     rh = (uint64_t)u.l.high * (uint64_t)b;
411     rh += (rl >> 32);
412     res.l.high = rh / c;
413     res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
414     return res.ll;
415 }
416
417 /***********************************************************/
418 /* serial device */
419
420 int serial_open_device(void)
421 {
422     char slave_name[1024];
423     int master_fd, slave_fd;
424
425     if (serial_console == NULL && nographic) {
426         /* use console for serial port */
427         return 0;
428     } else {
429         if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
430             fprintf(stderr, "warning: could not create pseudo terminal for serial port\n");
431             return -1;
432         }
433         fprintf(stderr, "Serial port redirected to %s\n", slave_name);
434         return master_fd;
435     }
436 }
437
438 /***********************************************************/
439 /* Linux network device redirector */
440
441 static int tun_open(char *ifname, int ifname_size)
442 {
443     struct ifreq ifr;
444     int fd, ret;
445     
446     fd = open("/dev/net/tun", O_RDWR);
447     if (fd < 0) {
448         fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
449         return -1;
450     }
451     memset(&ifr, 0, sizeof(ifr));
452     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
453     pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
454     ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
455     if (ret != 0) {
456         fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
457         close(fd);
458         return -1;
459     }
460     printf("Connected to host network interface: %s\n", ifr.ifr_name);
461     pstrcpy(ifname, ifname_size, ifr.ifr_name);
462     fcntl(fd, F_SETFL, O_NONBLOCK);
463     return fd;
464 }
465
466 static int net_init(void)
467 {
468     int pid, status, launch_script, i;
469     NetDriverState *nd;
470     char *args[MAX_NICS + 2];
471     char **parg;
472
473     launch_script = 0;
474     for(i = 0; i < nb_nics; i++) {
475         nd = &nd_table[i];
476         if (nd->fd < 0) {
477             nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
478             if (nd->fd >= 0) 
479                 launch_script = 1;
480         }
481     }
482
483     if (launch_script) {
484         /* try to launch network init script */
485         pid = fork();
486         if (pid >= 0) {
487             if (pid == 0) {
488                 parg = args;
489                 *parg++ = network_script;
490                 for(i = 0; i < nb_nics; i++) {
491                     nd = &nd_table[i];
492                     if (nd->fd >= 0) {
493                         *parg++ = nd->ifname;
494                     }
495                 }
496                 *parg++ = NULL;
497                 execv(network_script, args);
498                 exit(1);
499             }
500             while (waitpid(pid, &status, 0) != pid);
501             if (!WIFEXITED(status) ||
502                 WEXITSTATUS(status) != 0) {
503                 fprintf(stderr, "%s: could not launch network script\n",
504                         network_script);
505             }
506         }
507     }
508     return 0;
509 }
510
511 void net_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
512 {
513 #ifdef DEBUG_NE2000
514     printf("NE2000: sending packet size=%d\n", size);
515 #endif
516     write(nd->fd, buf, size);
517 }
518
519 /***********************************************************/
520 /* dumb display */
521
522 /* init terminal so that we can grab keys */
523 static struct termios oldtty;
524
525 static void term_exit(void)
526 {
527     tcsetattr (0, TCSANOW, &oldtty);
528 }
529
530 static void term_init(void)
531 {
532     struct termios tty;
533
534     tcgetattr (0, &tty);
535     oldtty = tty;
536
537     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
538                           |INLCR|IGNCR|ICRNL|IXON);
539     tty.c_oflag |= OPOST;
540     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
541     /* if graphical mode, we allow Ctrl-C handling */
542     if (nographic)
543         tty.c_lflag &= ~ISIG;
544     tty.c_cflag &= ~(CSIZE|PARENB);
545     tty.c_cflag |= CS8;
546     tty.c_cc[VMIN] = 1;
547     tty.c_cc[VTIME] = 0;
548     
549     tcsetattr (0, TCSANOW, &tty);
550
551     atexit(term_exit);
552
553     fcntl(0, F_SETFL, O_NONBLOCK);
554 }
555
556 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
557 {
558 }
559
560 static void dumb_resize(DisplayState *ds, int w, int h)
561 {
562 }
563
564 static void dumb_refresh(DisplayState *ds)
565 {
566     vga_update_display();
567 }
568
569 void dumb_display_init(DisplayState *ds)
570 {
571     ds->data = NULL;
572     ds->linesize = 0;
573     ds->depth = 0;
574     ds->dpy_update = dumb_update;
575     ds->dpy_resize = dumb_resize;
576     ds->dpy_refresh = dumb_refresh;
577 }
578
579 #if !defined(CONFIG_SOFTMMU)
580 /***********************************************************/
581 /* cpu signal handler */
582 static void host_segv_handler(int host_signum, siginfo_t *info, 
583                               void *puc)
584 {
585     if (cpu_signal_handler(host_signum, info, puc))
586         return;
587     term_exit();
588     abort();
589 }
590 #endif
591
592 static int timer_irq_pending;
593 static int timer_irq_count;
594
595 static int timer_ms;
596 static int gui_refresh_pending, gui_refresh_count;
597
598 static void host_alarm_handler(int host_signum, siginfo_t *info, 
599                                void *puc)
600 {
601     /* NOTE: since usually the OS asks a 100 Hz clock, there can be
602        some drift between cpu_get_ticks() and the interrupt time. So
603        we queue some interrupts to avoid missing some */
604     timer_irq_count += pit_get_out_edges(&pit_channels[0]);
605     if (timer_irq_count) {
606         if (timer_irq_count > 2)
607             timer_irq_count = 2;
608         timer_irq_count--;
609         timer_irq_pending = 1;
610     }
611     gui_refresh_count += timer_ms;
612     if (gui_refresh_count >= GUI_REFRESH_INTERVAL) {
613         gui_refresh_count = 0;
614         gui_refresh_pending = 1;
615     }
616
617     if (gui_refresh_pending || timer_irq_pending) {
618         /* just exit from the cpu to have a chance to handle timers */
619         cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
620     }
621 }
622
623 #define MAX_IO_HANDLERS 64
624
625 typedef struct IOHandlerRecord {
626     int fd;
627     IOCanRWHandler *fd_can_read;
628     IOReadHandler *fd_read;
629     void *opaque;
630     /* temporary data */
631     struct pollfd *ufd;
632     int max_size;
633 } IOHandlerRecord;
634
635 static IOHandlerRecord io_handlers[MAX_IO_HANDLERS];
636 static int nb_io_handlers = 0;
637
638 int add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read, 
639                         IOReadHandler *fd_read, void *opaque)
640 {
641     IOHandlerRecord *ioh;
642
643     if (nb_io_handlers >= MAX_IO_HANDLERS)
644         return -1;
645     ioh = &io_handlers[nb_io_handlers];
646     ioh->fd = fd;
647     ioh->fd_can_read = fd_can_read;
648     ioh->fd_read = fd_read;
649     ioh->opaque = opaque;
650     nb_io_handlers++;
651     return 0;
652 }
653
654 /* main execution loop */
655
656 CPUState *cpu_gdbstub_get_env(void *opaque)
657 {
658     return global_env;
659 }
660
661 int main_loop(void *opaque)
662 {
663     struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf, *gdb_ufd;
664     int ret, n, timeout, serial_ok, max_size, i;
665     uint8_t buf[4096];
666     IOHandlerRecord *ioh;
667     CPUState *env = global_env;
668
669     if (!term_inited) {
670         /* initialize terminal only there so that the user has a
671            chance to stop QEMU with Ctrl-C before the gdb connection
672            is launched */
673         term_inited = 1;
674         term_init();
675     }
676
677     serial_ok = 1;
678     cpu_enable_ticks();
679     for(;;) {
680 #if defined (DO_TB_FLUSH)
681         tb_flush();
682 #endif
683         ret = cpu_exec(env);
684         if (reset_requested) {
685             ret = EXCP_INTERRUPT; 
686             break;
687         }
688         if (ret == EXCP_DEBUG) {
689             ret = EXCP_DEBUG;
690             break;
691         }
692         /* if hlt instruction, we wait until the next IRQ */
693         if (ret == EXCP_HLT) 
694             timeout = 10;
695         else
696             timeout = 0;
697
698         /* poll any events */
699         pf = ufds;
700         ioh = io_handlers;
701         for(i = 0; i < nb_io_handlers; i++) {
702             max_size = ioh->fd_can_read(ioh->opaque);
703             if (max_size > 0) {
704                 if (max_size > sizeof(buf))
705                     max_size = sizeof(buf);
706                 pf->fd = ioh->fd;
707                 pf->events = POLLIN;
708                 ioh->ufd = pf;
709                 pf++;
710             } else {
711                 ioh->ufd = NULL;
712             }
713             ioh->max_size = max_size;
714             ioh++;
715         }
716
717         gdb_ufd = NULL;
718         if (gdbstub_fd > 0) {
719             gdb_ufd = pf;
720             pf->fd = gdbstub_fd;
721             pf->events = POLLIN;
722             pf++;
723         }
724
725         ret = poll(ufds, pf - ufds, timeout);
726         if (ret > 0) {
727             ioh = io_handlers;
728             for(i = 0; i < nb_io_handlers; i++) {
729                 pf = ioh->ufd;
730                 if (pf) {
731                     n = read(ioh->fd, buf, ioh->max_size);
732                     if (n > 0) {
733                         ioh->fd_read(ioh->opaque, buf, n);
734                     }
735                 }
736                 ioh++;
737             }
738             if (gdb_ufd && (gdb_ufd->revents & POLLIN)) {
739                 uint8_t buf[1];
740                 /* stop emulation if requested by gdb */
741                 n = read(gdbstub_fd, buf, 1);
742                 if (n == 1) {
743                     ret = EXCP_INTERRUPT; 
744                     break;
745                 }
746             }
747         }
748
749         /* timer IRQ */
750         if (timer_irq_pending) {
751 #if defined (TARGET_I386)
752             pic_set_irq(0, 1);
753             pic_set_irq(0, 0);
754             timer_irq_pending = 0;
755             rtc_timer();
756 #endif
757         }
758         /* XXX: add explicit timer */
759         SB16_run();
760
761         /* run dma transfers, if any */
762         DMA_run();
763
764         /* VGA */
765         if (gui_refresh_pending) {
766             display_state.dpy_refresh(&display_state);
767             gui_refresh_pending = 0;
768         }
769     }
770     cpu_disable_ticks();
771     return ret;
772 }
773
774 void help(void)
775 {
776     printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003 Fabrice Bellard\n"
777            "usage: %s [options] [disk_image]\n"
778            "\n"
779            "'disk_image' is a raw hard image image for IDE hard disk 0\n"
780            "\n"
781            "Standard options:\n"
782            "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
783            "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
784            "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
785            "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
786            "-boot [a|b|c|d] boot on floppy (a, b), hard disk (c) or CD-ROM (d)\n"
787            "-snapshot       write to temporary files instead of disk image files\n"
788            "-m megs         set virtual RAM size to megs MB\n"
789            "-nographic      disable graphical output and redirect serial I/Os to console\n"
790            "\n"
791            "Network options:\n"
792            "-n script       set network init script [default=%s]\n"
793            "-nics n         simulate 'n' network interfaces [default=1]\n"
794            "-tun-fd fd0[,...] use these fds as already opened tap/tun interfaces\n"
795            "\n"
796            "Linux boot specific:\n"
797            "-kernel bzImage use 'bzImage' as kernel image\n"
798            "-append cmdline use 'cmdline' as kernel command line\n"
799            "-initrd file    use 'file' as initial ram disk\n"
800            "\n"
801            "Debug/Expert options:\n"
802            "-s              wait gdb connection to port %d\n"
803            "-p port         change gdb connection port\n"
804            "-d              output log to %s\n"
805            "-hdachs c,h,s   force hard disk 0 geometry (usually qemu can guess it)\n"
806            "-L path         set the directory for the BIOS and VGA BIOS\n"
807 #ifdef USE_CODE_COPY
808            "-no-code-copy   disable code copy acceleration\n"
809 #endif
810
811            "\n"
812            "During emulation, use C-a h to get terminal commands:\n",
813 #ifdef CONFIG_SOFTMMU
814            "qemu",
815 #else
816            "qemu-fast",
817 #endif
818            DEFAULT_NETWORK_SCRIPT, 
819            DEFAULT_GDBSTUB_PORT,
820            "/tmp/qemu.log");
821     term_print_help();
822 #ifndef CONFIG_SOFTMMU
823     printf("\n"
824            "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
825            "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
826            "PC emulation.\n");
827 #endif
828     exit(1);
829 }
830
831 struct option long_options[] = {
832     { "initrd", 1, NULL, 0, },
833     { "hda", 1, NULL, 0, },
834     { "hdb", 1, NULL, 0, },
835     { "snapshot", 0, NULL, 0, },
836     { "hdachs", 1, NULL, 0, },
837     { "nographic", 0, NULL, 0, },
838     { "kernel", 1, NULL, 0, },
839     { "append", 1, NULL, 0, },
840     { "tun-fd", 1, NULL, 0, },
841     { "hdc", 1, NULL, 0, },
842     { "hdd", 1, NULL, 0, },
843     { "cdrom", 1, NULL, 0, },
844     { "boot", 1, NULL, 0, },
845     { "fda", 1, NULL, 0, },
846     { "fdb", 1, NULL, 0, },
847     { "no-code-copy", 0, NULL, 0 },
848     { "nics", 1, NULL, 0 },
849     { NULL, 0, NULL, 0 },
850 };
851
852 #ifdef CONFIG_SDL
853 /* SDL use the pthreads and they modify sigaction. We don't
854    want that. */
855 #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2)
856 extern void __libc_sigaction();
857 #define sigaction(sig, act, oact) __libc_sigaction(sig, act, oact)
858 #else
859 extern void __sigaction();
860 #define sigaction(sig, act, oact) __sigaction(sig, act, oact)
861 #endif
862 #endif /* CONFIG_SDL */
863
864 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
865
866 /* this stack is only used during signal handling */
867 #define SIGNAL_STACK_SIZE 32768
868
869 static uint8_t *signal_stack;
870
871 #endif
872
873 int main(int argc, char **argv)
874 {
875     int c, i, use_gdbstub, gdbstub_port, long_index, has_cdrom;
876     int snapshot, linux_boot;
877     struct sigaction act;
878     struct itimerval itv;
879     CPUState *env;
880     const char *initrd_filename;
881     const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
882     const char *kernel_filename, *kernel_cmdline;
883     DisplayState *ds = &display_state;
884     int cyls, heads, secs;
885
886     /* we never want that malloc() uses mmap() */
887     mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
888     initrd_filename = NULL;
889     for(i = 0; i < MAX_FD; i++)
890         fd_filename[i] = NULL;
891     for(i = 0; i < MAX_DISKS; i++)
892         hd_filename[i] = NULL;
893     ram_size = 32 * 1024 * 1024;
894     vga_ram_size = VGA_RAM_SIZE;
895     pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
896     use_gdbstub = 0;
897     gdbstub_port = DEFAULT_GDBSTUB_PORT;
898     snapshot = 0;
899     nographic = 0;
900     kernel_filename = NULL;
901     kernel_cmdline = "";
902     has_cdrom = 1;
903     cyls = heads = secs = 0;
904
905     nb_nics = 1;
906     for(i = 0; i < MAX_NICS; i++) {
907         NetDriverState *nd = &nd_table[i];
908         nd->fd = -1;
909         /* init virtual mac address */
910         nd->macaddr[0] = 0x52;
911         nd->macaddr[1] = 0x54;
912         nd->macaddr[2] = 0x00;
913         nd->macaddr[3] = 0x12;
914         nd->macaddr[4] = 0x34;
915         nd->macaddr[5] = 0x56 + i;
916     }
917     
918     for(;;) {
919         c = getopt_long_only(argc, argv, "hm:dn:sp:L:", long_options, &long_index);
920         if (c == -1)
921             break;
922         switch(c) {
923         case 0:
924             switch(long_index) {
925             case 0:
926                 initrd_filename = optarg;
927                 break;
928             case 1:
929                 hd_filename[0] = optarg;
930                 break;
931             case 2:
932                 hd_filename[1] = optarg;
933                 break;
934             case 3:
935                 snapshot = 1;
936                 break;
937             case 4:
938                 {
939                     const char *p;
940                     p = optarg;
941                     cyls = strtol(p, (char **)&p, 0);
942                     if (*p != ',')
943                         goto chs_fail;
944                     p++;
945                     heads = strtol(p, (char **)&p, 0);
946                     if (*p != ',')
947                         goto chs_fail;
948                     p++;
949                     secs = strtol(p, (char **)&p, 0);
950                     if (*p != '\0') {
951                     chs_fail:
952                         cyls = 0;
953                     }
954                 }
955                 break;
956             case 5:
957                 nographic = 1;
958                 break;
959             case 6:
960                 kernel_filename = optarg;
961                 break;
962             case 7:
963                 kernel_cmdline = optarg;
964                 break;
965             case 8:
966                 {
967                     const char *p;
968                     int fd;
969                     p = optarg;
970                     nb_nics = 0;
971                     for(;;) {
972                         fd = strtol(p, (char **)&p, 0);
973                         nd_table[nb_nics].fd = fd;
974                         snprintf(nd_table[nb_nics].ifname, 
975                                  sizeof(nd_table[nb_nics].ifname),
976                                  "fd%d", nb_nics);
977                         nb_nics++;
978                         if (*p == ',') {
979                             p++;
980                         } else if (*p != '\0') {
981                             fprintf(stderr, "qemu: invalid fd for network interface %d\n", nb_nics);
982                             exit(1);
983                         } else {
984                             break;
985                         }
986                     }
987                 }
988                 break;
989             case 9:
990                 hd_filename[2] = optarg;
991                 has_cdrom = 0;
992                 break;
993             case 10:
994                 hd_filename[3] = optarg;
995                 break;
996             case 11:
997                 hd_filename[2] = optarg;
998                 has_cdrom = 1;
999                 break;
1000             case 12:
1001                 boot_device = optarg[0];
1002                 if (boot_device != 'a' && boot_device != 'b' &&
1003                     boot_device != 'c' && boot_device != 'd') {
1004                     fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
1005                     exit(1);
1006                 }
1007                 break;
1008             case 13:
1009                 fd_filename[0] = optarg;
1010                 break;
1011             case 14:
1012                 fd_filename[1] = optarg;
1013                 break;
1014             case 15:
1015                 code_copy_enabled = 0;
1016                 break;
1017             case 16:
1018                 nb_nics = atoi(optarg);
1019                 if (nb_nics < 1 || nb_nics > MAX_NICS) {
1020                     fprintf(stderr, "qemu: invalid number of network interfaces\n");
1021                     exit(1);
1022                 }
1023                 break;
1024             }
1025             break;
1026         case 'h':
1027             help();
1028             break;
1029         case 'm':
1030             ram_size = atoi(optarg) * 1024 * 1024;
1031             if (ram_size <= 0)
1032                 help();
1033             if (ram_size > PHYS_RAM_MAX_SIZE) {
1034                 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
1035                         PHYS_RAM_MAX_SIZE / (1024 * 1024));
1036                 exit(1);
1037             }
1038             break;
1039         case 'd':
1040             cpu_set_log(CPU_LOG_ALL);
1041             break;
1042         case 'n':
1043             pstrcpy(network_script, sizeof(network_script), optarg);
1044             break;
1045         case 's':
1046             use_gdbstub = 1;
1047             break;
1048         case 'p':
1049             gdbstub_port = atoi(optarg);
1050             break;
1051         case 'L':
1052             bios_dir = optarg;
1053             break;
1054         }
1055     }
1056
1057     if (optind < argc) {
1058         hd_filename[0] = argv[optind++];
1059     }
1060
1061     linux_boot = (kernel_filename != NULL);
1062         
1063     if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
1064         fd_filename[0] == '\0')
1065         help();
1066     
1067     /* boot to cd by default if no hard disk */
1068     if (hd_filename[0] == '\0' && boot_device == 'c') {
1069         if (fd_filename[0] != '\0')
1070             boot_device = 'a';
1071         else
1072             boot_device = 'd';
1073     }
1074
1075 #if !defined(CONFIG_SOFTMMU)
1076     /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
1077     {
1078         static uint8_t stdout_buf[4096];
1079         setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
1080     }
1081 #else
1082     setvbuf(stdout, NULL, _IOLBF, 0);
1083 #endif
1084
1085     /* init host network redirectors */
1086     net_init();
1087
1088     /* init the memory */
1089     phys_ram_size = ram_size + vga_ram_size;
1090
1091 #ifdef CONFIG_SOFTMMU
1092     phys_ram_base = memalign(TARGET_PAGE_SIZE, phys_ram_size);
1093     if (!phys_ram_base) {
1094         fprintf(stderr, "Could not allocate physical memory\n");
1095         exit(1);
1096     }
1097 #else
1098     /* as we must map the same page at several addresses, we must use
1099        a fd */
1100     {
1101         const char *tmpdir;
1102
1103         tmpdir = getenv("QEMU_TMPDIR");
1104         if (!tmpdir)
1105             tmpdir = "/tmp";
1106         snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
1107         if (mkstemp(phys_ram_file) < 0) {
1108             fprintf(stderr, "Could not create temporary memory file '%s'\n", 
1109                     phys_ram_file);
1110             exit(1);
1111         }
1112         phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
1113         if (phys_ram_fd < 0) {
1114             fprintf(stderr, "Could not open temporary memory file '%s'\n", 
1115                     phys_ram_file);
1116             exit(1);
1117         }
1118         ftruncate(phys_ram_fd, phys_ram_size);
1119         unlink(phys_ram_file);
1120         phys_ram_base = mmap(get_mmap_addr(phys_ram_size), 
1121                              phys_ram_size, 
1122                              PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
1123                              phys_ram_fd, 0);
1124         if (phys_ram_base == MAP_FAILED) {
1125             fprintf(stderr, "Could not map physical memory\n");
1126             exit(1);
1127         }
1128     }
1129 #endif
1130
1131     /* we always create the cdrom drive, even if no disk is there */
1132     if (has_cdrom) {
1133         bs_table[2] = bdrv_new("cdrom");
1134         bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
1135     }
1136
1137     /* open the virtual block devices */
1138     for(i = 0; i < MAX_DISKS; i++) {
1139         if (hd_filename[i]) {
1140             if (!bs_table[i]) {
1141                 char buf[64];
1142                 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
1143                 bs_table[i] = bdrv_new(buf);
1144             }
1145             if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
1146                 fprintf(stderr, "qemu: could not open hard disk image '%s\n",
1147                         hd_filename[i]);
1148                 exit(1);
1149             }
1150             if (i == 0 && cyls != 0) 
1151                 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
1152         }
1153     }
1154
1155     /* we always create at least one floppy disk */
1156     fd_table[0] = bdrv_new("fda");
1157     bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
1158
1159     for(i = 0; i < MAX_FD; i++) {
1160         if (fd_filename[i]) {
1161             if (!fd_table[i]) {
1162                 char buf[64];
1163                 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
1164                 fd_table[i] = bdrv_new(buf);
1165                 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
1166             }
1167             if (fd_filename[i] != '\0') {
1168                 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
1169                     fprintf(stderr, "qemu: could not open floppy disk image '%s\n",
1170                             fd_filename[i]);
1171                     exit(1);
1172                 }
1173             }
1174         }
1175     }
1176
1177     /* init CPU state */
1178     env = cpu_init();
1179     global_env = env;
1180     cpu_single_env = env;
1181
1182     init_ioports();
1183     cpu_calibrate_ticks();
1184
1185     /* terminal init */
1186     if (nographic) {
1187         dumb_display_init(ds);
1188     } else {
1189 #ifdef CONFIG_SDL
1190         sdl_display_init(ds);
1191 #else
1192         dumb_display_init(ds);
1193 #endif
1194     }
1195
1196 #if defined(TARGET_I386)
1197     pc_init(ram_size, vga_ram_size, boot_device,
1198             ds, fd_filename, snapshot,
1199             kernel_filename, kernel_cmdline, initrd_filename);
1200 #elif defined(TARGET_PPC)
1201     ppc_init();
1202 #endif
1203
1204     /* launched after the device init so that it can display or not a
1205        banner */
1206     monitor_init();
1207
1208     /* setup cpu signal handlers for MMU / self modifying code handling */
1209 #if !defined(CONFIG_SOFTMMU)
1210
1211 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1212     {
1213         stack_t stk;
1214         signal_stack = malloc(SIGNAL_STACK_SIZE);
1215         stk.ss_sp = signal_stack;
1216         stk.ss_size = SIGNAL_STACK_SIZE;
1217         stk.ss_flags = 0;
1218
1219         if (sigaltstack(&stk, NULL) < 0) {
1220             perror("sigaltstack");
1221             exit(1);
1222         }
1223     }
1224 #endif
1225         
1226     sigfillset(&act.sa_mask);
1227     act.sa_flags = SA_SIGINFO;
1228 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1229     act.sa_flags |= SA_ONSTACK;
1230 #endif
1231     act.sa_sigaction = host_segv_handler;
1232     sigaction(SIGSEGV, &act, NULL);
1233     sigaction(SIGBUS, &act, NULL);
1234 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1235     sigaction(SIGFPE, &act, NULL);
1236 #endif
1237 #endif
1238
1239     /* timer signal */
1240     sigfillset(&act.sa_mask);
1241     act.sa_flags = SA_SIGINFO;
1242 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
1243     act.sa_flags |= SA_ONSTACK;
1244 #endif
1245     act.sa_sigaction = host_alarm_handler;
1246     sigaction(SIGALRM, &act, NULL);
1247
1248     itv.it_interval.tv_sec = 0;
1249     itv.it_interval.tv_usec = 1000;
1250     itv.it_value.tv_sec = 0;
1251     itv.it_value.tv_usec = 10 * 1000;
1252     setitimer(ITIMER_REAL, &itv, NULL);
1253     /* we probe the tick duration of the kernel to inform the user if
1254        the emulated kernel requested a too high timer frequency */
1255     getitimer(ITIMER_REAL, &itv);
1256     timer_ms = itv.it_interval.tv_usec / 1000;
1257     pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * PIT_FREQ) / 
1258         1000000;
1259
1260     if (use_gdbstub) {
1261         cpu_gdbstub(NULL, main_loop, gdbstub_port);
1262     } else {
1263         main_loop(NULL);
1264     }
1265     return 0;
1266 }