1/*
2 * QEMU PC System Emulator
3 *
4 * Copyright (c) 2003-2004 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 "hw.h"
25#include "pc.h"
26#include "fdc.h"
27#include "pci.h"
28#include "block.h"
29#include "sysemu.h"
30#include "blockdev.h"
31#include "audio/audio.h"
32#include "net.h"
33//#include "smbus.h"
34#include "boards.h"
35#include "android/globals.h"
36#include "monitor.h"
37#include "fw_cfg.h"
38//#include "hpet_emul.h"
39#include "watchdog.h"
40#include "smbios.h"
41#include "console.h"
42
43#include "goldfish_device.h"
44#include "goldfish_pipe.h"
45
46char* audio_input_source = NULL;
47/* output Bochs bios info messages */
48//#define DEBUG_BIOS
49
50#define BIOS_FILENAME "bios.bin"
51#define VGABIOS_FILENAME "vgabios.bin"
52#define VGABIOS_CIRRUS_FILENAME "vgabios-cirrus.bin"
53
54#define PC_MAX_BIOS_SIZE (4 * 1024 * 1024)
55
56/* Leave a chunk of memory at the top of RAM for the BIOS ACPI tables.  */
57#define ACPI_DATA_SIZE       0x10000
58#define BIOS_CFG_IOPORT 0x510
59#define FW_CFG_ACPI_TABLES (FW_CFG_ARCH_LOCAL + 0)
60#define FW_CFG_SMBIOS_ENTRIES (FW_CFG_ARCH_LOCAL + 1)
61
62#define MAX_IDE_BUS 2
63#ifndef CONFIG_ANDROID
64static fdctrl_t *floppy_controller;
65#endif
66static RTCState *rtc_state;
67static PITState *pit;
68static IOAPICState *ioapic;
69static PCIDevice *i440fx_state;
70
71typedef struct rom_reset_data {
72    uint8_t *data;
73    target_phys_addr_t addr;
74    unsigned size;
75} RomResetData;
76
77static void option_rom_reset(void *_rrd)
78{
79    RomResetData *rrd = _rrd;
80
81    cpu_physical_memory_write_rom(rrd->addr, rrd->data, rrd->size);
82}
83
84static void option_rom_setup_reset(target_phys_addr_t addr, unsigned size)
85{
86    RomResetData *rrd = qemu_malloc(sizeof *rrd);
87
88    rrd->data = qemu_malloc(size);
89    cpu_physical_memory_read(addr, rrd->data, size);
90    rrd->addr = addr;
91    rrd->size = size;
92    qemu_register_reset(option_rom_reset, 0, rrd);
93}
94
95static void ioport80_write(void *opaque, uint32_t addr, uint32_t data)
96{
97}
98
99/* MSDOS compatibility mode FPU exception support */
100static qemu_irq ferr_irq;
101/* XXX: add IGNNE support */
102void cpu_set_ferr(CPUX86State *s)
103{
104    qemu_irq_raise(ferr_irq);
105}
106
107static void ioportF0_write(void *opaque, uint32_t addr, uint32_t data)
108{
109    qemu_irq_lower(ferr_irq);
110}
111
112/* TSC handling */
113uint64_t cpu_get_tsc(CPUX86State *env)
114{
115    /* Note: when using kqemu, it is more logical to return the host TSC
116       because kqemu does not trap the RDTSC instruction for
117       performance reasons */
118#ifdef CONFIG_KQEMU
119    if (env->kqemu_enabled) {
120        return cpu_get_real_ticks();
121    } else
122#endif
123    {
124        return cpu_get_ticks();
125    }
126}
127
128/* SMM support */
129void cpu_smm_update(CPUState *env)
130{
131    if (i440fx_state && env == first_cpu)
132        i440fx_set_smm(i440fx_state, (env->hflags >> HF_SMM_SHIFT) & 1);
133}
134
135
136/* IRQ handling */
137int cpu_get_pic_interrupt(CPUState *env)
138{
139    int intno;
140
141    intno = apic_get_interrupt(env);
142    if (intno >= 0) {
143        /* set irq request if a PIC irq is still pending */
144        /* XXX: improve that */
145        pic_update_irq(isa_pic);
146        return intno;
147    }
148    /* read the irq from the PIC */
149    if (!apic_accept_pic_intr(env))
150        return -1;
151
152    intno = pic_read_irq(isa_pic);
153    return intno;
154}
155
156static void pic_irq_request(void *opaque, int irq, int level)
157{
158    CPUState *env = first_cpu;
159
160    if (env->apic_state) {
161        while (env) {
162            if (apic_accept_pic_intr(env))
163                apic_deliver_pic_intr(env, level);
164            env = env->next_cpu;
165        }
166    } else {
167        if (level)
168            cpu_interrupt(env, CPU_INTERRUPT_HARD);
169        else
170            cpu_reset_interrupt(env, CPU_INTERRUPT_HARD);
171    }
172}
173
174/* PC cmos mappings */
175
176#define REG_EQUIPMENT_BYTE          0x14
177
178#ifndef CONFIG_ANDROID
179static int cmos_get_fd_drive_type(int fd0)
180{
181    int val;
182
183    switch (fd0) {
184    case 0:
185        /* 1.44 Mb 3"5 drive */
186        val = 4;
187        break;
188    case 1:
189        /* 2.88 Mb 3"5 drive */
190        val = 5;
191        break;
192    case 2:
193        /* 1.2 Mb 5"5 drive */
194        val = 2;
195        break;
196    default:
197        val = 0;
198        break;
199    }
200    return val;
201}
202#endif
203
204static void cmos_init_hd(int type_ofs, int info_ofs, BlockDriverState *hd)
205{
206    RTCState *s = rtc_state;
207    int cylinders, heads, sectors;
208    bdrv_get_geometry_hint(hd, &cylinders, &heads, &sectors);
209    rtc_set_memory(s, type_ofs, 47);
210    rtc_set_memory(s, info_ofs, cylinders);
211    rtc_set_memory(s, info_ofs + 1, cylinders >> 8);
212    rtc_set_memory(s, info_ofs + 2, heads);
213    rtc_set_memory(s, info_ofs + 3, 0xff);
214    rtc_set_memory(s, info_ofs + 4, 0xff);
215    rtc_set_memory(s, info_ofs + 5, 0xc0 | ((heads > 8) << 3));
216    rtc_set_memory(s, info_ofs + 6, cylinders);
217    rtc_set_memory(s, info_ofs + 7, cylinders >> 8);
218    rtc_set_memory(s, info_ofs + 8, sectors);
219}
220
221/* convert boot_device letter to something recognizable by the bios */
222static int boot_device2nibble(char boot_device)
223{
224    switch(boot_device) {
225    case 'a':
226    case 'b':
227        return 0x01; /* floppy boot */
228    case 'c':
229        return 0x02; /* hard drive boot */
230    case 'd':
231        return 0x03; /* CD-ROM boot */
232    case 'n':
233        return 0x04; /* Network boot */
234    }
235    return 0;
236}
237
238/* copy/pasted from cmos_init, should be made a general function
239 and used there as well */
240static int pc_boot_set(void *opaque, const char *boot_device)
241{
242    Monitor *mon = cur_mon;
243#define PC_MAX_BOOT_DEVICES 3
244    RTCState *s = (RTCState *)opaque;
245    int nbds, bds[3] = { 0, };
246    int i;
247
248    nbds = strlen(boot_device);
249    if (nbds > PC_MAX_BOOT_DEVICES) {
250        monitor_printf(mon, "Too many boot devices for PC\n");
251        return(1);
252    }
253    for (i = 0; i < nbds; i++) {
254        bds[i] = boot_device2nibble(boot_device[i]);
255        if (bds[i] == 0) {
256            monitor_printf(mon, "Invalid boot device for PC: '%c'\n",
257                           boot_device[i]);
258            return(1);
259        }
260    }
261    rtc_set_memory(s, 0x3d, (bds[1] << 4) | bds[0]);
262    rtc_set_memory(s, 0x38, (bds[2] << 4));
263    return(0);
264}
265
266/* hd_table must contain 4 block drivers */
267static void cmos_init(ram_addr_t ram_size, ram_addr_t above_4g_mem_size,
268                      const char *boot_device, BlockDriverState **hd_table)
269{
270    RTCState *s = rtc_state;
271    int nbds, bds[3] = { 0, };
272    int val;
273#ifndef CONFIG_ANDROID
274    int fd0, fd1, nb;
275#endif
276    int i;
277
278    /* various important CMOS locations needed by PC/Bochs bios */
279
280    /* memory size */
281    val = 640; /* base memory in K */
282    rtc_set_memory(s, 0x15, val);
283    rtc_set_memory(s, 0x16, val >> 8);
284
285    val = (ram_size / 1024) - 1024;
286    if (val > 65535)
287        val = 65535;
288    rtc_set_memory(s, 0x17, val);
289    rtc_set_memory(s, 0x18, val >> 8);
290    rtc_set_memory(s, 0x30, val);
291    rtc_set_memory(s, 0x31, val >> 8);
292
293    if (above_4g_mem_size) {
294        rtc_set_memory(s, 0x5b, (unsigned int)above_4g_mem_size >> 16);
295        rtc_set_memory(s, 0x5c, (unsigned int)above_4g_mem_size >> 24);
296        rtc_set_memory(s, 0x5d, (uint64_t)above_4g_mem_size >> 32);
297    }
298
299    if (ram_size > (16 * 1024 * 1024))
300        val = (ram_size / 65536) - ((16 * 1024 * 1024) / 65536);
301    else
302        val = 0;
303    if (val > 65535)
304        val = 65535;
305    rtc_set_memory(s, 0x34, val);
306    rtc_set_memory(s, 0x35, val >> 8);
307
308    /* set the number of CPU */
309    rtc_set_memory(s, 0x5f, smp_cpus - 1);
310
311    /* set boot devices, and disable floppy signature check if requested */
312#define PC_MAX_BOOT_DEVICES 3
313    nbds = strlen(boot_device);
314    if (nbds > PC_MAX_BOOT_DEVICES) {
315        fprintf(stderr, "Too many boot devices for PC\n");
316        exit(1);
317    }
318    for (i = 0; i < nbds; i++) {
319        bds[i] = boot_device2nibble(boot_device[i]);
320        if (bds[i] == 0) {
321            fprintf(stderr, "Invalid boot device for PC: '%c'\n",
322                    boot_device[i]);
323            exit(1);
324        }
325    }
326    rtc_set_memory(s, 0x3d, (bds[1] << 4) | bds[0]);
327    rtc_set_memory(s, 0x38, (bds[2] << 4) | (fd_bootchk ?  0x0 : 0x1));
328
329    /* floppy type */
330
331#ifndef CONFIG_ANDROID
332    fd0 = fdctrl_get_drive_type(floppy_controller, 0);
333    fd1 = fdctrl_get_drive_type(floppy_controller, 1);
334
335    val = (cmos_get_fd_drive_type(fd0) << 4) | cmos_get_fd_drive_type(fd1);
336    rtc_set_memory(s, 0x10, val);
337
338    val = 0;
339    nb = 0;
340    if (fd0 < 3)
341        nb++;
342    if (fd1 < 3)
343        nb++;
344    switch (nb) {
345    case 0:
346        break;
347    case 1:
348        val |= 0x01; /* 1 drive, ready for boot */
349        break;
350    case 2:
351        val |= 0x41; /* 2 drives, ready for boot */
352        break;
353    }
354    val |= 0x02; /* FPU is there */
355    val |= 0x04; /* PS/2 mouse installed */
356    rtc_set_memory(s, REG_EQUIPMENT_BYTE, val);
357#endif
358
359    /* hard drives */
360
361    rtc_set_memory(s, 0x12, (hd_table[0] ? 0xf0 : 0) | (hd_table[1] ? 0x0f : 0));
362    if (hd_table[0])
363        cmos_init_hd(0x19, 0x1b, hd_table[0]);
364    if (hd_table[1])
365        cmos_init_hd(0x1a, 0x24, hd_table[1]);
366
367    val = 0;
368    for (i = 0; i < 4; i++) {
369        if (hd_table[i]) {
370            int cylinders, heads, sectors, translation;
371            /* NOTE: bdrv_get_geometry_hint() returns the physical
372                geometry.  It is always such that: 1 <= sects <= 63, 1
373                <= heads <= 16, 1 <= cylinders <= 16383. The BIOS
374                geometry can be different if a translation is done. */
375            translation = bdrv_get_translation_hint(hd_table[i]);
376            if (translation == BIOS_ATA_TRANSLATION_AUTO) {
377                bdrv_get_geometry_hint(hd_table[i], &cylinders, &heads, &sectors);
378                if (cylinders <= 1024 && heads <= 16 && sectors <= 63) {
379                    /* No translation. */
380                    translation = 0;
381                } else {
382                    /* LBA translation. */
383                    translation = 1;
384                }
385            } else {
386                translation--;
387            }
388            val |= translation << (i * 2);
389        }
390    }
391    rtc_set_memory(s, 0x39, val);
392}
393
394void ioport_set_a20(int enable)
395{
396    /* XXX: send to all CPUs ? */
397    cpu_x86_set_a20(first_cpu, enable);
398}
399
400int ioport_get_a20(void)
401{
402    return ((first_cpu->a20_mask >> 20) & 1);
403}
404
405static void ioport92_write(void *opaque, uint32_t addr, uint32_t val)
406{
407    ioport_set_a20((val >> 1) & 1);
408    /* XXX: bit 0 is fast reset */
409}
410
411static uint32_t ioport92_read(void *opaque, uint32_t addr)
412{
413    return ioport_get_a20() << 1;
414}
415
416/***********************************************************/
417/* Bochs BIOS debug ports */
418
419static void bochs_bios_write(void *opaque, uint32_t addr, uint32_t val)
420{
421    static const char shutdown_str[8] = "Shutdown";
422    static int shutdown_index = 0;
423
424    switch(addr) {
425        /* Bochs BIOS messages */
426    case 0x400:
427    case 0x401:
428        fprintf(stderr, "BIOS panic at rombios.c, line %d\n", val);
429        exit(1);
430    case 0x402:
431    case 0x403:
432#ifdef DEBUG_BIOS
433        fprintf(stderr, "%c", val);
434#endif
435        break;
436    case 0x8900:
437        /* same as Bochs power off */
438        if (val == shutdown_str[shutdown_index]) {
439            shutdown_index++;
440            if (shutdown_index == 8) {
441                shutdown_index = 0;
442                qemu_system_shutdown_request();
443            }
444        } else {
445            shutdown_index = 0;
446        }
447        break;
448
449        /* LGPL'ed VGA BIOS messages */
450    case 0x501:
451    case 0x502:
452        fprintf(stderr, "VGA BIOS panic, line %d\n", val);
453        exit(1);
454    case 0x500:
455    case 0x503:
456#ifdef DEBUG_BIOS
457        fprintf(stderr, "%c", val);
458#endif
459        break;
460    }
461}
462
463extern uint64_t node_cpumask[MAX_NODES];
464
465static void bochs_bios_init(void)
466{
467    void *fw_cfg;
468    uint8_t *smbios_table;
469    size_t smbios_len;
470    uint64_t *numa_fw_cfg;
471    int i, j;
472
473    register_ioport_write(0x400, 1, 2, bochs_bios_write, NULL);
474    register_ioport_write(0x401, 1, 2, bochs_bios_write, NULL);
475    register_ioport_write(0x402, 1, 1, bochs_bios_write, NULL);
476    register_ioport_write(0x403, 1, 1, bochs_bios_write, NULL);
477    register_ioport_write(0x8900, 1, 1, bochs_bios_write, NULL);
478
479    register_ioport_write(0x501, 1, 2, bochs_bios_write, NULL);
480    register_ioport_write(0x502, 1, 2, bochs_bios_write, NULL);
481    register_ioport_write(0x500, 1, 1, bochs_bios_write, NULL);
482    register_ioport_write(0x503, 1, 1, bochs_bios_write, NULL);
483
484    fw_cfg = fw_cfg_init(BIOS_CFG_IOPORT, BIOS_CFG_IOPORT + 1, 0, 0);
485    fw_cfg_add_i32(fw_cfg, FW_CFG_ID, 1);
486    fw_cfg_add_i64(fw_cfg, FW_CFG_RAM_SIZE, (uint64_t)ram_size);
487#ifndef CONFIG_ANDROID
488    fw_cfg_add_bytes(fw_cfg, FW_CFG_ACPI_TABLES, (uint8_t *)acpi_tables,
489                     acpi_tables_len);
490#endif
491    smbios_table = smbios_get_table(&smbios_len);
492    if (smbios_table)
493        fw_cfg_add_bytes(fw_cfg, FW_CFG_SMBIOS_ENTRIES,
494                         smbios_table, smbios_len);
495
496    /* allocate memory for the NUMA channel: one (64bit) word for the number
497     * of nodes, one word for each VCPU->node and one word for each node to
498     * hold the amount of memory.
499     */
500    numa_fw_cfg = qemu_mallocz((1 + smp_cpus + nb_numa_nodes) * 8);
501    numa_fw_cfg[0] = cpu_to_le64(nb_numa_nodes);
502    for (i = 0; i < smp_cpus; i++) {
503        for (j = 0; j < nb_numa_nodes; j++) {
504            if (node_cpumask[j] & (1 << i)) {
505                numa_fw_cfg[i + 1] = cpu_to_le64(j);
506                break;
507            }
508        }
509    }
510    for (i = 0; i < nb_numa_nodes; i++) {
511        numa_fw_cfg[smp_cpus + 1 + i] = cpu_to_le64(node_mem[i]);
512    }
513    fw_cfg_add_bytes(fw_cfg, FW_CFG_NUMA, (uint8_t *)numa_fw_cfg,
514                     (1 + smp_cpus + nb_numa_nodes) * 8);
515}
516
517/* Generate an initial boot sector which sets state and jump to
518   a specified vector */
519static void generate_bootsect(target_phys_addr_t option_rom,
520                              uint32_t gpr[8], uint16_t segs[6], uint16_t ip)
521{
522    uint8_t rom[512], *p, *reloc;
523    uint8_t sum;
524    int i;
525
526    memset(rom, 0, sizeof(rom));
527
528    p = rom;
529    /* Make sure we have an option rom signature */
530    *p++ = 0x55;
531    *p++ = 0xaa;
532
533    /* ROM size in sectors*/
534    *p++ = 1;
535
536    /* Hook int19 */
537
538    *p++ = 0x50;		/* push ax */
539    *p++ = 0x1e;		/* push ds */
540    *p++ = 0x31; *p++ = 0xc0;	/* xor ax, ax */
541    *p++ = 0x8e; *p++ = 0xd8;	/* mov ax, ds */
542
543    *p++ = 0xc7; *p++ = 0x06;   /* movvw _start,0x64 */
544    *p++ = 0x64; *p++ = 0x00;
545    reloc = p;
546    *p++ = 0x00; *p++ = 0x00;
547
548    *p++ = 0x8c; *p++ = 0x0e;   /* mov cs,0x66 */
549    *p++ = 0x66; *p++ = 0x00;
550
551    *p++ = 0x1f;		/* pop ds */
552    *p++ = 0x58;		/* pop ax */
553    *p++ = 0xcb;		/* lret */
554
555    /* Actual code */
556    *reloc = (p - rom);
557
558    *p++ = 0xfa;		/* CLI */
559    *p++ = 0xfc;		/* CLD */
560
561    for (i = 0; i < 6; i++) {
562	if (i == 1)		/* Skip CS */
563	    continue;
564
565	*p++ = 0xb8;		/* MOV AX,imm16 */
566	*p++ = segs[i];
567	*p++ = segs[i] >> 8;
568	*p++ = 0x8e;		/* MOV <seg>,AX */
569	*p++ = 0xc0 + (i << 3);
570    }
571
572    for (i = 0; i < 8; i++) {
573	*p++ = 0x66;		/* 32-bit operand size */
574	*p++ = 0xb8 + i;	/* MOV <reg>,imm32 */
575	*p++ = gpr[i];
576	*p++ = gpr[i] >> 8;
577	*p++ = gpr[i] >> 16;
578	*p++ = gpr[i] >> 24;
579    }
580
581    *p++ = 0xea;		/* JMP FAR */
582    *p++ = ip;			/* IP */
583    *p++ = ip >> 8;
584    *p++ = segs[1];		/* CS */
585    *p++ = segs[1] >> 8;
586
587    /* sign rom */
588    sum = 0;
589    for (i = 0; i < (sizeof(rom) - 1); i++)
590        sum += rom[i];
591    rom[sizeof(rom) - 1] = -sum;
592
593    cpu_physical_memory_write_rom(option_rom, rom, sizeof(rom));
594    option_rom_setup_reset(option_rom, sizeof (rom));
595}
596
597static long get_file_size(FILE *f)
598{
599    long where, size;
600
601    /* XXX: on Unix systems, using fstat() probably makes more sense */
602
603    where = ftell(f);
604    fseek(f, 0, SEEK_END);
605    size = ftell(f);
606    fseek(f, where, SEEK_SET);
607
608    return size;
609}
610
611static void load_linux(target_phys_addr_t option_rom,
612                       const char *kernel_filename,
613		       const char *initrd_filename,
614		       const char *kernel_cmdline,
615               target_phys_addr_t max_ram_size)
616{
617    uint16_t protocol;
618    uint32_t gpr[8];
619    uint16_t seg[6];
620    uint16_t real_seg;
621    int setup_size, kernel_size, initrd_size = 0, cmdline_size;
622    uint32_t initrd_max;
623    uint8_t header[1024];
624    target_phys_addr_t real_addr, prot_addr, cmdline_addr, initrd_addr = 0;
625    FILE *f, *fi;
626
627    /* Align to 16 bytes as a paranoia measure */
628    cmdline_size = (strlen(kernel_cmdline)+16) & ~15;
629
630    /* load the kernel header */
631    f = fopen(kernel_filename, "rb");
632    if (!f || !(kernel_size = get_file_size(f)) ||
633	fread(header, 1, 1024, f) != 1024) {
634	fprintf(stderr, "qemu: could not load kernel '%s'\n",
635		kernel_filename);
636	exit(1);
637    }
638
639    /* kernel protocol version */
640#if 0
641    fprintf(stderr, "header magic: %#x\n", ldl_p(header+0x202));
642#endif
643    if (ldl_p(header+0x202) == 0x53726448)
644	protocol = lduw_p(header+0x206);
645    else
646	protocol = 0;
647
648    if (protocol < 0x200 || !(header[0x211] & 0x01)) {
649	/* Low kernel */
650	real_addr    = 0x90000;
651	cmdline_addr = 0x9a000 - cmdline_size;
652	prot_addr    = 0x10000;
653    } else if (protocol < 0x202) {
654	/* High but ancient kernel */
655	real_addr    = 0x90000;
656	cmdline_addr = 0x9a000 - cmdline_size;
657	prot_addr    = 0x100000;
658    } else {
659	/* High and recent kernel */
660	real_addr    = 0x10000;
661	cmdline_addr = 0x20000;
662	prot_addr    = 0x100000;
663    }
664
665#if 0
666    fprintf(stderr,
667	    "qemu: real_addr     = 0x" TARGET_FMT_plx "\n"
668	    "qemu: cmdline_addr  = 0x" TARGET_FMT_plx "\n"
669	    "qemu: prot_addr     = 0x" TARGET_FMT_plx "\n",
670	    real_addr,
671	    cmdline_addr,
672	    prot_addr);
673#endif
674
675    /* highest address for loading the initrd */
676    if (protocol >= 0x203)
677	initrd_max = ldl_p(header+0x22c);
678    else
679	initrd_max = 0x37ffffff;
680
681    if (initrd_max >= max_ram_size-ACPI_DATA_SIZE)
682    	initrd_max = max_ram_size-ACPI_DATA_SIZE-1;
683
684    /* kernel command line */
685    pstrcpy_targphys(cmdline_addr, 4096, kernel_cmdline);
686
687    if (protocol >= 0x202) {
688	stl_p(header+0x228, cmdline_addr);
689    } else {
690	stw_p(header+0x20, 0xA33F);
691	stw_p(header+0x22, cmdline_addr-real_addr);
692    }
693
694    /* loader type */
695    /* High nybble = B reserved for Qemu; low nybble is revision number.
696       If this code is substantially changed, you may want to consider
697       incrementing the revision. */
698    if (protocol >= 0x200)
699	header[0x210] = 0xB0;
700
701    /* heap */
702    if (protocol >= 0x201) {
703	header[0x211] |= 0x80;	/* CAN_USE_HEAP */
704	stw_p(header+0x224, cmdline_addr-real_addr-0x200);
705    }
706
707    /* load initrd */
708    if (initrd_filename) {
709	if (protocol < 0x200) {
710	    fprintf(stderr, "qemu: linux kernel too old to load a ram disk %s, %s, %s\n",
711			kernel_filename, initrd_filename, kernel_cmdline);
712	    exit(1);
713	}
714
715	fi = fopen(initrd_filename, "rb");
716	if (!fi) {
717	    fprintf(stderr, "qemu: could not load initial ram disk '%s'\n",
718		    initrd_filename);
719	    exit(1);
720	}
721
722	initrd_size = get_file_size(fi);
723	initrd_addr = (initrd_max-initrd_size) & ~4095;
724
725	if (!fread_targphys_ok(initrd_addr, initrd_size, fi)) {
726	    fprintf(stderr, "qemu: read error on initial ram disk '%s'\n",
727		    initrd_filename);
728	    exit(1);
729	}
730	fclose(fi);
731
732	stl_p(header+0x218, initrd_addr);
733	stl_p(header+0x21c, initrd_size);
734    }
735
736    /* store the finalized header and load the rest of the kernel */
737    cpu_physical_memory_write(real_addr, header, 1024);
738
739    setup_size = header[0x1f1];
740    if (setup_size == 0)
741	setup_size = 4;
742
743    setup_size = (setup_size+1)*512;
744    kernel_size -= setup_size;	/* Size of protected-mode code */
745
746    if (!fread_targphys_ok(real_addr+1024, setup_size-1024, f) ||
747	!fread_targphys_ok(prot_addr, kernel_size, f)) {
748	fprintf(stderr, "qemu: read error on kernel '%s'\n",
749		kernel_filename);
750	exit(1);
751    }
752    fclose(f);
753
754    /* generate bootsector to set up the initial register state */
755    real_seg = real_addr >> 4;
756    seg[0] = seg[2] = seg[3] = seg[4] = seg[4] = real_seg;
757    seg[1] = real_seg+0x20;	/* CS */
758    memset(gpr, 0, sizeof gpr);
759    gpr[4] = cmdline_addr-real_addr-16;	/* SP (-16 is paranoia) */
760
761    option_rom_setup_reset(real_addr, setup_size);
762    option_rom_setup_reset(prot_addr, kernel_size);
763    option_rom_setup_reset(cmdline_addr, cmdline_size);
764    if (initrd_filename)
765        option_rom_setup_reset(initrd_addr, initrd_size);
766
767    generate_bootsect(option_rom, gpr, seg, 0);
768}
769
770static void main_cpu_reset(void *opaque)
771{
772    CPUState *env = opaque;
773    cpu_reset(env);
774}
775
776static const int ide_iobase[2] = { 0x1f0, 0x170 };
777static const int ide_iobase2[2] = { 0x3f6, 0x376 };
778static const int ide_irq[2] = { 14, 15 };
779
780#define NE2000_NB_MAX 6
781
782static int ne2000_io[NE2000_NB_MAX] = { 0x300, 0x320, 0x340, 0x360, 0x280, 0x380 };
783static int ne2000_irq[NE2000_NB_MAX] = { 9, 10, 11, 3, 4, 5 };
784
785/* static int serial_io[MAX_SERIAL_PORTS] = { 0x3f8, 0x2f8, 0x3e8, 0x2e8 };
786static int serial_irq[MAX_SERIAL_PORTS] = { 4, 3, 4, 3 };
787
788static int parallel_io[MAX_PARALLEL_PORTS] = { 0x378, 0x278, 0x3bc };
789static int parallel_irq[MAX_PARALLEL_PORTS] = { 7, 7, 7 }; */
790
791#ifdef HAS_AUDIO
792#ifndef CONFIG_ANDROID
793static void audio_init (PCIBus *pci_bus, qemu_irq *pic)
794{
795    struct soundhw *c;
796
797    for (c = soundhw; c->name; ++c) {
798        if (c->enabled) {
799            if (c->isa) {
800                c->init.init_isa(pic);
801            } else {
802                if (pci_bus) {
803                    c->init.init_pci(pci_bus);
804                }
805            }
806        }
807    }
808}
809#endif
810#endif
811
812static void pc_init_ne2k_isa(NICInfo *nd, qemu_irq *pic)
813{
814    static int nb_ne2k = 0;
815
816    if (nb_ne2k == NE2000_NB_MAX)
817        return;
818    isa_ne2000_init(ne2000_io[nb_ne2k], pic[ne2000_irq[nb_ne2k]], nd);
819    nb_ne2k++;
820}
821
822static int load_option_rom(const char *oprom, target_phys_addr_t start,
823                           target_phys_addr_t end)
824{
825        int size;
826        char *filename;
827
828        filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, oprom);
829        if (filename) {
830            size = get_image_size(filename);
831            if (size > 0 && start + size > end) {
832                fprintf(stderr, "Not enough space to load option rom '%s'\n",
833                        oprom);
834                exit(1);
835            }
836            size = load_image_targphys(filename, start, end - start);
837            qemu_free(filename);
838        } else {
839            size = -1;
840        }
841        if (size < 0) {
842            fprintf(stderr, "Could not load option rom '%s'\n", oprom);
843            exit(1);
844        }
845        /* Round up optiom rom size to the next 2k boundary */
846        size = (size + 2047) & ~2047;
847        option_rom_setup_reset(start, size);
848        return size;
849}
850
851int cpu_is_bsp(CPUState *env)
852{
853	return env->cpuid_apic_id == 0;
854}
855
856static struct goldfish_device event0_device = {
857    .name = "goldfish_events",
858    .id = 0,
859    .size = 0x1000,
860    /* FIXME: This is just a work around before we have a permanent fix on
861     * increasing number of IRQs available for x86 sysimages. IRQ3 is normally
862     * assigned to COM2/COM4, and we have our own custom IRQs for those. So,
863     * it's safe to reserve it for the events device. */
864    .irq = 3,
865    .irq_count = 1
866};
867
868static struct goldfish_device nand_device = {
869    .name = "goldfish_nand",
870    .id = 0,
871    .size = 0x1000
872};
873
874void goldfish_memlog_init(uint32_t base);
875
876/* PC hardware initialisation */
877static void pc_init1(ram_addr_t ram_size,
878                     const char *boot_device,
879                     const char *kernel_filename, const char *kernel_cmdline,
880                     const char *initrd_filename,
881                     int pci_enabled, const char *cpu_model)
882{
883    char *filename;
884    int ret, linux_boot, i;
885    ram_addr_t ram_addr, bios_offset, option_rom_offset;
886    ram_addr_t below_4g_mem_size, above_4g_mem_size = 0;
887    int bios_size, isa_bios_size, oprom_area_size;
888    PCIBus *pci_bus;
889    int piix3_devfn = -1;
890    CPUState *env;
891    qemu_irq *cpu_irq;
892    qemu_irq *i8259;
893#ifndef CONFIG_ANDROID
894    int index;
895#endif
896    BlockDriverState *hd[MAX_IDE_BUS * MAX_IDE_DEVS];
897#ifndef CONFIG_ANDROID
898    BlockDriverState *fd[MAX_FD];
899#endif
900    int using_vga = cirrus_vga_enabled || std_vga_enabled || vmsvga_enabled;
901
902    if (ram_size >= 0xe0000000 ) {
903        above_4g_mem_size = ram_size - 0xe0000000;
904        below_4g_mem_size = 0xe0000000;
905    } else {
906        below_4g_mem_size = ram_size;
907    }
908
909    linux_boot = (kernel_filename != NULL);
910
911    /* init CPUs */
912    if (cpu_model == NULL) {
913#ifdef TARGET_X86_64
914        cpu_model = "qemu64";
915#else
916        cpu_model = "qemu32";
917#endif
918    }
919
920    for(i = 0; i < smp_cpus; i++) {
921        env = cpu_init(cpu_model);
922        if (!env) {
923            fprintf(stderr, "Unable to find x86 CPU definition\n");
924            exit(1);
925        }
926        if ((env->cpuid_features & CPUID_APIC) || smp_cpus > 1) {
927            env->cpuid_apic_id = env->cpu_index;
928            apic_init(env);
929        }
930        qemu_register_reset(main_cpu_reset, 0, env);
931    }
932#ifndef CONFIG_ANDROID
933    vmport_init();
934
935    /* allocate RAM */
936    ram_addr = qemu_ram_alloc(NULL, "pc.ram",
937                              below_4g_mem_size + above_4g_mem_size);
938    cpu_register_physical_memory(0, 0xa0000, ram_addr);
939    cpu_register_physical_memory(0x100000,
940                 below_4g_mem_size - 0x100000,
941                 ram_addr + 0x100000);
942    if (above_4g_mem_size > 0) {
943        cpu_register_physical_memory(0x100000000ULL, above_4g_mem_size,
944                                     ram_addr + below_4g_mem_size);
945    }
946#else
947    /*
948     * Allocate a single contiguous RAM so that the goldfish
949     * framebuffer can work well especially when the frame buffer is
950     * large.
951     */
952    ram_addr = qemu_ram_alloc(NULL, "pc.ram", below_4g_mem_size);
953    cpu_register_physical_memory(0, below_4g_mem_size, ram_addr);
954#endif
955
956    /* above 4giga memory allocation */
957    if (above_4g_mem_size > 0) {
958#if TARGET_PHYS_ADDR_BITS == 32
959        hw_error("To much RAM for 32-bit physical address");
960#else
961        ram_addr = qemu_ram_alloc(above_4g_mem_size);
962        cpu_register_physical_memory(0x100000000ULL,
963                                     above_4g_mem_size,
964                                     ram_addr);
965#endif
966    }
967
968
969    /* BIOS load */
970    if (bios_name == NULL)
971        bios_name = BIOS_FILENAME;
972    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);
973    if (filename) {
974        bios_size = get_image_size(filename);
975    } else {
976        bios_size = -1;
977    }
978    if (bios_size <= 0 ||
979        (bios_size % 65536) != 0) {
980        goto bios_error;
981    }
982    bios_offset = qemu_ram_alloc(NULL, "bios.bin", bios_size);
983    ret = load_image(filename, qemu_get_ram_ptr(bios_offset));
984    if (ret != bios_size) {
985    bios_error:
986        fprintf(stderr, "qemu: could not load PC BIOS '%s'\n", bios_name);
987        exit(1);
988    }
989    if (filename) {
990        qemu_free(filename);
991    }
992    /* map the last 128KB of the BIOS in ISA space */
993    isa_bios_size = bios_size;
994    if (isa_bios_size > (128 * 1024))
995        isa_bios_size = 128 * 1024;
996    cpu_register_physical_memory(0x100000 - isa_bios_size,
997                                 isa_bios_size,
998                                 (bios_offset + bios_size - isa_bios_size) | IO_MEM_ROM);
999
1000
1001
1002    option_rom_offset = qemu_ram_alloc(NULL, "pc.rom", 0x20000);
1003    oprom_area_size = 0;
1004    cpu_register_physical_memory(0xc0000, 0x20000, option_rom_offset);
1005
1006    if (using_vga) {
1007        const char *vgabios_filename;
1008        /* VGA BIOS load */
1009        if (cirrus_vga_enabled) {
1010            vgabios_filename = VGABIOS_CIRRUS_FILENAME;
1011        } else {
1012            vgabios_filename = VGABIOS_FILENAME;
1013        }
1014        oprom_area_size = load_option_rom(vgabios_filename, 0xc0000, 0xe0000);
1015    }
1016    /* Although video roms can grow larger than 0x8000, the area between
1017     * 0xc0000 - 0xc8000 is reserved for them. It means we won't be looking
1018     * for any other kind of option rom inside this area */
1019    if (oprom_area_size < 0x8000)
1020        oprom_area_size = 0x8000;
1021
1022    if (linux_boot) {
1023        load_linux(0xc0000 + oprom_area_size,
1024                   kernel_filename, initrd_filename, kernel_cmdline, below_4g_mem_size);
1025        oprom_area_size += 2048;
1026    }
1027
1028    for (i = 0; i < nb_option_roms; i++) {
1029        oprom_area_size += load_option_rom(option_rom[i],
1030                                           0xc0000 + oprom_area_size, 0xe0000);
1031    }
1032
1033    /* map all the bios at the top of memory */
1034    cpu_register_physical_memory((uint32_t)(-bios_size),
1035                                 bios_size, bios_offset | IO_MEM_ROM);
1036
1037    bochs_bios_init();
1038
1039    cpu_irq = qemu_allocate_irqs(pic_irq_request, NULL, 1);
1040    i8259 = i8259_init(cpu_irq[0]);
1041    ferr_irq = i8259[GFD_ERR_IRQ];
1042
1043#define IRQ_PDEV_BUS 4
1044    goldfish_device_init(i8259, 0xff010000, 0x7f0000, 5, 5);
1045    goldfish_device_bus_init(0xff001000, IRQ_PDEV_BUS);
1046
1047    if (android_hw->hw_battery)
1048        goldfish_battery_init();
1049
1050    goldfish_memlog_init(0);
1051
1052#ifdef CONFIG_NAND
1053    goldfish_add_device_no_io(&nand_device);
1054    nand_dev_init(nand_device.base);
1055    pipe_dev_init();
1056#endif
1057
1058    {
1059        DriveInfo* info = drive_get( IF_IDE, 0, 0 );
1060        if (info != NULL) {
1061            goldfish_mmc_init(0xff005000, 0, info->bdrv);
1062        }
1063    }
1064
1065    if (pci_enabled) {
1066        pci_bus = i440fx_init(&i440fx_state, i8259);
1067        piix3_devfn = piix3_init(pci_bus, -1);
1068    } else {
1069        pci_bus = NULL;
1070    }
1071
1072    /* init basic PC hardware */
1073    register_ioport_write(0x80, 1, 1, ioport80_write, NULL);
1074
1075    register_ioport_write(0xf0, 1, 1, ioportF0_write, NULL);
1076
1077#ifndef CONFIG_ANDROID
1078    if (cirrus_vga_enabled) {
1079        if (pci_enabled) {
1080            pci_cirrus_vga_init(pci_bus);
1081        } else {
1082            isa_cirrus_vga_init();
1083        }
1084    } else if (vmsvga_enabled) {
1085        if (pci_enabled)
1086            pci_vmsvga_init(pci_bus);
1087        else
1088            fprintf(stderr, "%s: vmware_vga: no PCI bus\n", __FUNCTION__);
1089    } else if (std_vga_enabled) {
1090        if (pci_enabled) {
1091            pci_vga_init(pci_bus, 0, 0);
1092        } else {
1093            isa_vga_init();
1094        }
1095    }
1096#endif
1097
1098    rtc_state = rtc_init(0x70, i8259[8], 2000);
1099
1100    qemu_register_boot_set(pc_boot_set, rtc_state);
1101
1102    register_ioport_read(0x92, 1, 1, ioport92_read, NULL);
1103    register_ioport_write(0x92, 1, 1, ioport92_write, NULL);
1104
1105    if (pci_enabled) {
1106        ioapic = ioapic_init();
1107    }
1108    pit = pit_init(0x40, i8259[0]);
1109
1110#ifndef CONFIG_ANDROID
1111    pcspk_init(pit);
1112
1113    if (!no_hpet) {
1114        hpet_init(i8259);
1115    }
1116#endif
1117
1118    if (pci_enabled) {
1119        pic_set_alt_irq_func(isa_pic, ioapic_set_irq, ioapic);
1120    }
1121
1122    goldfish_tty_add(serial_hds[0], 0, 0, 0);
1123    /* FIXME: This is just a work around before we have a permanent fix on
1124     * increasing number of IRQs available for x86 sysimages. In order to free up
1125     * some IRQs for a better use, we limit number of TTY devices by 2. Normally
1126     * we don't need more than that, so always having 4 of them would waste two
1127     * precious IRQs. */
1128#if 0
1129    for(i = 1; i < MAX_SERIAL_PORTS; i++) {
1130#else
1131    for(i = 1; i < 2; i++) {
1132#endif
1133        if(serial_hds[i]) {
1134            goldfish_tty_add(serial_hds[i], i, 0, 0);
1135        }
1136    }
1137
1138#ifndef CONFIG_ANDROID
1139    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
1140        if (serial_hds[i]) {
1141            serial_init(serial_io[i], i8259[serial_irq[i]], 115200,
1142                        serial_hds[i]);
1143        }
1144    }
1145
1146    for(i = 0; i < MAX_PARALLEL_PORTS; i++) {
1147        if (parallel_hds[i]) {
1148            parallel_init(parallel_io[i], i8259[parallel_irq[i]],
1149                          parallel_hds[i]);
1150        }
1151    }
1152#endif
1153
1154    watchdog_pc_init(pci_bus);
1155
1156    for(i = 0; i < nb_nics; i++) {
1157        NICInfo *nd = &nd_table[i];
1158
1159        if (!pci_enabled || (nd->model && strcmp(nd->model, "ne2k_isa") == 0))
1160            pc_init_ne2k_isa(nd, i8259);
1161        else
1162            pci_nic_init(pci_bus, nd, -1, "ne2k_pci");
1163    }
1164
1165#ifdef CONFIG_ANDROID
1166    for(i = 0; i < MAX_IDE_BUS * MAX_IDE_DEVS; i++)
1167       hd[i] = NULL;
1168#else
1169    qemu_system_hot_add_init();
1170
1171    if (drive_get_max_bus(IF_IDE) >= MAX_IDE_BUS) {
1172        fprintf(stderr, "qemu: too many IDE bus\n");
1173        exit(1);
1174    }
1175
1176    for(i = 0; i < MAX_IDE_BUS * MAX_IDE_DEVS; i++) {
1177        index = drive_get_index(IF_IDE, i / MAX_IDE_DEVS, i % MAX_IDE_DEVS);
1178	if (index != -1)
1179	    hd[i] = drives_table[index].bdrv;
1180	else
1181	    hd[i] = NULL;
1182    }
1183
1184    if (pci_enabled) {
1185        pci_piix3_ide_init(pci_bus, hd, piix3_devfn + 1, i8259);
1186    } else {
1187        for(i = 0; i < MAX_IDE_BUS; i++) {
1188            isa_ide_init(ide_iobase[i], ide_iobase2[i], i8259[ide_irq[i]],
1189	                 hd[MAX_IDE_DEVS * i], hd[MAX_IDE_DEVS * i + 1]);
1190        }
1191    }
1192#endif
1193
1194    i8042_init(i8259[GFD_KBD_IRQ], i8259[GFD_MOUSE_IRQ], 0x60);
1195    DMA_init(0);
1196
1197    goldfish_fb_init(0);
1198
1199    goldfish_add_device_no_io(&event0_device);
1200    events_dev_init(event0_device.base, i8259[event0_device.irq]);
1201
1202#ifdef HAS_AUDIO
1203#ifndef CONFIG_ANDROID
1204    audio_init(pci_enabled ? pci_bus : NULL, i8259);
1205#else
1206    goldfish_audio_init(0xff004000, 0, audio_input_source);
1207#endif
1208#endif
1209
1210#ifndef CONFIG_ANDROID
1211    for(i = 0; i < MAX_FD; i++) {
1212        index = drive_get_index(IF_FLOPPY, 0, i);
1213	if (index != -1)
1214	    fd[i] = drives_table[index].bdrv;
1215	else
1216	    fd[i] = NULL;
1217    }
1218
1219    floppy_controller = fdctrl_init(i8259[6], 2, 0, 0x3f0, fd);
1220#endif
1221
1222    cmos_init(below_4g_mem_size, above_4g_mem_size, boot_device, hd);
1223
1224#ifndef CONFIG_ANDROID
1225    if (pci_enabled && usb_enabled) {
1226        usb_uhci_piix3_init(pci_bus, piix3_devfn + 2);
1227    }
1228
1229    if (pci_enabled && acpi_enabled) {
1230        uint8_t *eeprom_buf = qemu_mallocz(8 * 256); /* XXX: make this persistent */
1231        i2c_bus *smbus;
1232
1233        /* TODO: Populate SPD eeprom data.  */
1234        smbus = piix4_pm_init(pci_bus, piix3_devfn + 3, 0xb100, i8259[9]);
1235        for (i = 0; i < 8; i++) {
1236            DeviceState *eeprom;
1237            eeprom = qdev_create((BusState *)smbus, "smbus-eeprom");
1238            qdev_set_prop_int(eeprom, "address", 0x50 + i);
1239            qdev_set_prop_ptr(eeprom, "data", eeprom_buf + (i * 256));
1240            qdev_init(eeprom);
1241        }
1242    }
1243#endif
1244
1245    if (i440fx_state) {
1246        i440fx_init_memory_mappings(i440fx_state);
1247    }
1248
1249    if (pci_enabled) {
1250	int max_bus;
1251        int bus;
1252
1253        max_bus = drive_get_max_bus(IF_SCSI);
1254	for (bus = 0; bus <= max_bus; bus++) {
1255            pci_create_simple(pci_bus, -1, "lsi53c895a");
1256        }
1257    }
1258#ifndef CONFIG_ANDROID
1259    /* Add virtio block devices */
1260    if (pci_enabled) {
1261        int index;
1262        int unit_id = 0;
1263
1264        while ((index = drive_get_index(IF_VIRTIO, 0, unit_id)) != -1) {
1265            pci_create_simple(pci_bus, -1, "virtio-blk-pci");
1266            unit_id++;
1267        }
1268    }
1269
1270    /* Add virtio balloon device */
1271    if (pci_enabled && !no_virtio_balloon) {
1272        pci_create_simple(pci_bus, -1, "virtio-balloon-pci");
1273    }
1274
1275    /* Add virtio console devices */
1276    if (pci_enabled) {
1277        for(i = 0; i < MAX_VIRTIO_CONSOLES; i++) {
1278            if (virtcon_hds[i]) {
1279                pci_create_simple(pci_bus, -1, "virtio-console-pci");
1280            }
1281        }
1282    }
1283#endif
1284}
1285
1286static void pc_init_pci(ram_addr_t ram_size,
1287                        const char *boot_device,
1288                        const char *kernel_filename,
1289                        const char *kernel_cmdline,
1290                        const char *initrd_filename,
1291                        const char *cpu_model)
1292{
1293    pc_init1(ram_size, boot_device,
1294             kernel_filename, kernel_cmdline,
1295             initrd_filename, 1, cpu_model);
1296}
1297
1298static void pc_init_isa(ram_addr_t ram_size,
1299                        const char *boot_device,
1300                        const char *kernel_filename,
1301                        const char *kernel_cmdline,
1302                        const char *initrd_filename,
1303                        const char *cpu_model)
1304{
1305    pc_init1(ram_size, boot_device,
1306             kernel_filename, kernel_cmdline,
1307             initrd_filename, 0, cpu_model);
1308}
1309
1310/* set CMOS shutdown status register (index 0xF) as S3_resume(0xFE)
1311   BIOS will read it and start S3 resume at POST Entry */
1312void cmos_set_s3_resume(void)
1313{
1314    if (rtc_state)
1315        rtc_set_memory(rtc_state, 0xF, 0xFE);
1316}
1317
1318static QEMUMachine pc_machine = {
1319    .name = "pc",
1320    .desc = "Standard PC",
1321    .init = pc_init_pci,
1322    .max_cpus = 255,
1323    .is_default = 1,
1324};
1325
1326static QEMUMachine isapc_machine = {
1327    .name = "isapc",
1328    .desc = "ISA-only PC",
1329    .init = pc_init_isa,
1330    .max_cpus = 1,
1331};
1332
1333static void pc_machine_init(void)
1334{
1335    qemu_register_machine(&pc_machine);
1336    qemu_register_machine(&isapc_machine);
1337}
1338
1339machine_init(pc_machine_init);
1340