Statistics
| Branch: | Revision:

root / vl.c @ 07ad1b93

History | View | Annotate | Download (91.7 kB)

1
/*
2
 * QEMU PC System Emulator
3
 * 
4
 * Copyright (c) 2003 Fabrice Bellard
5
 * 
6
 * Permission is hereby granted, free of charge, to any person obtaining a copy
7
 * of this software and associated documentation files (the "Software"), to deal
8
 * in the Software without restriction, including without limitation the rights
9
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
 * copies of the Software, and to permit persons to whom the Software is
11
 * furnished to do so, subject to the following conditions:
12
 *
13
 * The above copyright notice and this permission notice shall be included in
14
 * all copies or substantial portions of the Software.
15
 *
16
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
19
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22
 * THE SOFTWARE.
23
 */
24
#include <stdlib.h>
25
#include <stdio.h>
26
#include <stdarg.h>
27
#include <string.h>
28
#include <getopt.h>
29
#include <inttypes.h>
30
#include <unistd.h>
31
#include <sys/mman.h>
32
#include <fcntl.h>
33
#include <signal.h>
34
#include <time.h>
35
#include <sys/time.h>
36
#include <malloc.h>
37
#include <termios.h>
38
#include <sys/poll.h>
39
#include <errno.h>
40
#include <sys/wait.h>
41

    
42
#include <sys/ioctl.h>
43
#include <sys/socket.h>
44
#include <linux/if.h>
45
#include <linux/if_tun.h>
46

    
47
#include "cpu.h"
48
#include "disas.h"
49
#include "thunk.h"
50

    
51
#include "vl.h"
52

    
53
#define DEFAULT_NETWORK_SCRIPT "/etc/qemu-ifup"
54
#define BIOS_FILENAME "bios.bin"
55
#define VGABIOS_FILENAME "vgabios.bin"
56

    
57
//#define DEBUG_UNUSED_IOPORT
58

    
59
//#define DEBUG_IRQ_LATENCY
60

    
61
/* output Bochs bios info messages */
62
//#define DEBUG_BIOS
63

    
64
//#define DEBUG_CMOS
65

    
66
/* debug PIC */
67
//#define DEBUG_PIC
68

    
69
/* debug NE2000 card */
70
//#define DEBUG_NE2000
71

    
72
/* debug PC keyboard */
73
//#define DEBUG_KBD
74

    
75
/* debug PC keyboard : only mouse */
76
//#define DEBUG_MOUSE
77

    
78
//#define DEBUG_SERIAL
79

    
80
#define PHYS_RAM_BASE     0xac000000
81
#define PHYS_RAM_MAX_SIZE (256 * 1024 * 1024)
82

    
83
#define KERNEL_LOAD_ADDR   0x00100000
84
#define INITRD_LOAD_ADDR   0x00400000
85
#define KERNEL_PARAMS_ADDR 0x00090000
86

    
87
#define GUI_REFRESH_INTERVAL 30 
88

    
89
/* from plex86 (BSD license) */
90
struct  __attribute__ ((packed)) linux_params {
91
  // For 0x00..0x3f, see 'struct screen_info' in linux/include/linux/tty.h.
92
  // I just padded out the VESA parts, rather than define them.
93

    
94
  /* 0x000 */ uint8_t   orig_x;
95
  /* 0x001 */ uint8_t   orig_y;
96
  /* 0x002 */ uint16_t  ext_mem_k;
97
  /* 0x004 */ uint16_t  orig_video_page;
98
  /* 0x006 */ uint8_t   orig_video_mode;
99
  /* 0x007 */ uint8_t   orig_video_cols;
100
  /* 0x008 */ uint16_t  unused1;
101
  /* 0x00a */ uint16_t  orig_video_ega_bx;
102
  /* 0x00c */ uint16_t  unused2;
103
  /* 0x00e */ uint8_t   orig_video_lines;
104
  /* 0x00f */ uint8_t   orig_video_isVGA;
105
  /* 0x010 */ uint16_t  orig_video_points;
106
  /* 0x012 */ uint8_t   pad0[0x20 - 0x12]; // VESA info.
107
  /* 0x020 */ uint16_t  cl_magic;  // Commandline magic number (0xA33F)
108
  /* 0x022 */ uint16_t  cl_offset; // Commandline offset.  Address of commandline
109
                                 // is calculated as 0x90000 + cl_offset, bu
110
                                 // only if cl_magic == 0xA33F.
111
  /* 0x024 */ uint8_t   pad1[0x40 - 0x24]; // VESA info.
112

    
113
  /* 0x040 */ uint8_t   apm_bios_info[20]; // struct apm_bios_info
114
  /* 0x054 */ uint8_t   pad2[0x80 - 0x54];
115

    
116
  // Following 2 from 'struct drive_info_struct' in drivers/block/cciss.h.
117
  // Might be truncated?
118
  /* 0x080 */ uint8_t   hd0_info[16]; // hd0-disk-parameter from intvector 0x41
119
  /* 0x090 */ uint8_t   hd1_info[16]; // hd1-disk-parameter from intvector 0x46
120

    
121
  // System description table truncated to 16 bytes
122
  // From 'struct sys_desc_table_struct' in linux/arch/i386/kernel/setup.c.
123
  /* 0x0a0 */ uint16_t  sys_description_len;
124
  /* 0x0a2 */ uint8_t   sys_description_table[14];
125
                        // [0] machine id
126
                        // [1] machine submodel id
127
                        // [2] BIOS revision
128
                        // [3] bit1: MCA bus
129

    
130
  /* 0x0b0 */ uint8_t   pad3[0x1e0 - 0xb0];
131
  /* 0x1e0 */ uint32_t  alt_mem_k;
132
  /* 0x1e4 */ uint8_t   pad4[4];
133
  /* 0x1e8 */ uint8_t   e820map_entries;
134
  /* 0x1e9 */ uint8_t   eddbuf_entries; // EDD_NR
135
  /* 0x1ea */ uint8_t   pad5[0x1f1 - 0x1ea];
136
  /* 0x1f1 */ uint8_t   setup_sects; // size of setup.S, number of sectors
137
  /* 0x1f2 */ uint16_t  mount_root_rdonly; // MOUNT_ROOT_RDONLY (if !=0)
138
  /* 0x1f4 */ uint16_t  sys_size; // size of compressed kernel-part in the
139
                                // (b)zImage-file (in 16 byte units, rounded up)
140
  /* 0x1f6 */ uint16_t  swap_dev; // (unused AFAIK)
141
  /* 0x1f8 */ uint16_t  ramdisk_flags;
142
  /* 0x1fa */ uint16_t  vga_mode; // (old one)
143
  /* 0x1fc */ uint16_t  orig_root_dev; // (high=Major, low=minor)
144
  /* 0x1fe */ uint8_t   pad6[1];
145
  /* 0x1ff */ uint8_t   aux_device_info;
146
  /* 0x200 */ uint16_t  jump_setup; // Jump to start of setup code,
147
                                  // aka "reserved" field.
148
  /* 0x202 */ uint8_t   setup_signature[4]; // Signature for SETUP-header, ="HdrS"
149
  /* 0x206 */ uint16_t  header_format_version; // Version number of header format;
150
  /* 0x208 */ uint8_t   setup_S_temp0[8]; // Used by setup.S for communication with
151
                                        // boot loaders, look there.
152
  /* 0x210 */ uint8_t   loader_type;
153
                        // 0 for old one.
154
                        // else 0xTV:
155
                        //   T=0: LILO
156
                        //   T=1: Loadlin
157
                        //   T=2: bootsect-loader
158
                        //   T=3: SYSLINUX
159
                        //   T=4: ETHERBOOT
160
                        //   V=version
161
  /* 0x211 */ uint8_t   loadflags;
162
                        // bit0 = 1: kernel is loaded high (bzImage)
163
                        // bit7 = 1: Heap and pointer (see below) set by boot
164
                        //   loader.
165
  /* 0x212 */ uint16_t  setup_S_temp1;
166
  /* 0x214 */ uint32_t  kernel_start;
167
  /* 0x218 */ uint32_t  initrd_start;
168
  /* 0x21c */ uint32_t  initrd_size;
169
  /* 0x220 */ uint8_t   setup_S_temp2[4];
170
  /* 0x224 */ uint16_t  setup_S_heap_end_pointer;
171
  /* 0x226 */ uint8_t   pad7[0x2d0 - 0x226];
172

    
173
  /* 0x2d0 : Int 15, ax=e820 memory map. */
174
  // (linux/include/asm-i386/e820.h, 'struct e820entry')
175
#define E820MAX  32
176
#define E820_RAM  1
177
#define E820_RESERVED 2
178
#define E820_ACPI 3 /* usable as RAM once ACPI tables have been read */
179
#define E820_NVS  4
180
  struct {
181
    uint64_t addr;
182
    uint64_t size;
183
    uint32_t type;
184
    } e820map[E820MAX];
185

    
186
  /* 0x550 */ uint8_t   pad8[0x600 - 0x550];
187

    
188
  // BIOS Enhanced Disk Drive Services.
189
  // (From linux/include/asm-i386/edd.h, 'struct edd_info')
190
  // Each 'struct edd_info is 78 bytes, times a max of 6 structs in array.
191
  /* 0x600 */ uint8_t   eddbuf[0x7d4 - 0x600];
192

    
193
  /* 0x7d4 */ uint8_t   pad9[0x800 - 0x7d4];
194
  /* 0x800 */ uint8_t   commandline[0x800];
195

    
196
  /* 0x1000 */
197
  uint64_t gdt_table[256];
198
  uint64_t idt_table[48];
199
};
200

    
201
#define KERNEL_CS     0x10
202
#define KERNEL_DS     0x18
203

    
204
/* XXX: use a two level table to limit memory usage */
205
#define MAX_IOPORTS 65536
206

    
207
static const char *bios_dir = CONFIG_QEMU_SHAREDIR;
208
char phys_ram_file[1024];
209
CPUX86State *global_env;
210
CPUX86State *cpu_single_env;
211
IOPortReadFunc *ioport_read_table[3][MAX_IOPORTS];
212
IOPortWriteFunc *ioport_write_table[3][MAX_IOPORTS];
213
BlockDriverState *bs_table[MAX_DISKS];
214
int vga_ram_size;
215
static DisplayState display_state;
216
int nographic;
217
int term_inited;
218
int64_t ticks_per_sec;
219
int boot_device = 'c';
220

    
221
/***********************************************************/
222
/* x86 io ports */
223

    
224
uint32_t default_ioport_readb(CPUX86State *env, uint32_t address)
225
{
226
#ifdef DEBUG_UNUSED_IOPORT
227
    fprintf(stderr, "inb: port=0x%04x\n", address);
228
#endif
229
    return 0xff;
230
}
231

    
232
void default_ioport_writeb(CPUX86State *env, uint32_t address, uint32_t data)
233
{
234
#ifdef DEBUG_UNUSED_IOPORT
235
    fprintf(stderr, "outb: port=0x%04x data=0x%02x\n", address, data);
236
#endif
237
}
238

    
239
/* default is to make two byte accesses */
240
uint32_t default_ioport_readw(CPUX86State *env, uint32_t address)
241
{
242
    uint32_t data;
243
    data = ioport_read_table[0][address & (MAX_IOPORTS - 1)](env, address);
244
    data |= ioport_read_table[0][(address + 1) & (MAX_IOPORTS - 1)](env, address + 1) << 8;
245
    return data;
246
}
247

    
248
void default_ioport_writew(CPUX86State *env, uint32_t address, uint32_t data)
249
{
250
    ioport_write_table[0][address & (MAX_IOPORTS - 1)](env, address, data & 0xff);
251
    ioport_write_table[0][(address + 1) & (MAX_IOPORTS - 1)](env, address + 1, (data >> 8) & 0xff);
252
}
253

    
254
uint32_t default_ioport_readl(CPUX86State *env, uint32_t address)
255
{
256
#ifdef DEBUG_UNUSED_IOPORT
257
    fprintf(stderr, "inl: port=0x%04x\n", address);
258
#endif
259
    return 0xffffffff;
260
}
261

    
262
void default_ioport_writel(CPUX86State *env, uint32_t address, uint32_t data)
263
{
264
#ifdef DEBUG_UNUSED_IOPORT
265
    fprintf(stderr, "outl: port=0x%04x data=0x%02x\n", address, data);
266
#endif
267
}
268

    
269
void init_ioports(void)
270
{
271
    int i;
272

    
273
    for(i = 0; i < MAX_IOPORTS; i++) {
274
        ioport_read_table[0][i] = default_ioport_readb;
275
        ioport_write_table[0][i] = default_ioport_writeb;
276
        ioport_read_table[1][i] = default_ioport_readw;
277
        ioport_write_table[1][i] = default_ioport_writew;
278
        ioport_read_table[2][i] = default_ioport_readl;
279
        ioport_write_table[2][i] = default_ioport_writel;
280
    }
281
}
282

    
283
/* size is the word size in byte */
284
int register_ioport_read(int start, int length, IOPortReadFunc *func, int size)
285
{
286
    int i, bsize;
287

    
288
    if (size == 1)
289
        bsize = 0;
290
    else if (size == 2)
291
        bsize = 1;
292
    else if (size == 4)
293
        bsize = 2;
294
    else
295
        return -1;
296
    for(i = start; i < start + length; i += size)
297
        ioport_read_table[bsize][i] = func;
298
    return 0;
299
}
300

    
301
/* size is the word size in byte */
302
int register_ioport_write(int start, int length, IOPortWriteFunc *func, int size)
303
{
304
    int i, bsize;
305

    
306
    if (size == 1)
307
        bsize = 0;
308
    else if (size == 2)
309
        bsize = 1;
310
    else if (size == 4)
311
        bsize = 2;
312
    else
313
        return -1;
314
    for(i = start; i < start + length; i += size)
315
        ioport_write_table[bsize][i] = func;
316
    return 0;
317
}
318

    
319
void pstrcpy(char *buf, int buf_size, const char *str)
320
{
321
    int c;
322
    char *q = buf;
323

    
324
    if (buf_size <= 0)
325
        return;
326

    
327
    for(;;) {
328
        c = *str++;
329
        if (c == 0 || q >= buf + buf_size - 1)
330
            break;
331
        *q++ = c;
332
    }
333
    *q = '\0';
334
}
335

    
336
/* strcat and truncate. */
337
char *pstrcat(char *buf, int buf_size, const char *s)
338
{
339
    int len;
340
    len = strlen(buf);
341
    if (len < buf_size) 
342
        pstrcpy(buf + len, buf_size - len, s);
343
    return buf;
344
}
345

    
346
int load_kernel(const char *filename, uint8_t *addr)
347
{
348
    int fd, size, setup_sects;
349
    uint8_t bootsect[512];
350

    
351
    fd = open(filename, O_RDONLY);
352
    if (fd < 0)
353
        return -1;
354
    if (read(fd, bootsect, 512) != 512)
355
        goto fail;
356
    setup_sects = bootsect[0x1F1];
357
    if (!setup_sects)
358
        setup_sects = 4;
359
    /* skip 16 bit setup code */
360
    lseek(fd, (setup_sects + 1) * 512, SEEK_SET);
361
    size = read(fd, addr, 16 * 1024 * 1024);
362
    if (size < 0)
363
        goto fail;
364
    close(fd);
365
    return size;
366
 fail:
367
    close(fd);
368
    return -1;
369
}
370

    
371
/* return the size or -1 if error */
372
int load_image(const char *filename, uint8_t *addr)
373
{
374
    int fd, size;
375
    fd = open(filename, O_RDONLY);
376
    if (fd < 0)
377
        return -1;
378
    size = lseek(fd, 0, SEEK_END);
379
    lseek(fd, 0, SEEK_SET);
380
    if (read(fd, addr, size) != size) {
381
        close(fd);
382
        return -1;
383
    }
384
    close(fd);
385
    return size;
386
}
387

    
388
void cpu_x86_outb(CPUX86State *env, int addr, int val)
389
{
390
    ioport_write_table[0][addr & (MAX_IOPORTS - 1)](env, addr, val);
391
}
392

    
393
void cpu_x86_outw(CPUX86State *env, int addr, int val)
394
{
395
    ioport_write_table[1][addr & (MAX_IOPORTS - 1)](env, addr, val);
396
}
397

    
398
void cpu_x86_outl(CPUX86State *env, int addr, int val)
399
{
400
    ioport_write_table[2][addr & (MAX_IOPORTS - 1)](env, addr, val);
401
}
402

    
403
int cpu_x86_inb(CPUX86State *env, int addr)
404
{
405
    return ioport_read_table[0][addr & (MAX_IOPORTS - 1)](env, addr);
406
}
407

    
408
int cpu_x86_inw(CPUX86State *env, int addr)
409
{
410
    return ioport_read_table[1][addr & (MAX_IOPORTS - 1)](env, addr);
411
}
412

    
413
int cpu_x86_inl(CPUX86State *env, int addr)
414
{
415
    return ioport_read_table[2][addr & (MAX_IOPORTS - 1)](env, addr);
416
}
417

    
418
/***********************************************************/
419
void ioport80_write(CPUX86State *env, uint32_t addr, uint32_t data)
420
{
421
}
422

    
423
void hw_error(const char *fmt, ...)
424
{
425
    va_list ap;
426

    
427
    va_start(ap, fmt);
428
    fprintf(stderr, "qemu: hardware error: ");
429
    vfprintf(stderr, fmt, ap);
430
    fprintf(stderr, "\n");
431
#ifdef TARGET_I386
432
    cpu_x86_dump_state(global_env, stderr, X86_DUMP_FPU | X86_DUMP_CCOP);
433
#endif
434
    va_end(ap);
435
    abort();
436
}
437

    
438
/***********************************************************/
439
/* cmos emulation */
440

    
441
#define RTC_SECONDS             0
442
#define RTC_SECONDS_ALARM       1
443
#define RTC_MINUTES             2
444
#define RTC_MINUTES_ALARM       3
445
#define RTC_HOURS               4
446
#define RTC_HOURS_ALARM         5
447
#define RTC_ALARM_DONT_CARE    0xC0
448

    
449
#define RTC_DAY_OF_WEEK         6
450
#define RTC_DAY_OF_MONTH        7
451
#define RTC_MONTH               8
452
#define RTC_YEAR                9
453

    
454
#define RTC_REG_A               10
455
#define RTC_REG_B               11
456
#define RTC_REG_C               12
457
#define RTC_REG_D               13
458

    
459
/* PC cmos mappings */
460
#define REG_EQUIPMENT_BYTE          0x14
461

    
462
uint8_t cmos_data[128];
463
uint8_t cmos_index;
464

    
465
void cmos_ioport_write(CPUX86State *env, uint32_t addr, uint32_t data)
466
{
467
    if (addr == 0x70) {
468
        cmos_index = data & 0x7f;
469
    } else {
470
#ifdef DEBUG_CMOS
471
        printf("cmos: write index=0x%02x val=0x%02x\n",
472
               cmos_index, data);
473
#endif        
474
        switch(addr) {
475
        case RTC_SECONDS_ALARM:
476
        case RTC_MINUTES_ALARM:
477
        case RTC_HOURS_ALARM:
478
            /* XXX: not supported */
479
            cmos_data[cmos_index] = data;
480
            break;
481
        case RTC_SECONDS:
482
        case RTC_MINUTES:
483
        case RTC_HOURS:
484
        case RTC_DAY_OF_WEEK:
485
        case RTC_DAY_OF_MONTH:
486
        case RTC_MONTH:
487
        case RTC_YEAR:
488
            cmos_data[cmos_index] = data;
489
            break;
490
        case RTC_REG_A:
491
        case RTC_REG_B:
492
            cmos_data[cmos_index] = data;
493
            break;
494
        case RTC_REG_C:
495
        case RTC_REG_D:
496
            /* cannot write to them */
497
            break;
498
        default:
499
            cmos_data[cmos_index] = data;
500
            break;
501
        }
502
    }
503
}
504

    
505
uint32_t cmos_ioport_read(CPUX86State *env, uint32_t addr)
506
{
507
    int ret;
508

    
509
    if (addr == 0x70) {
510
        return 0xff;
511
    } else {
512
        ret = cmos_data[cmos_index];
513
        switch(cmos_index) {
514
        case RTC_REG_A:
515
            /* toggle update-in-progress bit for Linux (same hack as
516
               plex86) */
517
            cmos_data[RTC_REG_A] ^= 0x80; 
518
            break;
519
        case RTC_REG_C:
520
            pic_set_irq(8, 0);
521
            cmos_data[RTC_REG_C] = 0x00; 
522
            break;
523
        }
524
#ifdef DEBUG_CMOS
525
        printf("cmos: read index=0x%02x val=0x%02x\n",
526
               cmos_index, ret);
527
#endif
528
        return ret;
529
    }
530
}
531

    
532

    
533
static inline int to_bcd(int a)
534
{
535
    return ((a / 10) << 4) | (a % 10);
536
}
537

    
538
void cmos_init(void)
539
{
540
    struct tm *tm;
541
    time_t ti;
542
    int val;
543

    
544
    ti = time(NULL);
545
    tm = gmtime(&ti);
546
    cmos_data[RTC_SECONDS] = to_bcd(tm->tm_sec);
547
    cmos_data[RTC_MINUTES] = to_bcd(tm->tm_min);
548
    cmos_data[RTC_HOURS] = to_bcd(tm->tm_hour);
549
    cmos_data[RTC_DAY_OF_WEEK] = to_bcd(tm->tm_wday);
550
    cmos_data[RTC_DAY_OF_MONTH] = to_bcd(tm->tm_mday);
551
    cmos_data[RTC_MONTH] = to_bcd(tm->tm_mon + 1);
552
    cmos_data[RTC_YEAR] = to_bcd(tm->tm_year % 100);
553

    
554
    cmos_data[RTC_REG_A] = 0x26;
555
    cmos_data[RTC_REG_B] = 0x02;
556
    cmos_data[RTC_REG_C] = 0x00;
557
    cmos_data[RTC_REG_D] = 0x80;
558

    
559
    /* various important CMOS locations needed by PC/Bochs bios */
560

    
561
    cmos_data[REG_EQUIPMENT_BYTE] = 0x02; /* FPU is there */
562
    cmos_data[REG_EQUIPMENT_BYTE] |= 0x04; /* PS/2 mouse installed */
563

    
564
    /* memory size */
565
    val = (phys_ram_size / 1024) - 1024;
566
    if (val > 65535)
567
        val = 65535;
568
    cmos_data[0x17] = val;
569
    cmos_data[0x18] = val >> 8;
570
    cmos_data[0x30] = val;
571
    cmos_data[0x31] = val >> 8;
572

    
573
    val = (phys_ram_size / 65536) - ((16 * 1024 * 1024) / 65536);
574
    if (val > 65535)
575
        val = 65535;
576
    cmos_data[0x34] = val;
577
    cmos_data[0x35] = val >> 8;
578
    
579
    switch(boot_device) {
580
    case 'a':
581
        cmos_data[0x3d] = 0x01; /* floppy boot */
582
        break;
583
    default:
584
    case 'c':
585
        cmos_data[0x3d] = 0x02; /* hard drive boot */
586
        break;
587
    case 'd':
588
        cmos_data[0x3d] = 0x03; /* CD-ROM boot */
589
        break;
590
    }
591

    
592
    register_ioport_write(0x70, 2, cmos_ioport_write, 1);
593
    register_ioport_read(0x70, 2, cmos_ioport_read, 1);
594
}
595

    
596
/***********************************************************/
597
/* 8259 pic emulation */
598

    
599
typedef struct PicState {
600
    uint8_t last_irr; /* edge detection */
601
    uint8_t irr; /* interrupt request register */
602
    uint8_t imr; /* interrupt mask register */
603
    uint8_t isr; /* interrupt service register */
604
    uint8_t priority_add; /* used to compute irq priority */
605
    uint8_t irq_base;
606
    uint8_t read_reg_select;
607
    uint8_t special_mask;
608
    uint8_t init_state;
609
    uint8_t auto_eoi;
610
    uint8_t rotate_on_autoeoi;
611
    uint8_t init4; /* true if 4 byte init */
612
} PicState;
613

    
614
/* 0 is master pic, 1 is slave pic */
615
PicState pics[2];
616
int pic_irq_requested;
617

    
618
/* set irq level. If an edge is detected, then the IRR is set to 1 */
619
static inline void pic_set_irq1(PicState *s, int irq, int level)
620
{
621
    int mask;
622
    mask = 1 << irq;
623
    if (level) {
624
        if ((s->last_irr & mask) == 0)
625
            s->irr |= mask;
626
        s->last_irr |= mask;
627
    } else {
628
        s->last_irr &= ~mask;
629
    }
630
}
631

    
632
static inline int get_priority(PicState *s, int mask)
633
{
634
    int priority;
635
    if (mask == 0)
636
        return -1;
637
    priority = 7;
638
    while ((mask & (1 << ((priority + s->priority_add) & 7))) == 0)
639
        priority--;
640
    return priority;
641
}
642

    
643
/* return the pic wanted interrupt. return -1 if none */
644
static int pic_get_irq(PicState *s)
645
{
646
    int mask, cur_priority, priority;
647

    
648
    mask = s->irr & ~s->imr;
649
    priority = get_priority(s, mask);
650
    if (priority < 0)
651
        return -1;
652
    /* compute current priority */
653
    cur_priority = get_priority(s, s->isr);
654
    if (priority > cur_priority) {
655
        /* higher priority found: an irq should be generated */
656
        return priority;
657
    } else {
658
        return -1;
659
    }
660
}
661

    
662
/* raise irq to CPU if necessary. must be called every time the active
663
   irq may change */
664
static void pic_update_irq(void)
665
{
666
    int irq2, irq;
667

    
668
    /* first look at slave pic */
669
    irq2 = pic_get_irq(&pics[1]);
670
    if (irq2 >= 0) {
671
        /* if irq request by slave pic, signal master PIC */
672
        pic_set_irq1(&pics[0], 2, 1);
673
        pic_set_irq1(&pics[0], 2, 0);
674
    }
675
    /* look at requested irq */
676
    irq = pic_get_irq(&pics[0]);
677
    if (irq >= 0) {
678
        if (irq == 2) {
679
            /* from slave pic */
680
            pic_irq_requested = 8 + irq2;
681
        } else {
682
            /* from master pic */
683
            pic_irq_requested = irq;
684
        }
685
        cpu_x86_interrupt(global_env, CPU_INTERRUPT_HARD);
686
    }
687
}
688

    
689
#ifdef DEBUG_IRQ_LATENCY
690
int64_t irq_time[16];
691
int64_t cpu_get_ticks(void);
692
#endif
693
#if defined(DEBUG_PIC)
694
int irq_level[16];
695
#endif
696

    
697
void pic_set_irq(int irq, int level)
698
{
699
#if defined(DEBUG_PIC)
700
    if (level != irq_level[irq]) {
701
        printf("pic_set_irq: irq=%d level=%d\n", irq, level);
702
        irq_level[irq] = level;
703
    }
704
#endif
705
#ifdef DEBUG_IRQ_LATENCY
706
    if (level) {
707
        irq_time[irq] = cpu_get_ticks();
708
    }
709
#endif
710
    pic_set_irq1(&pics[irq >> 3], irq & 7, level);
711
    pic_update_irq();
712
}
713

    
714
int cpu_x86_get_pic_interrupt(CPUX86State *env)
715
{
716
    int irq, irq2, intno;
717

    
718
    /* signal the pic that the irq was acked by the CPU */
719
    irq = pic_irq_requested;
720
#ifdef DEBUG_IRQ_LATENCY
721
    printf("IRQ%d latency=%0.3fus\n", 
722
           irq, 
723
           (double)(cpu_get_ticks() - irq_time[irq]) * 1000000.0 / ticks_per_sec);
724
#endif
725
#if defined(DEBUG_PIC)
726
    printf("pic_interrupt: irq=%d\n", irq);
727
#endif
728

    
729
    if (irq >= 8) {
730
        irq2 = irq & 7;
731
        pics[1].isr |= (1 << irq2);
732
        pics[1].irr &= ~(1 << irq2);
733
        irq = 2;
734
        intno = pics[1].irq_base + irq2;
735
    } else {
736
        intno = pics[0].irq_base + irq;
737
    }
738
    pics[0].isr |= (1 << irq);
739
    pics[0].irr &= ~(1 << irq);
740
    return intno;
741
}
742

    
743
void pic_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
744
{
745
    PicState *s;
746
    int priority;
747

    
748
#ifdef DEBUG_PIC
749
    printf("pic_write: addr=0x%02x val=0x%02x\n", addr, val);
750
#endif
751
    s = &pics[addr >> 7];
752
    addr &= 1;
753
    if (addr == 0) {
754
        if (val & 0x10) {
755
            /* init */
756
            memset(s, 0, sizeof(PicState));
757
            s->init_state = 1;
758
            s->init4 = val & 1;
759
            if (val & 0x02)
760
                hw_error("single mode not supported");
761
            if (val & 0x08)
762
                hw_error("level sensitive irq not supported");
763
        } else if (val & 0x08) {
764
            if (val & 0x02)
765
                s->read_reg_select = val & 1;
766
            if (val & 0x40)
767
                s->special_mask = (val >> 5) & 1;
768
        } else {
769
            switch(val) {
770
            case 0x00:
771
            case 0x80:
772
                s->rotate_on_autoeoi = val >> 7;
773
                break;
774
            case 0x20: /* end of interrupt */
775
            case 0xa0:
776
                priority = get_priority(s, s->isr);
777
                if (priority >= 0) {
778
                    s->isr &= ~(1 << ((priority + s->priority_add) & 7));
779
                }
780
                if (val == 0xa0)
781
                    s->priority_add = (s->priority_add + 1) & 7;
782
                pic_update_irq();
783
                break;
784
            case 0x60 ... 0x67:
785
                priority = val & 7;
786
                s->isr &= ~(1 << priority);
787
                pic_update_irq();
788
                break;
789
            case 0xc0 ... 0xc7:
790
                s->priority_add = (val + 1) & 7;
791
                pic_update_irq();
792
                break;
793
            case 0xe0 ... 0xe7:
794
                priority = val & 7;
795
                s->isr &= ~(1 << priority);
796
                s->priority_add = (priority + 1) & 7;
797
                pic_update_irq();
798
                break;
799
            }
800
        }
801
    } else {
802
        switch(s->init_state) {
803
        case 0:
804
            /* normal mode */
805
            s->imr = val;
806
            pic_update_irq();
807
            break;
808
        case 1:
809
            s->irq_base = val & 0xf8;
810
            s->init_state = 2;
811
            break;
812
        case 2:
813
            if (s->init4) {
814
                s->init_state = 3;
815
            } else {
816
                s->init_state = 0;
817
            }
818
            break;
819
        case 3:
820
            s->auto_eoi = (val >> 1) & 1;
821
            s->init_state = 0;
822
            break;
823
        }
824
    }
825
}
826

    
827
uint32_t pic_ioport_read(CPUX86State *env, uint32_t addr1)
828
{
829
    PicState *s;
830
    unsigned int addr;
831
    int ret;
832

    
833
    addr = addr1;
834
    s = &pics[addr >> 7];
835
    addr &= 1;
836
    if (addr == 0) {
837
        if (s->read_reg_select)
838
            ret = s->isr;
839
        else
840
            ret = s->irr;
841
    } else {
842
        ret = s->imr;
843
    }
844
#ifdef DEBUG_PIC
845
    printf("pic_read: addr=0x%02x val=0x%02x\n", addr1, ret);
846
#endif
847
    return ret;
848
}
849

    
850
void pic_init(void)
851
{
852
    register_ioport_write(0x20, 2, pic_ioport_write, 1);
853
    register_ioport_read(0x20, 2, pic_ioport_read, 1);
854
    register_ioport_write(0xa0, 2, pic_ioport_write, 1);
855
    register_ioport_read(0xa0, 2, pic_ioport_read, 1);
856
}
857

    
858
/***********************************************************/
859
/* 8253 PIT emulation */
860

    
861
#define PIT_FREQ 1193182
862

    
863
#define RW_STATE_LSB 0
864
#define RW_STATE_MSB 1
865
#define RW_STATE_WORD0 2
866
#define RW_STATE_WORD1 3
867
#define RW_STATE_LATCHED_WORD0 4
868
#define RW_STATE_LATCHED_WORD1 5
869

    
870
typedef struct PITChannelState {
871
    int count; /* can be 65536 */
872
    uint16_t latched_count;
873
    uint8_t rw_state;
874
    uint8_t mode;
875
    uint8_t bcd; /* not supported */
876
    uint8_t gate; /* timer start */
877
    int64_t count_load_time;
878
    int64_t count_last_edge_check_time;
879
} PITChannelState;
880

    
881
PITChannelState pit_channels[3];
882
int speaker_data_on;
883
int dummy_refresh_clock;
884
int pit_min_timer_count = 0;
885

    
886

    
887
#if defined(__powerpc__)
888

    
889
static inline uint32_t get_tbl(void) 
890
{
891
    uint32_t tbl;
892
    asm volatile("mftb %0" : "=r" (tbl));
893
    return tbl;
894
}
895

    
896
static inline uint32_t get_tbu(void) 
897
{
898
        uint32_t tbl;
899
        asm volatile("mftbu %0" : "=r" (tbl));
900
        return tbl;
901
}
902

    
903
int64_t cpu_get_real_ticks(void)
904
{
905
    uint32_t l, h, h1;
906
    /* NOTE: we test if wrapping has occurred */
907
    do {
908
        h = get_tbu();
909
        l = get_tbl();
910
        h1 = get_tbu();
911
    } while (h != h1);
912
    return ((int64_t)h << 32) | l;
913
}
914

    
915
#elif defined(__i386__)
916

    
917
int64_t cpu_get_real_ticks(void)
918
{
919
    int64_t val;
920
    asm("rdtsc" : "=A" (val));
921
    return val;
922
}
923

    
924
#else
925
#error unsupported CPU
926
#endif
927

    
928
static int64_t cpu_ticks_offset;
929
static int64_t cpu_ticks_last;
930

    
931
int64_t cpu_get_ticks(void)
932
{
933
    return cpu_get_real_ticks() + cpu_ticks_offset;
934
}
935

    
936
/* enable cpu_get_ticks() */
937
void cpu_enable_ticks(void)
938
{
939
    cpu_ticks_offset = cpu_ticks_last - cpu_get_real_ticks();
940
}
941

    
942
/* disable cpu_get_ticks() : the clock is stopped. You must not call
943
   cpu_get_ticks() after that.  */
944
void cpu_disable_ticks(void)
945
{
946
    cpu_ticks_last = cpu_get_ticks();
947
}
948

    
949
int64_t get_clock(void)
950
{
951
    struct timeval tv;
952
    gettimeofday(&tv, NULL);
953
    return tv.tv_sec * 1000000LL + tv.tv_usec;
954
}
955

    
956
void cpu_calibrate_ticks(void)
957
{
958
    int64_t usec, ticks;
959

    
960
    usec = get_clock();
961
    ticks = cpu_get_ticks();
962
    usleep(50 * 1000);
963
    usec = get_clock() - usec;
964
    ticks = cpu_get_ticks() - ticks;
965
    ticks_per_sec = (ticks * 1000000LL + (usec >> 1)) / usec;
966
}
967

    
968
/* compute with 96 bit intermediate result: (a*b)/c */
969
static uint64_t muldiv64(uint64_t a, uint32_t b, uint32_t c)
970
{
971
    union {
972
        uint64_t ll;
973
        struct {
974
#ifdef WORDS_BIGENDIAN
975
            uint32_t high, low;
976
#else
977
            uint32_t low, high;
978
#endif            
979
        } l;
980
    } u, res;
981
    uint64_t rl, rh;
982

    
983
    u.ll = a;
984
    rl = (uint64_t)u.l.low * (uint64_t)b;
985
    rh = (uint64_t)u.l.high * (uint64_t)b;
986
    rh += (rl >> 32);
987
    res.l.high = rh / c;
988
    res.l.low = (((rh % c) << 32) + (rl & 0xffffffff)) / c;
989
    return res.ll;
990
}
991

    
992
static int pit_get_count(PITChannelState *s)
993
{
994
    uint64_t d;
995
    int counter;
996

    
997
    d = muldiv64(cpu_get_ticks() - s->count_load_time, PIT_FREQ, ticks_per_sec);
998
    switch(s->mode) {
999
    case 0:
1000
    case 1:
1001
    case 4:
1002
    case 5:
1003
        counter = (s->count - d) & 0xffff;
1004
        break;
1005
    default:
1006
        counter = s->count - (d % s->count);
1007
        break;
1008
    }
1009
    return counter;
1010
}
1011

    
1012
/* get pit output bit */
1013
static int pit_get_out(PITChannelState *s)
1014
{
1015
    uint64_t d;
1016
    int out;
1017

    
1018
    d = muldiv64(cpu_get_ticks() - s->count_load_time, PIT_FREQ, ticks_per_sec);
1019
    switch(s->mode) {
1020
    default:
1021
    case 0:
1022
        out = (d >= s->count);
1023
        break;
1024
    case 1:
1025
        out = (d < s->count);
1026
        break;
1027
    case 2:
1028
        if ((d % s->count) == 0 && d != 0)
1029
            out = 1;
1030
        else
1031
            out = 0;
1032
        break;
1033
    case 3:
1034
        out = (d % s->count) < (s->count >> 1);
1035
        break;
1036
    case 4:
1037
    case 5:
1038
        out = (d == s->count);
1039
        break;
1040
    }
1041
    return out;
1042
}
1043

    
1044
/* get the number of 0 to 1 transitions we had since we call this
1045
   function */
1046
/* XXX: maybe better to use ticks precision to avoid getting edges
1047
   twice if checks are done at very small intervals */
1048
static int pit_get_out_edges(PITChannelState *s)
1049
{
1050
    uint64_t d1, d2;
1051
    int64_t ticks;
1052
    int ret, v;
1053

    
1054
    ticks = cpu_get_ticks();
1055
    d1 = muldiv64(s->count_last_edge_check_time - s->count_load_time, 
1056
                 PIT_FREQ, ticks_per_sec);
1057
    d2 = muldiv64(ticks - s->count_load_time, 
1058
                  PIT_FREQ, ticks_per_sec);
1059
    s->count_last_edge_check_time = ticks;
1060
    switch(s->mode) {
1061
    default:
1062
    case 0:
1063
        if (d1 < s->count && d2 >= s->count)
1064
            ret = 1;
1065
        else
1066
            ret = 0;
1067
        break;
1068
    case 1:
1069
        ret = 0;
1070
        break;
1071
    case 2:
1072
        d1 /= s->count;
1073
        d2 /= s->count;
1074
        ret = d2 - d1;
1075
        break;
1076
    case 3:
1077
        v = s->count - (s->count >> 1);
1078
        d1 = (d1 + v) / s->count;
1079
        d2 = (d2 + v) / s->count;
1080
        ret = d2 - d1;
1081
        break;
1082
    case 4:
1083
    case 5:
1084
        if (d1 < s->count && d2 >= s->count)
1085
            ret = 1;
1086
        else
1087
            ret = 0;
1088
        break;
1089
    }
1090
    return ret;
1091
}
1092

    
1093
static inline void pit_load_count(PITChannelState *s, int val)
1094
{
1095
    if (val == 0)
1096
        val = 0x10000;
1097
    s->count_load_time = cpu_get_ticks();
1098
    s->count_last_edge_check_time = s->count_load_time;
1099
    s->count = val;
1100
    if (s == &pit_channels[0] && val <= pit_min_timer_count) {
1101
        fprintf(stderr, 
1102
                "\nWARNING: qemu: on your system, accurate timer emulation is impossible if its frequency is more than %d Hz. If using a 2.5.xx Linux kernel, you must patch asm/param.h to change HZ from 1000 to 100.\n\n", 
1103
                PIT_FREQ / pit_min_timer_count);
1104
    }
1105
}
1106

    
1107
void pit_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1108
{
1109
    int channel, access;
1110
    PITChannelState *s;
1111

    
1112
    addr &= 3;
1113
    if (addr == 3) {
1114
        channel = val >> 6;
1115
        if (channel == 3)
1116
            return;
1117
        s = &pit_channels[channel];
1118
        access = (val >> 4) & 3;
1119
        switch(access) {
1120
        case 0:
1121
            s->latched_count = pit_get_count(s);
1122
            s->rw_state = RW_STATE_LATCHED_WORD0;
1123
            break;
1124
        default:
1125
            s->mode = (val >> 1) & 7;
1126
            s->bcd = val & 1;
1127
            s->rw_state = access - 1 +  RW_STATE_LSB;
1128
            break;
1129
        }
1130
    } else {
1131
        s = &pit_channels[addr];
1132
        switch(s->rw_state) {
1133
        case RW_STATE_LSB:
1134
            pit_load_count(s, val);
1135
            break;
1136
        case RW_STATE_MSB:
1137
            pit_load_count(s, val << 8);
1138
            break;
1139
        case RW_STATE_WORD0:
1140
        case RW_STATE_WORD1:
1141
            if (s->rw_state & 1) {
1142
                pit_load_count(s, (s->latched_count & 0xff) | (val << 8));
1143
            } else {
1144
                s->latched_count = val;
1145
            }
1146
            s->rw_state ^= 1;
1147
            break;
1148
        }
1149
    }
1150
}
1151

    
1152
uint32_t pit_ioport_read(CPUX86State *env, uint32_t addr)
1153
{
1154
    int ret, count;
1155
    PITChannelState *s;
1156
    
1157
    addr &= 3;
1158
    s = &pit_channels[addr];
1159
    switch(s->rw_state) {
1160
    case RW_STATE_LSB:
1161
    case RW_STATE_MSB:
1162
    case RW_STATE_WORD0:
1163
    case RW_STATE_WORD1:
1164
        count = pit_get_count(s);
1165
        if (s->rw_state & 1)
1166
            ret = (count >> 8) & 0xff;
1167
        else
1168
            ret = count & 0xff;
1169
        if (s->rw_state & 2)
1170
            s->rw_state ^= 1;
1171
        break;
1172
    default:
1173
    case RW_STATE_LATCHED_WORD0:
1174
    case RW_STATE_LATCHED_WORD1:
1175
        if (s->rw_state & 1)
1176
            ret = s->latched_count >> 8;
1177
        else
1178
            ret = s->latched_count & 0xff;
1179
        s->rw_state ^= 1;
1180
        break;
1181
    }
1182
    return ret;
1183
}
1184

    
1185
void speaker_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1186
{
1187
    speaker_data_on = (val >> 1) & 1;
1188
    pit_channels[2].gate = val & 1;
1189
}
1190

    
1191
uint32_t speaker_ioport_read(CPUX86State *env, uint32_t addr)
1192
{
1193
    int out;
1194
    out = pit_get_out(&pit_channels[2]);
1195
    dummy_refresh_clock ^= 1;
1196
    return (speaker_data_on << 1) | pit_channels[2].gate | (out << 5) |
1197
      (dummy_refresh_clock << 4);
1198
}
1199

    
1200
void pit_init(void)
1201
{
1202
    PITChannelState *s;
1203
    int i;
1204

    
1205
    cpu_calibrate_ticks();
1206

    
1207
    for(i = 0;i < 3; i++) {
1208
        s = &pit_channels[i];
1209
        s->mode = 3;
1210
        s->gate = (i != 2);
1211
        pit_load_count(s, 0);
1212
    }
1213

    
1214
    register_ioport_write(0x40, 4, pit_ioport_write, 1);
1215
    register_ioport_read(0x40, 3, pit_ioport_read, 1);
1216

    
1217
    register_ioport_read(0x61, 1, speaker_ioport_read, 1);
1218
    register_ioport_write(0x61, 1, speaker_ioport_write, 1);
1219
}
1220

    
1221
/***********************************************************/
1222
/* serial port emulation */
1223

    
1224
#define UART_IRQ        4
1225

    
1226
#define UART_LCR_DLAB        0x80        /* Divisor latch access bit */
1227

    
1228
#define UART_IER_MSI        0x08        /* Enable Modem status interrupt */
1229
#define UART_IER_RLSI        0x04        /* Enable receiver line status interrupt */
1230
#define UART_IER_THRI        0x02        /* Enable Transmitter holding register int. */
1231
#define UART_IER_RDI        0x01        /* Enable receiver data interrupt */
1232

    
1233
#define UART_IIR_NO_INT        0x01        /* No interrupts pending */
1234
#define UART_IIR_ID        0x06        /* Mask for the interrupt ID */
1235

    
1236
#define UART_IIR_MSI        0x00        /* Modem status interrupt */
1237
#define UART_IIR_THRI        0x02        /* Transmitter holding register empty */
1238
#define UART_IIR_RDI        0x04        /* Receiver data interrupt */
1239
#define UART_IIR_RLSI        0x06        /* Receiver line status interrupt */
1240

    
1241
/*
1242
 * These are the definitions for the Modem Control Register
1243
 */
1244
#define UART_MCR_LOOP        0x10        /* Enable loopback test mode */
1245
#define UART_MCR_OUT2        0x08        /* Out2 complement */
1246
#define UART_MCR_OUT1        0x04        /* Out1 complement */
1247
#define UART_MCR_RTS        0x02        /* RTS complement */
1248
#define UART_MCR_DTR        0x01        /* DTR complement */
1249

    
1250
/*
1251
 * These are the definitions for the Modem Status Register
1252
 */
1253
#define UART_MSR_DCD        0x80        /* Data Carrier Detect */
1254
#define UART_MSR_RI        0x40        /* Ring Indicator */
1255
#define UART_MSR_DSR        0x20        /* Data Set Ready */
1256
#define UART_MSR_CTS        0x10        /* Clear to Send */
1257
#define UART_MSR_DDCD        0x08        /* Delta DCD */
1258
#define UART_MSR_TERI        0x04        /* Trailing edge ring indicator */
1259
#define UART_MSR_DDSR        0x02        /* Delta DSR */
1260
#define UART_MSR_DCTS        0x01        /* Delta CTS */
1261
#define UART_MSR_ANY_DELTA 0x0F        /* Any of the delta bits! */
1262

    
1263
#define UART_LSR_TEMT        0x40        /* Transmitter empty */
1264
#define UART_LSR_THRE        0x20        /* Transmit-hold-register empty */
1265
#define UART_LSR_BI        0x10        /* Break interrupt indicator */
1266
#define UART_LSR_FE        0x08        /* Frame error indicator */
1267
#define UART_LSR_PE        0x04        /* Parity error indicator */
1268
#define UART_LSR_OE        0x02        /* Overrun error indicator */
1269
#define UART_LSR_DR        0x01        /* Receiver data ready */
1270

    
1271
typedef struct SerialState {
1272
    uint8_t divider;
1273
    uint8_t rbr; /* receive register */
1274
    uint8_t ier;
1275
    uint8_t iir; /* read only */
1276
    uint8_t lcr;
1277
    uint8_t mcr;
1278
    uint8_t lsr; /* read only */
1279
    uint8_t msr;
1280
    uint8_t scr;
1281
    /* NOTE: this hidden state is necessary for tx irq generation as
1282
       it can be reset while reading iir */
1283
    int thr_ipending;
1284
} SerialState;
1285

    
1286
SerialState serial_ports[1];
1287

    
1288
void serial_update_irq(void)
1289
{
1290
    SerialState *s = &serial_ports[0];
1291

    
1292
    if ((s->lsr & UART_LSR_DR) && (s->ier & UART_IER_RDI)) {
1293
        s->iir = UART_IIR_RDI;
1294
    } else if (s->thr_ipending && (s->ier & UART_IER_THRI)) {
1295
        s->iir = UART_IIR_THRI;
1296
    } else {
1297
        s->iir = UART_IIR_NO_INT;
1298
    }
1299
    if (s->iir != UART_IIR_NO_INT) {
1300
        pic_set_irq(UART_IRQ, 1);
1301
    } else {
1302
        pic_set_irq(UART_IRQ, 0);
1303
    }
1304
}
1305

    
1306
void serial_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1307
{
1308
    SerialState *s = &serial_ports[0];
1309
    unsigned char ch;
1310
    int ret;
1311
    
1312
    addr &= 7;
1313
#ifdef DEBUG_SERIAL
1314
    printf("serial: write addr=0x%02x val=0x%02x\n", addr, val);
1315
#endif
1316
    switch(addr) {
1317
    default:
1318
    case 0:
1319
        if (s->lcr & UART_LCR_DLAB) {
1320
            s->divider = (s->divider & 0xff00) | val;
1321
        } else {
1322
            s->thr_ipending = 0;
1323
            s->lsr &= ~UART_LSR_THRE;
1324
            serial_update_irq();
1325

    
1326
            ch = val;
1327
            do {
1328
                ret = write(1, &ch, 1);
1329
            } while (ret != 1);
1330
            s->thr_ipending = 1;
1331
            s->lsr |= UART_LSR_THRE;
1332
            s->lsr |= UART_LSR_TEMT;
1333
            serial_update_irq();
1334
        }
1335
        break;
1336
    case 1:
1337
        if (s->lcr & UART_LCR_DLAB) {
1338
            s->divider = (s->divider & 0x00ff) | (val << 8);
1339
        } else {
1340
            s->ier = val;
1341
            serial_update_irq();
1342
        }
1343
        break;
1344
    case 2:
1345
        break;
1346
    case 3:
1347
        s->lcr = val;
1348
        break;
1349
    case 4:
1350
        s->mcr = val;
1351
        break;
1352
    case 5:
1353
        break;
1354
    case 6:
1355
        s->msr = val;
1356
        break;
1357
    case 7:
1358
        s->scr = val;
1359
        break;
1360
    }
1361
}
1362

    
1363
uint32_t serial_ioport_read(CPUX86State *env, uint32_t addr)
1364
{
1365
    SerialState *s = &serial_ports[0];
1366
    uint32_t ret;
1367

    
1368
    addr &= 7;
1369
    switch(addr) {
1370
    default:
1371
    case 0:
1372
        if (s->lcr & UART_LCR_DLAB) {
1373
            ret = s->divider & 0xff; 
1374
        } else {
1375
            ret = s->rbr;
1376
            s->lsr &= ~(UART_LSR_DR | UART_LSR_BI);
1377
            serial_update_irq();
1378
        }
1379
        break;
1380
    case 1:
1381
        if (s->lcr & UART_LCR_DLAB) {
1382
            ret = (s->divider >> 8) & 0xff;
1383
        } else {
1384
            ret = s->ier;
1385
        }
1386
        break;
1387
    case 2:
1388
        ret = s->iir;
1389
        /* reset THR pending bit */
1390
        if ((ret & 0x7) == UART_IIR_THRI)
1391
            s->thr_ipending = 0;
1392
        serial_update_irq();
1393
        break;
1394
    case 3:
1395
        ret = s->lcr;
1396
        break;
1397
    case 4:
1398
        ret = s->mcr;
1399
        break;
1400
    case 5:
1401
        ret = s->lsr;
1402
        break;
1403
    case 6:
1404
        if (s->mcr & UART_MCR_LOOP) {
1405
            /* in loopback, the modem output pins are connected to the
1406
               inputs */
1407
            ret = (s->mcr & 0x0c) << 4;
1408
            ret |= (s->mcr & 0x02) << 3;
1409
            ret |= (s->mcr & 0x01) << 5;
1410
        } else {
1411
            ret = s->msr;
1412
        }
1413
        break;
1414
    case 7:
1415
        ret = s->scr;
1416
        break;
1417
    }
1418
#ifdef DEBUG_SERIAL
1419
    printf("serial: read addr=0x%02x val=0x%02x\n", addr, ret);
1420
#endif
1421
    return ret;
1422
}
1423

    
1424
#define TERM_ESCAPE 0x01 /* ctrl-a is used for escape */
1425
static int term_got_escape;
1426

    
1427
void term_print_help(void)
1428
{
1429
    printf("\n"
1430
           "C-a h    print this help\n"
1431
           "C-a x    exit emulatior\n"
1432
           "C-a s    save disk data back to file (if -snapshot)\n"
1433
           "C-a b    send break (magic sysrq)\n"
1434
           "C-a C-a  send C-a\n"
1435
           );
1436
}
1437

    
1438
/* called when a char is received */
1439
void serial_received_byte(SerialState *s, int ch)
1440
{
1441
    if (term_got_escape) {
1442
        term_got_escape = 0;
1443
        switch(ch) {
1444
        case 'h':
1445
            term_print_help();
1446
            break;
1447
        case 'x':
1448
            exit(0);
1449
            break;
1450
        case 's': 
1451
            {
1452
                int i;
1453
                for (i = 0; i < MAX_DISKS; i++) {
1454
                    if (bs_table[i])
1455
                        bdrv_commit(bs_table[i]);
1456
                }
1457
            }
1458
            break;
1459
        case 'b':
1460
            /* send break */
1461
            s->rbr = 0;
1462
            s->lsr |= UART_LSR_BI | UART_LSR_DR;
1463
            serial_update_irq();
1464
            break;
1465
        case 'd':
1466
            //            tb_flush();
1467
            cpu_set_log(CPU_LOG_ALL);
1468
            break;
1469
        case TERM_ESCAPE:
1470
            goto send_char;
1471
        }
1472
    } else if (ch == TERM_ESCAPE) {
1473
        term_got_escape = 1;
1474
    } else {
1475
    send_char:
1476
        s->rbr = ch;
1477
        s->lsr |= UART_LSR_DR;
1478
        serial_update_irq();
1479
    }
1480
}
1481

    
1482
void serial_init(void)
1483
{
1484
    SerialState *s = &serial_ports[0];
1485

    
1486
    s->lsr = UART_LSR_TEMT | UART_LSR_THRE;
1487
    s->iir = UART_IIR_NO_INT;
1488
    
1489
    register_ioport_write(0x3f8, 8, serial_ioport_write, 1);
1490
    register_ioport_read(0x3f8, 8, serial_ioport_read, 1);
1491
}
1492

    
1493
/***********************************************************/
1494
/* ne2000 emulation */
1495

    
1496
#define NE2000_IOPORT   0x300
1497
#define NE2000_IRQ      9
1498

    
1499
#define MAX_ETH_FRAME_SIZE 1514
1500

    
1501
#define E8390_CMD        0x00  /* The command register (for all pages) */
1502
/* Page 0 register offsets. */
1503
#define EN0_CLDALO        0x01        /* Low byte of current local dma addr  RD */
1504
#define EN0_STARTPG        0x01        /* Starting page of ring bfr WR */
1505
#define EN0_CLDAHI        0x02        /* High byte of current local dma addr  RD */
1506
#define EN0_STOPPG        0x02        /* Ending page +1 of ring bfr WR */
1507
#define EN0_BOUNDARY        0x03        /* Boundary page of ring bfr RD WR */
1508
#define EN0_TSR                0x04        /* Transmit status reg RD */
1509
#define EN0_TPSR        0x04        /* Transmit starting page WR */
1510
#define EN0_NCR                0x05        /* Number of collision reg RD */
1511
#define EN0_TCNTLO        0x05        /* Low  byte of tx byte count WR */
1512
#define EN0_FIFO        0x06        /* FIFO RD */
1513
#define EN0_TCNTHI        0x06        /* High byte of tx byte count WR */
1514
#define EN0_ISR                0x07        /* Interrupt status reg RD WR */
1515
#define EN0_CRDALO        0x08        /* low byte of current remote dma address RD */
1516
#define EN0_RSARLO        0x08        /* Remote start address reg 0 */
1517
#define EN0_CRDAHI        0x09        /* high byte, current remote dma address RD */
1518
#define EN0_RSARHI        0x09        /* Remote start address reg 1 */
1519
#define EN0_RCNTLO        0x0a        /* Remote byte count reg WR */
1520
#define EN0_RCNTHI        0x0b        /* Remote byte count reg WR */
1521
#define EN0_RSR                0x0c        /* rx status reg RD */
1522
#define EN0_RXCR        0x0c        /* RX configuration reg WR */
1523
#define EN0_TXCR        0x0d        /* TX configuration reg WR */
1524
#define EN0_COUNTER0        0x0d        /* Rcv alignment error counter RD */
1525
#define EN0_DCFG        0x0e        /* Data configuration reg WR */
1526
#define EN0_COUNTER1        0x0e        /* Rcv CRC error counter RD */
1527
#define EN0_IMR                0x0f        /* Interrupt mask reg WR */
1528
#define EN0_COUNTER2        0x0f        /* Rcv missed frame error counter RD */
1529

    
1530
#define EN1_PHYS        0x11
1531
#define EN1_CURPAG      0x17
1532
#define EN1_MULT        0x18
1533

    
1534
/*  Register accessed at EN_CMD, the 8390 base addr.  */
1535
#define E8390_STOP        0x01        /* Stop and reset the chip */
1536
#define E8390_START        0x02        /* Start the chip, clear reset */
1537
#define E8390_TRANS        0x04        /* Transmit a frame */
1538
#define E8390_RREAD        0x08        /* Remote read */
1539
#define E8390_RWRITE        0x10        /* Remote write  */
1540
#define E8390_NODMA        0x20        /* Remote DMA */
1541
#define E8390_PAGE0        0x00        /* Select page chip registers */
1542
#define E8390_PAGE1        0x40        /* using the two high-order bits */
1543
#define E8390_PAGE2        0x80        /* Page 3 is invalid. */
1544

    
1545
/* Bits in EN0_ISR - Interrupt status register */
1546
#define ENISR_RX        0x01        /* Receiver, no error */
1547
#define ENISR_TX        0x02        /* Transmitter, no error */
1548
#define ENISR_RX_ERR        0x04        /* Receiver, with error */
1549
#define ENISR_TX_ERR        0x08        /* Transmitter, with error */
1550
#define ENISR_OVER        0x10        /* Receiver overwrote the ring */
1551
#define ENISR_COUNTERS        0x20        /* Counters need emptying */
1552
#define ENISR_RDC        0x40        /* remote dma complete */
1553
#define ENISR_RESET        0x80        /* Reset completed */
1554
#define ENISR_ALL        0x3f        /* Interrupts we will enable */
1555

    
1556
/* Bits in received packet status byte and EN0_RSR*/
1557
#define ENRSR_RXOK        0x01        /* Received a good packet */
1558
#define ENRSR_CRC        0x02        /* CRC error */
1559
#define ENRSR_FAE        0x04        /* frame alignment error */
1560
#define ENRSR_FO        0x08        /* FIFO overrun */
1561
#define ENRSR_MPA        0x10        /* missed pkt */
1562
#define ENRSR_PHY        0x20        /* physical/multicast address */
1563
#define ENRSR_DIS        0x40        /* receiver disable. set in monitor mode */
1564
#define ENRSR_DEF        0x80        /* deferring */
1565

    
1566
/* Transmitted packet status, EN0_TSR. */
1567
#define ENTSR_PTX 0x01        /* Packet transmitted without error */
1568
#define ENTSR_ND  0x02        /* The transmit wasn't deferred. */
1569
#define ENTSR_COL 0x04        /* The transmit collided at least once. */
1570
#define ENTSR_ABT 0x08  /* The transmit collided 16 times, and was deferred. */
1571
#define ENTSR_CRS 0x10        /* The carrier sense was lost. */
1572
#define ENTSR_FU  0x20  /* A "FIFO underrun" occurred during transmit. */
1573
#define ENTSR_CDH 0x40        /* The collision detect "heartbeat" signal was lost. */
1574
#define ENTSR_OWC 0x80  /* There was an out-of-window collision. */
1575

    
1576
#define NE2000_MEM_SIZE 32768
1577

    
1578
typedef struct NE2000State {
1579
    uint8_t cmd;
1580
    uint32_t start;
1581
    uint32_t stop;
1582
    uint8_t boundary;
1583
    uint8_t tsr;
1584
    uint8_t tpsr;
1585
    uint16_t tcnt;
1586
    uint16_t rcnt;
1587
    uint32_t rsar;
1588
    uint8_t isr;
1589
    uint8_t dcfg;
1590
    uint8_t imr;
1591
    uint8_t phys[6]; /* mac address */
1592
    uint8_t curpag;
1593
    uint8_t mult[8]; /* multicast mask array */
1594
    uint8_t mem[NE2000_MEM_SIZE];
1595
} NE2000State;
1596

    
1597
NE2000State ne2000_state;
1598
int net_fd = -1;
1599
char network_script[1024];
1600

    
1601
void ne2000_reset(void)
1602
{
1603
    NE2000State *s = &ne2000_state;
1604
    int i;
1605

    
1606
    s->isr = ENISR_RESET;
1607
    s->mem[0] = 0x52;
1608
    s->mem[1] = 0x54;
1609
    s->mem[2] = 0x00;
1610
    s->mem[3] = 0x12;
1611
    s->mem[4] = 0x34;
1612
    s->mem[5] = 0x56;
1613
    s->mem[14] = 0x57;
1614
    s->mem[15] = 0x57;
1615

    
1616
    /* duplicate prom data */
1617
    for(i = 15;i >= 0; i--) {
1618
        s->mem[2 * i] = s->mem[i];
1619
        s->mem[2 * i + 1] = s->mem[i];
1620
    }
1621
}
1622

    
1623
void ne2000_update_irq(NE2000State *s)
1624
{
1625
    int isr;
1626
    isr = s->isr & s->imr;
1627
    if (isr)
1628
        pic_set_irq(NE2000_IRQ, 1);
1629
    else
1630
        pic_set_irq(NE2000_IRQ, 0);
1631
}
1632

    
1633
int net_init(void)
1634
{
1635
    struct ifreq ifr;
1636
    int fd, ret, pid, status;
1637
    
1638
    fd = open("/dev/net/tun", O_RDWR);
1639
    if (fd < 0) {
1640
        fprintf(stderr, "warning: could not open /dev/net/tun: no virtual network emulation\n");
1641
        return -1;
1642
    }
1643
    memset(&ifr, 0, sizeof(ifr));
1644
    ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
1645
    pstrcpy(ifr.ifr_name, IFNAMSIZ, "tun%d");
1646
    ret = ioctl(fd, TUNSETIFF, (void *) &ifr);
1647
    if (ret != 0) {
1648
        fprintf(stderr, "warning: could not configure /dev/net/tun: no virtual network emulation\n");
1649
        close(fd);
1650
        return -1;
1651
    }
1652
    printf("Connected to host network interface: %s\n", ifr.ifr_name);
1653
    fcntl(fd, F_SETFL, O_NONBLOCK);
1654
    net_fd = fd;
1655

    
1656
    /* try to launch network init script */
1657
    pid = fork();
1658
    if (pid >= 0) {
1659
        if (pid == 0) {
1660
            execl(network_script, network_script, ifr.ifr_name, NULL);
1661
            exit(1);
1662
        }
1663
        while (waitpid(pid, &status, 0) != pid);
1664
        if (!WIFEXITED(status) ||
1665
            WEXITSTATUS(status) != 0) {
1666
            fprintf(stderr, "%s: could not launch network script for '%s'\n",
1667
                    network_script, ifr.ifr_name);
1668
        }
1669
    }
1670
    return 0;
1671
}
1672

    
1673
void net_send_packet(NE2000State *s, const uint8_t *buf, int size)
1674
{
1675
#ifdef DEBUG_NE2000
1676
    printf("NE2000: sending packet size=%d\n", size);
1677
#endif
1678
    write(net_fd, buf, size);
1679
}
1680

    
1681
/* return true if the NE2000 can receive more data */
1682
int ne2000_can_receive(NE2000State *s)
1683
{
1684
    int avail, index, boundary;
1685
    
1686
    if (s->cmd & E8390_STOP)
1687
        return 0;
1688
    index = s->curpag << 8;
1689
    boundary = s->boundary << 8;
1690
    if (index < boundary)
1691
        avail = boundary - index;
1692
    else
1693
        avail = (s->stop - s->start) - (index - boundary);
1694
    if (avail < (MAX_ETH_FRAME_SIZE + 4))
1695
        return 0;
1696
    return 1;
1697
}
1698

    
1699
void ne2000_receive(NE2000State *s, uint8_t *buf, int size)
1700
{
1701
    uint8_t *p;
1702
    int total_len, next, avail, len, index;
1703

    
1704
#if defined(DEBUG_NE2000)
1705
    printf("NE2000: received len=%d\n", size);
1706
#endif
1707

    
1708
    index = s->curpag << 8;
1709
    /* 4 bytes for header */
1710
    total_len = size + 4;
1711
    /* address for next packet (4 bytes for CRC) */
1712
    next = index + ((total_len + 4 + 255) & ~0xff);
1713
    if (next >= s->stop)
1714
        next -= (s->stop - s->start);
1715
    /* prepare packet header */
1716
    p = s->mem + index;
1717
    p[0] = ENRSR_RXOK; /* receive status */
1718
    p[1] = next >> 8;
1719
    p[2] = total_len;
1720
    p[3] = total_len >> 8;
1721
    index += 4;
1722

    
1723
    /* write packet data */
1724
    while (size > 0) {
1725
        avail = s->stop - index;
1726
        len = size;
1727
        if (len > avail)
1728
            len = avail;
1729
        memcpy(s->mem + index, buf, len);
1730
        buf += len;
1731
        index += len;
1732
        if (index == s->stop)
1733
            index = s->start;
1734
        size -= len;
1735
    }
1736
    s->curpag = next >> 8;
1737
    
1738
    /* now we can signal we have receive something */
1739
    s->isr |= ENISR_RX;
1740
    ne2000_update_irq(s);
1741
}
1742

    
1743
void ne2000_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1744
{
1745
    NE2000State *s = &ne2000_state;
1746
    int offset, page;
1747

    
1748
    addr &= 0xf;
1749
#ifdef DEBUG_NE2000
1750
    printf("NE2000: write addr=0x%x val=0x%02x\n", addr, val);
1751
#endif
1752
    if (addr == E8390_CMD) {
1753
        /* control register */
1754
        s->cmd = val;
1755
        if (val & E8390_START) {
1756
            /* test specific case: zero length transfert */
1757
            if ((val & (E8390_RREAD | E8390_RWRITE)) &&
1758
                s->rcnt == 0) {
1759
                s->isr |= ENISR_RDC;
1760
                ne2000_update_irq(s);
1761
            }
1762
            if (val & E8390_TRANS) {
1763
                net_send_packet(s, s->mem + (s->tpsr << 8), s->tcnt);
1764
                /* signal end of transfert */
1765
                s->tsr = ENTSR_PTX;
1766
                s->isr |= ENISR_TX;
1767
                ne2000_update_irq(s);
1768
            }
1769
        }
1770
    } else {
1771
        page = s->cmd >> 6;
1772
        offset = addr | (page << 4);
1773
        switch(offset) {
1774
        case EN0_STARTPG:
1775
            s->start = val << 8;
1776
            break;
1777
        case EN0_STOPPG:
1778
            s->stop = val << 8;
1779
            break;
1780
        case EN0_BOUNDARY:
1781
            s->boundary = val;
1782
            break;
1783
        case EN0_IMR:
1784
            s->imr = val;
1785
            ne2000_update_irq(s);
1786
            break;
1787
        case EN0_TPSR:
1788
            s->tpsr = val;
1789
            break;
1790
        case EN0_TCNTLO:
1791
            s->tcnt = (s->tcnt & 0xff00) | val;
1792
            break;
1793
        case EN0_TCNTHI:
1794
            s->tcnt = (s->tcnt & 0x00ff) | (val << 8);
1795
            break;
1796
        case EN0_RSARLO:
1797
            s->rsar = (s->rsar & 0xff00) | val;
1798
            break;
1799
        case EN0_RSARHI:
1800
            s->rsar = (s->rsar & 0x00ff) | (val << 8);
1801
            break;
1802
        case EN0_RCNTLO:
1803
            s->rcnt = (s->rcnt & 0xff00) | val;
1804
            break;
1805
        case EN0_RCNTHI:
1806
            s->rcnt = (s->rcnt & 0x00ff) | (val << 8);
1807
            break;
1808
        case EN0_DCFG:
1809
            s->dcfg = val;
1810
            break;
1811
        case EN0_ISR:
1812
            s->isr &= ~val;
1813
            ne2000_update_irq(s);
1814
            break;
1815
        case EN1_PHYS ... EN1_PHYS + 5:
1816
            s->phys[offset - EN1_PHYS] = val;
1817
            break;
1818
        case EN1_CURPAG:
1819
            s->curpag = val;
1820
            break;
1821
        case EN1_MULT ... EN1_MULT + 7:
1822
            s->mult[offset - EN1_MULT] = val;
1823
            break;
1824
        }
1825
    }
1826
}
1827

    
1828
uint32_t ne2000_ioport_read(CPUX86State *env, uint32_t addr)
1829
{
1830
    NE2000State *s = &ne2000_state;
1831
    int offset, page, ret;
1832

    
1833
    addr &= 0xf;
1834
    if (addr == E8390_CMD) {
1835
        ret = s->cmd;
1836
    } else {
1837
        page = s->cmd >> 6;
1838
        offset = addr | (page << 4);
1839
        switch(offset) {
1840
        case EN0_TSR:
1841
            ret = s->tsr;
1842
            break;
1843
        case EN0_BOUNDARY:
1844
            ret = s->boundary;
1845
            break;
1846
        case EN0_ISR:
1847
            ret = s->isr;
1848
            break;
1849
        case EN1_PHYS ... EN1_PHYS + 5:
1850
            ret = s->phys[offset - EN1_PHYS];
1851
            break;
1852
        case EN1_CURPAG:
1853
            ret = s->curpag;
1854
            break;
1855
        case EN1_MULT ... EN1_MULT + 7:
1856
            ret = s->mult[offset - EN1_MULT];
1857
            break;
1858
        default:
1859
            ret = 0x00;
1860
            break;
1861
        }
1862
    }
1863
#ifdef DEBUG_NE2000
1864
    printf("NE2000: read addr=0x%x val=%02x\n", addr, ret);
1865
#endif
1866
    return ret;
1867
}
1868

    
1869
void ne2000_asic_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1870
{
1871
    NE2000State *s = &ne2000_state;
1872
    uint8_t *p;
1873

    
1874
#ifdef DEBUG_NE2000
1875
    printf("NE2000: asic write val=0x%04x\n", val);
1876
#endif
1877
    p = s->mem + s->rsar;
1878
    if (s->dcfg & 0x01) {
1879
        /* 16 bit access */
1880
        p[0] = val;
1881
        p[1] = val >> 8;
1882
        s->rsar += 2;
1883
        s->rcnt -= 2;
1884
    } else {
1885
        /* 8 bit access */
1886
        p[0] = val;
1887
        s->rsar++;
1888
        s->rcnt--;
1889
    }
1890
    /* wrap */
1891
    if (s->rsar == s->stop)
1892
        s->rsar = s->start;
1893
    if (s->rcnt == 0) {
1894
        /* signal end of transfert */
1895
        s->isr |= ENISR_RDC;
1896
        ne2000_update_irq(s);
1897
    }
1898
}
1899

    
1900
uint32_t ne2000_asic_ioport_read(CPUX86State *env, uint32_t addr)
1901
{
1902
    NE2000State *s = &ne2000_state;
1903
    uint8_t *p;
1904
    int ret;
1905

    
1906
    p = s->mem + s->rsar;
1907
    if (s->dcfg & 0x01) {
1908
        /* 16 bit access */
1909
        ret = p[0] | (p[1] << 8);
1910
        s->rsar += 2;
1911
        s->rcnt -= 2;
1912
    } else {
1913
        /* 8 bit access */
1914
        ret = p[0];
1915
        s->rsar++;
1916
        s->rcnt--;
1917
    }
1918
    /* wrap */
1919
    if (s->rsar == s->stop)
1920
        s->rsar = s->start;
1921
    if (s->rcnt == 0) {
1922
        /* signal end of transfert */
1923
        s->isr |= ENISR_RDC;
1924
        ne2000_update_irq(s);
1925
    }
1926
#ifdef DEBUG_NE2000
1927
    printf("NE2000: asic read val=0x%04x\n", ret);
1928
#endif
1929
    return ret;
1930
}
1931

    
1932
void ne2000_reset_ioport_write(CPUX86State *env, uint32_t addr, uint32_t val)
1933
{
1934
    /* nothing to do (end of reset pulse) */
1935
}
1936

    
1937
uint32_t ne2000_reset_ioport_read(CPUX86State *env, uint32_t addr)
1938
{
1939
    ne2000_reset();
1940
    return 0;
1941
}
1942

    
1943
void ne2000_init(void)
1944
{
1945
    register_ioport_write(NE2000_IOPORT, 16, ne2000_ioport_write, 1);
1946
    register_ioport_read(NE2000_IOPORT, 16, ne2000_ioport_read, 1);
1947

    
1948
    register_ioport_write(NE2000_IOPORT + 0x10, 1, ne2000_asic_ioport_write, 1);
1949
    register_ioport_read(NE2000_IOPORT + 0x10, 1, ne2000_asic_ioport_read, 1);
1950
    register_ioport_write(NE2000_IOPORT + 0x10, 2, ne2000_asic_ioport_write, 2);
1951
    register_ioport_read(NE2000_IOPORT + 0x10, 2, ne2000_asic_ioport_read, 2);
1952

    
1953
    register_ioport_write(NE2000_IOPORT + 0x1f, 1, ne2000_reset_ioport_write, 1);
1954
    register_ioport_read(NE2000_IOPORT + 0x1f, 1, ne2000_reset_ioport_read, 1);
1955
    ne2000_reset();
1956
}
1957

    
1958
/***********************************************************/
1959
/* keyboard emulation */
1960

    
1961
/*        Keyboard Controller Commands */
1962
#define KBD_CCMD_READ_MODE        0x20        /* Read mode bits */
1963
#define KBD_CCMD_WRITE_MODE        0x60        /* Write mode bits */
1964
#define KBD_CCMD_GET_VERSION        0xA1        /* Get controller version */
1965
#define KBD_CCMD_MOUSE_DISABLE        0xA7        /* Disable mouse interface */
1966
#define KBD_CCMD_MOUSE_ENABLE        0xA8        /* Enable mouse interface */
1967
#define KBD_CCMD_TEST_MOUSE        0xA9        /* Mouse interface test */
1968
#define KBD_CCMD_SELF_TEST        0xAA        /* Controller self test */
1969
#define KBD_CCMD_KBD_TEST        0xAB        /* Keyboard interface test */
1970
#define KBD_CCMD_KBD_DISABLE        0xAD        /* Keyboard interface disable */
1971
#define KBD_CCMD_KBD_ENABLE        0xAE        /* Keyboard interface enable */
1972
#define KBD_CCMD_READ_INPORT    0xC0    /* read input port */
1973
#define KBD_CCMD_READ_OUTPORT        0xD0    /* read output port */
1974
#define KBD_CCMD_WRITE_OUTPORT        0xD1    /* write output port */
1975
#define KBD_CCMD_WRITE_OBUF        0xD2
1976
#define KBD_CCMD_WRITE_AUX_OBUF        0xD3    /* Write to output buffer as if
1977
                                           initiated by the auxiliary device */
1978
#define KBD_CCMD_WRITE_MOUSE        0xD4        /* Write the following byte to the mouse */
1979
#define KBD_CCMD_DISABLE_A20    0xDD    /* HP vectra only ? */
1980
#define KBD_CCMD_ENABLE_A20     0xDF    /* HP vectra only ? */
1981
#define KBD_CCMD_RESET                0xFE
1982

    
1983
/* Keyboard Commands */
1984
#define KBD_CMD_SET_LEDS        0xED        /* Set keyboard leds */
1985
#define KBD_CMD_ECHO             0xEE
1986
#define KBD_CMD_GET_ID                 0xF2        /* get keyboard ID */
1987
#define KBD_CMD_SET_RATE        0xF3        /* Set typematic rate */
1988
#define KBD_CMD_ENABLE                0xF4        /* Enable scanning */
1989
#define KBD_CMD_RESET_DISABLE        0xF5        /* reset and disable scanning */
1990
#define KBD_CMD_RESET_ENABLE           0xF6    /* reset and enable scanning */
1991
#define KBD_CMD_RESET                0xFF        /* Reset */
1992

    
1993
/* Keyboard Replies */
1994
#define KBD_REPLY_POR                0xAA        /* Power on reset */
1995
#define KBD_REPLY_ACK                0xFA        /* Command ACK */
1996
#define KBD_REPLY_RESEND        0xFE        /* Command NACK, send the cmd again */
1997

    
1998
/* Status Register Bits */
1999
#define KBD_STAT_OBF                 0x01        /* Keyboard output buffer full */
2000
#define KBD_STAT_IBF                 0x02        /* Keyboard input buffer full */
2001
#define KBD_STAT_SELFTEST        0x04        /* Self test successful */
2002
#define KBD_STAT_CMD                0x08        /* Last write was a command write (0=data) */
2003
#define KBD_STAT_UNLOCKED        0x10        /* Zero if keyboard locked */
2004
#define KBD_STAT_MOUSE_OBF        0x20        /* Mouse output buffer full */
2005
#define KBD_STAT_GTO                 0x40        /* General receive/xmit timeout */
2006
#define KBD_STAT_PERR                 0x80        /* Parity error */
2007

    
2008
/* Controller Mode Register Bits */
2009
#define KBD_MODE_KBD_INT        0x01        /* Keyboard data generate IRQ1 */
2010
#define KBD_MODE_MOUSE_INT        0x02        /* Mouse data generate IRQ12 */
2011
#define KBD_MODE_SYS                 0x04        /* The system flag (?) */
2012
#define KBD_MODE_NO_KEYLOCK        0x08        /* The keylock doesn't affect the keyboard if set */
2013
#define KBD_MODE_DISABLE_KBD        0x10        /* Disable keyboard interface */
2014
#define KBD_MODE_DISABLE_MOUSE        0x20        /* Disable mouse interface */
2015
#define KBD_MODE_KCC                 0x40        /* Scan code conversion to PC format */
2016
#define KBD_MODE_RFU                0x80
2017

    
2018
/* Mouse Commands */
2019
#define AUX_SET_SCALE11                0xE6        /* Set 1:1 scaling */
2020
#define AUX_SET_SCALE21                0xE7        /* Set 2:1 scaling */
2021
#define AUX_SET_RES                0xE8        /* Set resolution */
2022
#define AUX_GET_SCALE                0xE9        /* Get scaling factor */
2023
#define AUX_SET_STREAM                0xEA        /* Set stream mode */
2024
#define AUX_POLL                0xEB        /* Poll */
2025
#define AUX_RESET_WRAP                0xEC        /* Reset wrap mode */
2026
#define AUX_SET_WRAP                0xEE        /* Set wrap mode */
2027
#define AUX_SET_REMOTE                0xF0        /* Set remote mode */
2028
#define AUX_GET_TYPE                0xF2        /* Get type */
2029
#define AUX_SET_SAMPLE                0xF3        /* Set sample rate */
2030
#define AUX_ENABLE_DEV                0xF4        /* Enable aux device */
2031
#define AUX_DISABLE_DEV                0xF5        /* Disable aux device */
2032
#define AUX_SET_DEFAULT                0xF6
2033
#define AUX_RESET                0xFF        /* Reset aux device */
2034
#define AUX_ACK                        0xFA        /* Command byte ACK. */
2035

    
2036
#define MOUSE_STATUS_REMOTE     0x40
2037
#define MOUSE_STATUS_ENABLED    0x20
2038
#define MOUSE_STATUS_SCALE21    0x10
2039

    
2040
#define KBD_QUEUE_SIZE 256
2041

    
2042
typedef struct {
2043
    uint8_t data[KBD_QUEUE_SIZE];
2044
    int rptr, wptr, count;
2045
} KBDQueue;
2046

    
2047
typedef struct KBDState {
2048
    KBDQueue queues[2];
2049
    uint8_t write_cmd; /* if non zero, write data to port 60 is expected */
2050
    uint8_t status;
2051
    uint8_t mode;
2052
    /* keyboard state */
2053
    int kbd_write_cmd;
2054
    int scan_enabled;
2055
    /* mouse state */
2056
    int mouse_write_cmd;
2057
    uint8_t mouse_status;
2058
    uint8_t mouse_resolution;
2059
    uint8_t mouse_sample_rate;
2060
    uint8_t mouse_wrap;
2061
    uint8_t mouse_type; /* 0 = PS2, 3 = IMPS/2, 4 = IMEX */
2062
    uint8_t mouse_detect_state;
2063
    int mouse_dx; /* current values, needed for 'poll' mode */
2064
    int mouse_dy;
2065
    int mouse_dz;
2066
    uint8_t mouse_buttons;
2067
} KBDState;
2068

    
2069
KBDState kbd_state;
2070
int reset_requested;
2071

    
2072
/* update irq and KBD_STAT_[MOUSE_]OBF */
2073
/* XXX: not generating the irqs if KBD_MODE_DISABLE_KBD is set may be
2074
   incorrect, but it avoids having to simulate exact delays */
2075
static void kbd_update_irq(KBDState *s)
2076
{
2077
    int irq12_level, irq1_level;
2078

    
2079
    irq1_level = 0;    
2080
    irq12_level = 0;    
2081
    s->status &= ~(KBD_STAT_OBF | KBD_STAT_MOUSE_OBF);
2082
    if (s->queues[0].count != 0 ||
2083
        s->queues[1].count != 0) {
2084
        s->status |= KBD_STAT_OBF;
2085
        if (s->queues[1].count != 0) {
2086
            s->status |= KBD_STAT_MOUSE_OBF;
2087
            if (s->mode & KBD_MODE_MOUSE_INT)
2088
                irq12_level = 1;
2089
        } else {
2090
            if ((s->mode & KBD_MODE_KBD_INT) && 
2091
                !(s->mode & KBD_MODE_DISABLE_KBD))
2092
                irq1_level = 1;
2093
        }
2094
    }
2095
    pic_set_irq(1, irq1_level);
2096
    pic_set_irq(12, irq12_level);
2097
}
2098

    
2099
static void kbd_queue(KBDState *s, int b, int aux)
2100
{
2101
    KBDQueue *q = &kbd_state.queues[aux];
2102

    
2103
#if defined(DEBUG_MOUSE) || defined(DEBUG_KBD)
2104
    if (aux)
2105
        printf("mouse event: 0x%02x\n", b);
2106
#ifdef DEBUG_KBD
2107
    else
2108
        printf("kbd event: 0x%02x\n", b);
2109
#endif
2110
#endif
2111
    if (q->count >= KBD_QUEUE_SIZE)
2112
        return;
2113
    q->data[q->wptr] = b;
2114
    if (++q->wptr == KBD_QUEUE_SIZE)
2115
        q->wptr = 0;
2116
    q->count++;
2117
    kbd_update_irq(s);
2118
}
2119

    
2120
void kbd_put_keycode(int keycode)
2121
{
2122
    KBDState *s = &kbd_state;
2123
    kbd_queue(s, keycode, 0);
2124
}
2125

    
2126
uint32_t kbd_read_status(CPUX86State *env, uint32_t addr)
2127
{
2128
    KBDState *s = &kbd_state;
2129
    int val;
2130
    val = s->status;
2131
#if defined(DEBUG_KBD)
2132
    printf("kbd: read status=0x%02x\n", val);
2133
#endif
2134
    return val;
2135
}
2136

    
2137
void kbd_write_command(CPUX86State *env, uint32_t addr, uint32_t val)
2138
{
2139
    KBDState *s = &kbd_state;
2140

    
2141
#ifdef DEBUG_KBD
2142
    printf("kbd: write cmd=0x%02x\n", val);
2143
#endif
2144
    switch(val) {
2145
    case KBD_CCMD_READ_MODE:
2146
        kbd_queue(s, s->mode, 0);
2147
        break;
2148
    case KBD_CCMD_WRITE_MODE:
2149
    case KBD_CCMD_WRITE_OBUF:
2150
    case KBD_CCMD_WRITE_AUX_OBUF:
2151
    case KBD_CCMD_WRITE_MOUSE:
2152
    case KBD_CCMD_WRITE_OUTPORT:
2153
        s->write_cmd = val;
2154
        break;
2155
    case KBD_CCMD_MOUSE_DISABLE:
2156
        s->mode |= KBD_MODE_DISABLE_MOUSE;
2157
        break;
2158
    case KBD_CCMD_MOUSE_ENABLE:
2159
        s->mode &= ~KBD_MODE_DISABLE_MOUSE;
2160
        break;
2161
    case KBD_CCMD_TEST_MOUSE:
2162
        kbd_queue(s, 0x00, 0);
2163
        break;
2164
    case KBD_CCMD_SELF_TEST:
2165
        s->status |= KBD_STAT_SELFTEST;
2166
        kbd_queue(s, 0x55, 0);
2167
        break;
2168
    case KBD_CCMD_KBD_TEST:
2169
        kbd_queue(s, 0x00, 0);
2170
        break;
2171
    case KBD_CCMD_KBD_DISABLE:
2172
        s->mode |= KBD_MODE_DISABLE_KBD;
2173
        kbd_update_irq(s);
2174
        break;
2175
    case KBD_CCMD_KBD_ENABLE:
2176
        s->mode &= ~KBD_MODE_DISABLE_KBD;
2177
        kbd_update_irq(s);
2178
        break;
2179
    case KBD_CCMD_READ_INPORT:
2180
        kbd_queue(s, 0x00, 0);
2181
        break;
2182
    case KBD_CCMD_READ_OUTPORT:
2183
        /* XXX: check that */
2184
        val = 0x01 | (a20_enabled << 1);
2185
        if (s->status & KBD_STAT_OBF)
2186
            val |= 0x10;
2187
        if (s->status & KBD_STAT_MOUSE_OBF)
2188
            val |= 0x20;
2189
        kbd_queue(s, val, 0);
2190
        break;
2191
    case KBD_CCMD_ENABLE_A20:
2192
        cpu_x86_set_a20(env, 1);
2193
        break;
2194
    case KBD_CCMD_DISABLE_A20:
2195
        cpu_x86_set_a20(env, 0);
2196
        break;
2197
    case KBD_CCMD_RESET:
2198
        reset_requested = 1;
2199
        cpu_x86_interrupt(global_env, CPU_INTERRUPT_EXIT);
2200
        break;
2201
    case 0xff:
2202
        /* ignore that - I don't know what is its use */
2203
        break;
2204
    default:
2205
        fprintf(stderr, "qemu: unsupported keyboard cmd=0x%02x\n", val);
2206
        break;
2207
    }
2208
}
2209

    
2210
uint32_t kbd_read_data(CPUX86State *env, uint32_t addr)
2211
{
2212
    KBDState *s = &kbd_state;
2213
    KBDQueue *q;
2214
    int val, index;
2215
    
2216
    q = &s->queues[0]; /* first check KBD data */
2217
    if (q->count == 0)
2218
        q = &s->queues[1]; /* then check AUX data */
2219
    if (q->count == 0) {
2220
        /* NOTE: if no data left, we return the last keyboard one
2221
           (needed for EMM386) */
2222
        /* XXX: need a timer to do things correctly */
2223
        q = &s->queues[0];
2224
        index = q->rptr - 1;
2225
        if (index < 0)
2226
            index = KBD_QUEUE_SIZE - 1;
2227
        val = q->data[index];
2228
    } else {
2229
        val = q->data[q->rptr];
2230
        if (++q->rptr == KBD_QUEUE_SIZE)
2231
            q->rptr = 0;
2232
        q->count--;
2233
        /* reading deasserts IRQ */
2234
        if (q == &s->queues[0])
2235
            pic_set_irq(1, 0);
2236
        else
2237
            pic_set_irq(12, 0);
2238
    }
2239
    /* reassert IRQs if data left */
2240
    kbd_update_irq(s);
2241
#ifdef DEBUG_KBD
2242
    printf("kbd: read data=0x%02x\n", val);
2243
#endif
2244
    return val;
2245
}
2246

    
2247
static void kbd_reset_keyboard(KBDState *s)
2248
{
2249
    s->scan_enabled = 1;
2250
}
2251

    
2252
static void kbd_write_keyboard(KBDState *s, int val)
2253
{
2254
    switch(s->kbd_write_cmd) {
2255
    default:
2256
    case -1:
2257
        switch(val) {
2258
        case 0x00:
2259
            kbd_queue(s, KBD_REPLY_ACK, 0);
2260
            break;
2261
        case 0x05:
2262
            kbd_queue(s, KBD_REPLY_RESEND, 0);
2263
            break;
2264
        case KBD_CMD_GET_ID:
2265
            kbd_queue(s, KBD_REPLY_ACK, 0);
2266
            kbd_queue(s, 0xab, 0);
2267
            kbd_queue(s, 0x83, 0);
2268
            break;
2269
        case KBD_CMD_ECHO:
2270
            kbd_queue(s, KBD_CMD_ECHO, 0);
2271
            break;
2272
        case KBD_CMD_ENABLE:
2273
            s->scan_enabled = 1;
2274
            kbd_queue(s, KBD_REPLY_ACK, 0);
2275
            break;
2276
        case KBD_CMD_SET_LEDS:
2277
        case KBD_CMD_SET_RATE:
2278
            s->kbd_write_cmd = val;
2279
            kbd_queue(s, KBD_REPLY_ACK, 0);
2280
            break;
2281
        case KBD_CMD_RESET_DISABLE:
2282
            kbd_reset_keyboard(s);
2283
            s->scan_enabled = 0;
2284
            kbd_queue(s, KBD_REPLY_ACK, 0);
2285
            break;
2286
        case KBD_CMD_RESET_ENABLE:
2287
            kbd_reset_keyboard(s);
2288
            s->scan_enabled = 1;
2289
            kbd_queue(s, KBD_REPLY_ACK, 0);
2290
            break;
2291
        case KBD_CMD_RESET:
2292
            kbd_reset_keyboard(s);
2293
            kbd_queue(s, KBD_REPLY_ACK, 0);
2294
            kbd_queue(s, KBD_REPLY_POR, 0);
2295
            break;
2296
        default:
2297
            kbd_queue(s, KBD_REPLY_ACK, 0);
2298
            break;
2299
        }
2300
        break;
2301
    case KBD_CMD_SET_LEDS:
2302
        kbd_queue(s, KBD_REPLY_ACK, 0);
2303
        s->kbd_write_cmd = -1;
2304
        break;
2305
    case KBD_CMD_SET_RATE:
2306
        kbd_queue(s, KBD_REPLY_ACK, 0);
2307
        s->kbd_write_cmd = -1;
2308
        break;
2309
    }
2310
}
2311

    
2312
static void kbd_mouse_send_packet(KBDState *s)
2313
{
2314
    unsigned int b;
2315
    int dx1, dy1, dz1;
2316

    
2317
    dx1 = s->mouse_dx;
2318
    dy1 = s->mouse_dy;
2319
    dz1 = s->mouse_dz;
2320
    /* XXX: increase range to 8 bits ? */
2321
    if (dx1 > 127)
2322
        dx1 = 127;
2323
    else if (dx1 < -127)
2324
        dx1 = -127;
2325
    if (dy1 > 127)
2326
        dy1 = 127;
2327
    else if (dy1 < -127)
2328
        dy1 = -127;
2329
    b = 0x08 | ((dx1 < 0) << 4) | ((dy1 < 0) << 5) | (s->mouse_buttons & 0x07);
2330
    kbd_queue(s, b, 1);
2331
    kbd_queue(s, dx1 & 0xff, 1);
2332
    kbd_queue(s, dy1 & 0xff, 1);
2333
    /* extra byte for IMPS/2 or IMEX */
2334
    switch(s->mouse_type) {
2335
    default:
2336
        break;
2337
    case 3:
2338
        if (dz1 > 127)
2339
            dz1 = 127;
2340
        else if (dz1 < -127)
2341
                dz1 = -127;
2342
        kbd_queue(s, dz1 & 0xff, 1);
2343
        break;
2344
    case 4:
2345
        if (dz1 > 7)
2346
            dz1 = 7;
2347
        else if (dz1 < -7)
2348
            dz1 = -7;
2349
        b = (dz1 & 0x0f) | ((s->mouse_buttons & 0x18) << 1);
2350
        kbd_queue(s, b, 1);
2351
        break;
2352
    }
2353

    
2354
    /* update deltas */
2355
    s->mouse_dx -= dx1;
2356
    s->mouse_dy -= dy1;
2357
    s->mouse_dz -= dz1;
2358
}
2359

    
2360
void kbd_mouse_event(int dx, int dy, int dz, int buttons_state)
2361
{
2362
    KBDState *s = &kbd_state;
2363

    
2364
    /* check if deltas are recorded when disabled */
2365
    if (!(s->mouse_status & MOUSE_STATUS_ENABLED))
2366
        return;
2367

    
2368
    s->mouse_dx += dx;
2369
    s->mouse_dy -= dy;
2370
    s->mouse_dz += dz;
2371
    s->mouse_buttons = buttons_state;
2372
    
2373
    if (!(s->mouse_status & MOUSE_STATUS_REMOTE) &&
2374
        (s->queues[1].count < (KBD_QUEUE_SIZE - 16))) {
2375
        for(;;) {
2376
            /* if not remote, send event. Multiple events are sent if
2377
               too big deltas */
2378
            kbd_mouse_send_packet(s);
2379
            if (s->mouse_dx == 0 && s->mouse_dy == 0 && s->mouse_dz == 0)
2380
                break;
2381
        }
2382
    }
2383
}
2384

    
2385
static void kbd_write_mouse(KBDState *s, int val)
2386
{
2387
#ifdef DEBUG_MOUSE
2388
    printf("kbd: write mouse 0x%02x\n", val);
2389
#endif
2390
    switch(s->mouse_write_cmd) {
2391
    default:
2392
    case -1:
2393
        /* mouse command */
2394
        if (s->mouse_wrap) {
2395
            if (val == AUX_RESET_WRAP) {
2396
                s->mouse_wrap = 0;
2397
                kbd_queue(s, AUX_ACK, 1);
2398
                return;
2399
            } else if (val != AUX_RESET) {
2400
                kbd_queue(s, val, 1);
2401
                return;
2402
            }
2403
        }
2404
        switch(val) {
2405
        case AUX_SET_SCALE11:
2406
            s->mouse_status &= ~MOUSE_STATUS_SCALE21;
2407
            kbd_queue(s, AUX_ACK, 1);
2408
            break;
2409
        case AUX_SET_SCALE21:
2410
            s->mouse_status |= MOUSE_STATUS_SCALE21;
2411
            kbd_queue(s, AUX_ACK, 1);
2412
            break;
2413
        case AUX_SET_STREAM:
2414
            s->mouse_status &= ~MOUSE_STATUS_REMOTE;
2415
            kbd_queue(s, AUX_ACK, 1);
2416
            break;
2417
        case AUX_SET_WRAP:
2418
            s->mouse_wrap = 1;
2419
            kbd_queue(s, AUX_ACK, 1);
2420
            break;
2421
        case AUX_SET_REMOTE:
2422
            s->mouse_status |= MOUSE_STATUS_REMOTE;
2423
            kbd_queue(s, AUX_ACK, 1);
2424
            break;
2425
        case AUX_GET_TYPE:
2426
            kbd_queue(s, AUX_ACK, 1);
2427
            kbd_queue(s, s->mouse_type, 1);
2428
            break;
2429
        case AUX_SET_RES:
2430
        case AUX_SET_SAMPLE:
2431
            s->mouse_write_cmd = val;
2432
            kbd_queue(s, AUX_ACK, 1);
2433
            break;
2434
        case AUX_GET_SCALE:
2435
            kbd_queue(s, AUX_ACK, 1);
2436
            kbd_queue(s, s->mouse_status, 1);
2437
            kbd_queue(s, s->mouse_resolution, 1);
2438
            kbd_queue(s, s->mouse_sample_rate, 1);
2439
            break;
2440
        case AUX_POLL:
2441
            kbd_queue(s, AUX_ACK, 1);
2442
            kbd_mouse_send_packet(s);
2443
            break;
2444
        case AUX_ENABLE_DEV:
2445
            s->mouse_status |= MOUSE_STATUS_ENABLED;
2446
            kbd_queue(s, AUX_ACK, 1);
2447
            break;
2448
        case AUX_DISABLE_DEV:
2449
            s->mouse_status &= ~MOUSE_STATUS_ENABLED;
2450
            kbd_queue(s, AUX_ACK, 1);
2451
            break;
2452
        case AUX_SET_DEFAULT:
2453
            s->mouse_sample_rate = 100;
2454
            s->mouse_resolution = 2;
2455
            s->mouse_status = 0;
2456
            kbd_queue(s, AUX_ACK, 1);
2457
            break;
2458
        case AUX_RESET:
2459
            s->mouse_sample_rate = 100;
2460
            s->mouse_resolution = 2;
2461
            s->mouse_status = 0;
2462
            kbd_queue(s, AUX_ACK, 1);
2463
            kbd_queue(s, 0xaa, 1);
2464
            kbd_queue(s, s->mouse_type, 1);
2465
            break;
2466
        default:
2467
            break;
2468
        }
2469
        break;
2470
    case AUX_SET_SAMPLE:
2471
        s->mouse_sample_rate = val;
2472
#if 0
2473
        /* detect IMPS/2 or IMEX */
2474
        switch(s->mouse_detect_state) {
2475
        default:
2476
        case 0:
2477
            if (val == 200)
2478
                s->mouse_detect_state = 1;
2479
            break;
2480
        case 1:
2481
            if (val == 100)
2482
                s->mouse_detect_state = 2;
2483
            else if (val == 200)
2484
                s->mouse_detect_state = 3;
2485
            else
2486
                s->mouse_detect_state = 0;
2487
            break;
2488
        case 2:
2489
            if (val == 80) 
2490
                s->mouse_type = 3; /* IMPS/2 */
2491
            s->mouse_detect_state = 0;
2492
            break;
2493
        case 3:
2494
            if (val == 80) 
2495
                s->mouse_type = 4; /* IMEX */
2496
            s->mouse_detect_state = 0;
2497
            break;
2498
        }
2499
#endif
2500
        kbd_queue(s, AUX_ACK, 1);
2501
        s->mouse_write_cmd = -1;
2502
        break;
2503
    case AUX_SET_RES:
2504
        s->mouse_resolution = val;
2505
        kbd_queue(s, AUX_ACK, 1);
2506
        s->mouse_write_cmd = -1;
2507
        break;
2508
    }
2509
}
2510

    
2511
void kbd_write_data(CPUX86State *env, uint32_t addr, uint32_t val)
2512
{
2513
    KBDState *s = &kbd_state;
2514

    
2515
#ifdef DEBUG_KBD
2516
    printf("kbd: write data=0x%02x\n", val);
2517
#endif
2518

    
2519
    switch(s->write_cmd) {
2520
    case 0:
2521
        kbd_write_keyboard(s, val);
2522
        break;
2523
    case KBD_CCMD_WRITE_MODE:
2524
        s->mode = val;
2525
        kbd_update_irq(s);
2526
        break;
2527
    case KBD_CCMD_WRITE_OBUF:
2528
        kbd_queue(s, val, 0);
2529
        break;
2530
    case KBD_CCMD_WRITE_AUX_OBUF:
2531
        kbd_queue(s, val, 1);
2532
        break;
2533
    case KBD_CCMD_WRITE_OUTPORT:
2534
        cpu_x86_set_a20(env, (val >> 1) & 1);
2535
        if (!(val & 1)) {
2536
            reset_requested = 1;
2537
            cpu_x86_interrupt(global_env, CPU_INTERRUPT_EXIT);
2538
        }
2539
        break;
2540
    case KBD_CCMD_WRITE_MOUSE:
2541
        kbd_write_mouse(s, val);
2542
        break;
2543
    default:
2544
        break;
2545
    }
2546
    s->write_cmd = 0;
2547
}
2548

    
2549
void kbd_reset(KBDState *s)
2550
{
2551
    KBDQueue *q;
2552
    int i;
2553

    
2554
    s->kbd_write_cmd = -1;
2555
    s->mouse_write_cmd = -1;
2556
    s->mode = KBD_MODE_KBD_INT | KBD_MODE_MOUSE_INT;
2557
    s->status = KBD_STAT_CMD | KBD_STAT_UNLOCKED;
2558
    for(i = 0; i < 2; i++) {
2559
        q = &s->queues[i];
2560
        q->rptr = 0;
2561
        q->wptr = 0;
2562
        q->count = 0;
2563
    }
2564
}
2565

    
2566
void kbd_init(void)
2567
{
2568
    kbd_reset(&kbd_state);
2569
    register_ioport_read(0x60, 1, kbd_read_data, 1);
2570
    register_ioport_write(0x60, 1, kbd_write_data, 1);
2571
    register_ioport_read(0x64, 1, kbd_read_status, 1);
2572
    register_ioport_write(0x64, 1, kbd_write_command, 1);
2573
}
2574

    
2575
/***********************************************************/
2576
/* Bochs BIOS debug ports */
2577

    
2578
void bochs_bios_write(CPUX86State *env, uint32_t addr, uint32_t val)
2579
{
2580
    switch(addr) {
2581
        /* Bochs BIOS messages */
2582
    case 0x400:
2583
    case 0x401:
2584
        fprintf(stderr, "BIOS panic at rombios.c, line %d\n", val);
2585
        exit(1);
2586
    case 0x402:
2587
    case 0x403:
2588
#ifdef DEBUG_BIOS
2589
        fprintf(stderr, "%c", val);
2590
#endif
2591
        break;
2592

    
2593
        /* LGPL'ed VGA BIOS messages */
2594
    case 0x501:
2595
    case 0x502:
2596
        fprintf(stderr, "VGA BIOS panic, line %d\n", val);
2597
        exit(1);
2598
    case 0x500:
2599
    case 0x503:
2600
#ifdef DEBUG_BIOS
2601
        fprintf(stderr, "%c", val);
2602
#endif
2603
        break;
2604
    }
2605
}
2606

    
2607
void bochs_bios_init(void)
2608
{
2609
    register_ioport_write(0x400, 1, bochs_bios_write, 2);
2610
    register_ioport_write(0x401, 1, bochs_bios_write, 2);
2611
    register_ioport_write(0x402, 1, bochs_bios_write, 1);
2612
    register_ioport_write(0x403, 1, bochs_bios_write, 1);
2613

    
2614
    register_ioport_write(0x501, 1, bochs_bios_write, 2);
2615
    register_ioport_write(0x502, 1, bochs_bios_write, 2);
2616
    register_ioport_write(0x500, 1, bochs_bios_write, 1);
2617
    register_ioport_write(0x503, 1, bochs_bios_write, 1);
2618
}
2619

    
2620
/***********************************************************/
2621
/* dumb display */
2622

    
2623
/* init terminal so that we can grab keys */
2624
static struct termios oldtty;
2625

    
2626
static void term_exit(void)
2627
{
2628
    tcsetattr (0, TCSANOW, &oldtty);
2629
}
2630

    
2631
static void term_init(void)
2632
{
2633
    struct termios tty;
2634

    
2635
    tcgetattr (0, &tty);
2636
    oldtty = tty;
2637

    
2638
    tty.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP
2639
                          |INLCR|IGNCR|ICRNL|IXON);
2640
    tty.c_oflag |= OPOST;
2641
    tty.c_lflag &= ~(ECHO|ECHONL|ICANON|IEXTEN);
2642
    /* if graphical mode, we allow Ctrl-C handling */
2643
    if (nographic)
2644
        tty.c_lflag &= ~ISIG;
2645
    tty.c_cflag &= ~(CSIZE|PARENB);
2646
    tty.c_cflag |= CS8;
2647
    tty.c_cc[VMIN] = 1;
2648
    tty.c_cc[VTIME] = 0;
2649
    
2650
    tcsetattr (0, TCSANOW, &tty);
2651

    
2652
    atexit(term_exit);
2653

    
2654
    fcntl(0, F_SETFL, O_NONBLOCK);
2655
}
2656

    
2657
static void dumb_update(DisplayState *ds, int x, int y, int w, int h)
2658
{
2659
}
2660

    
2661
static void dumb_resize(DisplayState *ds, int w, int h)
2662
{
2663
}
2664

    
2665
static void dumb_refresh(DisplayState *ds)
2666
{
2667
    vga_update_display();
2668
}
2669

    
2670
void dumb_display_init(DisplayState *ds)
2671
{
2672
    ds->data = NULL;
2673
    ds->linesize = 0;
2674
    ds->depth = 0;
2675
    ds->dpy_update = dumb_update;
2676
    ds->dpy_resize = dumb_resize;
2677
    ds->dpy_refresh = dumb_refresh;
2678
}
2679

    
2680
#if !defined(CONFIG_SOFTMMU)
2681
/***********************************************************/
2682
/* cpu signal handler */
2683
static void host_segv_handler(int host_signum, siginfo_t *info, 
2684
                              void *puc)
2685
{
2686
    if (cpu_signal_handler(host_signum, info, puc))
2687
        return;
2688
    term_exit();
2689
    abort();
2690
}
2691
#endif
2692

    
2693
static int timer_irq_pending;
2694
static int timer_irq_count;
2695

    
2696
static int timer_ms;
2697
static int gui_refresh_pending, gui_refresh_count;
2698

    
2699
static void host_alarm_handler(int host_signum, siginfo_t *info, 
2700
                               void *puc)
2701
{
2702
    /* NOTE: since usually the OS asks a 100 Hz clock, there can be
2703
       some drift between cpu_get_ticks() and the interrupt time. So
2704
       we queue some interrupts to avoid missing some */
2705
    timer_irq_count += pit_get_out_edges(&pit_channels[0]);
2706
    if (timer_irq_count) {
2707
        if (timer_irq_count > 2)
2708
            timer_irq_count = 2;
2709
        timer_irq_count--;
2710
        timer_irq_pending = 1;
2711
    }
2712
    gui_refresh_count += timer_ms;
2713
    if (gui_refresh_count >= GUI_REFRESH_INTERVAL) {
2714
        gui_refresh_count = 0;
2715
        gui_refresh_pending = 1;
2716
    }
2717

    
2718
    /* XXX: seems dangerous to run that here. */
2719
    DMA_run();
2720
    SB16_run();
2721

    
2722
    if (gui_refresh_pending || timer_irq_pending) {
2723
        /* just exit from the cpu to have a chance to handle timers */
2724
        cpu_x86_interrupt(global_env, CPU_INTERRUPT_EXIT);
2725
    }
2726
}
2727

    
2728
#ifdef CONFIG_SOFTMMU
2729
void *get_mmap_addr(unsigned long size)
2730
{
2731
    return NULL;
2732
}
2733
#else
2734
unsigned long mmap_addr = PHYS_RAM_BASE;
2735

    
2736
void *get_mmap_addr(unsigned long size)
2737
{
2738
    unsigned long addr;
2739
    addr = mmap_addr;
2740
    mmap_addr += ((size + 4095) & ~4095) + 4096;
2741
    return (void *)addr;
2742
}
2743
#endif
2744

    
2745
/* main execution loop */
2746

    
2747
CPUState *cpu_gdbstub_get_env(void *opaque)
2748
{
2749
    return global_env;
2750
}
2751

    
2752
int main_loop(void *opaque)
2753
{
2754
    struct pollfd ufds[3], *pf, *serial_ufd, *net_ufd, *gdb_ufd;
2755
    int ret, n, timeout, serial_ok;
2756
    uint8_t ch;
2757
    CPUState *env = global_env;
2758

    
2759
    if (!term_inited) {
2760
        /* initialize terminal only there so that the user has a
2761
           chance to stop QEMU with Ctrl-C before the gdb connection
2762
           is launched */
2763
        term_inited = 1;
2764
        term_init();
2765
    }
2766

    
2767
    serial_ok = 1;
2768
    cpu_enable_ticks();
2769
    for(;;) {
2770
        ret = cpu_x86_exec(env);
2771
        if (reset_requested) {
2772
            ret = EXCP_INTERRUPT; 
2773
            break;
2774
        }
2775
        if (ret == EXCP_DEBUG) {
2776
            ret = EXCP_DEBUG;
2777
            break;
2778
        }
2779
        /* if hlt instruction, we wait until the next IRQ */
2780
        if (ret == EXCP_HLT) 
2781
            timeout = 10;
2782
        else
2783
            timeout = 0;
2784
        /* poll any events */
2785
        serial_ufd = NULL;
2786
        pf = ufds;
2787
        if (serial_ok && !(serial_ports[0].lsr & UART_LSR_DR)) {
2788
            serial_ufd = pf;
2789
            pf->fd = 0;
2790
            pf->events = POLLIN;
2791
            pf++;
2792
        }
2793
        net_ufd = NULL;
2794
        if (net_fd > 0 && ne2000_can_receive(&ne2000_state)) {
2795
            net_ufd = pf;
2796
            pf->fd = net_fd;
2797
            pf->events = POLLIN;
2798
            pf++;
2799
        }
2800
        gdb_ufd = NULL;
2801
        if (gdbstub_fd > 0) {
2802
            gdb_ufd = pf;
2803
            pf->fd = gdbstub_fd;
2804
            pf->events = POLLIN;
2805
            pf++;
2806
        }
2807

    
2808
        ret = poll(ufds, pf - ufds, timeout);
2809
        if (ret > 0) {
2810
            if (serial_ufd && (serial_ufd->revents & POLLIN)) {
2811
                n = read(0, &ch, 1);
2812
                if (n == 1) {
2813
                    serial_received_byte(&serial_ports[0], ch);
2814
                } else {
2815
                    /* Closed, stop polling. */
2816
                    serial_ok = 0;
2817
                }
2818
            }
2819
            if (net_ufd && (net_ufd->revents & POLLIN)) {
2820
                uint8_t buf[MAX_ETH_FRAME_SIZE];
2821

    
2822
                n = read(net_fd, buf, MAX_ETH_FRAME_SIZE);
2823
                if (n > 0) {
2824
                    if (n < 60) {
2825
                        memset(buf + n, 0, 60 - n);
2826
                        n = 60;
2827
                    }
2828
                    ne2000_receive(&ne2000_state, buf, n);
2829
                }
2830
            }
2831
            if (gdb_ufd && (gdb_ufd->revents & POLLIN)) {
2832
                uint8_t buf[1];
2833
                /* stop emulation if requested by gdb */
2834
                n = read(gdbstub_fd, buf, 1);
2835
                if (n == 1) {
2836
                    ret = EXCP_INTERRUPT; 
2837
                    break;
2838
                }
2839
            }
2840
        }
2841

    
2842
        /* timer IRQ */
2843
        if (timer_irq_pending) {
2844
            pic_set_irq(0, 1);
2845
            pic_set_irq(0, 0);
2846
            timer_irq_pending = 0;
2847
            /* XXX: RTC test */
2848
            if (cmos_data[RTC_REG_B] & 0x50) {
2849
                pic_set_irq(8, 1);
2850
            }
2851
        }
2852

    
2853
        /* VGA */
2854
        if (gui_refresh_pending) {
2855
            display_state.dpy_refresh(&display_state);
2856
            gui_refresh_pending = 0;
2857
        }
2858
    }
2859
    cpu_disable_ticks();
2860
    return ret;
2861
}
2862

    
2863
void help(void)
2864
{
2865
    printf("QEMU PC emulator version " QEMU_VERSION ", Copyright (c) 2003 Fabrice Bellard\n"
2866
           "usage: %s [options] [disk_image]\n"
2867
           "\n"
2868
           "'disk_image' is a raw hard image image for IDE hard disk 0\n"
2869
           "\n"
2870
           "Standard options:\n"
2871
           "-hda/-hdb file  use 'file' as IDE hard disk 0/1 image\n"
2872
           "-hdc/-hdd file  use 'file' as IDE hard disk 2/3 image\n"
2873
           "-cdrom file     use 'file' as IDE cdrom 2 image\n"
2874
           "-boot [c|d]     boot on hard disk (c) or CD-ROM (d)\n"
2875
           "-snapshot       write to temporary files instead of disk image files\n"
2876
           "-m megs         set virtual RAM size to megs MB\n"
2877
           "-n script       set network init script [default=%s]\n"
2878
           "-tun-fd fd      this fd talks to tap/tun, use it.\n"
2879
           "-nographic      disable graphical output\n"
2880
           "\n"
2881
           "Linux boot specific (does not require PC BIOS):\n"
2882
           "-kernel bzImage use 'bzImage' as kernel image\n"
2883
           "-append cmdline use 'cmdline' as kernel command line\n"
2884
           "-initrd file    use 'file' as initial ram disk\n"
2885
           "\n"
2886
           "Debug/Expert options:\n"
2887
           "-s              wait gdb connection to port %d\n"
2888
           "-p port         change gdb connection port\n"
2889
           "-d              output log in /tmp/vl.log\n"
2890
           "-hdachs c,h,s   force hard disk 0 geometry (usually qemu can guess it)\n"
2891
           "-L path         set the directory for the BIOS and VGA BIOS\n"
2892
           "\n"
2893
           "During emulation, use C-a h to get terminal commands:\n",
2894
#ifdef CONFIG_SOFTMMU
2895
           "qemu",
2896
#else
2897
           "qemu-fast",
2898
#endif
2899
           DEFAULT_NETWORK_SCRIPT, 
2900
           DEFAULT_GDBSTUB_PORT);
2901
    term_print_help();
2902
#ifndef CONFIG_SOFTMMU
2903
    printf("\n"
2904
           "NOTE: this version of QEMU is faster but it needs slightly patched OSes to\n"
2905
           "work. Please use the 'qemu' executable to have a more accurate (but slower)\n"
2906
           "PC emulation.\n");
2907
#endif
2908
    exit(1);
2909
}
2910

    
2911
struct option long_options[] = {
2912
    { "initrd", 1, NULL, 0, },
2913
    { "hda", 1, NULL, 0, },
2914
    { "hdb", 1, NULL, 0, },
2915
    { "snapshot", 0, NULL, 0, },
2916
    { "hdachs", 1, NULL, 0, },
2917
    { "nographic", 0, NULL, 0, },
2918
    { "kernel", 1, NULL, 0, },
2919
    { "append", 1, NULL, 0, },
2920
    { "tun-fd", 1, NULL, 0, },
2921
    { "hdc", 1, NULL, 0, },
2922
    { "hdd", 1, NULL, 0, },
2923
    { "cdrom", 1, NULL, 0, },
2924
    { "boot", 1, NULL, 0, },
2925
    { NULL, 0, NULL, 0 },
2926
};
2927

    
2928
#ifdef CONFIG_SDL
2929
/* SDL use the pthreads and they modify sigaction. We don't
2930
   want that. */
2931
#if __GLIBC__ > 2 || (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 3)
2932
extern void __libc_sigaction();
2933
#define sigaction(sig, act, oact) __libc_sigaction(sig, act, oact)
2934
#else
2935
extern void __sigaction();
2936
#define sigaction(sig, act, oact) __sigaction(sig, act, oact)
2937
#endif
2938
#endif /* CONFIG_SDL */
2939

    
2940
int main(int argc, char **argv)
2941
{
2942
    int c, ret, initrd_size, i, use_gdbstub, gdbstub_port, long_index;
2943
    int snapshot, linux_boot, total_ram_size;
2944
    struct linux_params *params;
2945
    struct sigaction act;
2946
    struct itimerval itv;
2947
    CPUX86State *env;
2948
    const char *initrd_filename;
2949
    const char *hd_filename[MAX_DISKS];
2950
    const char *kernel_filename, *kernel_cmdline;
2951
    DisplayState *ds = &display_state;
2952

    
2953
    /* we never want that malloc() uses mmap() */
2954
    mallopt(M_MMAP_THRESHOLD, 4096 * 1024);
2955
    initrd_filename = NULL;
2956
    for(i = 0; i < MAX_DISKS; i++)
2957
        hd_filename[i] = NULL;
2958
    phys_ram_size = 32 * 1024 * 1024;
2959
    vga_ram_size = VGA_RAM_SIZE;
2960
    pstrcpy(network_script, sizeof(network_script), DEFAULT_NETWORK_SCRIPT);
2961
    use_gdbstub = 0;
2962
    gdbstub_port = DEFAULT_GDBSTUB_PORT;
2963
    snapshot = 0;
2964
    nographic = 0;
2965
    kernel_filename = NULL;
2966
    kernel_cmdline = "";
2967
    for(;;) {
2968
        c = getopt_long_only(argc, argv, "hm:dn:sp:L:", long_options, &long_index);
2969
        if (c == -1)
2970
            break;
2971
        switch(c) {
2972
        case 0:
2973
            switch(long_index) {
2974
            case 0:
2975
                initrd_filename = optarg;
2976
                break;
2977
            case 1:
2978
                hd_filename[0] = optarg;
2979
                break;
2980
            case 2:
2981
                hd_filename[1] = optarg;
2982
                break;
2983
            case 3:
2984
                snapshot = 1;
2985
                break;
2986
            case 4:
2987
                {
2988
                    int cyls, heads, secs;
2989
                    const char *p;
2990
                    p = optarg;
2991
                    cyls = strtol(p, (char **)&p, 0);
2992
                    if (*p != ',')
2993
                        goto chs_fail;
2994
                    p++;
2995
                    heads = strtol(p, (char **)&p, 0);
2996
                    if (*p != ',')
2997
                        goto chs_fail;
2998
                    p++;
2999
                    secs = strtol(p, (char **)&p, 0);
3000
                    if (*p != '\0')
3001
                        goto chs_fail;
3002
                    ide_set_geometry(0, cyls, heads, secs);
3003
                chs_fail: ;
3004
                }
3005
                break;
3006
            case 5:
3007
                nographic = 1;
3008
                break;
3009
            case 6:
3010
                kernel_filename = optarg;
3011
                break;
3012
            case 7:
3013
                kernel_cmdline = optarg;
3014
                break;
3015
            case 8:
3016
                net_fd = atoi(optarg);
3017
                break;
3018
            case 9:
3019
                hd_filename[2] = optarg;
3020
                break;
3021
            case 10:
3022
                hd_filename[3] = optarg;
3023
                break;
3024
            case 11:
3025
                hd_filename[2] = optarg;
3026
                ide_set_cdrom(2, 1);
3027
                break;
3028
            case 12:
3029
                boot_device = optarg[0];
3030
                if (boot_device != 'c' && boot_device != 'd') {
3031
                    fprintf(stderr, "qemu: invalid boot device '%c'\n", boot_device);
3032
                    exit(1);
3033
                }
3034
                break;
3035
            }
3036
            break;
3037
        case 'h':
3038
            help();
3039
            break;
3040
        case 'm':
3041
            phys_ram_size = atoi(optarg) * 1024 * 1024;
3042
            if (phys_ram_size <= 0)
3043
                help();
3044
            if (phys_ram_size > PHYS_RAM_MAX_SIZE) {
3045
                fprintf(stderr, "qemu: at most %d MB RAM can be simulated\n",
3046
                        PHYS_RAM_MAX_SIZE / (1024 * 1024));
3047
                exit(1);
3048
            }
3049
            break;
3050
        case 'd':
3051
            cpu_set_log(CPU_LOG_ALL);
3052
            break;
3053
        case 'n':
3054
            pstrcpy(network_script, sizeof(network_script), optarg);
3055
            break;
3056
        case 's':
3057
            use_gdbstub = 1;
3058
            break;
3059
        case 'p':
3060
            gdbstub_port = atoi(optarg);
3061
            break;
3062
        case 'L':
3063
            bios_dir = optarg;
3064
            break;
3065
        }
3066
    }
3067

    
3068
    if (optind < argc) {
3069
        hd_filename[0] = argv[optind++];
3070
    }
3071

    
3072
    linux_boot = (kernel_filename != NULL);
3073
        
3074
    if (!linux_boot && hd_filename[0] == '\0' && hd_filename[2] == '\0')
3075
        help();
3076
    
3077
    /* boot to cd by default if no hard disk */
3078
    if (hd_filename[0] == '\0' && boot_device == 'c')
3079
        boot_device = 'd';
3080

    
3081
    /* init debug */
3082
    setvbuf(stdout, NULL, _IOLBF, 0);
3083

    
3084
    /* init network tun interface */
3085
    if (net_fd < 0)
3086
        net_init();
3087

    
3088
    /* init the memory */
3089
    total_ram_size = phys_ram_size + vga_ram_size;
3090

    
3091
#ifdef CONFIG_SOFTMMU
3092
    phys_ram_base = malloc(total_ram_size);
3093
    if (!phys_ram_base) {
3094
        fprintf(stderr, "Could not allocate physical memory\n");
3095
        exit(1);
3096
    }
3097
#else
3098
    /* as we must map the same page at several addresses, we must use
3099
       a fd */
3100
    {
3101
        const char *tmpdir;
3102

    
3103
        tmpdir = getenv("QEMU_TMPDIR");
3104
        if (!tmpdir)
3105
            tmpdir = "/tmp";
3106
        snprintf(phys_ram_file, sizeof(phys_ram_file), "%s/vlXXXXXX", tmpdir);
3107
        if (mkstemp(phys_ram_file) < 0) {
3108
            fprintf(stderr, "Could not create temporary memory file '%s'\n", 
3109
                    phys_ram_file);
3110
            exit(1);
3111
        }
3112
        phys_ram_fd = open(phys_ram_file, O_CREAT | O_TRUNC | O_RDWR, 0600);
3113
        if (phys_ram_fd < 0) {
3114
            fprintf(stderr, "Could not open temporary memory file '%s'\n", 
3115
                    phys_ram_file);
3116
            exit(1);
3117
        }
3118
        ftruncate(phys_ram_fd, total_ram_size);
3119
        unlink(phys_ram_file);
3120
        phys_ram_base = mmap(get_mmap_addr(total_ram_size), 
3121
                             total_ram_size, 
3122
                             PROT_WRITE | PROT_READ, MAP_SHARED | MAP_FIXED, 
3123
                             phys_ram_fd, 0);
3124
        if (phys_ram_base == MAP_FAILED) {
3125
            fprintf(stderr, "Could not map physical memory\n");
3126
            exit(1);
3127
        }
3128
    }
3129
#endif
3130

    
3131
    /* open the virtual block devices */
3132
    for(i = 0; i < MAX_DISKS; i++) {
3133
        if (hd_filename[i]) {
3134
            bs_table[i] = bdrv_open(hd_filename[i], snapshot);
3135
            if (!bs_table[i]) {
3136
                fprintf(stderr, "qemu: could not open hard disk image '%s\n",
3137
                        hd_filename[i]);
3138
                exit(1);
3139
            }
3140
        }
3141
    }
3142

    
3143
    /* init CPU state */
3144
    env = cpu_init();
3145
    global_env = env;
3146
    cpu_single_env = env;
3147

    
3148
    init_ioports();
3149

    
3150
    /* allocate RAM */
3151
    cpu_register_physical_memory(0, phys_ram_size, 0);
3152

    
3153
    if (linux_boot) {
3154
        /* now we can load the kernel */
3155
        ret = load_kernel(kernel_filename, phys_ram_base + KERNEL_LOAD_ADDR);
3156
        if (ret < 0) {
3157
            fprintf(stderr, "qemu: could not load kernel '%s'\n", 
3158
                    kernel_filename);
3159
            exit(1);
3160
        }
3161
        
3162
        /* load initrd */
3163
        initrd_size = 0;
3164
        if (initrd_filename) {
3165
            initrd_size = load_image(initrd_filename, phys_ram_base + INITRD_LOAD_ADDR);
3166
            if (initrd_size < 0) {
3167
                fprintf(stderr, "qemu: could not load initial ram disk '%s'\n", 
3168
                        initrd_filename);
3169
                exit(1);
3170
            }
3171
        }
3172
        
3173
        /* init kernel params */
3174
        params = (void *)(phys_ram_base + KERNEL_PARAMS_ADDR);
3175
        memset(params, 0, sizeof(struct linux_params));
3176
        params->mount_root_rdonly = 0;
3177
        stw_raw(&params->cl_magic, 0xA33F);
3178
        stw_raw(&params->cl_offset, params->commandline - (uint8_t *)params);
3179
        stl_raw(&params->alt_mem_k, (phys_ram_size / 1024) - 1024);
3180
        pstrcat(params->commandline, sizeof(params->commandline), kernel_cmdline);
3181
        params->loader_type = 0x01;
3182
        if (initrd_size > 0) {
3183
            stl_raw(&params->initrd_start, INITRD_LOAD_ADDR);
3184
            stl_raw(&params->initrd_size, initrd_size);
3185
        }
3186
        params->orig_video_lines = 25;
3187
        params->orig_video_cols = 80;
3188

    
3189
        /* setup basic memory access */
3190
        env->cr[0] = 0x00000033;
3191
        cpu_x86_init_mmu(env);
3192
        
3193
        memset(params->idt_table, 0, sizeof(params->idt_table));
3194
        
3195
        stq_raw(&params->gdt_table[2], 0x00cf9a000000ffffLL); /* KERNEL_CS */
3196
        stq_raw(&params->gdt_table[3], 0x00cf92000000ffffLL); /* KERNEL_DS */
3197
        /* for newer kernels (2.6.0) CS/DS are at different addresses */
3198
        stq_raw(&params->gdt_table[12], 0x00cf9a000000ffffLL); /* KERNEL_CS */
3199
        stq_raw(&params->gdt_table[13], 0x00cf92000000ffffLL); /* KERNEL_DS */
3200
        
3201
        env->idt.base = (void *)((uint8_t *)params->idt_table - phys_ram_base);
3202
        env->idt.limit = sizeof(params->idt_table) - 1;
3203
        env->gdt.base = (void *)((uint8_t *)params->gdt_table - phys_ram_base);
3204
        env->gdt.limit = sizeof(params->gdt_table) - 1;
3205
        
3206
        cpu_x86_load_seg_cache(env, R_CS, KERNEL_CS, NULL, 0xffffffff, 0x00cf9a00);
3207
        cpu_x86_load_seg_cache(env, R_DS, KERNEL_DS, NULL, 0xffffffff, 0x00cf9200);
3208
        cpu_x86_load_seg_cache(env, R_ES, KERNEL_DS, NULL, 0xffffffff, 0x00cf9200);
3209
        cpu_x86_load_seg_cache(env, R_SS, KERNEL_DS, NULL, 0xffffffff, 0x00cf9200);
3210
        cpu_x86_load_seg_cache(env, R_FS, KERNEL_DS, NULL, 0xffffffff, 0x00cf9200);
3211
        cpu_x86_load_seg_cache(env, R_GS, KERNEL_DS, NULL, 0xffffffff, 0x00cf9200);
3212
        
3213
        env->eip = KERNEL_LOAD_ADDR;
3214
        env->regs[R_ESI] = KERNEL_PARAMS_ADDR;
3215
        env->eflags = 0x2;
3216

    
3217
    } else {
3218
        char buf[1024];
3219

    
3220
        /* RAW PC boot */
3221

    
3222
        /* BIOS load */
3223
        snprintf(buf, sizeof(buf), "%s/%s", bios_dir, BIOS_FILENAME);
3224
        ret = load_image(buf, phys_ram_base + 0x000f0000);
3225
        if (ret != 0x10000) {
3226
            fprintf(stderr, "qemu: could not load PC bios '%s'\n", buf);
3227
            exit(1);
3228
        }
3229

    
3230
        /* VGA BIOS load */
3231
        snprintf(buf, sizeof(buf), "%s/%s", bios_dir, VGABIOS_FILENAME);
3232
        ret = load_image(buf, phys_ram_base + 0x000c0000);
3233

    
3234
        /* setup basic memory access */
3235
        env->cr[0] = 0x60000010;
3236
        cpu_x86_init_mmu(env);
3237
        
3238
        env->idt.limit = 0xffff;
3239
        env->gdt.limit = 0xffff;
3240
        env->ldt.limit = 0xffff;
3241
        env->ldt.flags = DESC_P_MASK;
3242
        env->tr.limit = 0xffff;
3243
        env->tr.flags = DESC_P_MASK;
3244

    
3245
        /* not correct (CS base=0xffff0000) */
3246
        cpu_x86_load_seg_cache(env, R_CS, 0xf000, (uint8_t *)0x000f0000, 0xffff, 0); 
3247
        cpu_x86_load_seg_cache(env, R_DS, 0, NULL, 0xffff, 0);
3248
        cpu_x86_load_seg_cache(env, R_ES, 0, NULL, 0xffff, 0);
3249
        cpu_x86_load_seg_cache(env, R_SS, 0, NULL, 0xffff, 0);
3250
        cpu_x86_load_seg_cache(env, R_FS, 0, NULL, 0xffff, 0);
3251
        cpu_x86_load_seg_cache(env, R_GS, 0, NULL, 0xffff, 0);
3252

    
3253
        env->eip = 0xfff0;
3254
        env->regs[R_EDX] = 0x600; /* indicate P6 processor */
3255

    
3256
        env->eflags = 0x2;
3257

    
3258
        bochs_bios_init();
3259
    }
3260

    
3261
    /* terminal init */
3262
    if (nographic) {
3263
        dumb_display_init(ds);
3264
    } else {
3265
#ifdef CONFIG_SDL
3266
        sdl_display_init(ds);
3267
#else
3268
        dumb_display_init(ds);
3269
#endif
3270
    }
3271
    /* init basic PC hardware */
3272
    register_ioport_write(0x80, 1, ioport80_write, 1);
3273

    
3274
    vga_init(ds, phys_ram_base + phys_ram_size, phys_ram_size, 
3275
             vga_ram_size);
3276
    cmos_init();
3277
    pic_init();
3278
    pit_init();
3279
    serial_init();
3280
    ne2000_init();
3281
    ide_init();
3282
    kbd_init();
3283
    AUD_init();
3284
    DMA_init();
3285
    SB16_init();
3286
    
3287
    /* setup cpu signal handlers for MMU / self modifying code handling */
3288
    sigfillset(&act.sa_mask);
3289
    act.sa_flags = SA_SIGINFO;
3290
#if !defined(CONFIG_SOFTMMU)
3291
    act.sa_sigaction = host_segv_handler;
3292
    sigaction(SIGSEGV, &act, NULL);
3293
    sigaction(SIGBUS, &act, NULL);
3294
#endif
3295

    
3296
    act.sa_sigaction = host_alarm_handler;
3297
    sigaction(SIGALRM, &act, NULL);
3298

    
3299
    itv.it_interval.tv_sec = 0;
3300
    itv.it_interval.tv_usec = 1000;
3301
    itv.it_value.tv_sec = 0;
3302
    itv.it_value.tv_usec = 10 * 1000;
3303
    setitimer(ITIMER_REAL, &itv, NULL);
3304
    /* we probe the tick duration of the kernel to inform the user if
3305
       the emulated kernel requested a too high timer frequency */
3306
    getitimer(ITIMER_REAL, &itv);
3307
    timer_ms = itv.it_interval.tv_usec / 1000;
3308
    pit_min_timer_count = ((uint64_t)itv.it_interval.tv_usec * PIT_FREQ) / 
3309
        1000000;
3310

    
3311
    if (use_gdbstub) {
3312
        cpu_gdbstub(NULL, main_loop, gdbstub_port);
3313
    } else {
3314
        main_loop(NULL);
3315
    }
3316
    return 0;
3317
}