]> Git Repo - qemu.git/blob - vl.c
-localtime option
[qemu.git] / 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 "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
33 #ifndef _WIN32
34 #include <sys/times.h>
35 #include <sys/wait.h>
36 #include <termios.h>
37 #include <sys/poll.h>
38 #include <sys/mman.h>
39 #include <sys/ioctl.h>
40 #include <sys/socket.h>
41 #ifdef _BSD
42 #include <sys/stat.h>
43 #include <libutil.h>
44 #else
45 #include <linux/if.h>
46 #include <linux/if_tun.h>
47 #include <pty.h>
48 #include <malloc.h>
49 #include <linux/rtc.h>
50 #endif
51 #endif
52
53 #if defined(CONFIG_SLIRP)
54 #include "libslirp.h"
55 #endif
56
57 #ifdef _WIN32
58 #include <malloc.h>
59 #include <sys/timeb.h>
60 #include <windows.h>
61 #define getopt_long_only getopt_long
62 #define memalign(align, size) malloc(size)
63 #endif
64
65 #ifdef CONFIG_SDL
66 #if defined(__linux__)
67 /* SDL use the pthreads and they modify sigaction. We don't
68    want that. */
69 #if (__GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2))
70 extern void __libc_sigaction();
71 #define sigaction(sig, act, oact) __libc_sigaction(sig, act, oact)
72 #else
73 extern void __sigaction();
74 #define sigaction(sig, act, oact) __sigaction(sig, act, oact)
75 #endif
76 #endif /* __linux__ */
77 #endif /* CONFIG_SDL */
78
79 #include "disas.h"
80
81 #include "exec-all.h"
82
83 //#define DO_TB_FLUSH
84
85 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
86
87 //#define DEBUG_UNUSED_IOPORT
88 //#define DEBUG_IOPORT
89
90 #if !defined(CONFIG_SOFTMMU)
91 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
92 #else
93 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
94 #endif
95
96 #ifdef TARGET_PPC
97 #define DEFAULT_RAM_SIZE 144
98 #else
99 #define DEFAULT_RAM_SIZE 32
100 #endif
101 /* in ms */
102 #define GUI_REFRESH_INTERVAL 30
103
104 /* XXX: use a two level table to limit memory usage */
105 #define MAX_IOPORTS 65536
106
107 const char *bios_dir = CONFIG_QEMU_SHAREDIR;
108 char phys_ram_file[1024];
109 CPUState *global_env;
110 CPUState *cpu_single_env;
111 void *ioport_opaque[MAX_IOPORTS];
112 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
113 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
114 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
115 int vga_ram_size;
116 int bios_size;
117 static DisplayState display_state;
118 int nographic;
119 int64_t ticks_per_sec;
120 int boot_device = 'c';
121 int ram_size;
122 static char network_script[1024];
123 int pit_min_timer_count = 0;
124 int nb_nics;
125 NetDriverState nd_table[MAX_NICS];
126 SerialState *serial_console;
127 QEMUTimer *gui_timer;
128 int vm_running;
129 int audio_enabled = 0;
130 int pci_enabled = 0;
131 int prep_enabled = 0;
132 int rtc_utc = 1;
133
134 /***********************************************************/
135 /* x86 ISA bus support */
136
137 target_phys_addr_t isa_mem_base = 0;
138
139 uint32_t default_ioport_readb(void *opaque, uint32_t address)
140 {
141 #ifdef DEBUG_UNUSED_IOPORT
142     fprintf(stderr, "inb: port=0x%04x\n", address);
143 #endif
144     return 0xff;
145 }
146
147 void default_ioport_writeb(void *opaque, uint32_t address, uint32_t data)
148 {
149 #ifdef DEBUG_UNUSED_IOPORT
150     fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
151 #endif
152 }
153
154 /* default is to make two byte accesses */
155 uint32_t default_ioport_readw(void *opaque, uint32_t address)
156 {
157     uint32_t data;
158     data = ioport_read_table[0][address](ioport_opaque[address], address);
159     address = (address + 1) & (MAX_IOPORTS - 1);
160     data |= ioport_read_table[0][address](ioport_opaque[address], address) << 8;
161     return data;
162 }
163
164 void default_ioport_writew(void *opaque, uint32_t address, uint32_t data)
165 {
166     ioport_write_table[0][address](ioport_opaque[address], address, data & 0xff);
167     address = (address + 1) & (MAX_IOPORTS - 1);
168     ioport_write_table[0][address](ioport_opaque[address], address, (data >> 8) & 0xff);
169 }
170
171 uint32_t default_ioport_readl(void *opaque, uint32_t address)
172 {
173 #ifdef DEBUG_UNUSED_IOPORT
174     fprintf(stderr, "inl: port=0x%04x\n", address);
175 #endif
176     return 0xffffffff;
177 }
178
179 void default_ioport_writel(void *opaque, uint32_t address, uint32_t data)
180 {
181 #ifdef DEBUG_UNUSED_IOPORT
182     fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
183 #endif
184 }
185
186 void init_ioports(void)
187 {
188     int i;
189
190     for(i = 0; i < MAX_IOPORTS; i++) {
191         ioport_read_table[0][i] = default_ioport_readb;
192         ioport_write_table[0][i] = default_ioport_writeb;
193         ioport_read_table[1][i] = default_ioport_readw;
194         ioport_write_table[1][i] = default_ioport_writew;
195         ioport_read_table[2][i] = default_ioport_readl;
196         ioport_write_table[2][i] = default_ioport_writel;
197     }
198 }
199
200 /* size is the word size in byte */
201 int register_ioport_read(int start, int length, int size, 
202                          IOPortReadFunc *func, void *opaque)
203 {
204     int i, bsize;
205
206     if (size == 1) {
207         bsize = 0;
208     } else if (size == 2) {
209         bsize = 1;
210     } else if (size == 4) {
211         bsize = 2;
212     } else {
213         hw_error("register_ioport_read: invalid size");
214         return -1;
215     }
216     for(i = start; i < start + length; i += size) {
217         ioport_read_table[bsize][i] = func;
218         if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
219             hw_error("register_ioport_read: invalid opaque");
220         ioport_opaque[i] = opaque;
221     }
222     return 0;
223 }
224
225 /* size is the word size in byte */
226 int register_ioport_write(int start, int length, int size, 
227                           IOPortWriteFunc *func, void *opaque)
228 {
229     int i, bsize;
230
231     if (size == 1) {
232         bsize = 0;
233     } else if (size == 2) {
234         bsize = 1;
235     } else if (size == 4) {
236         bsize = 2;
237     } else {
238         hw_error("register_ioport_write: invalid size");
239         return -1;
240     }
241     for(i = start; i < start + length; i += size) {
242         ioport_write_table[bsize][i] = func;
243         if (ioport_opaque[i] != NULL && ioport_opaque[i] != opaque)
244             hw_error("register_ioport_read: invalid opaque");
245         ioport_opaque[i] = opaque;
246     }
247     return 0;
248 }
249
250 void isa_unassign_ioport(int start, int length)
251 {
252     int i;
253
254     for(i = start; i < start + length; i++) {
255         ioport_read_table[0][i] = default_ioport_readb;
256         ioport_read_table[1][i] = default_ioport_readw;
257         ioport_read_table[2][i] = default_ioport_readl;
258
259         ioport_write_table[0][i] = default_ioport_writeb;
260         ioport_write_table[1][i] = default_ioport_writew;
261         ioport_write_table[2][i] = default_ioport_writel;
262     }
263 }
264
265 void pstrcpy(char *buf, int buf_size, const char *str)
266 {
267     int c;
268     char *q = buf;
269
270     if (buf_size <= 0)
271         return;
272
273     for(;;) {
274         c = *str++;
275         if (c == 0 || q >= buf + buf_size - 1)
276             break;
277         *q++ = c;
278     }
279     *q = '\0';
280 }
281
282 /* strcat and truncate. */
283 char *pstrcat(char *buf, int buf_size, const char *s)
284 {
285     int len;
286     len = strlen(buf);
287     if (len < buf_size) 
288         pstrcpy(buf + len, buf_size - len, s);
289     return buf;
290 }
291
292 /* return the size or -1 if error */
293 int load_image(const char *filename, uint8_t *addr)
294 {
295     int fd, size;
296     fd = open(filename, O_RDONLY | O_BINARY);
297     if (fd < 0)
298         return -1;
299     size = lseek(fd, 0, SEEK_END);
300     lseek(fd, 0, SEEK_SET);
301     if (read(fd, addr, size) != size) {
302         close(fd);
303         return -1;
304     }
305     close(fd);
306     return size;
307 }
308
309 void cpu_outb(CPUState *env, int addr, int val)
310 {
311 #ifdef DEBUG_IOPORT
312     if (loglevel & CPU_LOG_IOPORT)
313         fprintf(logfile, "outb: %04x %02x\n", addr, val);
314 #endif    
315     ioport_write_table[0][addr](ioport_opaque[addr], addr, val);
316 }
317
318 void cpu_outw(CPUState *env, int addr, int val)
319 {
320 #ifdef DEBUG_IOPORT
321     if (loglevel & CPU_LOG_IOPORT)
322         fprintf(logfile, "outw: %04x %04x\n", addr, val);
323 #endif    
324     ioport_write_table[1][addr](ioport_opaque[addr], addr, val);
325 }
326
327 void cpu_outl(CPUState *env, int addr, int val)
328 {
329 #ifdef DEBUG_IOPORT
330     if (loglevel & CPU_LOG_IOPORT)
331         fprintf(logfile, "outl: %04x %08x\n", addr, val);
332 #endif
333     ioport_write_table[2][addr](ioport_opaque[addr], addr, val);
334 }
335
336 int cpu_inb(CPUState *env, int addr)
337 {
338     int val;
339     val = ioport_read_table[0][addr](ioport_opaque[addr], addr);
340 #ifdef DEBUG_IOPORT
341     if (loglevel & CPU_LOG_IOPORT)
342         fprintf(logfile, "inb : %04x %02x\n", addr, val);
343 #endif
344     return val;
345 }
346
347 int cpu_inw(CPUState *env, int addr)
348 {
349     int val;
350     val = ioport_read_table[1][addr](ioport_opaque[addr], addr);
351 #ifdef DEBUG_IOPORT
352     if (loglevel & CPU_LOG_IOPORT)
353         fprintf(logfile, "inw : %04x %04x\n", addr, val);
354 #endif
355     return val;
356 }
357
358 int cpu_inl(CPUState *env, int addr)
359 {
360     int val;
361     val = ioport_read_table[2][addr](ioport_opaque[addr], addr);
362 #ifdef DEBUG_IOPORT
363     if (loglevel & CPU_LOG_IOPORT)
364         fprintf(logfile, "inl : %04x %08x\n", addr, val);
365 #endif
366     return val;
367 }
368
369 /***********************************************************/
370 void hw_error(const char *fmt, ...)
371 {
372     va_list ap;
373
374     va_start(ap, fmt);
375     fprintf(stderr, "qemu: hardware error: ");
376     vfprintf(stderr, fmt, ap);
377     fprintf(stderr, "\n");
378 #ifdef TARGET_I386
379     cpu_x86_dump_state(global_env, stderr, X86_DUMP_FPU | X86_DUMP_CCOP);
380 #else
381     cpu_dump_state(global_env, stderr, 0);
382 #endif
383     va_end(ap);
384     abort();
385 }
386
387 /***********************************************************/
388 /* timers */
389
390 #if defined(__powerpc__)
391
392 static inline uint32_t get_tbl(void) 
393 {
394     uint32_t tbl;
395     asm volatile("mftb %0" : "=r" (tbl));
396     return tbl;
397 }
398
399 static inline uint32_t get_tbu(void) 
400 {
401         uint32_t tbl;
402         asm volatile("mftbu %0" : "=r" (tbl));
403         return tbl;
404 }
405
406 int64_t cpu_get_real_ticks(void)
407 {
408     uint32_t l, h, h1;
409     /* NOTE: we test if wrapping has occurred */
410     do {
411         h = get_tbu();
412         l = get_tbl();
413         h1 = get_tbu();
414     } while (h != h1);
415     return ((int64_t)h << 32) | l;
416 }
417
418 #elif defined(__i386__)
419
420 int64_t cpu_get_real_ticks(void)
421 {
422     int64_t val;
423     asm volatile ("rdtsc" : "=A" (val));
424     return val;
425 }
426
427 #elif defined(__x86_64__)
428
429 int64_t cpu_get_real_ticks(void)
430 {
431     uint32_t low,high;
432     int64_t val;
433     asm volatile("rdtsc" : "=a" (low), "=d" (high));
434     val = high;
435     val <<= 32;
436     val |= low;
437     return val;
438 }
439
440 #else
441 #error unsupported CPU
442 #endif
443
444 static int64_t cpu_ticks_offset;
445 static int cpu_ticks_enabled;
446
447 static inline int64_t cpu_get_ticks(void)
448 {
449     if (!cpu_ticks_enabled) {
450         return cpu_ticks_offset;
451     } else {
452         return cpu_get_real_ticks() + cpu_ticks_offset;
453     }
454 }
455
456 /* enable cpu_get_ticks() */
457 void cpu_enable_ticks(void)
458 {
459     if (!cpu_ticks_enabled) {
460         cpu_ticks_offset -= cpu_get_real_ticks();
461         cpu_ticks_enabled = 1;
462     }
463 }
464
465 /* disable cpu_get_ticks() : the clock is stopped. You must not call
466    cpu_get_ticks() after that.  */
467 void cpu_disable_ticks(void)
468 {
469     if (cpu_ticks_enabled) {
470         cpu_ticks_offset = cpu_get_ticks();
471         cpu_ticks_enabled = 0;
472     }
473 }
474
475 static int64_t get_clock(void)
476 {
477 #ifdef _WIN32
478     struct _timeb tb;
479     _ftime(&tb);
480     return ((int64_t)tb.time * 1000 + (int64_t)tb.millitm) * 1000;
481 #else
482     struct timeval tv;
483     gettimeofday(&tv, NULL);
484     return tv.tv_sec * 1000000LL + tv.tv_usec;
485 #endif
486 }
487
488 void cpu_calibrate_ticks(void)
489 {
490     int64_t usec, ticks;
491
492     usec = get_clock();
493     ticks = cpu_get_real_ticks();
494 #ifdef _WIN32
495     Sleep(50);
496 #else
497     usleep(50 * 1000);
498 #endif
499     usec = get_clock() - usec;
500     ticks = cpu_get_real_ticks() - ticks;
501     ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
502 }
503
504 /* compute with 96 bit intermediate result: (a*b)/c */
505 uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
506 {
507     union {
508         uint64_t ll;
509         struct {
510 #ifdef WORDS_BIGENDIAN
511             uint32_t high, low;
512 #else
513             uint32_t low, high;
514 #endif            
515         } l;
516     } u, res;
517     uint64_t rl, rh;
518
519     u.ll = a;
520     rl = (uint64_t)u.l.low * (uint64_t)b;
521     rh = (uint64_t)u.l.high * (uint64_t)b;
522     rh += (rl >> 32);
523     res.l.high = rh / c;
524     res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
525     return res.ll;
526 }
527
528 #define QEMU_TIMER_REALTIME 0
529 #define QEMU_TIMER_VIRTUAL  1
530
531 struct QEMUClock {
532     int type;
533     /* XXX: add frequency */
534 };
535
536 struct QEMUTimer {
537     QEMUClock *clock;
538     int64_t expire_time;
539     QEMUTimerCB *cb;
540     void *opaque;
541     struct QEMUTimer *next;
542 };
543
544 QEMUClock *rt_clock;
545 QEMUClock *vm_clock;
546
547 static QEMUTimer *active_timers[2];
548 #ifdef _WIN32
549 static MMRESULT timerID;
550 #else
551 /* frequency of the times() clock tick */
552 static int timer_freq;
553 #endif
554
555 QEMUClock *qemu_new_clock(int type)
556 {
557     QEMUClock *clock;
558     clock = qemu_mallocz(sizeof(QEMUClock));
559     if (!clock)
560         return NULL;
561     clock->type = type;
562     return clock;
563 }
564
565 QEMUTimer *qemu_new_timer(QEMUClock *clock, QEMUTimerCB *cb, void *opaque)
566 {
567     QEMUTimer *ts;
568
569     ts = qemu_mallocz(sizeof(QEMUTimer));
570     ts->clock = clock;
571     ts->cb = cb;
572     ts->opaque = opaque;
573     return ts;
574 }
575
576 void qemu_free_timer(QEMUTimer *ts)
577 {
578     qemu_free(ts);
579 }
580
581 /* stop a timer, but do not dealloc it */
582 void qemu_del_timer(QEMUTimer *ts)
583 {
584     QEMUTimer **pt, *t;
585
586     /* NOTE: this code must be signal safe because
587        qemu_timer_expired() can be called from a signal. */
588     pt = &active_timers[ts->clock->type];
589     for(;;) {
590         t = *pt;
591         if (!t)
592             break;
593         if (t == ts) {
594             *pt = t->next;
595             break;
596         }
597         pt = &t->next;
598     }
599 }
600
601 /* modify the current timer so that it will be fired when current_time
602    >= expire_time. The corresponding callback will be called. */
603 void qemu_mod_timer(QEMUTimer *ts, int64_t expire_time)
604 {
605     QEMUTimer **pt, *t;
606
607     qemu_del_timer(ts);
608
609     /* add the timer in the sorted list */
610     /* NOTE: this code must be signal safe because
611        qemu_timer_expired() can be called from a signal. */
612     pt = &active_timers[ts->clock->type];
613     for(;;) {
614         t = *pt;
615         if (!t)
616             break;
617         if (t->expire_time > expire_time) 
618             break;
619         pt = &t->next;
620     }
621     ts->expire_time = expire_time;
622     ts->next = *pt;
623     *pt = ts;
624 }
625
626 int qemu_timer_pending(QEMUTimer *ts)
627 {
628     QEMUTimer *t;
629     for(t = active_timers[ts->clock->type]; t != NULL; t = t->next) {
630         if (t == ts)
631             return 1;
632     }
633     return 0;
634 }
635
636 static inline int qemu_timer_expired(QEMUTimer *timer_head, int64_t current_time)
637 {
638     if (!timer_head)
639         return 0;
640     return (timer_head->expire_time <= current_time);
641 }
642
643 static void qemu_run_timers(QEMUTimer **ptimer_head, int64_t current_time)
644 {
645     QEMUTimer *ts;
646     
647     for(;;) {
648         ts = *ptimer_head;
649         if (ts->expire_time > current_time)
650             break;
651         /* remove timer from the list before calling the callback */
652         *ptimer_head = ts->next;
653         ts->next = NULL;
654         
655         /* run the callback (the timer list can be modified) */
656         ts->cb(ts->opaque);
657     }
658 }
659
660 int64_t qemu_get_clock(QEMUClock *clock)
661 {
662     switch(clock->type) {
663     case QEMU_TIMER_REALTIME:
664 #ifdef _WIN32
665         return GetTickCount();
666 #else
667         {
668             struct tms tp;
669
670             /* Note that using gettimeofday() is not a good solution
671                for timers because its value change when the date is
672                modified. */
673             if (timer_freq == 100) {
674                 return times(&tp) * 10;
675             } else {
676                 return ((int64_t)times(&tp) * 1000) / timer_freq;
677             }
678         }
679 #endif
680     default:
681     case QEMU_TIMER_VIRTUAL:
682         return cpu_get_ticks();
683     }
684 }
685
686 /* save a timer */
687 void qemu_put_timer(QEMUFile *f, QEMUTimer *ts)
688 {
689     uint64_t expire_time;
690
691     if (qemu_timer_pending(ts)) {
692         expire_time = ts->expire_time;
693     } else {
694         expire_time = -1;
695     }
696     qemu_put_be64(f, expire_time);
697 }
698
699 void qemu_get_timer(QEMUFile *f, QEMUTimer *ts)
700 {
701     uint64_t expire_time;
702
703     expire_time = qemu_get_be64(f);
704     if (expire_time != -1) {
705         qemu_mod_timer(ts, expire_time);
706     } else {
707         qemu_del_timer(ts);
708     }
709 }
710
711 static void timer_save(QEMUFile *f, void *opaque)
712 {
713     if (cpu_ticks_enabled) {
714         hw_error("cannot save state if virtual timers are running");
715     }
716     qemu_put_be64s(f, &cpu_ticks_offset);
717     qemu_put_be64s(f, &ticks_per_sec);
718 }
719
720 static int timer_load(QEMUFile *f, void *opaque, int version_id)
721 {
722     if (version_id != 1)
723         return -EINVAL;
724     if (cpu_ticks_enabled) {
725         return -EINVAL;
726     }
727     qemu_get_be64s(f, &cpu_ticks_offset);
728     qemu_get_be64s(f, &ticks_per_sec);
729     return 0;
730 }
731
732 #ifdef _WIN32
733 void CALLBACK host_alarm_handler(UINT uTimerID, UINT uMsg, 
734                                  DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2)
735 #else
736 static void host_alarm_handler(int host_signum)
737 #endif
738 {
739     if (qemu_timer_expired(active_timers[QEMU_TIMER_VIRTUAL],
740                            qemu_get_clock(vm_clock)) ||
741         qemu_timer_expired(active_timers[QEMU_TIMER_REALTIME],
742                            qemu_get_clock(rt_clock))) {
743         /* stop the cpu because a timer occured */
744         cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
745     }
746 }
747
748 #ifndef _WIN32
749
750 #if defined(__linux__)
751
752 #define RTC_FREQ 1024
753
754 static int rtc_fd;
755
756 static int start_rtc_timer(void)
757 {
758     rtc_fd = open("/dev/rtc", O_RDONLY);
759     if (rtc_fd < 0)
760         return -1;
761     if (ioctl(rtc_fd, RTC_IRQP_SET, RTC_FREQ) < 0) {
762         fprintf(stderr, "Could not configure '/dev/rtc' to have a 1024 Hz timer. This is not a fatal\n"
763                 "error, but for better emulation accuracy either use a 2.6 host Linux kernel or\n"
764                 "type 'echo 1024 > /proc/sys/dev/rtc/max-user-freq' as root.\n");
765         goto fail;
766     }
767     if (ioctl(rtc_fd, RTC_PIE_ON, 0) < 0) {
768     fail:
769         close(rtc_fd);
770         return -1;
771     }
772     pit_min_timer_count = PIT_FREQ / RTC_FREQ;
773     return 0;
774 }
775
776 #else
777
778 static int start_rtc_timer(void)
779 {
780     return -1;
781 }
782
783 #endif /* !defined(__linux__) */
784
785 #endif /* !defined(_WIN32) */
786
787 static void init_timers(void)
788 {
789     rt_clock = qemu_new_clock(QEMU_TIMER_REALTIME);
790     vm_clock = qemu_new_clock(QEMU_TIMER_VIRTUAL);
791
792 #ifdef _WIN32
793     {
794         int count=0;
795         timerID = timeSetEvent(10,    // interval (ms)
796                                0,     // resolution
797                                host_alarm_handler, // function
798                                (DWORD)&count,  // user parameter
799                                TIME_PERIODIC | TIME_CALLBACK_FUNCTION);
800         if( !timerID ) {
801             perror("failed timer alarm");
802             exit(1);
803         }
804     }
805     pit_min_timer_count = ((uint64_t)10000 * PIT_FREQ) / 1000000;
806 #else
807     {
808         struct sigaction act;
809         struct itimerval itv;
810         
811         /* get times() syscall frequency */
812         timer_freq = sysconf(_SC_CLK_TCK);
813         
814         /* timer signal */
815         sigfillset(&act.sa_mask);
816         act.sa_flags = 0;
817 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
818         act.sa_flags |= SA_ONSTACK;
819 #endif
820         act.sa_handler = host_alarm_handler;
821         sigaction(SIGALRM, &act, NULL);
822
823         itv.it_interval.tv_sec = 0;
824         itv.it_interval.tv_usec = 1000;
825         itv.it_value.tv_sec = 0;
826         itv.it_value.tv_usec = 10 * 1000;
827         setitimer(ITIMER_REAL, &itv, NULL);
828         /* we probe the tick duration of the kernel to inform the user if
829            the emulated kernel requested a too high timer frequency */
830         getitimer(ITIMER_REAL, &itv);
831
832         if (itv.it_interval.tv_usec > 1000) {
833             /* try to use /dev/rtc to have a faster timer */
834             if (start_rtc_timer() < 0)
835                 goto use_itimer;
836             /* disable itimer */
837             itv.it_interval.tv_sec = 0;
838             itv.it_interval.tv_usec = 0;
839             itv.it_value.tv_sec = 0;
840             itv.it_value.tv_usec = 0;
841             setitimer(ITIMER_REAL, &itv, NULL);
842
843             /* use the RTC */
844             sigaction(SIGIO, &act, NULL);
845             fcntl(rtc_fd, F_SETFL, O_ASYNC);
846             fcntl(rtc_fd, F_SETOWN, getpid());
847         } else {
848         use_itimer:
849             pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * 
850                                    PIT_FREQ) / 1000000;
851         }
852     }
853 #endif
854 }
855
856 void quit_timers(void)
857 {
858 #ifdef _WIN32
859     timeKillEvent(timerID);
860 #endif
861 }
862
863 /***********************************************************/
864 /* serial device */
865
866 #ifdef _WIN32
867
868 int serial_open_device(void)
869 {
870     return -1;
871 }
872
873 #else
874
875 int serial_open_device(void)
876 {
877     char slave_name[1024];
878     int master_fd, slave_fd;
879
880     if (serial_console == NULL && nographic) {
881         /* use console for serial port */
882         return 0;
883     } else {
884 #if 0
885         /* Not satisfying */
886         if (openpty(&master_fd, &slave_fd, slave_name, NULL, NULL) < 0) {
887             fprintf(stderr, "warning: could not create pseudo terminal for serial port\n");
888             return -1;
889         }
890         fprintf(stderr, "Serial port redirected to %s\n", slave_name);
891         return master_fd;
892 #else
893         return -1;
894 #endif
895     }
896 }
897
898 #endif
899
900 /***********************************************************/
901 /* Linux network device redirectors */
902
903 void hex_dump(FILE *f, const uint8_t *buf, int size)
904 {
905     int len, i, j, c;
906
907     for(i=0;i<size;i+=16) {
908         len = size - i;
909         if (len > 16)
910             len = 16;
911         fprintf(f, "%08x ", i);
912         for(j=0;j<16;j++) {
913             if (j < len)
914                 fprintf(f, " %02x", buf[i+j]);
915             else
916                 fprintf(f, "   ");
917         }
918         fprintf(f, " ");
919         for(j=0;j<len;j++) {
920             c = buf[i+j];
921             if (c < ' ' || c > '~')
922                 c = '.';
923             fprintf(f, "%c", c);
924         }
925         fprintf(f, "\n");
926     }
927 }
928
929 void qemu_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
930 {
931     nd->send_packet(nd, buf, size);
932 }
933
934 void qemu_add_read_packet(NetDriverState *nd, IOCanRWHandler *fd_can_read, 
935                           IOReadHandler *fd_read, void *opaque)
936 {
937     nd->add_read_packet(nd, fd_can_read, fd_read, opaque);
938 }
939
940 /* dummy network adapter */
941
942 static void dummy_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
943 {
944 }
945
946 static void dummy_add_read_packet(NetDriverState *nd, 
947                                   IOCanRWHandler *fd_can_read, 
948                                   IOReadHandler *fd_read, void *opaque)
949 {
950 }
951
952 static int net_dummy_init(NetDriverState *nd)
953 {
954     nd->send_packet = dummy_send_packet;
955     nd->add_read_packet = dummy_add_read_packet;
956     pstrcpy(nd->ifname, sizeof(nd->ifname), "dummy");
957     return 0;
958 }
959
960 #if defined(CONFIG_SLIRP)
961
962 /* slirp network adapter */
963
964 static void *slirp_fd_opaque;
965 static IOCanRWHandler *slirp_fd_can_read;
966 static IOReadHandler *slirp_fd_read;
967 static int slirp_inited;
968
969 int slirp_can_output(void)
970 {
971     return slirp_fd_can_read(slirp_fd_opaque);
972 }
973
974 void slirp_output(const uint8_t *pkt, int pkt_len)
975 {
976 #if 0
977     printf("output:\n");
978     hex_dump(stdout, pkt, pkt_len);
979 #endif
980     slirp_fd_read(slirp_fd_opaque, pkt, pkt_len);
981 }
982
983 static void slirp_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
984 {
985 #if 0
986     printf("input:\n");
987     hex_dump(stdout, buf, size);
988 #endif
989     slirp_input(buf, size);
990 }
991
992 static void slirp_add_read_packet(NetDriverState *nd, 
993                                   IOCanRWHandler *fd_can_read, 
994                                   IOReadHandler *fd_read, void *opaque)
995 {
996     slirp_fd_opaque = opaque;
997     slirp_fd_can_read = fd_can_read;
998     slirp_fd_read = fd_read;
999 }
1000
1001 static int net_slirp_init(NetDriverState *nd)
1002 {
1003     if (!slirp_inited) {
1004         slirp_inited = 1;
1005         slirp_init();
1006     }
1007     nd->send_packet = slirp_send_packet;
1008     nd->add_read_packet = slirp_add_read_packet;
1009     pstrcpy(nd->ifname, sizeof(nd->ifname), "slirp");
1010     return 0;
1011 }
1012
1013 #endif /* CONFIG_SLIRP */
1014
1015 #if !defined(_WIN32)
1016 #ifdef _BSD
1017 static int tun_open(char *ifname, int ifname_size)
1018 {
1019     int fd;
1020     char *dev;
1021     struct stat s;
1022
1023     fd = open("/dev/tap", O_RDWR);
1024     if (fd < 0) {
1025         fprintf(stderr, "warning: could not open /dev/tap: no virtual network emulation\n");
1026         return -1;
1027     }
1028
1029     fstat(fd, &s);
1030     dev = devname(s.st_rdev, S_IFCHR);
1031     pstrcpy(ifname, ifname_size, dev);
1032
1033     fcntl(fd, F_SETFL, O_NONBLOCK);
1034     return fd;
1035 }
1036 #else
1037 static int tun_open(char *ifname, int ifname_size)
1038 {
1039     struct ifreq ifr;
1040     int fd, ret;
1041     
1042     fd = open("/dev/net/tun", O_RDWR);
1043     if (fd < 0) {
1044         fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1045         return -1;
1046     }
1047     memset(&ifr, 0, sizeof(ifr));
1048     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1049     pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1050     ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1051     if (ret != 0) {
1052         fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1053         close(fd);
1054         return -1;
1055     }
1056     printf("Connected to host network interface: %s\n", ifr.ifr_name);
1057     pstrcpy(ifname, ifname_size, ifr.ifr_name);
1058     fcntl(fd, F_SETFL, O_NONBLOCK);
1059     return fd;
1060 }
1061 #endif
1062
1063 static void tun_send_packet(NetDriverState *nd, const uint8_t *buf, int size)
1064 {
1065     write(nd->fd, buf, size);
1066 }
1067
1068 static void tun_add_read_packet(NetDriverState *nd, 
1069                                 IOCanRWHandler *fd_can_read, 
1070                                 IOReadHandler *fd_read, void *opaque)
1071 {
1072     qemu_add_fd_read_handler(nd->fd, fd_can_read, fd_read, opaque);
1073 }
1074
1075 static int net_tun_init(NetDriverState *nd)
1076 {
1077     int pid, status;
1078     char *args[3];
1079     char **parg;
1080
1081     nd->fd = tun_open(nd->ifname, sizeof(nd->ifname));
1082     if (nd->fd < 0)
1083         return -1;
1084
1085     /* try to launch network init script */
1086     pid = fork();
1087     if (pid >= 0) {
1088         if (pid == 0) {
1089             parg = args;
1090             *parg++ = network_script;
1091             *parg++ = nd->ifname;
1092             *parg++ = NULL;
1093             execv(network_script, args);
1094             exit(1);
1095         }
1096         while (waitpid(pid, &status, 0) != pid);
1097         if (!WIFEXITED(status) ||
1098             WEXITSTATUS(status) != 0) {
1099             fprintf(stderr, "%s: could not launch network script\n",
1100                     network_script);
1101         }
1102     }
1103     nd->send_packet = tun_send_packet;
1104     nd->add_read_packet = tun_add_read_packet;
1105     return 0;
1106 }
1107
1108 static int net_fd_init(NetDriverState *nd, int fd)
1109 {
1110     nd->fd = fd;
1111     nd->send_packet = tun_send_packet;
1112     nd->add_read_packet = tun_add_read_packet;
1113     pstrcpy(nd->ifname, sizeof(nd->ifname), "tunfd");
1114     return 0;
1115 }
1116
1117 #endif /* !_WIN32 */
1118
1119 /***********************************************************/
1120 /* dumb display */
1121
1122 #ifdef _WIN32
1123
1124 static void term_exit(void)
1125 {
1126 }
1127
1128 static void term_init(void)
1129 {
1130 }
1131
1132 #else
1133
1134 /* init terminal so that we can grab keys */
1135 static struct termios oldtty;
1136
1137 static void term_exit(void)
1138 {
1139     tcsetattr (0, TCSANOW, &oldtty);
1140 }
1141
1142 static void term_init(void)
1143 {
1144     struct termios tty;
1145
1146     tcgetattr (0, &tty);
1147     oldtty = tty;
1148
1149     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
1150                           |INLCR|IGNCR|ICRNL|IXON);
1151     tty.c_oflag |= OPOST;
1152     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
1153     /* if graphical mode, we allow Ctrl-C handling */
1154     if (nographic)
1155         tty.c_lflag &= ~ISIG;
1156     tty.c_cflag &= ~(CSIZE|PARENB);
1157     tty.c_cflag |= CS8;
1158     tty.c_cc[VMIN] = 1;
1159     tty.c_cc[VTIME] = 0;
1160     
1161     tcsetattr (0, TCSANOW, &tty);
1162
1163     atexit(term_exit);
1164
1165     fcntl(0, F_SETFL, O_NONBLOCK);
1166 }
1167
1168 #endif
1169
1170 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
1171 {
1172 }
1173
1174 static void dumb_resize(DisplayState *ds, int w, int h)
1175 {
1176 }
1177
1178 static void dumb_refresh(DisplayState *ds)
1179 {
1180     vga_update_display();
1181 }
1182
1183 void dumb_display_init(DisplayState *ds)
1184 {
1185     ds->data = NULL;
1186     ds->linesize = 0;
1187     ds->depth = 0;
1188     ds->dpy_update = dumb_update;
1189     ds->dpy_resize = dumb_resize;
1190     ds->dpy_refresh = dumb_refresh;
1191 }
1192
1193 #if !defined(CONFIG_SOFTMMU)
1194 /***********************************************************/
1195 /* cpu signal handler */
1196 static void host_segv_handler(int host_signum, siginfo_t *info, 
1197                               void *puc)
1198 {
1199     if (cpu_signal_handler(host_signum, info, puc))
1200         return;
1201     term_exit();
1202     abort();
1203 }
1204 #endif
1205
1206 /***********************************************************/
1207 /* I/O handling */
1208
1209 #define MAX_IO_HANDLERS 64
1210
1211 typedef struct IOHandlerRecord {
1212     int fd;
1213     IOCanRWHandler *fd_can_read;
1214     IOReadHandler *fd_read;
1215     void *opaque;
1216     /* temporary data */
1217     struct pollfd *ufd;
1218     int max_size;
1219     struct IOHandlerRecord *next;
1220 } IOHandlerRecord;
1221
1222 static IOHandlerRecord *first_io_handler;
1223
1224 int qemu_add_fd_read_handler(int fd, IOCanRWHandler *fd_can_read, 
1225                              IOReadHandler *fd_read, void *opaque)
1226 {
1227     IOHandlerRecord *ioh;
1228
1229     ioh = qemu_mallocz(sizeof(IOHandlerRecord));
1230     if (!ioh)
1231         return -1;
1232     ioh->fd = fd;
1233     ioh->fd_can_read = fd_can_read;
1234     ioh->fd_read = fd_read;
1235     ioh->opaque = opaque;
1236     ioh->next = first_io_handler;
1237     first_io_handler = ioh;
1238     return 0;
1239 }
1240
1241 void qemu_del_fd_read_handler(int fd)
1242 {
1243     IOHandlerRecord **pioh, *ioh;
1244
1245     pioh = &first_io_handler;
1246     for(;;) {
1247         ioh = *pioh;
1248         if (ioh == NULL)
1249             break;
1250         if (ioh->fd == fd) {
1251             *pioh = ioh->next;
1252             break;
1253         }
1254         pioh = &ioh->next;
1255     }
1256 }
1257
1258 /***********************************************************/
1259 /* savevm/loadvm support */
1260
1261 void qemu_put_buffer(QEMUFile *f, const uint8_t *buf, int size)
1262 {
1263     fwrite(buf, 1, size, f);
1264 }
1265
1266 void qemu_put_byte(QEMUFile *f, int v)
1267 {
1268     fputc(v, f);
1269 }
1270
1271 void qemu_put_be16(QEMUFile *f, unsigned int v)
1272 {
1273     qemu_put_byte(f, v >> 8);
1274     qemu_put_byte(f, v);
1275 }
1276
1277 void qemu_put_be32(QEMUFile *f, unsigned int v)
1278 {
1279     qemu_put_byte(f, v >> 24);
1280     qemu_put_byte(f, v >> 16);
1281     qemu_put_byte(f, v >> 8);
1282     qemu_put_byte(f, v);
1283 }
1284
1285 void qemu_put_be64(QEMUFile *f, uint64_t v)
1286 {
1287     qemu_put_be32(f, v >> 32);
1288     qemu_put_be32(f, v);
1289 }
1290
1291 int qemu_get_buffer(QEMUFile *f, uint8_t *buf, int size)
1292 {
1293     return fread(buf, 1, size, f);
1294 }
1295
1296 int qemu_get_byte(QEMUFile *f)
1297 {
1298     int v;
1299     v = fgetc(f);
1300     if (v == EOF)
1301         return 0;
1302     else
1303         return v;
1304 }
1305
1306 unsigned int qemu_get_be16(QEMUFile *f)
1307 {
1308     unsigned int v;
1309     v = qemu_get_byte(f) << 8;
1310     v |= qemu_get_byte(f);
1311     return v;
1312 }
1313
1314 unsigned int qemu_get_be32(QEMUFile *f)
1315 {
1316     unsigned int v;
1317     v = qemu_get_byte(f) << 24;
1318     v |= qemu_get_byte(f) << 16;
1319     v |= qemu_get_byte(f) << 8;
1320     v |= qemu_get_byte(f);
1321     return v;
1322 }
1323
1324 uint64_t qemu_get_be64(QEMUFile *f)
1325 {
1326     uint64_t v;
1327     v = (uint64_t)qemu_get_be32(f) << 32;
1328     v |= qemu_get_be32(f);
1329     return v;
1330 }
1331
1332 int64_t qemu_ftell(QEMUFile *f)
1333 {
1334     return ftell(f);
1335 }
1336
1337 int64_t qemu_fseek(QEMUFile *f, int64_t pos, int whence)
1338 {
1339     if (fseek(f, pos, whence) < 0)
1340         return -1;
1341     return ftell(f);
1342 }
1343
1344 typedef struct SaveStateEntry {
1345     char idstr[256];
1346     int instance_id;
1347     int version_id;
1348     SaveStateHandler *save_state;
1349     LoadStateHandler *load_state;
1350     void *opaque;
1351     struct SaveStateEntry *next;
1352 } SaveStateEntry;
1353
1354 static SaveStateEntry *first_se;
1355
1356 int register_savevm(const char *idstr, 
1357                     int instance_id, 
1358                     int version_id,
1359                     SaveStateHandler *save_state,
1360                     LoadStateHandler *load_state,
1361                     void *opaque)
1362 {
1363     SaveStateEntry *se, **pse;
1364
1365     se = qemu_malloc(sizeof(SaveStateEntry));
1366     if (!se)
1367         return -1;
1368     pstrcpy(se->idstr, sizeof(se->idstr), idstr);
1369     se->instance_id = instance_id;
1370     se->version_id = version_id;
1371     se->save_state = save_state;
1372     se->load_state = load_state;
1373     se->opaque = opaque;
1374     se->next = NULL;
1375
1376     /* add at the end of list */
1377     pse = &first_se;
1378     while (*pse != NULL)
1379         pse = &(*pse)->next;
1380     *pse = se;
1381     return 0;
1382 }
1383
1384 #define QEMU_VM_FILE_MAGIC   0x5145564d
1385 #define QEMU_VM_FILE_VERSION 0x00000001
1386
1387 int qemu_savevm(const char *filename)
1388 {
1389     SaveStateEntry *se;
1390     QEMUFile *f;
1391     int len, len_pos, cur_pos, saved_vm_running, ret;
1392
1393     saved_vm_running = vm_running;
1394     vm_stop(0);
1395
1396     f = fopen(filename, "wb");
1397     if (!f) {
1398         ret = -1;
1399         goto the_end;
1400     }
1401
1402     qemu_put_be32(f, QEMU_VM_FILE_MAGIC);
1403     qemu_put_be32(f, QEMU_VM_FILE_VERSION);
1404
1405     for(se = first_se; se != NULL; se = se->next) {
1406         /* ID string */
1407         len = strlen(se->idstr);
1408         qemu_put_byte(f, len);
1409         qemu_put_buffer(f, se->idstr, len);
1410
1411         qemu_put_be32(f, se->instance_id);
1412         qemu_put_be32(f, se->version_id);
1413
1414         /* record size: filled later */
1415         len_pos = ftell(f);
1416         qemu_put_be32(f, 0);
1417         
1418         se->save_state(f, se->opaque);
1419
1420         /* fill record size */
1421         cur_pos = ftell(f);
1422         len = ftell(f) - len_pos - 4;
1423         fseek(f, len_pos, SEEK_SET);
1424         qemu_put_be32(f, len);
1425         fseek(f, cur_pos, SEEK_SET);
1426     }
1427
1428     fclose(f);
1429     ret = 0;
1430  the_end:
1431     if (saved_vm_running)
1432         vm_start();
1433     return ret;
1434 }
1435
1436 static SaveStateEntry *find_se(const char *idstr, int instance_id)
1437 {
1438     SaveStateEntry *se;
1439
1440     for(se = first_se; se != NULL; se = se->next) {
1441         if (!strcmp(se->idstr, idstr) && 
1442             instance_id == se->instance_id)
1443             return se;
1444     }
1445     return NULL;
1446 }
1447
1448 int qemu_loadvm(const char *filename)
1449 {
1450     SaveStateEntry *se;
1451     QEMUFile *f;
1452     int len, cur_pos, ret, instance_id, record_len, version_id;
1453     int saved_vm_running;
1454     unsigned int v;
1455     char idstr[256];
1456     
1457     saved_vm_running = vm_running;
1458     vm_stop(0);
1459
1460     f = fopen(filename, "rb");
1461     if (!f) {
1462         ret = -1;
1463         goto the_end;
1464     }
1465
1466     v = qemu_get_be32(f);
1467     if (v != QEMU_VM_FILE_MAGIC)
1468         goto fail;
1469     v = qemu_get_be32(f);
1470     if (v != QEMU_VM_FILE_VERSION) {
1471     fail:
1472         fclose(f);
1473         ret = -1;
1474         goto the_end;
1475     }
1476     for(;;) {
1477 #if defined (DO_TB_FLUSH)
1478         tb_flush(global_env);
1479 #endif
1480         len = qemu_get_byte(f);
1481         if (feof(f))
1482             break;
1483         qemu_get_buffer(f, idstr, len);
1484         idstr[len] = '\0';
1485         instance_id = qemu_get_be32(f);
1486         version_id = qemu_get_be32(f);
1487         record_len = qemu_get_be32(f);
1488 #if 0
1489         printf("idstr=%s instance=0x%x version=%d len=%d\n", 
1490                idstr, instance_id, version_id, record_len);
1491 #endif
1492         cur_pos = ftell(f);
1493         se = find_se(idstr, instance_id);
1494         if (!se) {
1495             fprintf(stderr, "qemu: warning: instance 0x%x of device '%s' not present in current VM\n", 
1496                     instance_id, idstr);
1497         } else {
1498             ret = se->load_state(f, se->opaque, version_id);
1499             if (ret < 0) {
1500                 fprintf(stderr, "qemu: warning: error while loading state for instance 0x%x of device '%s'\n", 
1501                         instance_id, idstr);
1502             }
1503         }
1504         /* always seek to exact end of record */
1505         qemu_fseek(f, cur_pos + record_len, SEEK_SET);
1506     }
1507     fclose(f);
1508     ret = 0;
1509  the_end:
1510     if (saved_vm_running)
1511         vm_start();
1512     return ret;
1513 }
1514
1515 /***********************************************************/
1516 /* cpu save/restore */
1517
1518 #if defined(TARGET_I386)
1519
1520 static void cpu_put_seg(QEMUFile *f, SegmentCache *dt)
1521 {
1522     qemu_put_be32(f, (uint32_t)dt->base);
1523     qemu_put_be32(f, dt->limit);
1524     qemu_put_be32(f, dt->flags);
1525 }
1526
1527 static void cpu_get_seg(QEMUFile *f, SegmentCache *dt)
1528 {
1529     dt->base = (uint8_t *)qemu_get_be32(f);
1530     dt->limit = qemu_get_be32(f);
1531     dt->flags = qemu_get_be32(f);
1532 }
1533
1534 void cpu_save(QEMUFile *f, void *opaque)
1535 {
1536     CPUState *env = opaque;
1537     uint16_t fptag, fpus, fpuc;
1538     uint32_t hflags;
1539     int i;
1540
1541     for(i = 0; i < 8; i++)
1542         qemu_put_be32s(f, &env->regs[i]);
1543     qemu_put_be32s(f, &env->eip);
1544     qemu_put_be32s(f, &env->eflags);
1545     qemu_put_be32s(f, &env->eflags);
1546     hflags = env->hflags; /* XXX: suppress most of the redundant hflags */
1547     qemu_put_be32s(f, &hflags);
1548     
1549     /* FPU */
1550     fpuc = env->fpuc;
1551     fpus = (env->fpus & ~0x3800) | (env->fpstt & 0x7) << 11;
1552     fptag = 0;
1553     for (i=7; i>=0; i--) {
1554         fptag <<= 2;
1555         if (env->fptags[i]) {
1556             fptag |= 3;
1557         }
1558     }
1559     
1560     qemu_put_be16s(f, &fpuc);
1561     qemu_put_be16s(f, &fpus);
1562     qemu_put_be16s(f, &fptag);
1563
1564     for(i = 0; i < 8; i++) {
1565         uint64_t mant;
1566         uint16_t exp;
1567         cpu_get_fp80(&mant, &exp, env->fpregs[i]);
1568         qemu_put_be64(f, mant);
1569         qemu_put_be16(f, exp);
1570     }
1571
1572     for(i = 0; i < 6; i++)
1573         cpu_put_seg(f, &env->segs[i]);
1574     cpu_put_seg(f, &env->ldt);
1575     cpu_put_seg(f, &env->tr);
1576     cpu_put_seg(f, &env->gdt);
1577     cpu_put_seg(f, &env->idt);
1578     
1579     qemu_put_be32s(f, &env->sysenter_cs);
1580     qemu_put_be32s(f, &env->sysenter_esp);
1581     qemu_put_be32s(f, &env->sysenter_eip);
1582     
1583     qemu_put_be32s(f, &env->cr[0]);
1584     qemu_put_be32s(f, &env->cr[2]);
1585     qemu_put_be32s(f, &env->cr[3]);
1586     qemu_put_be32s(f, &env->cr[4]);
1587     
1588     for(i = 0; i < 8; i++)
1589         qemu_put_be32s(f, &env->dr[i]);
1590
1591     /* MMU */
1592     qemu_put_be32s(f, &env->a20_mask);
1593 }
1594
1595 int cpu_load(QEMUFile *f, void *opaque, int version_id)
1596 {
1597     CPUState *env = opaque;
1598     int i;
1599     uint32_t hflags;
1600     uint16_t fpus, fpuc, fptag;
1601
1602     if (version_id != 1)
1603         return -EINVAL;
1604     for(i = 0; i < 8; i++)
1605         qemu_get_be32s(f, &env->regs[i]);
1606     qemu_get_be32s(f, &env->eip);
1607     qemu_get_be32s(f, &env->eflags);
1608     qemu_get_be32s(f, &env->eflags);
1609     qemu_get_be32s(f, &hflags);
1610
1611     qemu_get_be16s(f, &fpuc);
1612     qemu_get_be16s(f, &fpus);
1613     qemu_get_be16s(f, &fptag);
1614
1615     for(i = 0; i < 8; i++) {
1616         uint64_t mant;
1617         uint16_t exp;
1618         mant = qemu_get_be64(f);
1619         exp = qemu_get_be16(f);
1620         env->fpregs[i] = cpu_set_fp80(mant, exp);
1621     }
1622
1623     env->fpuc = fpuc;
1624     env->fpstt = (fpus >> 11) & 7;
1625     env->fpus = fpus & ~0x3800;
1626     for(i = 0; i < 8; i++) {
1627         env->fptags[i] = ((fptag & 3) == 3);
1628         fptag >>= 2;
1629     }
1630     
1631     for(i = 0; i < 6; i++)
1632         cpu_get_seg(f, &env->segs[i]);
1633     cpu_get_seg(f, &env->ldt);
1634     cpu_get_seg(f, &env->tr);
1635     cpu_get_seg(f, &env->gdt);
1636     cpu_get_seg(f, &env->idt);
1637     
1638     qemu_get_be32s(f, &env->sysenter_cs);
1639     qemu_get_be32s(f, &env->sysenter_esp);
1640     qemu_get_be32s(f, &env->sysenter_eip);
1641     
1642     qemu_get_be32s(f, &env->cr[0]);
1643     qemu_get_be32s(f, &env->cr[2]);
1644     qemu_get_be32s(f, &env->cr[3]);
1645     qemu_get_be32s(f, &env->cr[4]);
1646     
1647     for(i = 0; i < 8; i++)
1648         qemu_get_be32s(f, &env->dr[i]);
1649
1650     /* MMU */
1651     qemu_get_be32s(f, &env->a20_mask);
1652
1653     /* XXX: compute hflags from scratch, except for CPL and IIF */
1654     env->hflags = hflags;
1655     tlb_flush(env, 1);
1656     return 0;
1657 }
1658
1659 #elif defined(TARGET_PPC)
1660 void cpu_save(QEMUFile *f, void *opaque)
1661 {
1662 }
1663
1664 int cpu_load(QEMUFile *f, void *opaque, int version_id)
1665 {
1666     return 0;
1667 }
1668 #else
1669
1670 #warning No CPU save/restore functions
1671
1672 #endif
1673
1674 /***********************************************************/
1675 /* ram save/restore */
1676
1677 /* we just avoid storing empty pages */
1678 static void ram_put_page(QEMUFile *f, const uint8_t *buf, int len)
1679 {
1680     int i, v;
1681
1682     v = buf[0];
1683     for(i = 1; i < len; i++) {
1684         if (buf[i] != v)
1685             goto normal_save;
1686     }
1687     qemu_put_byte(f, 1);
1688     qemu_put_byte(f, v);
1689     return;
1690  normal_save:
1691     qemu_put_byte(f, 0); 
1692     qemu_put_buffer(f, buf, len);
1693 }
1694
1695 static int ram_get_page(QEMUFile *f, uint8_t *buf, int len)
1696 {
1697     int v;
1698
1699     v = qemu_get_byte(f);
1700     switch(v) {
1701     case 0:
1702         if (qemu_get_buffer(f, buf, len) != len)
1703             return -EIO;
1704         break;
1705     case 1:
1706         v = qemu_get_byte(f);
1707         memset(buf, v, len);
1708         break;
1709     default:
1710         return -EINVAL;
1711     }
1712     return 0;
1713 }
1714
1715 static void ram_save(QEMUFile *f, void *opaque)
1716 {
1717     int i;
1718     qemu_put_be32(f, phys_ram_size);
1719     for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
1720         ram_put_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
1721     }
1722 }
1723
1724 static int ram_load(QEMUFile *f, void *opaque, int version_id)
1725 {
1726     int i, ret;
1727
1728     if (version_id != 1)
1729         return -EINVAL;
1730     if (qemu_get_be32(f) != phys_ram_size)
1731         return -EINVAL;
1732     for(i = 0; i < phys_ram_size; i+= TARGET_PAGE_SIZE) {
1733         ret = ram_get_page(f, phys_ram_base + i, TARGET_PAGE_SIZE);
1734         if (ret)
1735             return ret;
1736     }
1737     return 0;
1738 }
1739
1740 /***********************************************************/
1741 /* main execution loop */
1742
1743 void gui_update(void *opaque)
1744 {
1745     display_state.dpy_refresh(&display_state);
1746     qemu_mod_timer(gui_timer, GUI_REFRESH_INTERVAL + qemu_get_clock(rt_clock));
1747 }
1748
1749 /* XXX: support several handlers */
1750 VMStopHandler *vm_stop_cb;
1751 VMStopHandler *vm_stop_opaque;
1752
1753 int qemu_add_vm_stop_handler(VMStopHandler *cb, void *opaque)
1754 {
1755     vm_stop_cb = cb;
1756     vm_stop_opaque = opaque;
1757     return 0;
1758 }
1759
1760 void qemu_del_vm_stop_handler(VMStopHandler *cb, void *opaque)
1761 {
1762     vm_stop_cb = NULL;
1763 }
1764
1765 void vm_start(void)
1766 {
1767     if (!vm_running) {
1768         cpu_enable_ticks();
1769         vm_running = 1;
1770     }
1771 }
1772
1773 void vm_stop(int reason) 
1774 {
1775     if (vm_running) {
1776         cpu_disable_ticks();
1777         vm_running = 0;
1778         if (reason != 0) {
1779             if (vm_stop_cb) {
1780                 vm_stop_cb(vm_stop_opaque, reason);
1781             }
1782         }
1783     }
1784 }
1785
1786 int main_loop(void)
1787 {
1788 #ifndef _WIN32
1789     struct pollfd ufds[MAX_IO_HANDLERS + 1], *pf;
1790     IOHandlerRecord *ioh, *ioh_next;
1791     uint8_t buf[4096];
1792     int n, max_size;
1793 #endif
1794     int ret, timeout;
1795     CPUState *env = global_env;
1796
1797     for(;;) {
1798         if (vm_running) {
1799             ret = cpu_exec(env);
1800             if (reset_requested) {
1801                 ret = EXCP_INTERRUPT; 
1802                 break;
1803             }
1804             if (ret == EXCP_DEBUG) {
1805                 vm_stop(EXCP_DEBUG);
1806             }
1807             /* if hlt instruction, we wait until the next IRQ */
1808             /* XXX: use timeout computed from timers */
1809             if (ret == EXCP_HLT) 
1810                 timeout = 10;
1811             else
1812                 timeout = 0;
1813         } else {
1814             timeout = 10;
1815         }
1816
1817 #ifdef _WIN32
1818         if (timeout > 0)
1819             Sleep(timeout);
1820 #else
1821
1822         /* poll any events */
1823         /* XXX: separate device handlers from system ones */
1824         pf = ufds;
1825         for(ioh = first_io_handler; ioh != NULL; ioh = ioh->next) {
1826             if (!ioh->fd_can_read) {
1827                 max_size = 0;
1828                 pf->fd = ioh->fd;
1829                 pf->events = POLLIN;
1830                 ioh->ufd = pf;
1831                 pf++;
1832             } else {
1833                 max_size = ioh->fd_can_read(ioh->opaque);
1834                 if (max_size > 0) {
1835                     if (max_size > sizeof(buf))
1836                         max_size = sizeof(buf);
1837                     pf->fd = ioh->fd;
1838                     pf->events = POLLIN;
1839                     ioh->ufd = pf;
1840                     pf++;
1841                 } else {
1842                     ioh->ufd = NULL;
1843                 }
1844             }
1845             ioh->max_size = max_size;
1846         }
1847         
1848         ret = poll(ufds, pf - ufds, timeout);
1849         if (ret > 0) {
1850             /* XXX: better handling of removal */
1851             for(ioh = first_io_handler; ioh != NULL; ioh = ioh_next) {
1852                 ioh_next = ioh->next;
1853                 pf = ioh->ufd;
1854                 if (pf) {
1855                     if (pf->revents & POLLIN) {
1856                         if (ioh->max_size == 0) {
1857                             /* just a read event */
1858                             ioh->fd_read(ioh->opaque, NULL, 0);
1859                         } else {
1860                             n = read(ioh->fd, buf, ioh->max_size);
1861                             if (n >= 0) {
1862                                 ioh->fd_read(ioh->opaque, buf, n);
1863                             } else if (errno != EAGAIN) {
1864                                 ioh->fd_read(ioh->opaque, NULL, -errno);
1865                             }
1866                         }
1867                     }
1868                 }
1869             }
1870         }
1871
1872 #if defined(CONFIG_SLIRP)
1873         /* XXX: merge with poll() */
1874         if (slirp_inited) {
1875             fd_set rfds, wfds, xfds;
1876             int nfds;
1877             struct timeval tv;
1878
1879             nfds = -1;
1880             FD_ZERO(&rfds);
1881             FD_ZERO(&wfds);
1882             FD_ZERO(&xfds);
1883             slirp_select_fill(&nfds, &rfds, &wfds, &xfds);
1884             tv.tv_sec = 0;
1885             tv.tv_usec = 0;
1886             ret = select(nfds + 1, &rfds, &wfds, &xfds, &tv);
1887             if (ret >= 0) {
1888                 slirp_select_poll(&rfds, &wfds, &xfds);
1889             }
1890         }
1891 #endif
1892
1893 #endif
1894
1895         if (vm_running) {
1896             qemu_run_timers(&active_timers[QEMU_TIMER_VIRTUAL], 
1897                             qemu_get_clock(vm_clock));
1898             
1899             if (audio_enabled) {
1900                 /* XXX: add explicit timer */
1901                 SB16_run();
1902             }
1903             
1904             /* run dma transfers, if any */
1905             DMA_run();
1906         }
1907
1908         /* real time timers */
1909         qemu_run_timers(&active_timers[QEMU_TIMER_REALTIME], 
1910                         qemu_get_clock(rt_clock));
1911     }
1912     cpu_disable_ticks();
1913     return ret;
1914 }
1915
1916 void help(void)
1917 {
1918     printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003-2004 Fabrice Bellard\n"
1919            "usage: %s [options] [disk_image]\n"
1920            "\n"
1921            "'disk_image' is a raw hard image image for IDE hard disk 0\n"
1922            "\n"
1923            "Standard options:\n"
1924            "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
1925            "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
1926            "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
1927            "-cdrom file     use 'file' as IDE cdrom image (cdrom is ide1 master)\n"
1928            "-boot [a|b|c|d] boot on floppy (a, b), hard disk (c) or CD-ROM (d)\n"
1929            "-snapshot       write to temporary files instead of disk image files\n"
1930            "-m megs         set virtual RAM size to megs MB [default=%d]\n"
1931            "-nographic      disable graphical output and redirect serial I/Os to console\n"
1932            "-enable-audio   enable audio support\n"
1933            "-localtime      set the real time clock to local time [default=utc]\n"
1934            "\n"
1935            "Network options:\n"
1936            "-nics n         simulate 'n' network cards [default=1]\n"
1937            "-macaddr addr   set the mac address of the first interface\n"
1938            "-n script       set tap/tun network init script [default=%s]\n"
1939            "-tun-fd fd      use this fd as already opened tap/tun interface\n"
1940 #ifdef CONFIG_SLIRP
1941            "-user-net       use user mode network stack [default if no tap/tun script]\n"
1942 #endif
1943            "-dummy-net      use dummy network stack\n"
1944            "\n"
1945            "Linux boot specific:\n"
1946            "-kernel bzImage use 'bzImage' as kernel image\n"
1947            "-append cmdline use 'cmdline' as kernel command line\n"
1948            "-initrd file    use 'file' as initial ram disk\n"
1949            "\n"
1950            "Debug/Expert options:\n"
1951            "-S              freeze CPU at startup (use 'c' to start execution)\n"
1952            "-s              wait gdb connection to port %d\n"
1953            "-p port         change gdb connection port\n"
1954            "-d item1,...    output log to %s (use -d ? for a list of log items)\n"
1955            "-hdachs c,h,s   force hard disk 0 geometry (usually qemu can guess it)\n"
1956            "-L path         set the directory for the BIOS and VGA BIOS\n"
1957 #ifdef USE_CODE_COPY
1958            "-no-code-copy   disable code copy acceleration\n"
1959 #endif
1960
1961            "\n"
1962            "During emulation, use C-a h to get terminal commands:\n",
1963 #ifdef CONFIG_SOFTMMU
1964            "qemu",
1965 #else
1966            "qemu-fast",
1967 #endif
1968            DEFAULT_RAM_SIZE,
1969            DEFAULT_NETWORK_SCRIPT,
1970            DEFAULT_GDBSTUB_PORT,
1971            "/tmp/qemu.log");
1972     term_print_help();
1973 #ifndef CONFIG_SOFTMMU
1974     printf("\n"
1975            "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
1976            "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
1977            "PC emulation.\n");
1978 #endif
1979     exit(1);
1980 }
1981
1982 #define HAS_ARG 0x0001
1983
1984 enum {
1985     QEMU_OPTION_h,
1986
1987     QEMU_OPTION_fda,
1988     QEMU_OPTION_fdb,
1989     QEMU_OPTION_hda,
1990     QEMU_OPTION_hdb,
1991     QEMU_OPTION_hdc,
1992     QEMU_OPTION_hdd,
1993     QEMU_OPTION_cdrom,
1994     QEMU_OPTION_boot,
1995     QEMU_OPTION_snapshot,
1996     QEMU_OPTION_m,
1997     QEMU_OPTION_nographic,
1998     QEMU_OPTION_enable_audio,
1999
2000     QEMU_OPTION_nics,
2001     QEMU_OPTION_macaddr,
2002     QEMU_OPTION_n,
2003     QEMU_OPTION_tun_fd,
2004     QEMU_OPTION_user_net,
2005     QEMU_OPTION_dummy_net,
2006
2007     QEMU_OPTION_kernel,
2008     QEMU_OPTION_append,
2009     QEMU_OPTION_initrd,
2010
2011     QEMU_OPTION_S,
2012     QEMU_OPTION_s,
2013     QEMU_OPTION_p,
2014     QEMU_OPTION_d,
2015     QEMU_OPTION_hdachs,
2016     QEMU_OPTION_L,
2017     QEMU_OPTION_no_code_copy,
2018     QEMU_OPTION_pci,
2019     QEMU_OPTION_prep,
2020     QEMU_OPTION_localtime,
2021 };
2022
2023 typedef struct QEMUOption {
2024     const char *name;
2025     int flags;
2026     int index;
2027 } QEMUOption;
2028
2029 const QEMUOption qemu_options[] = {
2030     { "h", 0, QEMU_OPTION_h },
2031
2032     { "fda", HAS_ARG, QEMU_OPTION_fda },
2033     { "fdb", HAS_ARG, QEMU_OPTION_fdb },
2034     { "hda", HAS_ARG, QEMU_OPTION_hda },
2035     { "hdb", HAS_ARG, QEMU_OPTION_hdb },
2036     { "hdc", HAS_ARG, QEMU_OPTION_hdc },
2037     { "hdd", HAS_ARG, QEMU_OPTION_hdd },
2038     { "cdrom", HAS_ARG, QEMU_OPTION_cdrom },
2039     { "boot", HAS_ARG, QEMU_OPTION_boot },
2040     { "snapshot", 0, QEMU_OPTION_snapshot },
2041     { "m", HAS_ARG, QEMU_OPTION_m },
2042     { "nographic", 0, QEMU_OPTION_nographic },
2043     { "enable-audio", 0, QEMU_OPTION_enable_audio },
2044
2045     { "nics", HAS_ARG, QEMU_OPTION_nics},
2046     { "macaddr", HAS_ARG, QEMU_OPTION_macaddr},
2047     { "n", HAS_ARG, QEMU_OPTION_n },
2048     { "tun-fd", HAS_ARG, QEMU_OPTION_tun_fd },
2049 #ifdef CONFIG_SLIRP
2050     { "user-net", 0, QEMU_OPTION_user_net },
2051 #endif
2052     { "dummy-net", 0, QEMU_OPTION_dummy_net },
2053
2054     { "kernel", HAS_ARG, QEMU_OPTION_kernel },
2055     { "append", HAS_ARG, QEMU_OPTION_append },
2056     { "initrd", HAS_ARG, QEMU_OPTION_initrd },
2057
2058     { "S", 0, QEMU_OPTION_S },
2059     { "s", 0, QEMU_OPTION_s },
2060     { "p", HAS_ARG, QEMU_OPTION_p },
2061     { "d", HAS_ARG, QEMU_OPTION_d },
2062     { "hdachs", HAS_ARG, QEMU_OPTION_hdachs },
2063     { "L", HAS_ARG, QEMU_OPTION_L },
2064     { "no-code-copy", 0, QEMU_OPTION_no_code_copy },
2065
2066     /* temporary options */
2067     { "pci", 0, QEMU_OPTION_pci },
2068 #ifdef TARGET_PPC
2069     { "prep", 0, QEMU_OPTION_prep },
2070 #endif
2071     { "localtime", 0, QEMU_OPTION_localtime },
2072     { NULL },
2073 };
2074
2075 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2076
2077 /* this stack is only used during signal handling */
2078 #define SIGNAL_STACK_SIZE 32768
2079
2080 static uint8_t *signal_stack;
2081
2082 #endif
2083
2084 #define NET_IF_TUN   0
2085 #define NET_IF_USER  1
2086 #define NET_IF_DUMMY 2
2087
2088 int main(int argc, char **argv)
2089 {
2090 #ifdef CONFIG_GDBSTUB
2091     int use_gdbstub, gdbstub_port;
2092 #endif
2093     int i, has_cdrom;
2094     int snapshot, linux_boot;
2095     CPUState *env;
2096     const char *initrd_filename;
2097     const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
2098     const char *kernel_filename, *kernel_cmdline;
2099     DisplayState *ds = &display_state;
2100     int cyls, heads, secs;
2101     int start_emulation = 1;
2102     uint8_t macaddr[6];
2103     int net_if_type, nb_tun_fds, tun_fds[MAX_NICS];
2104     int optind;
2105     const char *r, *optarg;
2106
2107 #if !defined(CONFIG_SOFTMMU)
2108     /* we never want that malloc() uses mmap() */
2109     mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
2110 #endif
2111     initrd_filename = NULL;
2112     for(i = 0; i < MAX_FD; i++)
2113         fd_filename[i] = NULL;
2114     for(i = 0; i < MAX_DISKS; i++)
2115         hd_filename[i] = NULL;
2116     ram_size = DEFAULT_RAM_SIZE * 1024 * 1024;
2117     vga_ram_size = VGA_RAM_SIZE;
2118     bios_size = BIOS_SIZE;
2119     pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
2120 #ifdef CONFIG_GDBSTUB
2121     use_gdbstub = 0;
2122     gdbstub_port = DEFAULT_GDBSTUB_PORT;
2123 #endif
2124     snapshot = 0;
2125     nographic = 0;
2126     kernel_filename = NULL;
2127     kernel_cmdline = "";
2128     has_cdrom = 1;
2129     cyls = heads = secs = 0;
2130
2131     nb_tun_fds = 0;
2132     net_if_type = -1;
2133     nb_nics = 1;
2134     /* default mac address of the first network interface */
2135     macaddr[0] = 0x52;
2136     macaddr[1] = 0x54;
2137     macaddr[2] = 0x00;
2138     macaddr[3] = 0x12;
2139     macaddr[4] = 0x34;
2140     macaddr[5] = 0x56;
2141
2142     optind = 1;
2143     for(;;) {
2144         if (optind >= argc)
2145             break;
2146         r = argv[optind];
2147         if (r[0] != '-') {
2148             hd_filename[0] = argv[optind++];
2149         } else {
2150             const QEMUOption *popt;
2151
2152             optind++;
2153             popt = qemu_options;
2154             for(;;) {
2155                 if (!popt->name) {
2156                     fprintf(stderr, "%s: invalid option -- '%s'\n", 
2157                             argv[0], r);
2158                     exit(1);
2159                 }
2160                 if (!strcmp(popt->name, r + 1))
2161                     break;
2162                 popt++;
2163             }
2164             if (popt->flags & HAS_ARG) {
2165                 if (optind >= argc) {
2166                     fprintf(stderr, "%s: option '%s' requires an argument\n",
2167                             argv[0], r);
2168                     exit(1);
2169                 }
2170                 optarg = argv[optind++];
2171             } else {
2172                 optarg = NULL;
2173             }
2174
2175             switch(popt->index) {
2176             case QEMU_OPTION_initrd:
2177                 initrd_filename = optarg;
2178                 break;
2179             case QEMU_OPTION_hda:
2180                 hd_filename[0] = optarg;
2181                 break;
2182             case QEMU_OPTION_hdb:
2183                 hd_filename[1] = optarg;
2184                 break;
2185             case QEMU_OPTION_snapshot:
2186                 snapshot = 1;
2187                 break;
2188             case QEMU_OPTION_hdachs:
2189                 {
2190                     const char *p;
2191                     p = optarg;
2192                     cyls = strtol(p, (char **)&p, 0);
2193                     if (*p != ',')
2194                         goto chs_fail;
2195                     p++;
2196                     heads = strtol(p, (char **)&p, 0);
2197                     if (*p != ',')
2198                         goto chs_fail;
2199                     p++;
2200                     secs = strtol(p, (char **)&p, 0);
2201                     if (*p != '\0') {
2202                     chs_fail:
2203                         cyls = 0;
2204                     }
2205                 }
2206                 break;
2207             case QEMU_OPTION_nographic:
2208                 nographic = 1;
2209                 break;
2210             case QEMU_OPTION_kernel:
2211                 kernel_filename = optarg;
2212                 break;
2213             case QEMU_OPTION_append:
2214                 kernel_cmdline = optarg;
2215                 break;
2216             case QEMU_OPTION_tun_fd:
2217                 {
2218                     const char *p;
2219                     int fd;
2220                     net_if_type = NET_IF_TUN;
2221                     if (nb_tun_fds < MAX_NICS) {
2222                         fd = strtol(optarg, (char **)&p, 0);
2223                         if (*p != '\0') {
2224                             fprintf(stderr, "qemu: invalid fd for network interface %d\n", nb_tun_fds);
2225                             exit(1);
2226                         }
2227                         tun_fds[nb_tun_fds++] = fd;
2228                     }
2229                 }
2230                 break;
2231             case QEMU_OPTION_hdc:
2232                 hd_filename[2] = optarg;
2233                 has_cdrom = 0;
2234                 break;
2235             case QEMU_OPTION_hdd:
2236                 hd_filename[3] = optarg;
2237                 break;
2238             case QEMU_OPTION_cdrom:
2239                 hd_filename[2] = optarg;
2240                 has_cdrom = 1;
2241                 break;
2242             case QEMU_OPTION_boot:
2243                 boot_device = optarg[0];
2244                 if (boot_device != 'a' && boot_device != 'b' &&
2245                     boot_device != 'c' && boot_device != 'd') {
2246                     fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
2247                     exit(1);
2248                 }
2249                 break;
2250             case QEMU_OPTION_fda:
2251                 fd_filename[0] = optarg;
2252                 break;
2253             case QEMU_OPTION_fdb:
2254                 fd_filename[1] = optarg;
2255                 break;
2256             case QEMU_OPTION_no_code_copy:
2257                 code_copy_enabled = 0;
2258                 break;
2259             case QEMU_OPTION_nics:
2260                 nb_nics = atoi(optarg);
2261                 if (nb_nics < 0 || nb_nics > MAX_NICS) {
2262                     fprintf(stderr, "qemu: invalid number of network interfaces\n");
2263                     exit(1);
2264                 }
2265                 break;
2266             case QEMU_OPTION_macaddr:
2267                 {
2268                     const char *p;
2269                     int i;
2270                     p = optarg;
2271                     for(i = 0; i < 6; i++) {
2272                         macaddr[i] = strtol(p, (char **)&p, 16);
2273                         if (i == 5) {
2274                             if (*p != '\0') 
2275                                 goto macaddr_error;
2276                         } else {
2277                             if (*p != ':') {
2278                             macaddr_error:
2279                                 fprintf(stderr, "qemu: invalid syntax for ethernet address\n");
2280                                 exit(1);
2281                             }
2282                             p++;
2283                         }
2284                     }
2285                 }
2286                 break;
2287             case QEMU_OPTION_user_net:
2288                 net_if_type = NET_IF_USER;
2289                 break;
2290             case QEMU_OPTION_dummy_net:
2291                 net_if_type = NET_IF_DUMMY;
2292                 break;
2293             case QEMU_OPTION_enable_audio:
2294                 audio_enabled = 1;
2295                 break;
2296             case QEMU_OPTION_h:
2297                 help();
2298                 break;
2299             case QEMU_OPTION_m:
2300                 ram_size = atoi(optarg) * 1024 * 1024;
2301                 if (ram_size <= 0)
2302                     help();
2303                 if (ram_size > PHYS_RAM_MAX_SIZE) {
2304                     fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
2305                             PHYS_RAM_MAX_SIZE / (1024 * 1024));
2306                     exit(1);
2307                 }
2308                 break;
2309             case QEMU_OPTION_d:
2310                 {
2311                     int mask;
2312                     CPULogItem *item;
2313                     
2314                     mask = cpu_str_to_log_mask(optarg);
2315                     if (!mask) {
2316                         printf("Log items (comma separated):\n");
2317                     for(item = cpu_log_items; item->mask != 0; item++) {
2318                         printf("%-10s %s\n", item->name, item->help);
2319                     }
2320                     exit(1);
2321                     }
2322                     cpu_set_log(mask);
2323                 }
2324                 break;
2325             case QEMU_OPTION_n:
2326                 pstrcpy(network_script, sizeof(network_script), optarg);
2327                 break;
2328 #ifdef CONFIG_GDBSTUB
2329             case QEMU_OPTION_s:
2330                 use_gdbstub = 1;
2331                 break;
2332             case QEMU_OPTION_p:
2333                 gdbstub_port = atoi(optarg);
2334                 break;
2335 #endif
2336             case QEMU_OPTION_L:
2337                 bios_dir = optarg;
2338                 break;
2339             case QEMU_OPTION_S:
2340                 start_emulation = 0;
2341                 break;
2342             case QEMU_OPTION_pci:
2343                 pci_enabled = 1;
2344                 break;
2345             case QEMU_OPTION_prep:
2346                 prep_enabled = 1;
2347                 break;
2348             case QEMU_OPTION_localtime:
2349                 rtc_utc = 0;
2350                 break;
2351             }
2352         }
2353     }
2354
2355     linux_boot = (kernel_filename != NULL);
2356         
2357     if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
2358         fd_filename[0] == '\0')
2359         help();
2360     
2361     /* boot to cd by default if no hard disk */
2362     if (hd_filename[0] == '\0' && boot_device == 'c') {
2363         if (fd_filename[0] != '\0')
2364             boot_device = 'a';
2365         else
2366             boot_device = 'd';
2367     }
2368
2369 #if !defined(CONFIG_SOFTMMU)
2370     /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
2371     {
2372         static uint8_t stdout_buf[4096];
2373         setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
2374     }
2375 #else
2376     setvbuf(stdout, NULL, _IOLBF, 0);
2377 #endif
2378
2379     /* init host network redirectors */
2380     if (net_if_type == -1) {
2381         net_if_type = NET_IF_TUN;
2382 #if defined(CONFIG_SLIRP)
2383         if (access(network_script, R_OK) < 0) {
2384             net_if_type = NET_IF_USER;
2385         }
2386 #endif
2387     }
2388
2389     for(i = 0; i < nb_nics; i++) {
2390         NetDriverState *nd = &nd_table[i];
2391         nd->index = i;
2392         /* init virtual mac address */
2393         nd->macaddr[0] = macaddr[0];
2394         nd->macaddr[1] = macaddr[1];
2395         nd->macaddr[2] = macaddr[2];
2396         nd->macaddr[3] = macaddr[3];
2397         nd->macaddr[4] = macaddr[4];
2398         nd->macaddr[5] = macaddr[5] + i;
2399         switch(net_if_type) {
2400 #if defined(CONFIG_SLIRP)
2401         case NET_IF_USER:
2402             net_slirp_init(nd);
2403             break;
2404 #endif
2405 #if !defined(_WIN32)
2406         case NET_IF_TUN:
2407             if (i < nb_tun_fds) {
2408                 net_fd_init(nd, tun_fds[i]);
2409             } else {
2410                 if (net_tun_init(nd) < 0)
2411                     net_dummy_init(nd);
2412             }
2413             break;
2414 #endif
2415         case NET_IF_DUMMY:
2416         default:
2417             net_dummy_init(nd);
2418             break;
2419         }
2420     }
2421
2422     /* init the memory */
2423     phys_ram_size = ram_size + vga_ram_size + bios_size;
2424
2425 #ifdef CONFIG_SOFTMMU
2426 #ifdef _BSD
2427     /* mallocs are always aligned on BSD. */
2428     phys_ram_base = malloc(phys_ram_size);
2429 #else
2430     phys_ram_base = memalign(TARGET_PAGE_SIZE, phys_ram_size);
2431 #endif
2432     if (!phys_ram_base) {
2433         fprintf(stderr, "Could not allocate physical memory\n");
2434         exit(1);
2435     }
2436 #else
2437     /* as we must map the same page at several addresses, we must use
2438        a fd */
2439     {
2440         const char *tmpdir;
2441
2442         tmpdir = getenv("QEMU_TMPDIR");
2443         if (!tmpdir)
2444             tmpdir = "/tmp";
2445         snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
2446         if (mkstemp(phys_ram_file) < 0) {
2447             fprintf(stderr, "Could not create temporary memory file '%s'\n", 
2448                     phys_ram_file);
2449             exit(1);
2450         }
2451         phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
2452         if (phys_ram_fd < 0) {
2453             fprintf(stderr, "Could not open temporary memory file '%s'\n", 
2454                     phys_ram_file);
2455             exit(1);
2456         }
2457         ftruncate(phys_ram_fd, phys_ram_size);
2458         unlink(phys_ram_file);
2459         phys_ram_base = mmap(get_mmap_addr(phys_ram_size), 
2460                              phys_ram_size, 
2461                              PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
2462                              phys_ram_fd, 0);
2463         if (phys_ram_base == MAP_FAILED) {
2464             fprintf(stderr, "Could not map physical memory\n");
2465             exit(1);
2466         }
2467     }
2468 #endif
2469
2470     /* we always create the cdrom drive, even if no disk is there */
2471     if (has_cdrom) {
2472         bs_table[2] = bdrv_new("cdrom");
2473         bdrv_set_type_hint(bs_table[2], BDRV_TYPE_CDROM);
2474     }
2475
2476     /* open the virtual block devices */
2477     for(i = 0; i < MAX_DISKS; i++) {
2478         if (hd_filename[i]) {
2479             if (!bs_table[i]) {
2480                 char buf[64];
2481                 snprintf(buf, sizeof(buf), "hd%c", i + 'a');
2482                 bs_table[i] = bdrv_new(buf);
2483             }
2484             if (bdrv_open(bs_table[i], hd_filename[i], snapshot) < 0) {
2485                 fprintf(stderr, "qemu: could not open hard disk image '%s\n",
2486                         hd_filename[i]);
2487                 exit(1);
2488             }
2489             if (i == 0 && cyls != 0) 
2490                 bdrv_set_geometry_hint(bs_table[i], cyls, heads, secs);
2491         }
2492     }
2493
2494     /* we always create at least one floppy disk */
2495     fd_table[0] = bdrv_new("fda");
2496     bdrv_set_type_hint(fd_table[0], BDRV_TYPE_FLOPPY);
2497
2498     for(i = 0; i < MAX_FD; i++) {
2499         if (fd_filename[i]) {
2500             if (!fd_table[i]) {
2501                 char buf[64];
2502                 snprintf(buf, sizeof(buf), "fd%c", i + 'a');
2503                 fd_table[i] = bdrv_new(buf);
2504                 bdrv_set_type_hint(fd_table[i], BDRV_TYPE_FLOPPY);
2505             }
2506             if (fd_filename[i] != '\0') {
2507                 if (bdrv_open(fd_table[i], fd_filename[i], snapshot) < 0) {
2508                     fprintf(stderr, "qemu: could not open floppy disk image '%s'\n",
2509                             fd_filename[i]);
2510                     exit(1);
2511                 }
2512             }
2513         }
2514     }
2515
2516     /* init CPU state */
2517     env = cpu_init();
2518     global_env = env;
2519     cpu_single_env = env;
2520
2521     register_savevm("timer", 0, 1, timer_save, timer_load, env);
2522     register_savevm("cpu", 0, 1, cpu_save, cpu_load, env);
2523     register_savevm("ram", 0, 1, ram_save, ram_load, NULL);
2524
2525     init_ioports();
2526     cpu_calibrate_ticks();
2527
2528     /* terminal init */
2529     if (nographic) {
2530         dumb_display_init(ds);
2531     } else {
2532 #ifdef CONFIG_SDL
2533         sdl_display_init(ds);
2534 #else
2535         dumb_display_init(ds);
2536 #endif
2537     }
2538
2539     /* setup cpu signal handlers for MMU / self modifying code handling */
2540 #if !defined(CONFIG_SOFTMMU)
2541     
2542 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2543     {
2544         stack_t stk;
2545         signal_stack = memalign(16, SIGNAL_STACK_SIZE);
2546         stk.ss_sp = signal_stack;
2547         stk.ss_size = SIGNAL_STACK_SIZE;
2548         stk.ss_flags = 0;
2549
2550         if (sigaltstack(&stk, NULL) < 0) {
2551             perror("sigaltstack");
2552             exit(1);
2553         }
2554     }
2555 #endif
2556     {
2557         struct sigaction act;
2558         
2559         sigfillset(&act.sa_mask);
2560         act.sa_flags = SA_SIGINFO;
2561 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2562         act.sa_flags |= SA_ONSTACK;
2563 #endif
2564         act.sa_sigaction = host_segv_handler;
2565         sigaction(SIGSEGV, &act, NULL);
2566         sigaction(SIGBUS, &act, NULL);
2567 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
2568         sigaction(SIGFPE, &act, NULL);
2569 #endif
2570     }
2571 #endif
2572
2573 #ifndef _WIN32
2574     {
2575         struct sigaction act;
2576         sigfillset(&act.sa_mask);
2577         act.sa_flags = 0;
2578         act.sa_handler = SIG_IGN;
2579         sigaction(SIGPIPE, &act, NULL);
2580     }
2581 #endif
2582     init_timers();
2583
2584 #if defined(TARGET_I386)
2585     pc_init(ram_size, vga_ram_size, boot_device,
2586             ds, fd_filename, snapshot,
2587             kernel_filename, kernel_cmdline, initrd_filename);
2588 #elif defined(TARGET_PPC)
2589     ppc_init(ram_size, vga_ram_size, boot_device,
2590              ds, fd_filename, snapshot,
2591              kernel_filename, kernel_cmdline, initrd_filename);
2592 #endif
2593
2594     /* launched after the device init so that it can display or not a
2595        banner */
2596     monitor_init();
2597
2598     gui_timer = qemu_new_timer(rt_clock, gui_update, NULL);
2599     qemu_mod_timer(gui_timer, qemu_get_clock(rt_clock));
2600
2601 #ifdef CONFIG_GDBSTUB
2602     if (use_gdbstub) {
2603         if (gdbserver_start(gdbstub_port) < 0) {
2604             fprintf(stderr, "Could not open gdbserver socket on port %d\n", 
2605                     gdbstub_port);
2606             exit(1);
2607         } else {
2608             printf("Waiting gdb connection on port %d\n", gdbstub_port);
2609         }
2610     } else 
2611 #endif
2612     if (start_emulation)
2613     {
2614         vm_start();
2615     }
2616     term_init();
2617     main_loop();
2618     quit_timers();
2619     return 0;
2620 }
This page took 0.15986 seconds and 4 git commands to generate.