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