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