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