native FPU support in code copy mode
[qemu] / vl.c
1 /*
2  * QEMU PC System Emulator
3  * 
4  * Copyright (c) 2003 Fabrice Bellard
5  * 
6  * Permission is hereby granted, free of charge, to any person obtaining a copy
7  * of this software and associated documentation files (the "Software"), to deal
8  * in the Software without restriction, including without limitation the rights
9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10  * copies of the Software, and to permit persons to whom the Software is
11  * furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included in
14  * all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19  * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22  * THE SOFTWARE.
23  */
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <stdarg.h>
27 #include <string.h>
28 #include <ctype.h>
29 #include <getopt.h>
30 #include <inttypes.h>
31 #include <unistd.h>
32 #include <sys/mman.h>
33 #include <fcntl.h>
34 #include <signal.h>
35 #include <time.h>
36 #include <sys/time.h>
37 #include <malloc.h>
38 #include <termios.h>
39 #include <sys/poll.h>
40 #include <errno.h>
41 #include <sys/wait.h>
42
43 #include <sys/ioctl.h>
44 #include <sys/socket.h>
45 #include <linux/if.h>
46 #include <linux/if_tun.h>
47
48 #include "disas.h"
49 #include "thunk.h"
50
51 #include "vl.h"
52
53 #define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
54 #define BIOS_FILENAME "bios.bin"
55 #define VGABIOS_FILENAME "vgabios.bin"
56
57 //#define DEBUG_UNUSED_IOPORT
58
59 //#define DEBUG_IRQ_LATENCY
60
61 /* output Bochs bios info messages */
62 //#define DEBUG_BIOS
63
64 //#define DEBUG_CMOS
65
66 /* debug PIC */
67 //#define DEBUG_PIC
68
69 /* debug NE2000 card */
70 //#define DEBUG_NE2000
71
72 /* debug PC keyboard */
73 //#define DEBUG_KBD
74
75 /* debug PC keyboard : only mouse */
76 //#define DEBUG_MOUSE
77
78 //#define DEBUG_SERIAL
79
80 #if !defined(CONFIG_SOFTMMU)
81 #define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
82 #else
83 #define PHYS_RAM_MAX_SIZE (2047 * 1024 * 1024)
84 #endif
85
86 #if defined (TARGET_I386)
87 #define KERNEL_LOAD_ADDR   0x00100000
88 #elif defined (TARGET_PPC)
89 //#define USE_OPEN_FIRMWARE
90 #if !defined (USE_OPEN_FIRMWARE)
91 #define KERNEL_LOAD_ADDR    0x01000000
92 #define KERNEL_STACK_ADDR   0x01200000
93 #else
94 #define KERNEL_LOAD_ADDR    0x00000000
95 #define KERNEL_STACK_ADDR   0x00400000
96 #endif
97 #endif
98 #define INITRD_LOAD_ADDR     0x00400000
99 #define KERNEL_PARAMS_ADDR   0x00090000
100 #define KERNEL_CMDLINE_ADDR  0x00099000
101
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 static const char *bios_dir = CONFIG_QEMU_SHAREDIR;
108 char phys_ram_file[1024];
109 CPUState *global_env;
110 CPUState *cpu_single_env;
111 IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
112 IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
113 BlockDriverState *bs_table[MAX_DISKS], *fd_table[MAX_FD];
114 int vga_ram_size;
115 static DisplayState display_state;
116 int nographic;
117 int term_inited;
118 int64_t ticks_per_sec;
119 int boot_device = 'c';
120 static int ram_size;
121
122 /***********************************************************/
123 /* x86 io ports */
124
125 uint32_t default_ioport_readb(CPUState *env, uint32_t address)
126 {
127 #ifdef DEBUG_UNUSED_IOPORT
128     fprintf(stderr, "inb: port=0x%04x\n", address);
129 #endif
130     return 0xff;
131 }
132
133 void default_ioport_writeb(CPUState *env, uint32_t address, uint32_t data)
134 {
135 #ifdef DEBUG_UNUSED_IOPORT
136     fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
137 #endif
138 }
139
140 /* default is to make two byte accesses */
141 uint32_t default_ioport_readw(CPUState *env, uint32_t address)
142 {
143     uint32_t data;
144     data = ioport_read_table[0][address & (MAX_IOPORTS - 1)](env, address);
145     data |= ioport_read_table[0][(address + 1) & (MAX_IOPORTS - 1)](env, address + 1) << 8;
146     return data;
147 }
148
149 void default_ioport_writew(CPUState *env, uint32_t address, uint32_t data)
150 {
151     ioport_write_table[0][address & (MAX_IOPORTS - 1)](env, address, data & 0xff);
152     ioport_write_table[0][(address + 1) & (MAX_IOPORTS - 1)](env, address + 1, (data >> 8) & 0xff);
153 }
154
155 uint32_t default_ioport_readl(CPUState *env, uint32_t address)
156 {
157 #ifdef DEBUG_UNUSED_IOPORT
158     fprintf(stderr, "inl: port=0x%04x\n", address);
159 #endif
160     return 0xffffffff;
161 }
162
163 void default_ioport_writel(CPUState *env, uint32_t address, uint32_t data)
164 {
165 #ifdef DEBUG_UNUSED_IOPORT
166     fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
167 #endif
168 }
169
170 void init_ioports(void)
171 {
172     int i;
173
174     for(i = 0; i < MAX_IOPORTS; i++) {
175         ioport_read_table[0][i] = default_ioport_readb;
176         ioport_write_table[0][i] = default_ioport_writeb;
177         ioport_read_table[1][i] = default_ioport_readw;
178         ioport_write_table[1][i] = default_ioport_writew;
179         ioport_read_table[2][i] = default_ioport_readl;
180         ioport_write_table[2][i] = default_ioport_writel;
181     }
182 }
183
184 /* size is the word size in byte */
185 int register_ioport_read(int start, int length, IOPortReadFunc *func, int size)
186 {
187     int i, bsize;
188
189     if (size == 1)
190         bsize = 0;
191     else if (size == 2)
192         bsize = 1;
193     else if (size == 4)
194         bsize = 2;
195     else
196         return -1;
197     for(i = start; i < start + length; i += size)
198         ioport_read_table[bsize][i] = func;
199     return 0;
200 }
201
202 /* size is the word size in byte */
203 int register_ioport_write(int start, int length, IOPortWriteFunc *func, int size)
204 {
205     int i, bsize;
206
207     if (size == 1)
208         bsize = 0;
209     else if (size == 2)
210         bsize = 1;
211     else if (size == 4)
212         bsize = 2;
213     else
214         return -1;
215     for(i = start; i < start + length; i += size)
216         ioport_write_table[bsize][i] = func;
217     return 0;
218 }
219
220 void pstrcpy(char *buf, int buf_size, const char *str)
221 {
222     int c;
223     char *q = buf;
224
225     if (buf_size <= 0)
226         return;
227
228     for(;;) {
229         c = *str++;
230         if (c == 0 || q >= buf + buf_size - 1)
231             break;
232         *q++ = c;
233     }
234     *q = '\0';
235 }
236
237 /* strcat and truncate. */
238 char *pstrcat(char *buf, int buf_size, const char *s)
239 {
240     int len;
241     len = strlen(buf);
242     if (len < buf_size) 
243         pstrcpy(buf + len, buf_size - len, s);
244     return buf;
245 }
246
247 #if defined (TARGET_I386)
248 int load_kernel(const char *filename, uint8_t *addr, 
249                 uint8_t *real_addr)
250 {
251     int fd, size;
252     int setup_sects;
253
254     fd = open(filename, O_RDONLY);
255     if (fd < 0)
256         return -1;
257
258     /* load 16 bit code */
259     if (read(fd, real_addr, 512) != 512)
260         goto fail;
261     setup_sects = real_addr[0x1F1];
262     if (!setup_sects)
263         setup_sects = 4;
264     if (read(fd, real_addr + 512, setup_sects * 512) != 
265         setup_sects * 512)
266         goto fail;
267     
268     /* load 32 bit code */
269     size = read(fd, addr, 16 * 1024 * 1024);
270     if (size < 0)
271         goto fail;
272     close(fd);
273     return size;
274  fail:
275     close(fd);
276     return -1;
277 }
278 #endif
279
280 /* return the size or -1 if error */
281 int load_image(const char *filename, uint8_t *addr)
282 {
283     int fd, size;
284     fd = open(filename, O_RDONLY);
285     if (fd < 0)
286         return -1;
287     size = lseek(fd, 0, SEEK_END);
288     lseek(fd, 0, SEEK_SET);
289     if (read(fd, addr, size) != size) {
290         close(fd);
291         return -1;
292     }
293     close(fd);
294     return size;
295 }
296
297 void cpu_outb(CPUState *env, int addr, int val)
298 {
299     ioport_write_table[0][addr & (MAX_IOPORTS - 1)](env, addr, val);
300 }
301
302 void cpu_outw(CPUState *env, int addr, int val)
303 {
304     ioport_write_table[1][addr & (MAX_IOPORTS - 1)](env, addr, val);
305 }
306
307 void cpu_outl(CPUState *env, int addr, int val)
308 {
309     ioport_write_table[2][addr & (MAX_IOPORTS - 1)](env, addr, val);
310 }
311
312 int cpu_inb(CPUState *env, int addr)
313 {
314     return ioport_read_table[0][addr & (MAX_IOPORTS - 1)](env, addr);
315 }
316
317 int cpu_inw(CPUState *env, int addr)
318 {
319     return ioport_read_table[1][addr & (MAX_IOPORTS - 1)](env, addr);
320 }
321
322 int cpu_inl(CPUState *env, int addr)
323 {
324     return ioport_read_table[2][addr & (MAX_IOPORTS - 1)](env, addr);
325 }
326
327 /***********************************************************/
328 void ioport80_write(CPUState *env, uint32_t addr, uint32_t data)
329 {
330 }
331
332 void hw_error(const char *fmt, ...)
333 {
334     va_list ap;
335
336     va_start(ap, fmt);
337     fprintf(stderr, "qemu: hardware error: ");
338     vfprintf(stderr, fmt, ap);
339     fprintf(stderr, "\n");
340 #ifdef TARGET_I386
341     cpu_x86_dump_state(global_env, stderr, X86_DUMP_FPU | X86_DUMP_CCOP);
342 #else
343     cpu_dump_state(global_env, stderr, 0);
344 #endif
345     va_end(ap);
346     abort();
347 }
348
349 /***********************************************************/
350 /* cmos emulation */
351
352 #if defined (TARGET_I386)
353 #define RTC_SECONDS             0
354 #define RTC_SECONDS_ALARM       1
355 #define RTC_MINUTES             2
356 #define RTC_MINUTES_ALARM       3
357 #define RTC_HOURS               4
358 #define RTC_HOURS_ALARM         5
359 #define RTC_ALARM_DONT_CARE    0xC0
360
361 #define RTC_DAY_OF_WEEK         6
362 #define RTC_DAY_OF_MONTH        7
363 #define RTC_MONTH               8
364 #define RTC_YEAR                9
365
366 #define RTC_REG_A               10
367 #define RTC_REG_B               11
368 #define RTC_REG_C               12
369 #define RTC_REG_D               13
370
371 /* PC cmos mappings */
372 #define REG_EQUIPMENT_BYTE          0x14
373 #define REG_IBM_CENTURY_BYTE        0x32
374 #define REG_IBM_PS2_CENTURY_BYTE    0x37
375
376 uint8_t cmos_data[128];
377 uint8_t cmos_index;
378
379 void cmos_ioport_write(CPUState *env, uint32_t addr, uint32_t data)
380 {
381     if (addr == 0x70) {
382         cmos_index = data & 0x7f;
383     } else {
384 #ifdef DEBUG_CMOS
385         printf("cmos: write index=0x%02x val=0x%02x\n",
386                cmos_index, data);
387 #endif        
388         switch(addr) {
389         case RTC_SECONDS_ALARM:
390         case RTC_MINUTES_ALARM:
391         case RTC_HOURS_ALARM:
392             /* XXX: not supported */
393             cmos_data[cmos_index] = data;
394             break;
395         case RTC_SECONDS:
396         case RTC_MINUTES:
397         case RTC_HOURS:
398         case RTC_DAY_OF_WEEK:
399         case RTC_DAY_OF_MONTH:
400         case RTC_MONTH:
401         case RTC_YEAR:
402             cmos_data[cmos_index] = data;
403             break;
404         case RTC_REG_A:
405         case RTC_REG_B:
406             cmos_data[cmos_index] = data;
407             break;
408         case RTC_REG_C:
409         case RTC_REG_D:
410             /* cannot write to them */
411             break;
412         default:
413             cmos_data[cmos_index] = data;
414             break;
415         }
416     }
417 }
418
419 static inline int to_bcd(int a)
420 {
421     return ((a / 10) << 4) | (a % 10);
422 }
423
424 static void cmos_update_time(void)
425 {
426     struct tm *tm;
427     time_t ti;
428
429     ti = time(NULL);
430     tm = gmtime(&ti);
431     cmos_data[RTC_SECONDS] = to_bcd(tm->tm_sec);
432     cmos_data[RTC_MINUTES] = to_bcd(tm->tm_min);
433     cmos_data[RTC_HOURS] = to_bcd(tm->tm_hour);
434     cmos_data[RTC_DAY_OF_WEEK] = to_bcd(tm->tm_wday);
435     cmos_data[RTC_DAY_OF_MONTH] = to_bcd(tm->tm_mday);
436     cmos_data[RTC_MONTH] = to_bcd(tm->tm_mon + 1);
437     cmos_data[RTC_YEAR] = to_bcd(tm->tm_year % 100);
438     cmos_data[REG_IBM_CENTURY_BYTE] = to_bcd((tm->tm_year / 100) + 19);
439     cmos_data[REG_IBM_PS2_CENTURY_BYTE] = cmos_data[REG_IBM_CENTURY_BYTE];
440 }
441
442 uint32_t cmos_ioport_read(CPUState *env, uint32_t addr)
443 {
444     int ret;
445
446     if (addr == 0x70) {
447         return 0xff;
448     } else {
449         switch(cmos_index) {
450         case RTC_SECONDS:
451         case RTC_MINUTES:
452         case RTC_HOURS:
453         case RTC_DAY_OF_WEEK:
454         case RTC_DAY_OF_MONTH:
455         case RTC_MONTH:
456         case RTC_YEAR:
457         case REG_IBM_CENTURY_BYTE:
458         case REG_IBM_PS2_CENTURY_BYTE:
459             cmos_update_time();
460             ret = cmos_data[cmos_index];
461             break;
462         case RTC_REG_A:
463             ret = cmos_data[cmos_index];
464             /* toggle update-in-progress bit for Linux (same hack as
465                plex86) */
466             cmos_data[RTC_REG_A] ^= 0x80; 
467             break;
468         case RTC_REG_C:
469             ret = cmos_data[cmos_index];
470             pic_set_irq(8, 0);
471             cmos_data[RTC_REG_C] = 0x00; 
472             break;
473         default:
474             ret = cmos_data[cmos_index];
475             break;
476         }
477 #ifdef DEBUG_CMOS
478         printf("cmos: read index=0x%02x val=0x%02x\n",
479                cmos_index, ret);
480 #endif
481         return ret;
482     }
483 }
484
485 void cmos_init(void)
486 {
487     int val;
488
489     cmos_update_time();
490
491     cmos_data[RTC_REG_A] = 0x26;
492     cmos_data[RTC_REG_B] = 0x02;
493     cmos_data[RTC_REG_C] = 0x00;
494     cmos_data[RTC_REG_D] = 0x80;
495
496     /* various important CMOS locations needed by PC/Bochs bios */
497
498     cmos_data[REG_EQUIPMENT_BYTE] = 0x02; /* FPU is there */
499     cmos_data[REG_EQUIPMENT_BYTE] |= 0x04; /* PS/2 mouse installed */
500
501     /* memory size */
502     val = (ram_size / 1024) - 1024;
503     if (val > 65535)
504         val = 65535;
505     cmos_data[0x17] = val;
506     cmos_data[0x18] = val >> 8;
507     cmos_data[0x30] = val;
508     cmos_data[0x31] = val >> 8;
509
510     val = (ram_size / 65536) - ((16 * 1024 * 1024) / 65536);
511     if (val > 65535)
512         val = 65535;
513     cmos_data[0x34] = val;
514     cmos_data[0x35] = val >> 8;
515     
516     switch(boot_device) {
517     case 'a':
518     case 'b':
519         cmos_data[0x3d] = 0x01; /* floppy boot */
520         break;
521     default:
522     case 'c':
523         cmos_data[0x3d] = 0x02; /* hard drive boot */
524         break;
525     case 'd':
526         cmos_data[0x3d] = 0x03; /* CD-ROM boot */
527         break;
528     }
529
530     register_ioport_write(0x70, 2, cmos_ioport_write, 1);
531     register_ioport_read(0x70, 2, cmos_ioport_read, 1);
532 }
533
534 void cmos_register_fd (uint8_t fd0, uint8_t fd1)
535 {
536     int nb = 0;
537
538     cmos_data[0x10] = 0;
539     switch (fd0) {
540     case 0:
541         /* 1.44 Mb 3"5 drive */
542         cmos_data[0x10] |= 0x40;
543         break;
544     case 1:
545         /* 2.88 Mb 3"5 drive */
546         cmos_data[0x10] |= 0x60;
547         break;
548     case 2:
549         /* 1.2 Mb 5"5 drive */
550         cmos_data[0x10] |= 0x20;
551         break;
552     }
553     switch (fd1) {
554     case 0:
555         /* 1.44 Mb 3"5 drive */
556         cmos_data[0x10] |= 0x04;
557         break;
558     case 1:
559         /* 2.88 Mb 3"5 drive */
560         cmos_data[0x10] |= 0x06;
561         break;
562     case 2:
563         /* 1.2 Mb 5"5 drive */
564         cmos_data[0x10] |= 0x02;
565         break;
566     }
567     if (fd0 < 3)
568         nb++;
569     if (fd1 < 3)
570         nb++;
571     switch (nb) {
572     case 0:
573         break;
574     case 1:
575         cmos_data[REG_EQUIPMENT_BYTE] |= 0x01; /* 1 drive, ready for boot */
576         break;
577     case 2:
578         cmos_data[REG_EQUIPMENT_BYTE] |= 0x41; /* 2 drives, ready for boot */
579         break;
580     }
581 }
582 #endif /* TARGET_I386 */
583
584 /***********************************************************/
585 /* 8259 pic emulation */
586
587 typedef struct PicState {
588     uint8_t last_irr; /* edge detection */
589     uint8_t irr; /* interrupt request register */
590     uint8_t imr; /* interrupt mask register */
591     uint8_t isr; /* interrupt service register */
592     uint8_t priority_add; /* highest irq priority */
593     uint8_t irq_base;
594     uint8_t read_reg_select;
595     uint8_t poll;
596     uint8_t special_mask;
597     uint8_t init_state;
598     uint8_t auto_eoi;
599     uint8_t rotate_on_auto_eoi;
600     uint8_t special_fully_nested_mode;
601     uint8_t init4; /* true if 4 byte init */
602 } PicState;
603
604 /* 0 is master pic, 1 is slave pic */
605 PicState pics[2];
606 int pic_irq_requested;
607
608 /* set irq level. If an edge is detected, then the IRR is set to 1 */
609 static inline void pic_set_irq1(PicState *s, int irq, int level)
610 {
611     int mask;
612     mask = 1 << irq;
613     if (level) {
614         if ((s->last_irr & mask) == 0)
615             s->irr |= mask;
616         s->last_irr |= mask;
617     } else {
618         s->last_irr &= ~mask;
619     }
620 }
621
622 /* return the highest priority found in mask (highest = smallest
623    number). Return 8 if no irq */
624 static inline int get_priority(PicState *s, int mask)
625 {
626     int priority;
627     if (mask == 0)
628         return 8;
629     priority = 0;
630     while ((mask & (1 << ((priority + s->priority_add) & 7))) == 0)
631         priority++;
632     return priority;
633 }
634
635 /* return the pic wanted interrupt. return -1 if none */
636 static int pic_get_irq(PicState *s)
637 {
638     int mask, cur_priority, priority;
639
640     mask = s->irr & ~s->imr;
641     priority = get_priority(s, mask);
642     if (priority == 8)
643         return -1;
644     /* compute current priority. If special fully nested mode on the
645        master, the IRQ coming from the slave is not taken into account
646        for the priority computation. */
647     mask = s->isr;
648     if (s->special_fully_nested_mode && s == &pics[0])
649         mask &= ~(1 << 2);
650     cur_priority = get_priority(s, mask);
651     if (priority < cur_priority) {
652         /* higher priority found: an irq should be generated */
653         return (priority + s->priority_add) & 7;
654     } else {
655         return -1;
656     }
657 }
658
659 /* raise irq to CPU if necessary. must be called every time the active
660    irq may change */
661 void pic_update_irq(void)
662 {
663     int irq2, irq;
664
665     /* first look at slave pic */
666     irq2 = pic_get_irq(&pics[1]);
667     if (irq2 >= 0) {
668         /* if irq request by slave pic, signal master PIC */
669         pic_set_irq1(&pics[0], 2, 1);
670         pic_set_irq1(&pics[0], 2, 0);
671     }
672     /* look at requested irq */
673     irq = pic_get_irq(&pics[0]);
674     if (irq >= 0) {
675         if (irq == 2) {
676             /* from slave pic */
677             pic_irq_requested = 8 + irq2;
678         } else {
679             /* from master pic */
680             pic_irq_requested = irq;
681         }
682 #if defined(DEBUG_PIC)
683         {
684             int i;
685             for(i = 0; i < 2; i++) {
686                 printf("pic%d: imr=%x irr=%x padd=%d\n", 
687                        i, pics[i].imr, pics[i].irr, pics[i].priority_add);
688                 
689             }
690         }
691         printf("pic: cpu_interrupt req=%d\n", pic_irq_requested);
692 #endif
693         cpu_interrupt(global_env, CPU_INTERRUPT_HARD);
694     }
695 }
696
697 #ifdef DEBUG_IRQ_LATENCY
698 int64_t irq_time[16];
699 int64_t cpu_get_ticks(void);
700 #endif
701 #if defined(DEBUG_PIC)
702 int irq_level[16];
703 #endif
704
705 void pic_set_irq(int irq, int level)
706 {
707 #if defined(DEBUG_PIC)
708     if (level != irq_level[irq]) {
709         printf("pic_set_irq: irq=%d level=%d\n", irq, level);
710         irq_level[irq] = level;
711     }
712 #endif
713 #ifdef DEBUG_IRQ_LATENCY
714     if (level) {
715         irq_time[irq] = cpu_get_ticks();
716     }
717 #endif
718     pic_set_irq1(&pics[irq >> 3], irq & 7, level);
719     pic_update_irq();
720 }
721
722 /* acknowledge interrupt 'irq' */
723 static inline void pic_intack(PicState *s, int irq)
724 {
725     if (s->auto_eoi) {
726         if (s->rotate_on_auto_eoi)
727             s->priority_add = (irq + 1) & 7;
728     } else {
729         s->isr |= (1 << irq);
730     }
731     s->irr &= ~(1 << irq);
732 }
733
734 int cpu_x86_get_pic_interrupt(CPUState *env)
735 {
736     int irq, irq2, intno;
737
738     /* signal the pic that the irq was acked by the CPU */
739     irq = pic_irq_requested;
740 #ifdef DEBUG_IRQ_LATENCY
741     printf("IRQ%d latency=%0.3fus\n", 
742            irq, 
743            (double)(cpu_get_ticks() - irq_time[irq]) * 1000000.0 / ticks_per_sec);
744 #endif
745 #if defined(DEBUG_PIC)
746     printf("pic_interrupt: irq=%d\n", irq);
747 #endif
748
749     if (irq >= 8) {
750         irq2 = irq & 7;
751         pic_intack(&pics[1], irq2);
752         irq = 2;
753         intno = pics[1].irq_base + irq2;
754     } else {
755         intno = pics[0].irq_base + irq;
756     }
757     pic_intack(&pics[0], irq);
758     return intno;
759 }
760
761 void pic_ioport_write(CPUState *env, uint32_t addr, uint32_t val)
762 {
763     PicState *s;
764     int priority, cmd, irq;
765
766 #ifdef DEBUG_PIC
767     printf("pic_write: addr=0x%02x val=0x%02x\n", addr, val);
768 #endif
769     s = &pics[addr >> 7];
770     addr &= 1;
771     if (addr == 0) {
772         if (val & 0x10) {
773             /* init */
774             memset(s, 0, sizeof(PicState));
775             s->init_state = 1;
776             s->init4 = val & 1;
777             if (val & 0x02)
778                 hw_error("single mode not supported");
779             if (val & 0x08)
780                 hw_error("level sensitive irq not supported");
781         } else if (val & 0x08) {
782             if (val & 0x04)
783                 s->poll = 1;
784             if (val & 0x02)
785                 s->read_reg_select = val & 1;
786             if (val & 0x40)
787                 s->special_mask = (val >> 5) & 1;
788         } else {
789             cmd = val >> 5;
790             switch(cmd) {
791             case 0:
792             case 4:
793                 s->rotate_on_auto_eoi = cmd >> 2;
794                 break;
795             case 1: /* end of interrupt */
796             case 5:
797                 priority = get_priority(s, s->isr);
798                 if (priority != 8) {
799                     irq = (priority + s->priority_add) & 7;
800                     s->isr &= ~(1 << irq);
801                     if (cmd == 5)
802                         s->priority_add = (irq + 1) & 7;
803                     pic_update_irq();
804                 }
805                 break;
806             case 3:
807                 irq = val & 7;
808                 s->isr &= ~(1 << irq);
809                 pic_update_irq();
810                 break;
811             case 6:
812                 s->priority_add = (val + 1) & 7;
813                 pic_update_irq();
814                 break;
815             case 7:
816                 irq = val & 7;
817                 s->isr &= ~(1 << irq);
818                 s->priority_add = (irq + 1) & 7;
819                 pic_update_irq();
820                 break;
821             default:
822                 /* no operation */
823                 break;
824             }
825         }
826     } else {
827         switch(s->init_state) {
828         case 0:
829             /* normal mode */
830             s->imr = val;
831             pic_update_irq();
832             break;
833         case 1:
834             s->irq_base = val & 0xf8;
835             s->init_state = 2;
836             break;
837         case 2:
838             if (s->init4) {
839                 s->init_state = 3;
840             } else {
841                 s->init_state = 0;
842             }
843             break;
844         case 3:
845             s->special_fully_nested_mode = (val >> 4) & 1;
846             s->auto_eoi = (val >> 1) & 1;
847             s->init_state = 0;
848             break;
849         }
850     }
851 }
852
853 static uint32_t pic_poll_read (PicState *s, uint32_t addr1)
854 {
855     int ret;
856
857     ret = pic_get_irq(s);
858     if (ret >= 0) {
859         if (addr1 >> 7) {
860             pics[0].isr &= ~(1 << 2);
861             pics[0].irr &= ~(1 << 2);
862         }
863         s->irr &= ~(1 << ret);
864         s->isr &= ~(1 << ret);
865         if (addr1 >> 7 || ret != 2)
866             pic_update_irq();
867     } else {
868         ret = 0x07;
869         pic_update_irq();
870     }
871
872     return ret;
873 }
874
875 uint32_t pic_ioport_read(CPUState *env, uint32_t addr1)
876 {
877     PicState *s;
878     unsigned int addr;
879     int ret;
880
881     addr = addr1;
882     s = &pics[addr >> 7];
883     addr &= 1;
884     if (s->poll) {
885         ret = pic_poll_read(s, addr1);
886         s->poll = 0;
887     } else {
888         if (addr == 0) {
889             if (s->read_reg_select)
890                 ret = s->isr;
891             else
892                 ret = s->irr;
893         } else {
894             ret = s->imr;
895         }
896     }
897 #ifdef DEBUG_PIC
898     printf("pic_read: addr=0x%02x val=0x%02x\n", addr1, ret);
899 #endif
900     return ret;
901 }
902
903 /* memory mapped interrupt status */
904 uint32_t pic_intack_read(CPUState *env)
905 {
906     int ret;
907
908     ret = pic_poll_read(&pics[0], 0x00);
909     if (ret == 2)
910         ret = pic_poll_read(&pics[1], 0x80) + 8;
911     /* Prepare for ISR read */
912     pics[0].read_reg_select = 1;
913     
914     return ret;
915 }
916
917 void pic_init(void)
918 {
919 #if defined (TARGET_I386) || defined (TARGET_PPC)
920     register_ioport_write(0x20, 2, pic_ioport_write, 1);
921     register_ioport_read(0x20, 2, pic_ioport_read, 1);
922     register_ioport_write(0xa0, 2, pic_ioport_write, 1);
923     register_ioport_read(0xa0, 2, pic_ioport_read, 1);
924 #endif
925 }
926
927 /***********************************************************/
928 /* 8253 PIT emulation */
929
930 #define PIT_FREQ 1193182
931
932 #define RW_STATE_LSB 0
933 #define RW_STATE_MSB 1
934 #define RW_STATE_WORD0 2
935 #define RW_STATE_WORD1 3
936 #define RW_STATE_LATCHED_WORD0 4
937 #define RW_STATE_LATCHED_WORD1 5
938
939 typedef struct PITChannelState {
940     int count; /* can be 65536 */
941     uint16_t latched_count;
942     uint8_t rw_state;
943     uint8_t mode;
944     uint8_t bcd; /* not supported */
945     uint8_t gate; /* timer start */
946     int64_t count_load_time;
947     int64_t count_last_edge_check_time;
948 } PITChannelState;
949
950 PITChannelState pit_channels[3];
951 int speaker_data_on;
952 int dummy_refresh_clock;
953 int pit_min_timer_count = 0;
954
955
956 #if defined(__powerpc__)
957
958 static inline uint32_t get_tbl(void) 
959 {
960     uint32_t tbl;
961     asm volatile("mftb %0" : "=r" (tbl));
962     return tbl;
963 }
964
965 static inline uint32_t get_tbu(void) 
966 {
967         uint32_t tbl;
968         asm volatile("mftbu %0" : "=r" (tbl));
969         return tbl;
970 }
971
972 int64_t cpu_get_real_ticks(void)
973 {
974     uint32_t l, h, h1;
975     /* NOTE: we test if wrapping has occurred */
976     do {
977         h = get_tbu();
978         l = get_tbl();
979         h1 = get_tbu();
980     } while (h != h1);
981     return ((int64_t)h << 32) | l;
982 }
983
984 #elif defined(__i386__)
985
986 int64_t cpu_get_real_ticks(void)
987 {
988     int64_t val;
989     asm("rdtsc" : "=A" (val));
990     return val;
991 }
992
993 #else
994 #error unsupported CPU
995 #endif
996
997 static int64_t cpu_ticks_offset;
998 static int64_t cpu_ticks_last;
999
1000 int64_t cpu_get_ticks(void)
1001 {
1002     return cpu_get_real_ticks() + cpu_ticks_offset;
1003 }
1004
1005 /* enable cpu_get_ticks() */
1006 void cpu_enable_ticks(void)
1007 {
1008     cpu_ticks_offset = cpu_ticks_last - cpu_get_real_ticks();
1009 }
1010
1011 /* disable cpu_get_ticks() : the clock is stopped. You must not call
1012    cpu_get_ticks() after that.  */
1013 void cpu_disable_ticks(void)
1014 {
1015     cpu_ticks_last = cpu_get_ticks();
1016 }
1017
1018 int64_t get_clock(void)
1019 {
1020     struct timeval tv;
1021     gettimeofday(&tv, NULL);
1022     return tv.tv_sec * 1000000LL + tv.tv_usec;
1023 }
1024
1025 void cpu_calibrate_ticks(void)
1026 {
1027     int64_t usec, ticks;
1028
1029     usec = get_clock();
1030     ticks = cpu_get_ticks();
1031     usleep(50 * 1000);
1032     usec = get_clock() - usec;
1033     ticks = cpu_get_ticks() - ticks;
1034     ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
1035 }
1036
1037 /* compute with 96 bit intermediate result: (a*b)/c */
1038 static uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
1039 {
1040     union {
1041         uint64_t ll;
1042         struct {
1043 #ifdef WORDS_BIGENDIAN
1044             uint32_t high, low;
1045 #else
1046             uint32_t low, high;
1047 #endif            
1048         } l;
1049     } u, res;
1050     uint64_t rl, rh;
1051
1052     u.ll = a;
1053     rl = (uint64_t)u.l.low * (uint64_t)b;
1054     rh = (uint64_t)u.l.high * (uint64_t)b;
1055     rh += (rl >> 32);
1056     res.l.high = rh / c;
1057     res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
1058     return res.ll;
1059 }
1060
1061 static int pit_get_count(PITChannelState *s)
1062 {
1063     uint64_t d;
1064     int counter;
1065
1066     d = muldiv64(cpu_get_ticks() - s->count_load_time, PIT_FREQ, ticks_per_sec);
1067     switch(s->mode) {
1068     case 0:
1069     case 1:
1070     case 4:
1071     case 5:
1072         counter = (s->count - d) & 0xffff;
1073         break;
1074     case 3:
1075         /* XXX: may be incorrect for odd counts */
1076         counter = s->count - ((2 * d) % s->count);
1077         break;
1078     default:
1079         counter = s->count - (d % s->count);
1080         break;
1081     }
1082     return counter;
1083 }
1084
1085 /* get pit output bit */
1086 static int pit_get_out(PITChannelState *s)
1087 {
1088     uint64_t d;
1089     int out;
1090
1091     d = muldiv64(cpu_get_ticks() - s->count_load_time, PIT_FREQ, ticks_per_sec);
1092     switch(s->mode) {
1093     default:
1094     case 0:
1095         out = (d >= s->count);
1096         break;
1097     case 1:
1098         out = (d < s->count);
1099         break;
1100     case 2:
1101         if ((d % s->count) == 0 && d != 0)
1102             out = 1;
1103         else
1104             out = 0;
1105         break;
1106     case 3:
1107         out = (d % s->count) < ((s->count + 1) >> 1);
1108         break;
1109     case 4:
1110     case 5:
1111         out = (d == s->count);
1112         break;
1113     }
1114     return out;
1115 }
1116
1117 /* get the number of 0 to 1 transitions we had since we call this
1118    function */
1119 /* XXX: maybe better to use ticks precision to avoid getting edges
1120    twice if checks are done at very small intervals */
1121 static int pit_get_out_edges(PITChannelState *s)
1122 {
1123     uint64_t d1, d2;
1124     int64_t ticks;
1125     int ret, v;
1126
1127     ticks = cpu_get_ticks();
1128     d1 = muldiv64(s->count_last_edge_check_time - s->count_load_time, 
1129                  PIT_FREQ, ticks_per_sec);
1130     d2 = muldiv64(ticks - s->count_load_time, 
1131                   PIT_FREQ, ticks_per_sec);
1132     s->count_last_edge_check_time = ticks;
1133     switch(s->mode) {
1134     default:
1135     case 0:
1136         if (d1 < s->count && d2 >= s->count)
1137             ret = 1;
1138         else
1139             ret = 0;
1140         break;
1141     case 1:
1142         ret = 0;
1143         break;
1144     case 2:
1145         d1 /= s->count;
1146         d2 /= s->count;
1147         ret = d2 - d1;
1148         break;
1149     case 3:
1150         v = s->count - ((s->count + 1) >> 1);
1151         d1 = (d1 + v) / s->count;
1152         d2 = (d2 + v) / s->count;
1153         ret = d2 - d1;
1154         break;
1155     case 4:
1156     case 5:
1157         if (d1 < s->count && d2 >= s->count)
1158             ret = 1;
1159         else
1160             ret = 0;
1161         break;
1162     }
1163     return ret;
1164 }
1165
1166 /* val must be 0 or 1 */
1167 static inline void pit_set_gate(PITChannelState *s, int val)
1168 {
1169     switch(s->mode) {
1170     default:
1171     case 0:
1172     case 4:
1173         /* XXX: just disable/enable counting */
1174         break;
1175     case 1:
1176     case 5:
1177         if (s->gate < val) {
1178             /* restart counting on rising edge */
1179             s->count_load_time = cpu_get_ticks();
1180             s->count_last_edge_check_time = s->count_load_time;
1181         }
1182         break;
1183     case 2:
1184     case 3:
1185         if (s->gate < val) {
1186             /* restart counting on rising edge */
1187             s->count_load_time = cpu_get_ticks();
1188             s->count_last_edge_check_time = s->count_load_time;
1189         }
1190         /* XXX: disable/enable counting */
1191         break;
1192     }
1193     s->gate = val;
1194 }
1195
1196 static inline void pit_load_count(PITChannelState *s, int val)
1197 {
1198     if (val == 0)
1199         val = 0x10000;
1200     s->count_load_time = cpu_get_ticks();
1201     s->count_last_edge_check_time = s->count_load_time;
1202     s->count = val;
1203     if (s == &pit_channels[0] && val <= pit_min_timer_count) {
1204         fprintf(stderr, 
1205                 "\nWARNING: qemu: on your system, accurate timer emulation is impossible if its frequency is more than %d Hz. If using a 2.6 guest Linux kernel, you must patch asm/param.h to change HZ from 1000 to 100.\n\n", 
1206                 PIT_FREQ / pit_min_timer_count);
1207     }
1208 }
1209
1210 void pit_ioport_write(CPUState *env, uint32_t addr, uint32_t val)
1211 {
1212     int channel, access;
1213     PITChannelState *s;
1214
1215     addr &= 3;
1216     if (addr == 3) {
1217         channel = val >> 6;
1218         if (channel == 3)
1219             return;
1220         s = &pit_channels[channel];
1221         access = (val >> 4) & 3;
1222         switch(access) {
1223         case 0:
1224             s->latched_count = pit_get_count(s);
1225             s->rw_state = RW_STATE_LATCHED_WORD0;
1226             break;
1227         default:
1228             s->mode = (val >> 1) & 7;
1229             s->bcd = val & 1;
1230             s->rw_state = access - 1 +  RW_STATE_LSB;
1231             break;
1232         }
1233     } else {
1234         s = &pit_channels[addr];
1235         switch(s->rw_state) {
1236         case RW_STATE_LSB:
1237             pit_load_count(s, val);
1238             break;
1239         case RW_STATE_MSB:
1240             pit_load_count(s, val << 8);
1241             break;
1242         case RW_STATE_WORD0:
1243         case RW_STATE_WORD1:
1244             if (s->rw_state & 1) {
1245                 pit_load_count(s, (s->latched_count & 0xff) | (val << 8));
1246             } else {
1247                 s->latched_count = val;
1248             }
1249             s->rw_state ^= 1;
1250             break;
1251         }
1252     }
1253 }
1254
1255 uint32_t pit_ioport_read(CPUState *env, uint32_t addr)
1256 {
1257     int ret, count;
1258     PITChannelState *s;
1259     
1260     addr &= 3;
1261     s = &pit_channels[addr];
1262     switch(s->rw_state) {
1263     case RW_STATE_LSB:
1264     case RW_STATE_MSB:
1265     case RW_STATE_WORD0:
1266     case RW_STATE_WORD1:
1267         count = pit_get_count(s);
1268         if (s->rw_state & 1)
1269             ret = (count >> 8) & 0xff;
1270         else
1271             ret = count & 0xff;
1272         if (s->rw_state & 2)
1273             s->rw_state ^= 1;
1274         break;
1275     default:
1276     case RW_STATE_LATCHED_WORD0:
1277     case RW_STATE_LATCHED_WORD1:
1278         if (s->rw_state & 1)
1279             ret = s->latched_count >> 8;
1280         else
1281             ret = s->latched_count & 0xff;
1282         s->rw_state ^= 1;
1283         break;
1284     }
1285     return ret;
1286 }
1287
1288 #if defined (TARGET_I386)
1289 void speaker_ioport_write(CPUState *env, uint32_t addr, uint32_t val)
1290 {
1291     speaker_data_on = (val >> 1) & 1;
1292     pit_set_gate(&pit_channels[2], val & 1);
1293 }
1294
1295 uint32_t speaker_ioport_read(CPUState *env, uint32_t addr)
1296 {
1297     int out;
1298     out = pit_get_out(&pit_channels[2]);
1299     dummy_refresh_clock ^= 1;
1300     return (speaker_data_on << 1) | pit_channels[2].gate | (out << 5) |
1301       (dummy_refresh_clock << 4);
1302 }
1303 #endif
1304
1305 void pit_init(void)
1306 {
1307     PITChannelState *s;
1308     int i;
1309
1310     cpu_calibrate_ticks();
1311
1312     for(i = 0;i < 3; i++) {
1313         s = &pit_channels[i];
1314         s->mode = 3;
1315         s->gate = (i != 2);
1316         pit_load_count(s, 0);
1317     }
1318
1319     register_ioport_write(0x40, 4, pit_ioport_write, 1);
1320     register_ioport_read(0x40, 3, pit_ioport_read, 1);
1321
1322 #if defined (TARGET_I386)
1323     register_ioport_read(0x61, 1, speaker_ioport_read, 1);
1324     register_ioport_write(0x61, 1, speaker_ioport_write, 1);
1325 #endif
1326 }
1327
1328 /***********************************************************/
1329 /* serial port emulation */
1330
1331 #define UART_IRQ        4
1332
1333 #define UART_LCR_DLAB   0x80    /* Divisor latch access bit */
1334
1335 #define UART_IER_MSI    0x08    /* Enable Modem status interrupt */
1336 #define UART_IER_RLSI   0x04    /* Enable receiver line status interrupt */
1337 #define UART_IER_THRI   0x02    /* Enable Transmitter holding register int. */
1338 #define UART_IER_RDI    0x01    /* Enable receiver data interrupt */
1339
1340 #define UART_IIR_NO_INT 0x01    /* No interrupts pending */
1341 #define UART_IIR_ID     0x06    /* Mask for the interrupt ID */
1342
1343 #define UART_IIR_MSI    0x00    /* Modem status interrupt */
1344 #define UART_IIR_THRI   0x02    /* Transmitter holding register empty */
1345 #define UART_IIR_RDI    0x04    /* Receiver data interrupt */
1346 #define UART_IIR_RLSI   0x06    /* Receiver line status interrupt */
1347
1348 /*
1349  * These are the definitions for the Modem Control Register
1350  */
1351 #define UART_MCR_LOOP   0x10    /* Enable loopback test mode */
1352 #define UART_MCR_OUT2   0x08    /* Out2 complement */
1353 #define UART_MCR_OUT1   0x04    /* Out1 complement */
1354 #define UART_MCR_RTS    0x02    /* RTS complement */
1355 #define UART_MCR_DTR    0x01    /* DTR complement */
1356
1357 /*
1358  * These are the definitions for the Modem Status Register
1359  */
1360 #define UART_MSR_DCD    0x80    /* Data Carrier Detect */
1361 #define UART_MSR_RI     0x40    /* Ring Indicator */
1362 #define UART_MSR_DSR    0x20    /* Data Set Ready */
1363 #define UART_MSR_CTS    0x10    /* Clear to Send */
1364 #define UART_MSR_DDCD   0x08    /* Delta DCD */
1365 #define UART_MSR_TERI   0x04    /* Trailing edge ring indicator */
1366 #define UART_MSR_DDSR   0x02    /* Delta DSR */
1367 #define UART_MSR_DCTS   0x01    /* Delta CTS */
1368 #define UART_MSR_ANY_DELTA 0x0F /* Any of the delta bits! */
1369
1370 #define UART_LSR_TEMT   0x40    /* Transmitter empty */
1371 #define UART_LSR_THRE   0x20    /* Transmit-hold-register empty */
1372 #define UART_LSR_BI     0x10    /* Break interrupt indicator */
1373 #define UART_LSR_FE     0x08    /* Frame error indicator */
1374 #define UART_LSR_PE     0x04    /* Parity error indicator */
1375 #define UART_LSR_OE     0x02    /* Overrun error indicator */
1376 #define UART_LSR_DR     0x01    /* Receiver data ready */
1377
1378 typedef struct SerialState {
1379     uint8_t divider;
1380     uint8_t rbr; /* receive register */
1381     uint8_t ier;
1382     uint8_t iir; /* read only */
1383     uint8_t lcr;
1384     uint8_t mcr;
1385     uint8_t lsr; /* read only */
1386     uint8_t msr;
1387     uint8_t scr;
1388     /* NOTE: this hidden state is necessary for tx irq generation as
1389        it can be reset while reading iir */
1390     int thr_ipending;
1391 } SerialState;
1392
1393 SerialState serial_ports[1];
1394
1395 void serial_update_irq(void)
1396 {
1397     SerialState *s = &serial_ports[0];
1398
1399     if ((s->lsr & UART_LSR_DR) && (s->ier & UART_IER_RDI)) {
1400         s->iir = UART_IIR_RDI;
1401     } else if (s->thr_ipending && (s->ier & UART_IER_THRI)) {
1402         s->iir = UART_IIR_THRI;
1403     } else {
1404         s->iir = UART_IIR_NO_INT;
1405     }
1406     if (s->iir != UART_IIR_NO_INT) {
1407         pic_set_irq(UART_IRQ, 1);
1408     } else {
1409         pic_set_irq(UART_IRQ, 0);
1410     }
1411 }
1412
1413 void serial_ioport_write(CPUState *env, uint32_t addr, uint32_t val)
1414 {
1415     SerialState *s = &serial_ports[0];
1416     unsigned char ch;
1417     int ret;
1418     
1419     addr &= 7;
1420 #ifdef DEBUG_SERIAL
1421     printf("serial: write addr=0x%02x val=0x%02x\n", addr, val);
1422 #endif
1423     switch(addr) {
1424     default:
1425     case 0:
1426         if (s->lcr & UART_LCR_DLAB) {
1427             s->divider = (s->divider & 0xff00) | val;
1428         } else {
1429             s->thr_ipending = 0;
1430             s->lsr &= ~UART_LSR_THRE;
1431             serial_update_irq();
1432
1433             ch = val;
1434             do {
1435                 ret = write(1, &ch, 1);
1436             } while (ret != 1);
1437             s->thr_ipending = 1;
1438             s->lsr |= UART_LSR_THRE;
1439             s->lsr |= UART_LSR_TEMT;
1440             serial_update_irq();
1441         }
1442         break;
1443     case 1:
1444         if (s->lcr & UART_LCR_DLAB) {
1445             s->divider = (s->divider & 0x00ff) | (val << 8);
1446         } else {
1447             s->ier = val;
1448             serial_update_irq();
1449         }
1450         break;
1451     case 2:
1452         break;
1453     case 3:
1454         s->lcr = val;
1455         break;
1456     case 4:
1457         s->mcr = val;
1458         break;
1459     case 5:
1460         break;
1461     case 6:
1462         s->msr = val;
1463         break;
1464     case 7:
1465         s->scr = val;
1466         break;
1467     }
1468 }
1469
1470 uint32_t serial_ioport_read(CPUState *env, uint32_t addr)
1471 {
1472     SerialState *s = &serial_ports[0];
1473     uint32_t ret;
1474
1475     addr &= 7;
1476     switch(addr) {
1477     default:
1478     case 0:
1479         if (s->lcr & UART_LCR_DLAB) {
1480             ret = s->divider & 0xff; 
1481         } else {
1482             ret = s->rbr;
1483             s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
1484             serial_update_irq();
1485         }
1486         break;
1487     case 1:
1488         if (s->lcr & UART_LCR_DLAB) {
1489             ret = (s->divider >> 8) & 0xff;
1490         } else {
1491             ret = s->ier;
1492         }
1493         break;
1494     case 2:
1495         ret = s->iir;
1496         /* reset THR pending bit */
1497         if ((ret & 0x7) == UART_IIR_THRI)
1498             s->thr_ipending = 0;
1499         serial_update_irq();
1500         break;
1501     case 3:
1502         ret = s->lcr;
1503         break;
1504     case 4:
1505         ret = s->mcr;
1506         break;
1507     case 5:
1508         ret = s->lsr;
1509         break;
1510     case 6:
1511         if (s->mcr & UART_MCR_LOOP) {
1512             /* in loopback, the modem output pins are connected to the
1513                inputs */
1514             ret = (s->mcr & 0x0c) << 4;
1515             ret |= (s->mcr & 0x02) << 3;
1516             ret |= (s->mcr & 0x01) << 5;
1517         } else {
1518             ret = s->msr;
1519         }
1520         break;
1521     case 7:
1522         ret = s->scr;
1523         break;
1524     }
1525 #ifdef DEBUG_SERIAL
1526     printf("serial: read addr=0x%02x val=0x%02x\n", addr, ret);
1527 #endif
1528     return ret;
1529 }
1530
1531 #define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1532 static int term_got_escape, term_command;
1533 static unsigned char term_cmd_buf[128];
1534
1535 typedef struct term_cmd_t {
1536     const unsigned char *name;
1537     void (*handler)(unsigned char *params);
1538 } term_cmd_t;
1539
1540 static void do_change_cdrom (unsigned char *params);
1541 static void do_change_fd0 (unsigned char *params);
1542 static void do_change_fd1 (unsigned char *params);
1543
1544 static term_cmd_t term_cmds[] = {
1545     { "changecd", &do_change_cdrom, },
1546     { "changefd0", &do_change_fd0, },
1547     { "changefd1", &do_change_fd1, },
1548     { NULL, NULL, },
1549 };
1550
1551 void term_print_help(void)
1552 {
1553     printf("\n"
1554            "C-a h    print this help\n"
1555            "C-a x    exit emulatior\n"
1556            "C-a d    switch on/off debug log\n"
1557            "C-a s    save disk data back to file (if -snapshot)\n"
1558            "C-a b    send break (magic sysrq)\n"
1559            "C-a c    send qemu internal command\n"
1560            "C-a C-a  send C-a\n"
1561            );
1562 }
1563
1564 static void do_change_cdrom (unsigned char *params)
1565 {
1566     /* Dunno how to do it... */
1567 }
1568
1569 static void do_change_fd (int fd, unsigned char *params)
1570 {
1571     unsigned char *name_start, *name_end, *ros;
1572     int ro;
1573
1574     for (name_start = params;
1575          isspace(*name_start); name_start++)
1576         continue;
1577     if (*name_start == '\0')
1578         return;
1579     for (name_end = name_start;
1580          !isspace(*name_end) && *name_end != '\0'; name_end++)
1581         continue;
1582     for (ros = name_end + 1; isspace(*ros); ros++)
1583         continue;
1584     if (ros[0] == 'r' && ros[1] == 'o')
1585         ro = 1;
1586     else
1587         ro = 0;
1588     *name_end = '\0';
1589     printf("Change fd %d to %s (%s)\n", fd, name_start, params);
1590     fdctrl_disk_change(fd, name_start, ro);
1591 }
1592
1593 static void do_change_fd0 (unsigned char *params)
1594 {
1595     do_change_fd(0, params);
1596 }
1597
1598 static void do_change_fd1 (unsigned char *params)
1599 {
1600     do_change_fd(1, params);
1601 }
1602
1603 static void serial_treat_command ()
1604 {
1605     unsigned char *cmd_start, *cmd_end;
1606     int i;
1607
1608     for (cmd_start = term_cmd_buf; isspace(*cmd_start); cmd_start++)
1609         continue;
1610     for (cmd_end = cmd_start;
1611          !isspace(*cmd_end) && *cmd_end != '\0'; cmd_end++)
1612         continue;
1613     for (i = 0; term_cmds[i].name != NULL; i++) {
1614         if (strlen(term_cmds[i].name) == (cmd_end - cmd_start) &&
1615             memcmp(term_cmds[i].name, cmd_start, cmd_end - cmd_start) == 0) {
1616             (*term_cmds[i].handler)(cmd_end + 1);
1617             return;
1618         }
1619     }
1620     *cmd_end = '\0';
1621     printf("Unknown term command: %s\n", cmd_start);
1622 }
1623
1624 extern FILE *logfile;
1625
1626 /* called when a char is received */
1627 void serial_received_byte(SerialState *s, int ch)
1628 {
1629     if (term_command) {
1630         if (ch == '\n' || ch == '\r' || term_command == 127) {
1631             printf("\n");
1632             serial_treat_command();
1633             term_command = 0;
1634         } else {
1635             if (ch == 0x7F || ch == 0x08) {
1636                 if (term_command > 1) {
1637                     term_cmd_buf[--term_command - 1] = '\0';
1638                     printf("\r                                               "
1639                            "                               ");
1640                     printf("\r> %s", term_cmd_buf);
1641                 }
1642             } else if (ch > 0x1f) {
1643                 term_cmd_buf[term_command++ - 1] = ch;
1644                 term_cmd_buf[term_command - 1] = '\0';
1645                 printf("\r> %s", term_cmd_buf);
1646             }
1647             fflush(stdout);
1648         }
1649     } else if (term_got_escape) {
1650         term_got_escape = 0;
1651         switch(ch) {
1652         case 'h':
1653             term_print_help();
1654             break;
1655         case 'x':
1656             exit(0);
1657             break;
1658         case 's': 
1659             {
1660                 int i;
1661                 for (i = 0; i < MAX_DISKS; i++) {
1662                     if (bs_table[i])
1663                         bdrv_commit(bs_table[i]);
1664                 }
1665             }
1666             break;
1667         case 'b':
1668             /* send break */
1669             s->rbr = 0;
1670             s->lsr |= UART_LSR_BI | UART_LSR_DR;
1671             serial_update_irq();
1672             break;
1673         case 'c':
1674             printf("> ");
1675             fflush(stdout);
1676             term_command = 1;
1677             break;
1678         case 'd':
1679             cpu_set_log(CPU_LOG_ALL);
1680             break;
1681         case TERM_ESCAPE:
1682             goto send_char;
1683         }
1684     } else if (ch == TERM_ESCAPE) {
1685         term_got_escape = 1;
1686     } else {
1687     send_char:
1688         s->rbr = ch;
1689         s->lsr |= UART_LSR_DR;
1690         serial_update_irq();
1691     }
1692 }
1693
1694 void serial_init(void)
1695 {
1696     SerialState *s = &serial_ports[0];
1697
1698     s->lsr = UART_LSR_TEMT | UART_LSR_THRE;
1699     s->iir = UART_IIR_NO_INT;
1700     
1701 #if defined(TARGET_I386) || defined (TARGET_PPC)
1702     register_ioport_write(0x3f8, 8, serial_ioport_write, 1);
1703     register_ioport_read(0x3f8, 8, serial_ioport_read, 1);
1704 #endif
1705 }
1706
1707 /***********************************************************/
1708 /* ne2000 emulation */
1709
1710 #if defined (TARGET_I386)
1711 #define NE2000_IOPORT   0x300
1712 #define NE2000_IRQ      9
1713
1714 #define MAX_ETH_FRAME_SIZE 1514
1715
1716 #define E8390_CMD       0x00  /* The command register (for all pages) */
1717 /* Page 0 register offsets. */
1718 #define EN0_CLDALO      0x01    /* Low byte of current local dma addr  RD */
1719 #define EN0_STARTPG     0x01    /* Starting page of ring bfr WR */
1720 #define EN0_CLDAHI      0x02    /* High byte of current local dma addr  RD */
1721 #define EN0_STOPPG      0x02    /* Ending page +1 of ring bfr WR */
1722 #define EN0_BOUNDARY    0x03    /* Boundary page of ring bfr RD WR */
1723 #define EN0_TSR         0x04    /* Transmit status reg RD */
1724 #define EN0_TPSR        0x04    /* Transmit starting page WR */
1725 #define EN0_NCR         0x05    /* Number of collision reg RD */
1726 #define EN0_TCNTLO      0x05    /* Low  byte of tx byte count WR */
1727 #define EN0_FIFO        0x06    /* FIFO RD */
1728 #define EN0_TCNTHI      0x06    /* High byte of tx byte count WR */
1729 #define EN0_ISR         0x07    /* Interrupt status reg RD WR */
1730 #define EN0_CRDALO      0x08    /* low byte of current remote dma address RD */
1731 #define EN0_RSARLO      0x08    /* Remote start address reg 0 */
1732 #define EN0_CRDAHI      0x09    /* high byte, current remote dma address RD */
1733 #define EN0_RSARHI      0x09    /* Remote start address reg 1 */
1734 #define EN0_RCNTLO      0x0a    /* Remote byte count reg WR */
1735 #define EN0_RCNTHI      0x0b    /* Remote byte count reg WR */
1736 #define EN0_RSR         0x0c    /* rx status reg RD */
1737 #define EN0_RXCR        0x0c    /* RX configuration reg WR */
1738 #define EN0_TXCR        0x0d    /* TX configuration reg WR */
1739 #define EN0_COUNTER0    0x0d    /* Rcv alignment error counter RD */
1740 #define EN0_DCFG        0x0e    /* Data configuration reg WR */
1741 #define EN0_COUNTER1    0x0e    /* Rcv CRC error counter RD */
1742 #define EN0_IMR         0x0f    /* Interrupt mask reg WR */
1743 #define EN0_COUNTER2    0x0f    /* Rcv missed frame error counter RD */
1744
1745 #define EN1_PHYS        0x11
1746 #define EN1_CURPAG      0x17
1747 #define EN1_MULT        0x18
1748
1749 /*  Register accessed at EN_CMD, the 8390 base addr.  */
1750 #define E8390_STOP      0x01    /* Stop and reset the chip */
1751 #define E8390_START     0x02    /* Start the chip, clear reset */
1752 #define E8390_TRANS     0x04    /* Transmit a frame */
1753 #define E8390_RREAD     0x08    /* Remote read */
1754 #define E8390_RWRITE    0x10    /* Remote write  */
1755 #define E8390_NODMA     0x20    /* Remote DMA */
1756 #define E8390_PAGE0     0x00    /* Select page chip registers */
1757 #define E8390_PAGE1     0x40    /* using the two high-order bits */
1758 #define E8390_PAGE2     0x80    /* Page 3 is invalid. */
1759
1760 /* Bits in EN0_ISR - Interrupt status register */
1761 #define ENISR_RX        0x01    /* Receiver, no error */
1762 #define ENISR_TX        0x02    /* Transmitter, no error */
1763 #define ENISR_RX_ERR    0x04    /* Receiver, with error */
1764 #define ENISR_TX_ERR    0x08    /* Transmitter, with error */
1765 #define ENISR_OVER      0x10    /* Receiver overwrote the ring */
1766 #define ENISR_COUNTERS  0x20    /* Counters need emptying */
1767 #define ENISR_RDC       0x40    /* remote dma complete */
1768 #define ENISR_RESET     0x80    /* Reset completed */
1769 #define ENISR_ALL       0x3f    /* Interrupts we will enable */
1770
1771 /* Bits in received packet status byte and EN0_RSR*/
1772 #define ENRSR_RXOK      0x01    /* Received a good packet */
1773 #define ENRSR_CRC       0x02    /* CRC error */
1774 #define ENRSR_FAE       0x04    /* frame alignment error */
1775 #define ENRSR_FO        0x08    /* FIFO overrun */
1776 #define ENRSR_MPA       0x10    /* missed pkt */
1777 #define ENRSR_PHY       0x20    /* physical/multicast address */
1778 #define ENRSR_DIS       0x40    /* receiver disable. set in monitor mode */
1779 #define ENRSR_DEF       0x80    /* deferring */
1780
1781 /* Transmitted packet status, EN0_TSR. */
1782 #define ENTSR_PTX 0x01  /* Packet transmitted without error */
1783 #define ENTSR_ND  0x02  /* The transmit wasn't deferred. */
1784 #define ENTSR_COL 0x04  /* The transmit collided at least once. */
1785 #define ENTSR_ABT 0x08  /* The transmit collided 16 times, and was deferred. */
1786 #define ENTSR_CRS 0x10  /* The carrier sense was lost. */
1787 #define ENTSR_FU  0x20  /* A "FIFO underrun" occurred during transmit. */
1788 #define ENTSR_CDH 0x40  /* The collision detect "heartbeat" signal was lost. */
1789 #define ENTSR_OWC 0x80  /* There was an out-of-window collision. */
1790
1791 #define NE2000_MEM_SIZE 32768
1792
1793 typedef struct NE2000State {
1794     uint8_t cmd;
1795     uint32_t start;
1796     uint32_t stop;
1797     uint8_t boundary;
1798     uint8_t tsr;
1799     uint8_t tpsr;
1800     uint16_t tcnt;
1801     uint16_t rcnt;
1802     uint32_t rsar;
1803     uint8_t isr;
1804     uint8_t dcfg;
1805     uint8_t imr;
1806     uint8_t phys[6]; /* mac address */
1807     uint8_t curpag;
1808     uint8_t mult[8]; /* multicast mask array */
1809     uint8_t mem[NE2000_MEM_SIZE];
1810 } NE2000State;
1811
1812 NE2000State ne2000_state;
1813 int net_fd = -1;
1814 char network_script[1024];
1815
1816 void ne2000_reset(void)
1817 {
1818     NE2000State *s = &ne2000_state;
1819     int i;
1820
1821     s->isr = ENISR_RESET;
1822     s->mem[0] = 0x52;
1823     s->mem[1] = 0x54;
1824     s->mem[2] = 0x00;
1825     s->mem[3] = 0x12;
1826     s->mem[4] = 0x34;
1827     s->mem[5] = 0x56;
1828     s->mem[14] = 0x57;
1829     s->mem[15] = 0x57;
1830
1831     /* duplicate prom data */
1832     for(i = 15;i >= 0; i--) {
1833         s->mem[2 * i] = s->mem[i];
1834         s->mem[2 * i + 1] = s->mem[i];
1835     }
1836 }
1837
1838 void ne2000_update_irq(NE2000State *s)
1839 {
1840     int isr;
1841     isr = s->isr & s->imr;
1842     if (isr)
1843         pic_set_irq(NE2000_IRQ, 1);
1844     else
1845         pic_set_irq(NE2000_IRQ, 0);
1846 }
1847
1848 int net_init(void)
1849 {
1850     struct ifreq ifr;
1851     int fd, ret, pid, status;
1852     
1853     fd = open("/dev/net/tun", O_RDWR);
1854     if (fd < 0) {
1855         fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1856         return -1;
1857     }
1858     memset(&ifr, 0, sizeof(ifr));
1859     ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1860     pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1861     ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1862     if (ret != 0) {
1863         fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1864         close(fd);
1865         return -1;
1866     }
1867     printf("Connected to host network interface: %s\n", ifr.ifr_name);
1868     fcntl(fd, F_SETFL, O_NONBLOCK);
1869     net_fd = fd;
1870
1871     /* try to launch network init script */
1872     pid = fork();
1873     if (pid >= 0) {
1874         if (pid == 0) {
1875             execl(network_script, network_script, ifr.ifr_name, NULL);
1876             exit(1);
1877         }
1878         while (waitpid(pid, &status, 0) != pid);
1879         if (!WIFEXITED(status) ||
1880             WEXITSTATUS(status) != 0) {
1881             fprintf(stderr, "%s: could not launch network script for '%s'\n",
1882                     network_script, ifr.ifr_name);
1883         }
1884     }
1885     return 0;
1886 }
1887
1888 void net_send_packet(NE2000State *s, const uint8_t *buf, int size)
1889 {
1890 #ifdef DEBUG_NE2000
1891     printf("NE2000: sending packet size=%d\n", size);
1892 #endif
1893     write(net_fd, buf, size);
1894 }
1895
1896 /* return true if the NE2000 can receive more data */
1897 int ne2000_can_receive(NE2000State *s)
1898 {
1899     int avail, index, boundary;
1900     
1901     if (s->cmd & E8390_STOP)
1902         return 0;
1903     index = s->curpag << 8;
1904     boundary = s->boundary << 8;
1905     if (index < boundary)
1906         avail = boundary - index;
1907     else
1908         avail = (s->stop - s->start) - (index - boundary);
1909     if (avail < (MAX_ETH_FRAME_SIZE + 4))
1910         return 0;
1911     return 1;
1912 }
1913
1914 void ne2000_receive(NE2000State *s, uint8_t *buf, int size)
1915 {
1916     uint8_t *p;
1917     int total_len, next, avail, len, index;
1918
1919 #if defined(DEBUG_NE2000)
1920     printf("NE2000: received len=%d\n", size);
1921 #endif
1922
1923     index = s->curpag << 8;
1924     /* 4 bytes for header */
1925     total_len = size + 4;
1926     /* address for next packet (4 bytes for CRC) */
1927     next = index + ((total_len + 4 + 255) & ~0xff);
1928     if (next >= s->stop)
1929         next -= (s->stop - s->start);
1930     /* prepare packet header */
1931     p = s->mem + index;
1932     p[0] = ENRSR_RXOK; /* receive status */
1933     p[1] = next >> 8;
1934     p[2] = total_len;
1935     p[3] = total_len >> 8;
1936     index += 4;
1937
1938     /* write packet data */
1939     while (size > 0) {
1940         avail = s->stop - index;
1941         len = size;
1942         if (len > avail)
1943             len = avail;
1944         memcpy(s->mem + index, buf, len);
1945         buf += len;
1946         index += len;
1947         if (index == s->stop)
1948             index = s->start;
1949         size -= len;
1950     }
1951     s->curpag = next >> 8;
1952     
1953     /* now we can signal we have receive something */
1954     s->isr |= ENISR_RX;
1955     ne2000_update_irq(s);
1956 }
1957
1958 void ne2000_ioport_write(CPUState *env, uint32_t addr, uint32_t val)
1959 {
1960     NE2000State *s = &ne2000_state;
1961     int offset, page;
1962
1963     addr &= 0xf;
1964 #ifdef DEBUG_NE2000
1965     printf("NE2000: write addr=0x%x val=0x%02x\n", addr, val);
1966 #endif
1967     if (addr == E8390_CMD) {
1968         /* control register */
1969         s->cmd = val;
1970         if (val & E8390_START) {
1971             /* test specific case: zero length transfert */
1972             if ((val & (E8390_RREAD | E8390_RWRITE)) &&
1973                 s->rcnt == 0) {
1974                 s->isr |= ENISR_RDC;
1975                 ne2000_update_irq(s);
1976             }
1977             if (val & E8390_TRANS) {
1978                 net_send_packet(s, s->mem + (s->tpsr << 8), s->tcnt);
1979                 /* signal end of transfert */
1980                 s->tsr = ENTSR_PTX;
1981                 s->isr |= ENISR_TX;
1982                 ne2000_update_irq(s);
1983             }
1984         }
1985     } else {
1986         page = s->cmd >> 6;
1987         offset = addr | (page << 4);
1988         switch(offset) {
1989         case EN0_STARTPG:
1990             s->start = val << 8;
1991             break;
1992         case EN0_STOPPG:
1993             s->stop = val << 8;
1994             break;
1995         case EN0_BOUNDARY:
1996             s->boundary = val;
1997             break;
1998         case EN0_IMR:
1999             s->imr = val;
2000             ne2000_update_irq(s);
2001             break;
2002         case EN0_TPSR:
2003             s->tpsr = val;
2004             break;
2005         case EN0_TCNTLO:
2006             s->tcnt = (s->tcnt & 0xff00) | val;
2007             break;
2008         case EN0_TCNTHI:
2009             s->tcnt = (s->tcnt & 0x00ff) | (val << 8);
2010             break;
2011         case EN0_RSARLO:
2012             s->rsar = (s->rsar & 0xff00) | val;
2013             break;
2014         case EN0_RSARHI:
2015             s->rsar = (s->rsar & 0x00ff) | (val << 8);
2016             break;
2017         case EN0_RCNTLO:
2018             s->rcnt = (s->rcnt & 0xff00) | val;
2019             break;
2020         case EN0_RCNTHI:
2021             s->rcnt = (s->rcnt & 0x00ff) | (val << 8);
2022             break;
2023         case EN0_DCFG:
2024             s->dcfg = val;
2025             break;
2026         case EN0_ISR:
2027             s->isr &= ~val;
2028             ne2000_update_irq(s);
2029             break;
2030         case EN1_PHYS ... EN1_PHYS + 5:
2031             s->phys[offset - EN1_PHYS] = val;
2032             break;
2033         case EN1_CURPAG:
2034             s->curpag = val;
2035             break;
2036         case EN1_MULT ... EN1_MULT + 7:
2037             s->mult[offset - EN1_MULT] = val;
2038             break;
2039         }
2040     }
2041 }
2042
2043 uint32_t ne2000_ioport_read(CPUState *env, uint32_t addr)
2044 {
2045     NE2000State *s = &ne2000_state;
2046     int offset, page, ret;
2047
2048     addr &= 0xf;
2049     if (addr == E8390_CMD) {
2050         ret = s->cmd;
2051     } else {
2052         page = s->cmd >> 6;
2053         offset = addr | (page << 4);
2054         switch(offset) {
2055         case EN0_TSR:
2056             ret = s->tsr;
2057             break;
2058         case EN0_BOUNDARY:
2059             ret = s->boundary;
2060             break;
2061         case EN0_ISR:
2062             ret = s->isr;
2063             break;
2064         case EN1_PHYS ... EN1_PHYS + 5:
2065             ret = s->phys[offset - EN1_PHYS];
2066             break;
2067         case EN1_CURPAG:
2068             ret = s->curpag;
2069             break;
2070         case EN1_MULT ... EN1_MULT + 7:
2071             ret = s->mult[offset - EN1_MULT];
2072             break;
2073         default:
2074             ret = 0x00;
2075             break;
2076         }
2077     }
2078 #ifdef DEBUG_NE2000
2079     printf("NE2000: read addr=0x%x val=%02x\n", addr, ret);
2080 #endif
2081     return ret;
2082 }
2083
2084 void ne2000_asic_ioport_write(CPUState *env, uint32_t addr, uint32_t val)
2085 {
2086     NE2000State *s = &ne2000_state;
2087     uint8_t *p;
2088
2089 #ifdef DEBUG_NE2000
2090     printf("NE2000: asic write val=0x%04x\n", val);
2091 #endif
2092     p = s->mem + s->rsar;
2093     if (s->dcfg & 0x01) {
2094         /* 16 bit access */
2095         p[0] = val;
2096         p[1] = val >> 8;
2097         s->rsar += 2;
2098         s->rcnt -= 2;
2099     } else {
2100         /* 8 bit access */
2101         p[0] = val;
2102         s->rsar++;
2103         s->rcnt--;
2104     }
2105     /* wrap */
2106     if (s->rsar == s->stop)
2107         s->rsar = s->start;
2108     if (s->rcnt == 0) {
2109         /* signal end of transfert */
2110         s->isr |= ENISR_RDC;
2111         ne2000_update_irq(s);
2112     }
2113 }
2114
2115 uint32_t ne2000_asic_ioport_read(CPUState *env, uint32_t addr)
2116 {
2117     NE2000State *s = &ne2000_state;
2118     uint8_t *p;
2119     int ret;
2120
2121     p = s->mem + s->rsar;
2122     if (s->dcfg & 0x01) {
2123         /* 16 bit access */
2124         ret = p[0] | (p[1] << 8);
2125         s->rsar += 2;
2126         s->rcnt -= 2;
2127     } else {
2128         /* 8 bit access */
2129         ret = p[0];
2130         s->rsar++;
2131         s->rcnt--;
2132     }
2133     /* wrap */
2134     if (s->rsar == s->stop)
2135         s->rsar = s->start;
2136     if (s->rcnt == 0) {
2137         /* signal end of transfert */
2138         s->isr |= ENISR_RDC;
2139         ne2000_update_irq(s);
2140     }
2141 #ifdef DEBUG_NE2000
2142     printf("NE2000: asic read val=0x%04x\n", ret);
2143 #endif
2144     return ret;
2145 }
2146
2147 void ne2000_reset_ioport_write(CPUState *env, uint32_t addr, uint32_t val)
2148 {
2149     /* nothing to do (end of reset pulse) */
2150 }
2151
2152 uint32_t ne2000_reset_ioport_read(CPUState *env, uint32_t addr)
2153 {
2154     ne2000_reset();
2155     return 0;
2156 }
2157
2158 void ne2000_init(void)
2159 {
2160     register_ioport_write(NE2000_IOPORT, 16, ne2000_ioport_write, 1);
2161     register_ioport_read(NE2000_IOPORT, 16, ne2000_ioport_read, 1);
2162
2163     register_ioport_write(NE2000_IOPORT + 0x10, 1, ne2000_asic_ioport_write, 1);
2164     register_ioport_read(NE2000_IOPORT + 0x10, 1, ne2000_asic_ioport_read, 1);
2165     register_ioport_write(NE2000_IOPORT + 0x10, 2, ne2000_asic_ioport_write, 2);
2166     register_ioport_read(NE2000_IOPORT + 0x10, 2, ne2000_asic_ioport_read, 2);
2167
2168     register_ioport_write(NE2000_IOPORT + 0x1f, 1, ne2000_reset_ioport_write, 1);
2169     register_ioport_read(NE2000_IOPORT + 0x1f, 1, ne2000_reset_ioport_read, 1);
2170     ne2000_reset();
2171 }
2172 #endif
2173
2174 /***********************************************************/
2175 /* PC floppy disk controler emulation glue */
2176 #define PC_FDC_DMA  0x2
2177 #define PC_FDC_IRQ  0x6
2178 #define PC_FDC_BASE 0x3F0
2179
2180 static void fdctrl_register (unsigned char **disknames, int ro,
2181                              char boot_device)
2182 {
2183     int i;
2184
2185     fdctrl_init(PC_FDC_IRQ, PC_FDC_DMA, 0, PC_FDC_BASE, boot_device);
2186     for (i = 0; i < MAX_FD; i++) {
2187         if (disknames[i] != NULL)
2188             fdctrl_disk_change(i, disknames[i], ro);
2189     }
2190 }
2191
2192 /***********************************************************/
2193 /* keyboard emulation */
2194
2195 /*      Keyboard Controller Commands */
2196 #define KBD_CCMD_READ_MODE      0x20    /* Read mode bits */
2197 #define KBD_CCMD_WRITE_MODE     0x60    /* Write mode bits */
2198 #define KBD_CCMD_GET_VERSION    0xA1    /* Get controller version */
2199 #define KBD_CCMD_MOUSE_DISABLE  0xA7    /* Disable mouse interface */
2200 #define KBD_CCMD_MOUSE_ENABLE   0xA8    /* Enable mouse interface */
2201 #define KBD_CCMD_TEST_MOUSE     0xA9    /* Mouse interface test */
2202 #define KBD_CCMD_SELF_TEST      0xAA    /* Controller self test */
2203 #define KBD_CCMD_KBD_TEST       0xAB    /* Keyboard interface test */
2204 #define KBD_CCMD_KBD_DISABLE    0xAD    /* Keyboard interface disable */
2205 #define KBD_CCMD_KBD_ENABLE     0xAE    /* Keyboard interface enable */
2206 #define KBD_CCMD_READ_INPORT    0xC0    /* read input port */
2207 #define KBD_CCMD_READ_OUTPORT   0xD0    /* read output port */
2208 #define KBD_CCMD_WRITE_OUTPORT  0xD1    /* write output port */
2209 #define KBD_CCMD_WRITE_OBUF     0xD2
2210 #define KBD_CCMD_WRITE_AUX_OBUF 0xD3    /* Write to output buffer as if
2211                                            initiated by the auxiliary device */
2212 #define KBD_CCMD_WRITE_MOUSE    0xD4    /* Write the following byte to the mouse */
2213 #define KBD_CCMD_DISABLE_A20    0xDD    /* HP vectra only ? */
2214 #define KBD_CCMD_ENABLE_A20     0xDF    /* HP vectra only ? */
2215 #define KBD_CCMD_RESET          0xFE
2216
2217 /* Keyboard Commands */
2218 #define KBD_CMD_SET_LEDS        0xED    /* Set keyboard leds */
2219 #define KBD_CMD_ECHO            0xEE
2220 #define KBD_CMD_GET_ID          0xF2    /* get keyboard ID */
2221 #define KBD_CMD_SET_RATE        0xF3    /* Set typematic rate */
2222 #define KBD_CMD_ENABLE          0xF4    /* Enable scanning */
2223 #define KBD_CMD_RESET_DISABLE   0xF5    /* reset and disable scanning */
2224 #define KBD_CMD_RESET_ENABLE    0xF6    /* reset and enable scanning */
2225 #define KBD_CMD_RESET           0xFF    /* Reset */
2226
2227 /* Keyboard Replies */
2228 #define KBD_REPLY_POR           0xAA    /* Power on reset */
2229 #define KBD_REPLY_ACK           0xFA    /* Command ACK */
2230 #define KBD_REPLY_RESEND        0xFE    /* Command NACK, send the cmd again */
2231
2232 /* Status Register Bits */
2233 #define KBD_STAT_OBF            0x01    /* Keyboard output buffer full */
2234 #define KBD_STAT_IBF            0x02    /* Keyboard input buffer full */
2235 #define KBD_STAT_SELFTEST       0x04    /* Self test successful */
2236 #define KBD_STAT_CMD            0x08    /* Last write was a command write (0=data) */
2237 #define KBD_STAT_UNLOCKED       0x10    /* Zero if keyboard locked */
2238 #define KBD_STAT_MOUSE_OBF      0x20    /* Mouse output buffer full */
2239 #define KBD_STAT_GTO            0x40    /* General receive/xmit timeout */
2240 #define KBD_STAT_PERR           0x80    /* Parity error */
2241
2242 /* Controller Mode Register Bits */
2243 #define KBD_MODE_KBD_INT        0x01    /* Keyboard data generate IRQ1 */
2244 #define KBD_MODE_MOUSE_INT      0x02    /* Mouse data generate IRQ12 */
2245 #define KBD_MODE_SYS            0x04    /* The system flag (?) */
2246 #define KBD_MODE_NO_KEYLOCK     0x08    /* The keylock doesn't affect the keyboard if set */
2247 #define KBD_MODE_DISABLE_KBD    0x10    /* Disable keyboard interface */
2248 #define KBD_MODE_DISABLE_MOUSE  0x20    /* Disable mouse interface */
2249 #define KBD_MODE_KCC            0x40    /* Scan code conversion to PC format */
2250 #define KBD_MODE_RFU            0x80
2251
2252 /* Mouse Commands */
2253 #define AUX_SET_SCALE11         0xE6    /* Set 1:1 scaling */
2254 #define AUX_SET_SCALE21         0xE7    /* Set 2:1 scaling */
2255 #define AUX_SET_RES             0xE8    /* Set resolution */
2256 #define AUX_GET_SCALE           0xE9    /* Get scaling factor */
2257 #define AUX_SET_STREAM          0xEA    /* Set stream mode */
2258 #define AUX_POLL                0xEB    /* Poll */
2259 #define AUX_RESET_WRAP          0xEC    /* Reset wrap mode */
2260 #define AUX_SET_WRAP            0xEE    /* Set wrap mode */
2261 #define AUX_SET_REMOTE          0xF0    /* Set remote mode */
2262 #define AUX_GET_TYPE            0xF2    /* Get type */
2263 #define AUX_SET_SAMPLE          0xF3    /* Set sample rate */
2264 #define AUX_ENABLE_DEV          0xF4    /* Enable aux device */
2265 #define AUX_DISABLE_DEV         0xF5    /* Disable aux device */
2266 #define AUX_SET_DEFAULT         0xF6
2267 #define AUX_RESET               0xFF    /* Reset aux device */
2268 #define AUX_ACK                 0xFA    /* Command byte ACK. */
2269
2270 #define MOUSE_STATUS_REMOTE     0x40
2271 #define MOUSE_STATUS_ENABLED    0x20
2272 #define MOUSE_STATUS_SCALE21    0x10
2273
2274 #define KBD_QUEUE_SIZE 256
2275
2276 typedef struct {
2277     uint8_t data[KBD_QUEUE_SIZE];
2278     int rptr, wptr, count;
2279 } KBDQueue;
2280
2281 typedef struct KBDState {
2282     KBDQueue queues[2];
2283     uint8_t write_cmd; /* if non zero, write data to port 60 is expected */
2284     uint8_t status;
2285     uint8_t mode;
2286     /* keyboard state */
2287     int kbd_write_cmd;
2288     int scan_enabled;
2289     /* mouse state */
2290     int mouse_write_cmd;
2291     uint8_t mouse_status;
2292     uint8_t mouse_resolution;
2293     uint8_t mouse_sample_rate;
2294     uint8_t mouse_wrap;
2295     uint8_t mouse_type; /* 0 = PS2, 3 = IMPS/2, 4 = IMEX */
2296     uint8_t mouse_detect_state;
2297     int mouse_dx; /* current values, needed for 'poll' mode */
2298     int mouse_dy;
2299     int mouse_dz;
2300     uint8_t mouse_buttons;
2301 } KBDState;
2302
2303 KBDState kbd_state;
2304 int reset_requested;
2305
2306 /* update irq and KBD_STAT_[MOUSE_]OBF */
2307 /* XXX: not generating the irqs if KBD_MODE_DISABLE_KBD is set may be
2308    incorrect, but it avoids having to simulate exact delays */
2309 static void kbd_update_irq(KBDState *s)
2310 {
2311     int irq12_level, irq1_level;
2312
2313     irq1_level = 0;    
2314     irq12_level = 0;    
2315     s->status &= ~(KBD_STAT_OBF | KBD_STAT_MOUSE_OBF);
2316     if (s->queues[0].count != 0 ||
2317         s->queues[1].count != 0) {
2318         s->status |= KBD_STAT_OBF;
2319         if (s->queues[1].count != 0) {
2320             s->status |= KBD_STAT_MOUSE_OBF;
2321             if (s->mode & KBD_MODE_MOUSE_INT)
2322                 irq12_level = 1;
2323         } else {
2324             if ((s->mode & KBD_MODE_KBD_INT) && 
2325                 !(s->mode & KBD_MODE_DISABLE_KBD))
2326                 irq1_level = 1;
2327         }
2328     }
2329     pic_set_irq(1, irq1_level);
2330     pic_set_irq(12, irq12_level);
2331 }
2332
2333 static void kbd_queue(KBDState *s, int b, int aux)
2334 {
2335     KBDQueue *q = &kbd_state.queues[aux];
2336
2337 #if defined(DEBUG_MOUSE) || defined(DEBUG_KBD)
2338     if (aux)
2339         printf("mouse event: 0x%02x\n", b);
2340 #ifdef DEBUG_KBD
2341     else
2342         printf("kbd event: 0x%02x\n", b);
2343 #endif
2344 #endif
2345     if (q->count >= KBD_QUEUE_SIZE)
2346         return;
2347     q->data[q->wptr] = b;
2348     if (++q->wptr == KBD_QUEUE_SIZE)
2349         q->wptr = 0;
2350     q->count++;
2351     kbd_update_irq(s);
2352 }
2353
2354 void kbd_put_keycode(int keycode)
2355 {
2356     KBDState *s = &kbd_state;
2357     kbd_queue(s, keycode, 0);
2358 }
2359
2360 uint32_t kbd_read_status(CPUState *env, uint32_t addr)
2361 {
2362     KBDState *s = &kbd_state;
2363     int val;
2364     val = s->status;
2365 #if defined(DEBUG_KBD)
2366     printf("kbd: read status=0x%02x\n", val);
2367 #endif
2368     return val;
2369 }
2370
2371 void kbd_write_command(CPUState *env, uint32_t addr, uint32_t val)
2372 {
2373     KBDState *s = &kbd_state;
2374
2375 #ifdef DEBUG_KBD
2376     printf("kbd: write cmd=0x%02x\n", val);
2377 #endif
2378     switch(val) {
2379     case KBD_CCMD_READ_MODE:
2380         kbd_queue(s, s->mode, 0);
2381         break;
2382     case KBD_CCMD_WRITE_MODE:
2383     case KBD_CCMD_WRITE_OBUF:
2384     case KBD_CCMD_WRITE_AUX_OBUF:
2385     case KBD_CCMD_WRITE_MOUSE:
2386     case KBD_CCMD_WRITE_OUTPORT:
2387         s->write_cmd = val;
2388         break;
2389     case KBD_CCMD_MOUSE_DISABLE:
2390         s->mode |= KBD_MODE_DISABLE_MOUSE;
2391         break;
2392     case KBD_CCMD_MOUSE_ENABLE:
2393         s->mode &= ~KBD_MODE_DISABLE_MOUSE;
2394         break;
2395     case KBD_CCMD_TEST_MOUSE:
2396         kbd_queue(s, 0x00, 0);
2397         break;
2398     case KBD_CCMD_SELF_TEST:
2399         s->status |= KBD_STAT_SELFTEST;
2400         kbd_queue(s, 0x55, 0);
2401         break;
2402     case KBD_CCMD_KBD_TEST:
2403         kbd_queue(s, 0x00, 0);
2404         break;
2405     case KBD_CCMD_KBD_DISABLE:
2406         s->mode |= KBD_MODE_DISABLE_KBD;
2407         kbd_update_irq(s);
2408         break;
2409     case KBD_CCMD_KBD_ENABLE:
2410         s->mode &= ~KBD_MODE_DISABLE_KBD;
2411         kbd_update_irq(s);
2412         break;
2413     case KBD_CCMD_READ_INPORT:
2414         kbd_queue(s, 0x00, 0);
2415         break;
2416     case KBD_CCMD_READ_OUTPORT:
2417         /* XXX: check that */
2418 #ifdef TARGET_I386
2419         val = 0x01 | (((cpu_single_env->a20_mask >> 20) & 1) << 1);
2420 #else
2421         val = 0x01;
2422 #endif
2423         if (s->status & KBD_STAT_OBF)
2424             val |= 0x10;
2425         if (s->status & KBD_STAT_MOUSE_OBF)
2426             val |= 0x20;
2427         kbd_queue(s, val, 0);
2428         break;
2429 #ifdef TARGET_I386
2430     case KBD_CCMD_ENABLE_A20:
2431         cpu_x86_set_a20(env, 1);
2432         break;
2433     case KBD_CCMD_DISABLE_A20:
2434         cpu_x86_set_a20(env, 0);
2435         break;
2436 #endif
2437     case KBD_CCMD_RESET:
2438         reset_requested = 1;
2439         cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
2440         break;
2441     case 0xff:
2442         /* ignore that - I don't know what is its use */
2443         break;
2444     default:
2445         fprintf(stderr, "qemu: unsupported keyboard cmd=0x%02x\n", val);
2446         break;
2447     }
2448 }
2449
2450 uint32_t kbd_read_data(CPUState *env, uint32_t addr)
2451 {
2452     KBDState *s = &kbd_state;
2453     KBDQueue *q;
2454     int val, index;
2455     
2456     q = &s->queues[0]; /* first check KBD data */
2457     if (q->count == 0)
2458         q = &s->queues[1]; /* then check AUX data */
2459     if (q->count == 0) {
2460         /* NOTE: if no data left, we return the last keyboard one
2461            (needed for EMM386) */
2462         /* XXX: need a timer to do things correctly */
2463         q = &s->queues[0];
2464         index = q->rptr - 1;
2465         if (index < 0)
2466             index = KBD_QUEUE_SIZE - 1;
2467         val = q->data[index];
2468     } else {
2469         val = q->data[q->rptr];
2470         if (++q->rptr == KBD_QUEUE_SIZE)
2471             q->rptr = 0;
2472         q->count--;
2473         /* reading deasserts IRQ */
2474         if (q == &s->queues[0])
2475             pic_set_irq(1, 0);
2476         else
2477             pic_set_irq(12, 0);
2478     }
2479     /* reassert IRQs if data left */
2480     kbd_update_irq(s);
2481 #ifdef DEBUG_KBD
2482     printf("kbd: read data=0x%02x\n", val);
2483 #endif
2484     return val;
2485 }
2486
2487 static void kbd_reset_keyboard(KBDState *s)
2488 {
2489     s->scan_enabled = 1;
2490 }
2491
2492 static void kbd_write_keyboard(KBDState *s, int val)
2493 {
2494     switch(s->kbd_write_cmd) {
2495     default:
2496     case -1:
2497         switch(val) {
2498         case 0x00:
2499             kbd_queue(s, KBD_REPLY_ACK, 0);
2500             break;
2501         case 0x05:
2502             kbd_queue(s, KBD_REPLY_RESEND, 0);
2503             break;
2504         case KBD_CMD_GET_ID:
2505             kbd_queue(s, KBD_REPLY_ACK, 0);
2506             kbd_queue(s, 0xab, 0);
2507             kbd_queue(s, 0x83, 0);
2508             break;
2509         case KBD_CMD_ECHO:
2510             kbd_queue(s, KBD_CMD_ECHO, 0);
2511             break;
2512         case KBD_CMD_ENABLE:
2513             s->scan_enabled = 1;
2514             kbd_queue(s, KBD_REPLY_ACK, 0);
2515             break;
2516         case KBD_CMD_SET_LEDS:
2517         case KBD_CMD_SET_RATE:
2518             s->kbd_write_cmd = val;
2519             kbd_queue(s, KBD_REPLY_ACK, 0);
2520             break;
2521         case KBD_CMD_RESET_DISABLE:
2522             kbd_reset_keyboard(s);
2523             s->scan_enabled = 0;
2524             kbd_queue(s, KBD_REPLY_ACK, 0);
2525             break;
2526         case KBD_CMD_RESET_ENABLE:
2527             kbd_reset_keyboard(s);
2528             s->scan_enabled = 1;
2529             kbd_queue(s, KBD_REPLY_ACK, 0);
2530             break;
2531         case KBD_CMD_RESET:
2532             kbd_reset_keyboard(s);
2533             kbd_queue(s, KBD_REPLY_ACK, 0);
2534             kbd_queue(s, KBD_REPLY_POR, 0);
2535             break;
2536         default:
2537             kbd_queue(s, KBD_REPLY_ACK, 0);
2538             break;
2539         }
2540         break;
2541     case KBD_CMD_SET_LEDS:
2542         kbd_queue(s, KBD_REPLY_ACK, 0);
2543         s->kbd_write_cmd = -1;
2544         break;
2545     case KBD_CMD_SET_RATE:
2546         kbd_queue(s, KBD_REPLY_ACK, 0);
2547         s->kbd_write_cmd = -1;
2548         break;
2549     }
2550 }
2551
2552 static void kbd_mouse_send_packet(KBDState *s)
2553 {
2554     unsigned int b;
2555     int dx1, dy1, dz1;
2556
2557     dx1 = s->mouse_dx;
2558     dy1 = s->mouse_dy;
2559     dz1 = s->mouse_dz;
2560     /* XXX: increase range to 8 bits ? */
2561     if (dx1 > 127)
2562         dx1 = 127;
2563     else if (dx1 < -127)
2564         dx1 = -127;
2565     if (dy1 > 127)
2566         dy1 = 127;
2567     else if (dy1 < -127)
2568         dy1 = -127;
2569     b = 0x08 | ((dx1 < 0) << 4) | ((dy1 < 0) << 5) | (s->mouse_buttons & 0x07);
2570     kbd_queue(s, b, 1);
2571     kbd_queue(s, dx1 & 0xff, 1);
2572     kbd_queue(s, dy1 & 0xff, 1);
2573     /* extra byte for IMPS/2 or IMEX */
2574     switch(s->mouse_type) {
2575     default:
2576         break;
2577     case 3:
2578         if (dz1 > 127)
2579             dz1 = 127;
2580         else if (dz1 < -127)
2581                 dz1 = -127;
2582         kbd_queue(s, dz1 & 0xff, 1);
2583         break;
2584     case 4:
2585         if (dz1 > 7)
2586             dz1 = 7;
2587         else if (dz1 < -7)
2588             dz1 = -7;
2589         b = (dz1 & 0x0f) | ((s->mouse_buttons & 0x18) << 1);
2590         kbd_queue(s, b, 1);
2591         break;
2592     }
2593
2594     /* update deltas */
2595     s->mouse_dx -= dx1;
2596     s->mouse_dy -= dy1;
2597     s->mouse_dz -= dz1;
2598 }
2599
2600 void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
2601 {
2602     KBDState *s = &kbd_state;
2603
2604     /* check if deltas are recorded when disabled */
2605     if (!(s->mouse_status & MOUSE_STATUS_ENABLED))
2606         return;
2607
2608     s->mouse_dx += dx;
2609     s->mouse_dy -= dy;
2610     s->mouse_dz += dz;
2611     s->mouse_buttons = buttons_state;
2612     
2613     if (!(s->mouse_status & MOUSE_STATUS_REMOTE) &&
2614         (s->queues[1].count < (KBD_QUEUE_SIZE - 16))) {
2615         for(;;) {
2616             /* if not remote, send event. Multiple events are sent if
2617                too big deltas */
2618             kbd_mouse_send_packet(s);
2619             if (s->mouse_dx == 0 && s->mouse_dy == 0 && s->mouse_dz == 0)
2620                 break;
2621         }
2622     }
2623 }
2624
2625 static void kbd_write_mouse(KBDState *s, int val)
2626 {
2627 #ifdef DEBUG_MOUSE
2628     printf("kbd: write mouse 0x%02x\n", val);
2629 #endif
2630     switch(s->mouse_write_cmd) {
2631     default:
2632     case -1:
2633         /* mouse command */
2634         if (s->mouse_wrap) {
2635             if (val == AUX_RESET_WRAP) {
2636                 s->mouse_wrap = 0;
2637                 kbd_queue(s, AUX_ACK, 1);
2638                 return;
2639             } else if (val != AUX_RESET) {
2640                 kbd_queue(s, val, 1);
2641                 return;
2642             }
2643         }
2644         switch(val) {
2645         case AUX_SET_SCALE11:
2646             s->mouse_status &= ~MOUSE_STATUS_SCALE21;
2647             kbd_queue(s, AUX_ACK, 1);
2648             break;
2649         case AUX_SET_SCALE21:
2650             s->mouse_status |= MOUSE_STATUS_SCALE21;
2651             kbd_queue(s, AUX_ACK, 1);
2652             break;
2653         case AUX_SET_STREAM:
2654             s->mouse_status &= ~MOUSE_STATUS_REMOTE;
2655             kbd_queue(s, AUX_ACK, 1);
2656             break;
2657         case AUX_SET_WRAP:
2658             s->mouse_wrap = 1;
2659             kbd_queue(s, AUX_ACK, 1);
2660             break;
2661         case AUX_SET_REMOTE:
2662             s->mouse_status |= MOUSE_STATUS_REMOTE;
2663             kbd_queue(s, AUX_ACK, 1);
2664             break;
2665         case AUX_GET_TYPE:
2666             kbd_queue(s, AUX_ACK, 1);
2667             kbd_queue(s, s->mouse_type, 1);
2668             break;
2669         case AUX_SET_RES:
2670         case AUX_SET_SAMPLE:
2671             s->mouse_write_cmd = val;
2672             kbd_queue(s, AUX_ACK, 1);
2673             break;
2674         case AUX_GET_SCALE:
2675             kbd_queue(s, AUX_ACK, 1);
2676             kbd_queue(s, s->mouse_status, 1);
2677             kbd_queue(s, s->mouse_resolution, 1);
2678             kbd_queue(s, s->mouse_sample_rate, 1);
2679             break;
2680         case AUX_POLL:
2681             kbd_queue(s, AUX_ACK, 1);
2682             kbd_mouse_send_packet(s);
2683             break;
2684         case AUX_ENABLE_DEV:
2685             s->mouse_status |= MOUSE_STATUS_ENABLED;
2686             kbd_queue(s, AUX_ACK, 1);
2687             break;
2688         case AUX_DISABLE_DEV:
2689             s->mouse_status &= ~MOUSE_STATUS_ENABLED;
2690             kbd_queue(s, AUX_ACK, 1);
2691             break;
2692         case AUX_SET_DEFAULT:
2693             s->mouse_sample_rate = 100;
2694             s->mouse_resolution = 2;
2695             s->mouse_status = 0;
2696             kbd_queue(s, AUX_ACK, 1);
2697             break;
2698         case AUX_RESET:
2699             s->mouse_sample_rate = 100;
2700             s->mouse_resolution = 2;
2701             s->mouse_status = 0;
2702             kbd_queue(s, AUX_ACK, 1);
2703             kbd_queue(s, 0xaa, 1);
2704             kbd_queue(s, s->mouse_type, 1);
2705             break;
2706         default:
2707             break;
2708         }
2709         break;
2710     case AUX_SET_SAMPLE:
2711         s->mouse_sample_rate = val;
2712 #if 0
2713         /* detect IMPS/2 or IMEX */
2714         switch(s->mouse_detect_state) {
2715         default:
2716         case 0:
2717             if (val == 200)
2718                 s->mouse_detect_state = 1;
2719             break;
2720         case 1:
2721             if (val == 100)
2722                 s->mouse_detect_state = 2;
2723             else if (val == 200)
2724                 s->mouse_detect_state = 3;
2725             else
2726                 s->mouse_detect_state = 0;
2727             break;
2728         case 2:
2729             if (val == 80) 
2730                 s->mouse_type = 3; /* IMPS/2 */
2731             s->mouse_detect_state = 0;
2732             break;
2733         case 3:
2734             if (val == 80) 
2735                 s->mouse_type = 4; /* IMEX */
2736             s->mouse_detect_state = 0;
2737             break;
2738         }
2739 #endif
2740         kbd_queue(s, AUX_ACK, 1);
2741         s->mouse_write_cmd = -1;
2742         break;
2743     case AUX_SET_RES:
2744         s->mouse_resolution = val;
2745         kbd_queue(s, AUX_ACK, 1);
2746         s->mouse_write_cmd = -1;
2747         break;
2748     }
2749 }
2750
2751 void kbd_write_data(CPUState *env, uint32_t addr, uint32_t val)
2752 {
2753     KBDState *s = &kbd_state;
2754
2755 #ifdef DEBUG_KBD
2756     printf("kbd: write data=0x%02x\n", val);
2757 #endif
2758
2759     switch(s->write_cmd) {
2760     case 0:
2761         kbd_write_keyboard(s, val);
2762         break;
2763     case KBD_CCMD_WRITE_MODE:
2764         s->mode = val;
2765         kbd_update_irq(s);
2766         break;
2767     case KBD_CCMD_WRITE_OBUF:
2768         kbd_queue(s, val, 0);
2769         break;
2770     case KBD_CCMD_WRITE_AUX_OBUF:
2771         kbd_queue(s, val, 1);
2772         break;
2773     case KBD_CCMD_WRITE_OUTPORT:
2774 #ifdef TARGET_I386
2775         cpu_x86_set_a20(env, (val >> 1) & 1);
2776 #endif
2777         if (!(val & 1)) {
2778             reset_requested = 1;
2779             cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
2780         }
2781         break;
2782     case KBD_CCMD_WRITE_MOUSE:
2783         kbd_write_mouse(s, val);
2784         break;
2785     default:
2786         break;
2787     }
2788     s->write_cmd = 0;
2789 }
2790
2791 void kbd_reset(KBDState *s)
2792 {
2793     KBDQueue *q;
2794     int i;
2795
2796     s->kbd_write_cmd = -1;
2797     s->mouse_write_cmd = -1;
2798     s->mode = KBD_MODE_KBD_INT | KBD_MODE_MOUSE_INT;
2799     s->status = KBD_STAT_CMD | KBD_STAT_UNLOCKED;
2800     for(i = 0; i < 2; i++) {
2801         q = &s->queues[i];
2802         q->rptr = 0;
2803         q->wptr = 0;
2804         q->count = 0;
2805     }
2806 }
2807
2808 void kbd_init(void)
2809 {
2810     kbd_reset(&kbd_state);
2811 #if defined (TARGET_I386) || defined (TARGET_PPC)
2812     register_ioport_read(0x60, 1, kbd_read_data, 1);
2813     register_ioport_write(0x60, 1, kbd_write_data, 1);
2814     register_ioport_read(0x64, 1, kbd_read_status, 1);
2815     register_ioport_write(0x64, 1, kbd_write_command, 1);
2816 #endif
2817 }
2818
2819 /***********************************************************/
2820 /* Bochs BIOS debug ports */
2821 #ifdef TARGET_I386
2822 void bochs_bios_write(CPUX86State *env, uint32_t addr, uint32_t val)
2823 {
2824     switch(addr) {
2825         /* Bochs BIOS messages */
2826     case 0x400:
2827     case 0x401:
2828         fprintf(stderr, "BIOS panic at rombios.c, line %d\n", val);
2829         exit(1);
2830     case 0x402:
2831     case 0x403:
2832 #ifdef DEBUG_BIOS
2833         fprintf(stderr, "%c", val);
2834 #endif
2835         break;
2836
2837         /* LGPL'ed VGA BIOS messages */
2838     case 0x501:
2839     case 0x502:
2840         fprintf(stderr, "VGA BIOS panic, line %d\n", val);
2841         exit(1);
2842     case 0x500:
2843     case 0x503:
2844 #ifdef DEBUG_BIOS
2845         fprintf(stderr, "%c", val);
2846 #endif
2847         break;
2848     }
2849 }
2850
2851 void bochs_bios_init(void)
2852 {
2853     register_ioport_write(0x400, 1, bochs_bios_write, 2);
2854     register_ioport_write(0x401, 1, bochs_bios_write, 2);
2855     register_ioport_write(0x402, 1, bochs_bios_write, 1);
2856     register_ioport_write(0x403, 1, bochs_bios_write, 1);
2857
2858     register_ioport_write(0x501, 1, bochs_bios_write, 2);
2859     register_ioport_write(0x502, 1, bochs_bios_write, 2);
2860     register_ioport_write(0x500, 1, bochs_bios_write, 1);
2861     register_ioport_write(0x503, 1, bochs_bios_write, 1);
2862 }
2863 #endif
2864
2865 /***********************************************************/
2866 /* dumb display */
2867
2868 /* init terminal so that we can grab keys */
2869 static struct termios oldtty;
2870
2871 static void term_exit(void)
2872 {
2873     tcsetattr (0, TCSANOW, &oldtty);
2874 }
2875
2876 static void term_init(void)
2877 {
2878     struct termios tty;
2879
2880     tcgetattr (0, &tty);
2881     oldtty = tty;
2882
2883     tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2884                           |INLCR|IGNCR|ICRNL|IXON);
2885     tty.c_oflag |= OPOST;
2886     tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2887     /* if graphical mode, we allow Ctrl-C handling */
2888     if (nographic)
2889         tty.c_lflag &= ~ISIG;
2890     tty.c_cflag &= ~(CSIZE|PARENB);
2891     tty.c_cflag |= CS8;
2892     tty.c_cc[VMIN] = 1;
2893     tty.c_cc[VTIME] = 0;
2894     
2895     tcsetattr (0, TCSANOW, &tty);
2896
2897     atexit(term_exit);
2898
2899     fcntl(0, F_SETFL, O_NONBLOCK);
2900 }
2901
2902 static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2903 {
2904 }
2905
2906 static void dumb_resize(DisplayState *ds, int w, int h)
2907 {
2908 }
2909
2910 static void dumb_refresh(DisplayState *ds)
2911 {
2912     vga_update_display();
2913 }
2914
2915 void dumb_display_init(DisplayState *ds)
2916 {
2917     ds->data = NULL;
2918     ds->linesize = 0;
2919     ds->depth = 0;
2920     ds->dpy_update = dumb_update;
2921     ds->dpy_resize = dumb_resize;
2922     ds->dpy_refresh = dumb_refresh;
2923 }
2924
2925 #if !defined(CONFIG_SOFTMMU)
2926 /***********************************************************/
2927 /* cpu signal handler */
2928 static void host_segv_handler(int host_signum, siginfo_t *info, 
2929                               void *puc)
2930 {
2931     if (cpu_signal_handler(host_signum, info, puc))
2932         return;
2933     term_exit();
2934     abort();
2935 }
2936 #endif
2937
2938 static int timer_irq_pending;
2939 static int timer_irq_count;
2940
2941 static int timer_ms;
2942 static int gui_refresh_pending, gui_refresh_count;
2943
2944 static void host_alarm_handler(int host_signum, siginfo_t *info, 
2945                                void *puc)
2946 {
2947     /* NOTE: since usually the OS asks a 100 Hz clock, there can be
2948        some drift between cpu_get_ticks() and the interrupt time. So
2949        we queue some interrupts to avoid missing some */
2950     timer_irq_count += pit_get_out_edges(&pit_channels[0]);
2951     if (timer_irq_count) {
2952         if (timer_irq_count > 2)
2953             timer_irq_count = 2;
2954         timer_irq_count--;
2955         timer_irq_pending = 1;
2956     }
2957     gui_refresh_count += timer_ms;
2958     if (gui_refresh_count >= GUI_REFRESH_INTERVAL) {
2959         gui_refresh_count = 0;
2960         gui_refresh_pending = 1;
2961     }
2962
2963     if (gui_refresh_pending || timer_irq_pending) {
2964         /* just exit from the cpu to have a chance to handle timers */
2965         cpu_interrupt(global_env, CPU_INTERRUPT_EXIT);
2966     }
2967 }
2968
2969 /* main execution loop */
2970
2971 CPUState *cpu_gdbstub_get_env(void *opaque)
2972 {
2973     return global_env;
2974 }
2975
2976 int main_loop(void *opaque)
2977 {
2978     struct pollfd ufds[3], *pf, *serial_ufd, *gdb_ufd;
2979 #if defined (TARGET_I386)
2980     struct pollfd *net_ufd;
2981 #endif
2982     int ret, n, timeout, serial_ok;
2983     uint8_t ch;
2984     CPUState *env = global_env;
2985
2986     if (!term_inited) {
2987         /* initialize terminal only there so that the user has a
2988            chance to stop QEMU with Ctrl-C before the gdb connection
2989            is launched */
2990         term_inited = 1;
2991         term_init();
2992     }
2993
2994     serial_ok = 1;
2995     cpu_enable_ticks();
2996     for(;;) {
2997 #if defined (DO_TB_FLUSH)
2998         tb_flush();
2999 #endif
3000         ret = cpu_exec(env);
3001         if (reset_requested) {
3002             ret = EXCP_INTERRUPT; 
3003             break;
3004         }
3005         if (ret == EXCP_DEBUG) {
3006             ret = EXCP_DEBUG;
3007             break;
3008         }
3009         /* if hlt instruction, we wait until the next IRQ */
3010         if (ret == EXCP_HLT) 
3011             timeout = 10;
3012         else
3013             timeout = 0;
3014         /* poll any events */
3015         serial_ufd = NULL;
3016         pf = ufds;
3017         if (serial_ok && !(serial_ports[0].lsr & UART_LSR_DR)) {
3018             serial_ufd = pf;
3019             pf->fd = 0;
3020             pf->events = POLLIN;
3021             pf++;
3022         }
3023 #if defined (TARGET_I386)
3024         net_ufd = NULL;
3025         if (net_fd > 0 && ne2000_can_receive(&ne2000_state)) {
3026             net_ufd = pf;
3027             pf->fd = net_fd;
3028             pf->events = POLLIN;
3029             pf++;
3030         }
3031 #endif
3032         gdb_ufd = NULL;
3033         if (gdbstub_fd > 0) {
3034             gdb_ufd = pf;
3035             pf->fd = gdbstub_fd;
3036             pf->events = POLLIN;
3037             pf++;
3038         }
3039
3040         ret = poll(ufds, pf - ufds, timeout);
3041         if (ret > 0) {
3042             if (serial_ufd && (serial_ufd->revents & POLLIN)) {
3043                 n = read(0, &ch, 1);
3044                 if (n == 1) {
3045                     serial_received_byte(&serial_ports[0], ch);
3046                 } else {
3047                     /* Closed, stop polling. */
3048                     serial_ok = 0;
3049                 }
3050             }
3051 #if defined (TARGET_I386)
3052             if (net_ufd && (net_ufd->revents & POLLIN)) {
3053                 uint8_t buf[MAX_ETH_FRAME_SIZE];
3054
3055                 n = read(net_fd, buf, MAX_ETH_FRAME_SIZE);
3056                 if (n > 0) {
3057                     if (n < 60) {
3058                         memset(buf + n, 0, 60 - n);
3059                         n = 60;
3060                     }
3061                     ne2000_receive(&ne2000_state, buf, n);
3062                 }
3063             }
3064 #endif
3065             if (gdb_ufd && (gdb_ufd->revents & POLLIN)) {
3066                 uint8_t buf[1];
3067                 /* stop emulation if requested by gdb */
3068                 n = read(gdbstub_fd, buf, 1);
3069                 if (n == 1) {
3070                     ret = EXCP_INTERRUPT; 
3071                     break;
3072                 }
3073             }
3074         }
3075
3076         /* timer IRQ */
3077         if (timer_irq_pending) {
3078 #if defined (TARGET_I386)
3079             pic_set_irq(0, 1);
3080             pic_set_irq(0, 0);
3081             timer_irq_pending = 0;
3082             /* XXX: RTC test */
3083             if (cmos_data[RTC_REG_B] & 0x50) {
3084                 pic_set_irq(8, 1);
3085             }
3086 #endif
3087         }
3088         /* XXX: add explicit timer */
3089         SB16_run();
3090
3091         /* run dma transfers, if any */
3092         DMA_run();
3093
3094         /* VGA */
3095         if (gui_refresh_pending) {
3096             display_state.dpy_refresh(&display_state);
3097             gui_refresh_pending = 0;
3098         }
3099     }
3100     cpu_disable_ticks();
3101     return ret;
3102 }
3103
3104 void help(void)
3105 {
3106     printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003 Fabrice Bellard\n"
3107            "usage: %s [options] [disk_image]\n"
3108            "\n"
3109            "'disk_image' is a raw hard image image for IDE hard disk 0\n"
3110            "\n"
3111            "Standard options:\n"
3112            "-fda/-fdb file  use 'file' as floppy disk 0/1 image\n"
3113            "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
3114            "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
3115            "-cdrom file     use 'file' as IDE cdrom 2 image\n"
3116            "-boot [a|b|c|d] boot on floppy (a, b), hard disk (c) or CD-ROM (d)\n"
3117            "-snapshot       write to temporary files instead of disk image files\n"
3118            "-m megs         set virtual RAM size to megs MB\n"
3119            "-n script       set network init script [default=%s]\n"
3120            "-tun-fd fd      this fd talks to tap/tun, use it.\n"
3121            "-nographic      disable graphical output\n"
3122            "\n"
3123            "Linux boot specific (does not require PC BIOS):\n"
3124            "-kernel bzImage use 'bzImage' as kernel image\n"
3125            "-append cmdline use 'cmdline' as kernel command line\n"
3126            "-initrd file    use 'file' as initial ram disk\n"
3127            "\n"
3128            "Debug/Expert options:\n"
3129            "-s              wait gdb connection to port %d\n"
3130            "-p port         change gdb connection port\n"
3131            "-d              output log to %s\n"
3132            "-hdachs c,h,s   force hard disk 0 geometry (usually qemu can guess it)\n"
3133            "-L path         set the directory for the BIOS and VGA BIOS\n"
3134 #ifdef USE_CODE_COPY
3135            "-no-code-copy   disable code copy acceleration\n"
3136 #endif
3137
3138            "\n"
3139            "During emulation, use C-a h to get terminal commands:\n",
3140 #ifdef CONFIG_SOFTMMU
3141            "qemu",
3142 #else
3143            "qemu-fast",
3144 #endif
3145            DEFAULT_NETWORK_SCRIPT, 
3146            DEFAULT_GDBSTUB_PORT,
3147            "/tmp/qemu.log");
3148     term_print_help();
3149 #ifndef CONFIG_SOFTMMU
3150     printf("\n"
3151            "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
3152            "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
3153            "PC emulation.\n");
3154 #endif
3155     exit(1);
3156 }
3157
3158 struct option long_options[] = {
3159     { "initrd", 1, NULL, 0, },
3160     { "hda", 1, NULL, 0, },
3161     { "hdb", 1, NULL, 0, },
3162     { "snapshot", 0, NULL, 0, },
3163     { "hdachs", 1, NULL, 0, },
3164     { "nographic", 0, NULL, 0, },
3165     { "kernel", 1, NULL, 0, },
3166     { "append", 1, NULL, 0, },
3167     { "tun-fd", 1, NULL, 0, },
3168     { "hdc", 1, NULL, 0, },
3169     { "hdd", 1, NULL, 0, },
3170     { "cdrom", 1, NULL, 0, },
3171     { "boot", 1, NULL, 0, },
3172     { "fda", 1, NULL, 0, },
3173     { "fdb", 1, NULL, 0, },
3174     { "no-code-copy", 0, NULL, 0},
3175     { NULL, 0, NULL, 0 },
3176 };
3177
3178 #ifdef CONFIG_SDL
3179 /* SDL use the pthreads and they modify sigaction. We don't
3180    want that. */
3181 #if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 2)
3182 extern void __libc_sigaction();
3183 #define sigaction(sig, act, oact) __libc_sigaction(sig, act, oact)
3184 #else
3185 extern void __sigaction();
3186 #define sigaction(sig, act, oact) __sigaction(sig, act, oact)
3187 #endif
3188 #endif /* CONFIG_SDL */
3189
3190 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3191
3192 /* this stack is only used during signal handling */
3193 #define SIGNAL_STACK_SIZE 32768
3194
3195 static uint8_t *signal_stack;
3196
3197 #endif
3198
3199 int main(int argc, char **argv)
3200 {
3201     int c, ret, initrd_size, i, use_gdbstub, gdbstub_port, long_index;
3202     int snapshot, linux_boot;
3203     struct sigaction act;
3204     struct itimerval itv;
3205     CPUState *env;
3206     const char *initrd_filename;
3207     const char *hd_filename[MAX_DISKS], *fd_filename[MAX_FD];
3208     const char *kernel_filename, *kernel_cmdline;
3209     char buf[1024];
3210     DisplayState *ds = &display_state;
3211
3212     /* we never want that malloc() uses mmap() */
3213     mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
3214     initrd_filename = NULL;
3215     for(i = 0; i < MAX_FD; i++)
3216         fd_filename[i] = NULL;
3217     for(i = 0; i < MAX_DISKS; i++)
3218         hd_filename[i] = NULL;
3219     ram_size = 32 * 1024 * 1024;
3220     vga_ram_size = VGA_RAM_SIZE;
3221 #if defined (TARGET_I386)
3222     pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
3223 #endif
3224     use_gdbstub = 0;
3225     gdbstub_port = DEFAULT_GDBSTUB_PORT;
3226     snapshot = 0;
3227     nographic = 0;
3228     kernel_filename = NULL;
3229     kernel_cmdline = "";
3230     for(;;) {
3231         c = getopt_long_only(argc, argv, "hm:dn:sp:L:", long_options, &long_index);
3232         if (c == -1)
3233             break;
3234         switch(c) {
3235         case 0:
3236             switch(long_index) {
3237             case 0:
3238                 initrd_filename = optarg;
3239                 break;
3240             case 1:
3241                 hd_filename[0] = optarg;
3242                 break;
3243             case 2:
3244                 hd_filename[1] = optarg;
3245                 break;
3246             case 3:
3247                 snapshot = 1;
3248                 break;
3249             case 4:
3250                 {
3251                     int cyls, heads, secs;
3252                     const char *p;
3253                     p = optarg;
3254                     cyls = strtol(p, (char **)&p, 0);
3255                     if (*p != ',')
3256                         goto chs_fail;
3257                     p++;
3258                     heads = strtol(p, (char **)&p, 0);
3259                     if (*p != ',')
3260                         goto chs_fail;
3261                     p++;
3262                     secs = strtol(p, (char **)&p, 0);
3263                     if (*p != '\0')
3264                         goto chs_fail;
3265                     ide_set_geometry(0, cyls, heads, secs);
3266                 chs_fail: ;
3267                 }
3268                 break;
3269             case 5:
3270                 nographic = 1;
3271                 break;
3272             case 6:
3273                 kernel_filename = optarg;
3274                 break;
3275             case 7:
3276                 kernel_cmdline = optarg;
3277                 break;
3278 #if defined (TARGET_I386)
3279             case 8:
3280                 net_fd = atoi(optarg);
3281                 break;
3282 #endif
3283             case 9:
3284                 hd_filename[2] = optarg;
3285                 break;
3286             case 10:
3287                 hd_filename[3] = optarg;
3288                 break;
3289             case 11:
3290                 hd_filename[2] = optarg;
3291                 ide_set_cdrom(2, 1);
3292                 break;
3293             case 12:
3294                 boot_device = optarg[0];
3295                 if (boot_device != 'a' && boot_device != 'b' &&
3296                     boot_device != 'c' && boot_device != 'd') {
3297                     fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
3298                     exit(1);
3299                 }
3300                 break;
3301             case 13:
3302                 fd_filename[0] = optarg;
3303                 break;
3304             case 14:
3305                 fd_filename[1] = optarg;
3306                 break;
3307             case 15:
3308                 code_copy_enabled = 0;
3309                 break;
3310             }
3311             break;
3312         case 'h':
3313             help();
3314             break;
3315         case 'm':
3316             ram_size = atoi(optarg) * 1024 * 1024;
3317             if (ram_size <= 0)
3318                 help();
3319             if (ram_size > PHYS_RAM_MAX_SIZE) {
3320                 fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
3321                         PHYS_RAM_MAX_SIZE / (1024 * 1024));
3322                 exit(1);
3323             }
3324             break;
3325         case 'd':
3326             cpu_set_log(CPU_LOG_ALL);
3327             break;
3328 #if defined (TARGET_I386)
3329         case 'n':
3330             pstrcpy(network_script, sizeof(network_script), optarg);
3331             break;
3332 #endif
3333         case 's':
3334             use_gdbstub = 1;
3335             break;
3336         case 'p':
3337             gdbstub_port = atoi(optarg);
3338             break;
3339         case 'L':
3340             bios_dir = optarg;
3341             break;
3342         }
3343     }
3344
3345     if (optind < argc) {
3346         hd_filename[0] = argv[optind++];
3347     }
3348
3349     linux_boot = (kernel_filename != NULL);
3350         
3351     if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0' &&
3352         fd_filename[0] == '\0')
3353         help();
3354     
3355     /* boot to cd by default if no hard disk */
3356     if (hd_filename[0] == '\0' && boot_device == 'c') {
3357         if (fd_filename[0] != '\0')
3358             boot_device = 'a';
3359         else
3360             boot_device = 'd';
3361     }
3362
3363 #if !defined(CONFIG_SOFTMMU)
3364     /* must avoid mmap() usage of glibc by setting a buffer "by hand" */
3365     {
3366         static uint8_t stdout_buf[4096];
3367         setvbuf(stdout, stdout_buf, _IOLBF, sizeof(stdout_buf));
3368     }
3369 #else
3370     setvbuf(stdout, NULL, _IOLBF, 0);
3371 #endif
3372
3373     /* init network tun interface */
3374 #if defined (TARGET_I386)
3375     if (net_fd < 0)
3376         net_init();
3377 #endif
3378
3379     /* init the memory */
3380     phys_ram_size = ram_size + vga_ram_size;
3381
3382 #ifdef CONFIG_SOFTMMU
3383     phys_ram_base = memalign(TARGET_PAGE_SIZE, phys_ram_size);
3384     if (!phys_ram_base) {
3385         fprintf(stderr, "Could not allocate physical memory\n");
3386         exit(1);
3387     }
3388 #else
3389     /* as we must map the same page at several addresses, we must use
3390        a fd */
3391     {
3392         const char *tmpdir;
3393
3394         tmpdir = getenv("QEMU_TMPDIR");
3395         if (!tmpdir)
3396             tmpdir = "/tmp";
3397         snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
3398         if (mkstemp(phys_ram_file) < 0) {
3399             fprintf(stderr, "Could not create temporary memory file '%s'\n", 
3400                     phys_ram_file);
3401             exit(1);
3402         }
3403         phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
3404         if (phys_ram_fd < 0) {
3405             fprintf(stderr, "Could not open temporary memory file '%s'\n", 
3406                     phys_ram_file);
3407             exit(1);
3408         }
3409         ftruncate(phys_ram_fd, phys_ram_size);
3410         unlink(phys_ram_file);
3411         phys_ram_base = mmap(get_mmap_addr(phys_ram_size), 
3412                              phys_ram_size, 
3413                              PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
3414                              phys_ram_fd, 0);
3415         if (phys_ram_base == MAP_FAILED) {
3416             fprintf(stderr, "Could not map physical memory\n");
3417             exit(1);
3418         }
3419     }
3420 #endif
3421
3422     /* open the virtual block devices */
3423     for(i = 0; i < MAX_DISKS; i++) {
3424         if (hd_filename[i]) {
3425             bs_table[i] = bdrv_open(hd_filename[i], snapshot);
3426             if (!bs_table[i]) {
3427                 fprintf(stderr, "qemu: could not open hard disk image '%s\n",
3428                         hd_filename[i]);
3429                 exit(1);
3430             }
3431         }
3432     }
3433
3434     /* init CPU state */
3435     env = cpu_init();
3436     global_env = env;
3437     cpu_single_env = env;
3438
3439     init_ioports();
3440
3441     /* allocate RAM */
3442     cpu_register_physical_memory(0, ram_size, 0);
3443
3444 #if defined(TARGET_I386)
3445     /* RAW PC boot */
3446
3447     /* BIOS load */
3448     snprintf(buf, sizeof(buf), "%s/%s", bios_dir, BIOS_FILENAME);
3449     ret = load_image(buf, phys_ram_base + 0x000f0000);
3450     if (ret != 0x10000) {
3451         fprintf(stderr, "qemu: could not load PC bios '%s'\n", buf);
3452         exit(1);
3453     }
3454     
3455     /* VGA BIOS load */
3456     snprintf(buf, sizeof(buf), "%s/%s", bios_dir, VGABIOS_FILENAME);
3457     ret = load_image(buf, phys_ram_base + 0x000c0000);
3458     
3459     /* setup basic memory access */
3460     cpu_register_physical_memory(0xc0000, 0x10000, 0xc0000 | IO_MEM_ROM);
3461     cpu_register_physical_memory(0xf0000, 0x10000, 0xf0000 | IO_MEM_ROM);
3462     
3463     bochs_bios_init();
3464
3465     if (linux_boot) {
3466         extern uint8_t linux_boot_start;
3467         extern uint8_t linux_boot_end;
3468
3469         if (bs_table[0] == NULL) {
3470             fprintf(stderr, "A disk image must be given for 'hda' when booting a Linux kernel\n");
3471             exit(1);
3472         }
3473         bdrv_set_boot_sector(bs_table[0], &linux_boot_start,
3474                              &linux_boot_end - &linux_boot_start);
3475
3476         /* now we can load the kernel */
3477         ret = load_kernel(kernel_filename, 
3478                           phys_ram_base + KERNEL_LOAD_ADDR,
3479                           phys_ram_base + KERNEL_PARAMS_ADDR);
3480         if (ret < 0) {
3481             fprintf(stderr, "qemu: could not load kernel '%s'\n", 
3482                     kernel_filename);
3483             exit(1);
3484         }
3485         
3486         /* load initrd */
3487         initrd_size = 0;
3488         if (initrd_filename) {
3489             initrd_size = load_image(initrd_filename, phys_ram_base + INITRD_LOAD_ADDR);
3490             if (initrd_size < 0) {
3491                 fprintf(stderr, "qemu: could not load initial ram disk '%s'\n", 
3492                         initrd_filename);
3493                 exit(1);
3494             }
3495         }
3496         if (initrd_size > 0) {
3497             stl_raw(phys_ram_base + KERNEL_PARAMS_ADDR + 0x218, INITRD_LOAD_ADDR);
3498             stl_raw(phys_ram_base + KERNEL_PARAMS_ADDR + 0x21c, initrd_size);
3499         }
3500         pstrcpy(phys_ram_base + KERNEL_CMDLINE_ADDR, 4096,
3501                 kernel_cmdline);
3502         stw_raw(phys_ram_base + KERNEL_PARAMS_ADDR + 0x20, 0xA33F);
3503         stw_raw(phys_ram_base + KERNEL_PARAMS_ADDR + 0x22,
3504                 KERNEL_CMDLINE_ADDR - KERNEL_PARAMS_ADDR);
3505         /* loader type */
3506         stw_raw(phys_ram_base + KERNEL_PARAMS_ADDR + 0x210, 0x01);
3507     }
3508 #elif defined(TARGET_PPC)
3509     /* allocate ROM */
3510     //        snprintf(buf, sizeof(buf), "%s/%s", bios_dir, BIOS_FILENAME);
3511     snprintf(buf, sizeof(buf), "%s", BIOS_FILENAME);
3512     printf("load BIOS at %p\n", phys_ram_base + 0x000f0000);
3513     ret = load_image(buf, phys_ram_base + 0x000f0000);
3514     if (ret != 0x10000) {
3515         fprintf(stderr, "qemu: could not load PPC bios '%s' (%d)\n%m\n",
3516                 buf, ret);
3517         exit(1);
3518     }
3519 #endif
3520
3521     /* terminal init */
3522     if (nographic) {
3523         dumb_display_init(ds);
3524     } else {
3525 #ifdef CONFIG_SDL
3526         sdl_display_init(ds);
3527 #else
3528         dumb_display_init(ds);
3529 #endif
3530     }
3531     /* init basic PC hardware */
3532     register_ioport_write(0x80, 1, ioport80_write, 1);
3533
3534     vga_initialize(ds, phys_ram_base + ram_size, ram_size, 
3535              vga_ram_size);
3536 #if defined (TARGET_I386)
3537     cmos_init();
3538 #endif
3539     pic_init();
3540     pit_init();
3541     serial_init();
3542 #if defined (TARGET_I386)
3543     ne2000_init();
3544 #endif
3545     ide_init();
3546     kbd_init();
3547     AUD_init();
3548     DMA_init();
3549 #if defined (TARGET_I386)
3550     SB16_init();
3551 #endif
3552 #if defined (TARGET_PPC)
3553     PPC_end_init();
3554 #endif
3555     fdctrl_register((unsigned char **)fd_filename, snapshot, boot_device);
3556
3557     /* setup cpu signal handlers for MMU / self modifying code handling */
3558 #if !defined(CONFIG_SOFTMMU)
3559
3560 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3561     {
3562         stack_t stk;
3563         signal_stack = malloc(SIGNAL_STACK_SIZE);
3564         stk.ss_sp = signal_stack;
3565         stk.ss_size = SIGNAL_STACK_SIZE;
3566         stk.ss_flags = 0;
3567
3568         if (sigaltstack(&stk, NULL) < 0) {
3569             perror("sigaltstack");
3570             exit(1);
3571         }
3572     }
3573 #endif
3574         
3575     sigfillset(&act.sa_mask);
3576     act.sa_flags = SA_SIGINFO;
3577 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3578     act.sa_flags |= SA_ONSTACK;
3579 #endif
3580     act.sa_sigaction = host_segv_handler;
3581     sigaction(SIGSEGV, &act, NULL);
3582     sigaction(SIGBUS, &act, NULL);
3583 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3584     sigaction(SIGFPE, &act, NULL);
3585 #endif
3586 #endif
3587
3588     /* timer signal */
3589     sigfillset(&act.sa_mask);
3590     act.sa_flags = SA_SIGINFO;
3591 #if defined (TARGET_I386) && defined(USE_CODE_COPY)
3592     act.sa_flags |= SA_ONSTACK;
3593 #endif
3594     act.sa_sigaction = host_alarm_handler;
3595     sigaction(SIGALRM, &act, NULL);
3596
3597     itv.it_interval.tv_sec = 0;
3598     itv.it_interval.tv_usec = 1000;
3599     itv.it_value.tv_sec = 0;
3600     itv.it_value.tv_usec = 10 * 1000;
3601     setitimer(ITIMER_REAL, &itv, NULL);
3602     /* we probe the tick duration of the kernel to inform the user if
3603        the emulated kernel requested a too high timer frequency */
3604     getitimer(ITIMER_REAL, &itv);
3605     timer_ms = itv.it_interval.tv_usec / 1000;
3606     pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * PIT_FREQ) / 
3607         1000000;
3608
3609     if (use_gdbstub) {
3610         cpu_gdbstub(NULL, main_loop, gdbstub_port);
3611     } else {
3612         main_loop(NULL);
3613     }
3614     return 0;
3615 }