Esempio n. 1
0
File: mips_r4k.c Progetto: CPFL/gxen
static void main_cpu_reset(void *opaque)
{
    CPUState *env = opaque;
    cpu_reset(env);

    if (loaderparams.kernel_filename)
        load_kernel (env);
}
Esempio n. 2
0
  /**
   * Runs rbx from the filesystem. Searches for the Rubinius runtime files
   * according to the algorithm in find_runtime().
   */
  void Environment::run_from_filesystem() {
    int i = 0;
    state->vm()->set_root_stack(reinterpret_cast<uintptr_t>(&i),
                                VM::cStackDepthMax);

    std::string runtime = system_prefix() + RBX_RUNTIME_PATH;

    load_platform_conf(runtime);
    boot_vm();
    start_finalizer();

    load_argv(argc_, argv_);

    start_signals();
    state->vm()->initialize_config();

    load_tool();

    G(rubinius)->set_const(state, "Signature", Integer::from(state, signature_));

    if(LANGUAGE_20_ENABLED(state)) {
      runtime += "/20";
    } else if(LANGUAGE_19_ENABLED(state)) {
      runtime += "/19";
    } else {
      runtime += "/18";
    }
    G(rubinius)->set_const(state, "RUNTIME_PATH", String::create(state,
                           runtime.c_str(), runtime.size()));

    load_kernel(runtime);
    shared->finalizer_handler()->start_thread(state);

    run_file(runtime + "/loader.rbc");

    state->vm()->thread_state()->clear();

    Object* loader = G(rubinius)->get_const(state, state->symbol("Loader"));
    if(loader->nil_p()) {
      rubinius::bug("Unable to find loader");
    }

    OnStack<1> os(state, loader);

    Object* inst = loader->send(state, 0, state->symbol("new"));
    if(inst) {
      OnStack<1> os2(state, inst);

      inst->send(state, 0, state->symbol("main"));
    } else {
      rubinius::bug("Unable to instantiate loader");
    }
  }
Esempio n. 3
0
unsigned int add_two_vectors_gpu ( unsigned int n, int * a, int * b, int * c )
{

	int err = -1;

	/* get the GPU id */
	cl_platform_id gpu_id = get_gpu_id( &err );
	if( err ) 
	{	
      		return ( 0 );
	}
	
	/* get the device id */
	cl_device_id dev_id = get_dev_id( gpu_id, &err );
	if( err )
	{	
      		return ( 0 );
	}

	/* create the context using dev_id */
	cl_context context = create_context( dev_id, &err );
	if( err )
	{	
      		return ( 0 );
	}

	/* create a list to hold the commands to be executed by GPU */
	cl_command_queue cmd_queue = create_cmd_queue ( dev_id, context, &err );
	if( err )
	{	
      		return ( 0 );
	}

	/* create a kernel */
	cl_kernel kernel;

	/* load the kernel ``kernel.cl'' with name ``vectors_kernel''*/
	kernel = load_kernel ( "kernel.cl", "vectors_kernel", dev_id, context, &err );
	if( err )
	{	
      		return ( 0 );
	}

	/* run the kernel */
	if( ! ( kernel_launch ( kernel, context, cmd_queue, n, a, b, c ) ) )
		return (0);			

        clReleaseContext ( context );
	clReleaseCommandQueue ( cmd_queue );
        clReleaseKernel ( kernel );

	return ( 1 );
 }
Esempio n. 4
0
static void moxiesim_init(MachineState *machine)
{
    MoxieCPU *cpu = NULL;
    ram_addr_t ram_size = machine->ram_size;
    const char *cpu_model = machine->cpu_model;
    const char *kernel_filename = machine->kernel_filename;
    const char *kernel_cmdline = machine->kernel_cmdline;
    const char *initrd_filename = machine->initrd_filename;
    CPUMoxieState *env;
    MemoryRegion *address_space_mem = get_system_memory();
    MemoryRegion *ram = g_new(MemoryRegion, 1);
    MemoryRegion *rom = g_new(MemoryRegion, 1);
    hwaddr ram_base = 0x200000;
    LoaderParams loader_params;

    /* Init CPUs. */
    if (cpu_model == NULL) {
        cpu_model = "MoxieLite-moxie-cpu";
    }
    cpu = cpu_moxie_init(cpu_model);
    if (!cpu) {
        fprintf(stderr, "Unable to find CPU definition\n");
        exit(1);
    }
    env = &cpu->env;

    qemu_register_reset(main_cpu_reset, cpu);

    /* Allocate RAM. */
    memory_region_init_ram(ram, NULL, "moxiesim.ram", ram_size, &error_fatal);
    vmstate_register_ram_global(ram);
    memory_region_add_subregion(address_space_mem, ram_base, ram);

    memory_region_init_ram(rom, NULL, "moxie.rom", 128*0x1000, &error_fatal);
    vmstate_register_ram_global(rom);
    memory_region_add_subregion(get_system_memory(), 0x1000, rom);

    if (kernel_filename) {
        loader_params.ram_size = ram_size;
        loader_params.kernel_filename = kernel_filename;
        loader_params.kernel_cmdline = kernel_cmdline;
        loader_params.initrd_filename = initrd_filename;
        load_kernel(cpu, &loader_params);
    }

    /* A single 16450 sits at offset 0x3f8.  */
    if (serial_hds[0]) {
        serial_mm_init(address_space_mem, 0x3f8, 0, env->irq[4],
                       8000000/16, serial_hds[0], DEVICE_LITTLE_ENDIAN);
    }
}
Esempio n. 5
0
void
_startC(register_t a0, register_t a1, register_t a2, register_t a3)
{
	unsigned int * code;
	int i;
	void (*entry_point)(register_t, register_t, register_t, register_t);

	/* 
	 * Relocate segment to the predefined memory location
	 * Most likely it will be KSEG0/KSEG1 address
	 */
	entry_point = load_kernel(kernel_start);

	/* Pass saved registers to original _start */
	entry_point(a0, a1, a2, a3);
}
Esempio n. 6
0
static void moxiesim_init(MachineState *machine)
{
    MoxieCPU *cpu = NULL;
    ram_addr_t ram_size = machine->ram_size;
    const char *kernel_filename = machine->kernel_filename;
    const char *kernel_cmdline = machine->kernel_cmdline;
    const char *initrd_filename = machine->initrd_filename;
    CPUMoxieState *env;
    MemoryRegion *address_space_mem = get_system_memory();
    MemoryRegion *ram = g_new(MemoryRegion, 1);
    MemoryRegion *rom = g_new(MemoryRegion, 1);
    hwaddr ram_base = 0x200000;
    LoaderParams loader_params;

    /* Init CPUs. */
    cpu = MOXIE_CPU(cpu_create(machine->cpu_type));
    env = &cpu->env;

    qemu_register_reset(main_cpu_reset, cpu);

    /* Allocate RAM. */
    memory_region_init_ram(ram, NULL, "moxiesim.ram", ram_size, &error_fatal);
    memory_region_add_subregion(address_space_mem, ram_base, ram);

    memory_region_init_ram(rom, NULL, "moxie.rom", FIRMWARE_SIZE, &error_fatal);
    memory_region_add_subregion(get_system_memory(), FIRMWARE_BASE, rom);

    if (kernel_filename) {
        loader_params.ram_size = ram_size;
        loader_params.kernel_filename = kernel_filename;
        loader_params.kernel_cmdline = kernel_cmdline;
        loader_params.initrd_filename = initrd_filename;
        load_kernel(cpu, &loader_params);
    }
    if (bios_name) {
        if (load_image_targphys(bios_name, FIRMWARE_BASE, FIRMWARE_SIZE) < 0) {
            error_report("Failed to load firmware '%s'", bios_name);
        }
    }

    /* A single 16450 sits at offset 0x3f8.  */
    if (serial_hds[0]) {
        serial_mm_init(address_space_mem, 0x3f8, 0, env->irq[4],
                       8000000/16, serial_hds[0], DEVICE_LITTLE_ENDIAN);
    }
}
Esempio n. 7
0
File: main.c Progetto: fchai/cnix
void main (void)
    {
    struct phys_info pi;
    struct e820_mem_region regions [10];
    struct e820_mem_map map;
    int    kernel_size;
    unsigned long * kernel_base;
    unsigned long * p;
    int i;

    __asm__ __volatile__ ("cli");

    kernel_size = load_kernel ();

    printf ("kernel size = %d\n", kernel_size);

    pi.e820_mem_map.regions = regions;

    if (!probe_mem_e820 (&pi.e820_mem_map))
        printf ("probe_mem_e820 OK\n");

#if 0
    for (i = 0; i < pi.e820_mem_map.nr_regions; i++)
        printf ("map [%d] : %08x %08x %d %d\n", i,
                pi.e820_mem_map.regions[i].base_addr_lo,
                pi.e820_mem_map.regions[i].len_lo,
                pi.e820_mem_map.regions[i].type,
                pi.e820_mem_map.regions[i].ext_attr);
#endif

    enter_protect ();

    code (32);

    kernel_base = (unsigned long *) KERNEL_BASE;
    p = (unsigned long *) __boot_loader_end;

    do {
        *kernel_base++ = *p++;
        kernel_size -= sizeof (unsigned long);
    } while (kernel_size);

    ((void (*) (struct phys_info *)) KERNEL_BASE) (&pi);
    for (;;) {__asm__ ("hlt");}
    }
Esempio n. 8
0
void bootloader_main(void) {

	/* Init hardware */
	hw_init();

	/* Initialize elf-loader environment */
	init_elf_loader();

    /* Load the nano kernel. Doing this will install exception vectors */
    boot_printf("Boot: loading nano kernel ...\n");
	nano_init_t * nano_init = (nano_init_t *)load_nano(); //We have to rederive this as an executable cap
    nano_init = (nano_init_t*)cheri_setoffset(cheri_getpcc(),cheri_getoffset(nano_init));

    /* TODO: we could have some boot exception vectors if we want exception  handling in boot. */
    /* These should be in ROM as a part of the boot image (i.e. make a couple more dedicated sections */
    cp0_status_bev_set(0);

    boot_printf("Boot: loading kernel ...\n");
    size_t entry = load_kernel();

    boot_printf("Boot: loading init ...\n");
    boot_info_t *bi = load_init();

    size_t invalid_length = bi->init_end;
    capability phy_start = cheri_setbounds(cheri_setoffset(cheri_getdefault(), MIPS_KSEG0), invalid_length);

    /* Do we actually need this? */
    //boot_printf("Invalidating %p length %lx:\n", phy_start, invalid_length);
    //caches_invalidate(phy_start, invalid_length);


    register_t mem_size = bi->init_end - bi->nano_end;

    /* Jumps to the nano kernel init. This will completely destroy boot and so we can never return here.
     * All registers will be cleared apart from a specified few. mem_size of memory will be left unmanaged and the
     * rest will be returned as a reservation. The third argument is an extra argument to the kernel */

    boot_printf("Jumping to nano kernel...\n");
    BOOT_PRINT_CAP(nano_init);
    nano_init(mem_size, entry, bi->init_begin - bi->kernel_begin, bi->init_entry);
}
Esempio n. 9
0
void c_start(void)
{
	/* Main C entry point */
	loader.kernel_size = (uint32_t)&kernel_end - (uint32_t)&kernel_start;
	loader.initrd_start = (uint32_t)&fs_start;
	loader.initrd_size = (uint32_t)&fs_end - (uint32_t)&fs_start;
	loader.kernel_entry = (uint32_t)&kernel_entry;
	if (loader.kernel_size) {
		loader.cmdline_start = (uint32_t)&kernel_cmd;
		loader.cmdline_size = &kernel_cmd_end - &kernel_cmd;
	}
	load_kernel(&loader);

	/* Start the kernel */
	if(loader.fdt_start) {
		boot_kernel(&loader, 0, -1, loader.fdt_start, 0);
	} else {
		boot_kernel(&loader, 0, PLAT_ID, loader.atags_start, 0);
	}

	semi_write0("[bootwrapper] ERROR: returned from boot_kernel\n");
}
Esempio n. 10
0
void multiboot_loader(uint32_t uMagic, multiboot_info_t *pMultiboot) {
	uint32_t uPhysicalMemoryTotal, uMultibootMmapLenght;
	multiboot_memory_map_t *pMultibootMmap;

	if (!init_screen())
		return;

	if (!process_cpu_features())
		return;

	if (!process_multiboot(uMagic, pMultiboot, &uPhysicalMemoryTotal, &pMultibootMmap, &uMultibootMmapLenght))
		return;

	phys_alloc_init(pMultibootMmap, uMultibootMmapLenght);
	
	if (!virt_init())
		return;
	
	uint64_t entry = load_kernel(__PACKED_KERNEL_START, __PACKED_KERNEL_END);
	
	_goto64(entry);
}
Esempio n. 11
0
int bmain() {
    void (*kaddress)();

    /* relocate rpb/bqo (which are used by ROM-routines) */

    bcopy ((void*)bootregs[11], rpb, sizeof(struct rpb));
    bcopy ((void*)rpb->iovec, bqo, rpb->iovecsz);

    rpb->rpb_base = rpb;
    rpb->iovec = (int)bqo;

    reinit_vmb_boot_device();

    kprintf("booting ...\n");

    kprintf("loading kernel ...\n");
    kaddress = (void (*))load_kernel();

    kprintf("starting kernel ...\n");
    kaddress();

    kprintf("fatal error! halting ...\n");
    asm("halt");
}
Esempio n. 12
0
void init(uint64_t loader, struct unfold64_objl *object_list, struct unfold64_mmap *memory_map) {

	// parse configuration
	for (size_t i = 0; i < object_list->count; i++) {
		if (!strcmp(object_list->entry[i].name, "/boot/pconf")) {
			config_parse((char*) object_list->entry[i].base);
			break;
		}
	}

	// initialize the physical memory manager
	pmm_init(memory_map);

	// initialize paging
	pcx_init();

	// initialize interrupt handling
	idt_init();

	// allocate the CCB for processor 0
	ccb_new();

	// initialize LAPIC timer
	struct ccb *ccb = ccb_get_self();

	ccb->lapic->destination_format  = 0xFFFFFFFF;
	ccb->lapic->logical_destination = (ccb->lapic->logical_destination & 0xFFFFFF) | 1;
	ccb->lapic->lvt_timer           = 0x10000;
	ccb->lapic->lvt_performance_monitoring_counters = 0x400;
	ccb->lapic->lvt_lint0           = 0x10000;
	ccb->lapic->lvt_lint1           = 0x10000;
	ccb->lapic->task_priority       = 0;

	ccb->lapic->spurious_interrupt_vector  = 33 | 0x100;
	ccb->lapic->timer_initial_count        = 100000; // roughly 1 KHz
	ccb->lapic->lvt_timer                  = 32 | 0x20000;
	ccb->lapic->timer_divide_configuration = 3; // 16

	// initialize interrupt routes

	// pinion (pagefault, zombie, etc.) interrupt vector page
	pinion_vector_page_vtable.on_reset = pinion_on_reset;
	interrupt_add_vector_page(0x0080, &pinion_vector_page_vtable);

	// IRQ interrupt vector page
	irq_vector_page_vtable.on_fire = irq_on_fire;
	irq_vector_page_vtable.on_reset = irq_on_reset;
	interrupt_add_vector_page(0x0100, &irq_vector_page_vtable);

	// initialize ACPI (for IRQ routing info)
	init_acpi();

	// allocate initial thread TCB and add to scheduler
	scheduler_add_tcb(tcb_new());

	// schedule first thread
	scheduler_schedule();

	// load kernel image
	load_kernel(object_list);
}
Esempio n. 13
0
int main(void)
{
	u32 rootfs;
	u8 *load_address;
	char *rfs_txt;
	u32 image = 0;
	struct jffs2_raw_inode *node, *mfg_node;
	char *cmdline = 0, *altcmdline = 0;
	u32 kernel_nand_addr = 0, alt_kernel_nand_addr = 0;
	int board_id;
	u32 ret = 0;
	u32 ret2 = 0;
	u8 selection = 0;
	u8 displayOn = 0;
	unsigned char cSel;

#ifdef CPU_LF1000
	/* disable the USB controller */
	BIT_SET(REG16(LF1000_UDC_BASE+UDC_PCR), PCE);
#endif
	adc_init();
	board_id = load_board_id();
	display_backlight(board_id);
	clock_init();
	db_init();
#ifdef CONFIG_MACH_LF_LF1000
	/* now that backlight is on, see if we have enough battery to boot */
	if(gpio_get_val(LOW_BATT_PORT, LOW_BATT_PIN) == 0 &&
		ADC_TO_MV(adc_get_reading(LF1000_ADC_VBATSENSE)) < BOOT_MIN_MV){
		display_init();
		db_puts("PANIC: battery voltage too low!\n");
		guru_med(0xBA77DEAD,0x0BAD0BAD);
		// die();
	}
#endif /* CONFIG_MACH_LF_LF1000 */
#ifdef UBOOT_SUPPORT
	if(((REG32(LF1000_GPIO_BASE+GPIOCPAD) & BUTTON_MSK) == BUTTON_MSK)) {
		display_init();
		displayOn = 1;
		fbinit();
		fbclear();

		renderString(5,2,"OpenDidj lightning-boot " LB_VERSION "  /  " __DATE__ );
		renderString(5,4,"Select an option:");
		db_puts("OpenDidj lightning-boot " LB_VERSION "  /  " __DATE__ );
		db_puts("\n");

		make_crc_table();

		timer_init();
		offset = 0;
//			tmr_poll_start(2000);
		db_puts("Switch to 115200 baud\n");

		/* set the baud rate */
		UART16(BRD) = 1; /* FIXME (for now "1"  sets 115200 baud , "11" sets 19200 baud) */
		UART16(UARTCLKGEN) = ((UARTDIV-1)<<UARTCLKDIV)|(UART_PLL<<UARTCLKSRCSEL);

// Reggie added for julspower, autoboot if zimage is present on the SD card.
ret2 = check_autoboot(&cSel);
if ( ret2 == 0 )
{
	selection=cSel;
	db_puts("\nAutobooting zImage from SD\n");
	goto selection_section;
}

		selection = do_menu();

selection_section:
		load_address = (u8 *)(UBOOT_ADDR);
		switch ( selection ) {
			case 0:
				goto normal_boot;
			case 1: goto normal_boot;
			case 2: goto normal_boot;
			case 3:
				xmodemInit(db_putchar,db_getc_async);
				ret = xmodemReceive(ubcopy);
				break;
			case 4:
				ret = sd_load("u-boot.bin",load_address);
				break;
			case 5:
				ret = sd_load("zImage",load_address);
				break;
			case 6:
			// Reggie added, feature to load lightning-boot.bin from SD
			// filename *must* be 8.3 or it will fail to load, so lets
			// make it easy on ourselves and name it lb.bin on the sd
				load_address = (u8 *)(UBOOT_ADDR2);
				ret = sd_load("lb.bin",load_address);
				db_puts("\nLoading Lightning Boot from SD\n");
				break;
		}

		if ( ret != 0 ) guru_med(selection,ret);

		db_puts("\nboot jmp\n");

		/* jump to u-boot */
		((void (*)( int r0, int r1, int r2))load_address)
			(0, MACH_TYPE_LF1000, 0);

		/* never get here! */
		guru_med(0x000000F0,0);
		// die();
	}
#endif /* UBOOT_SUPPORT */
normal_boot:
	/* Set up the kernel command line */

	/* read entire /flags partition */
	nand_read(fs_buffer, BOOT_FLAGS_ADDR, BOOT_FLAGS_SIZE);

	/* find rootfs file */
	node = jffs2_cat((char *)fs_buffer, BOOT_FLAGS_SIZE, "rootfs");
	rootfs = RFS0;
	if(node == 0) {
		db_puts("warning: failed to find rootfs flags!\n");
	}
	else {
		rfs_txt = (char*)node+sizeof(struct jffs2_raw_inode)-4;
		if(!strncmp(rfs_txt, "RFS1", 4)) {
			db_puts("booting RFS1\n");
			// this should be made to use RFS2?
			rootfs = RFS1;
		}
// Reggie added to check cmdline options, if /flags/rootfs has been set to > RFS1
		if (selection==1){
// set to the default SD config just in case the rootfs flag is set for didj(RFS0/1)
		rootfs = RFS2;
		db_puts("nand/SD boot\n");
		{
//		if(!strncmp(rfs_txt, "RFS2", 4)) {
//			db_puts("booting SDRFS\n");
//			rootfs = RFS2;
//		}
//		else if(!strncmp(rfs_txt, "RFS3", 4)) {
		if(!strncmp(rfs_txt, "RFS3", 4)) {
			db_puts("booting nand/SD DEBUG\n");
			rootfs = RFS3;
		}


	}
	}
#ifdef NFS_SUPPORT
		else if(!strncmp(rfs_txt, "NFS0", 4)) {
			db_puts("booting NFS0\n");
			rootfs = NFS0;
		}
		else if(!strncmp(rfs_txt, "NFS1", 4)) {
			db_puts("booting NFS1\n");
			rootfs = NFS1;
		}
#endif /* NFS_SUPPORT */
		else {
			db_puts("booting RFS0\n");
		}
	}

	/* Find the mfcart file */
	mfg_node = jffs2_cat((char *)fs_buffer, BOOT_FLAGS_SIZE, "mfcart");
	if(mfg_node != 0) {
		db_puts("Booting with mfg cartridge layout.\n");
	}
	else
	{
	// Reggie added, setup for custom command line read from /flags/cmdline
	// try and keep some sanity for the mfcart flag to trump everything, not
	// sure we really need to worry about the carts at all and could remove
	// the code? same with the NFS support, although that might come with
	// future developments
	if (selection == 2){
	rootfs = RFS4;
	}

	}

	/* construct the command line */
	if(mfg_node == 0) {
		if(rootfs == RFS0) {
			cmdline = CMDLINE_BASE CMDLINE_RFS0 CMDLINE_UBI;
			altcmdline = CMDLINE_BASE CMDLINE_RFS1 CMDLINE_UBI;
			kernel_nand_addr = BOOT0_ADDR;
			alt_kernel_nand_addr = BOOT1_ADDR;

		}
		else if(rootfs == RFS1) {
			cmdline = CMDLINE_BASE CMDLINE_RFS1 CMDLINE_UBI;
			altcmdline = CMDLINE_BASE CMDLINE_RFS0 CMDLINE_UBI;
			// Reggie changed, we want to boot the kernel from
			// kernel0 but the rootfs from RFS1
			kernel_nand_addr = BOOT0_ADDR;
			alt_kernel_nand_addr = BOOT0_ADDR;
		}
// Reggie added, just a copy of the RFS1 boot commands.
// the kernel that boots the SD rootfs should be burnt
// to kernel1 partition, this way if the SD kernel fails
// it will fall back to booting the original kernel0/RFS0
// well, in theory
// both RFS2/3 functions boot from the same kernel parition(kernel1)
// and the same SD partition (mmcpblk0p2, ext3)
// so alt_/kernel_nand_addr are set to BOOT1_ADDR, altcmdline falls
// back to the other SD based RFS option
		else if(rootfs == RFS2) {
			cmdline = CMDLINE_BASE CMDLINE_RFS2 CMDLINE_UBI;
			altcmdline = CMDLINE_BASE CMDLINE_RFS3 CMDLINE_UBI;
			kernel_nand_addr = BOOT1_ADDR;
			alt_kernel_nand_addr = BOOT1_ADDR;
		}
		else if(rootfs == RFS3) {
			cmdline = CMDLINE_BASE CMDLINE_RFS3 CMDLINE_UBI;
			altcmdline = CMDLINE_BASE CMDLINE_RFS2 CMDLINE_UBI;
			kernel_nand_addr = BOOT1_ADDR;
			alt_kernel_nand_addr = BOOT1_ADDR;
		}

		// Reggie also added this, code to read custom cmdline from
		// a file called "cmdline" on the vfat SD partition, mmcblk0p1
		else if (rootfs == RFS4){
		// look for cmdline in the root of the vfat partition on the
		// uSD card and load the contents into cmdline_txt
		cmdline_load("cmdline", (u8 *)cmdline_txt);
		db_puts(cmdline_txt);
		cmdline = (char *)cmdline_txt;
		altcmdline = CMDLINE_BASE CMDLINE_RFS2 CMDLINE_UBI;
		// always boot the explorer kernel (BOOT1_ADDR) no matter
		// how the cmdline is constructed
		kernel_nand_addr = BOOT1_ADDR;
		alt_kernel_nand_addr = BOOT1_ADDR;
		}


#ifdef NFS_SUPPORT
		else if(rootfs == NFS0) {
			cmdline = CMDLINE_BASE CMDLINE_NFS CMDLINE_UBI;
			altcmdline = CMDLINE_BASE CMDLINE_NFS CMDLINE_UBI;
			kernel_nand_addr = BOOT0_ADDR;
			alt_kernel_nand_addr = BOOT1_ADDR;

		}
		else if(rootfs == NFS1) {
			cmdline = CMDLINE_BASE CMDLINE_NFS CMDLINE_UBI;
			altcmdline = CMDLINE_BASE CMDLINE_NFS CMDLINE_UBI;
			kernel_nand_addr = BOOT1_ADDR;
			alt_kernel_nand_addr = BOOT0_ADDR;

		}
#endif /* NFS_SUPPORT */
	}

	if(tfs_load_summary(sum_buffer, kernel_nand_addr)) {
		db_puts("warning: booting alternative kernel!\n");
		if(tfs_load_summary(sum_buffer, alt_kernel_nand_addr)) {
			db_puts("PANIC: unable to load alt summary\n");
			guru_med(0xA0000000,1);
			//die();
		}
	}

	db_stopwatch_start("LOAD KERNEL");
	if (rootfs==RFS4){
	 db_puts("RFS4 loading\n");
	image = load_kernel(cmdline);
	}
	else{
	  db_puts("normal cmdline\n");
	  db_puts(cmdline);
	image = load_kernel(cmdline);
	}
	db_stopwatch_stop();
	if(image == 0) {
		db_puts("Warning: booting alternative kernel!\n");
		if(tfs_load_summary(sum_buffer, alt_kernel_nand_addr) != 0) {
			guru_med(0xA0000000,2);
			//die();
		}
		image = load_kernel(altcmdline);
		if(image == 0) {
			db_puts("PANIC: nothing to boot\n");
			guru_med(0xA0000000,3);
			//die();
		}
	}

#ifdef DISPLAY_SUPPORT
	db_stopwatch_start("SPLASH");
	db_puts("Loading bootsplash\n");

	tfs_load_file("bootsplash.rgb", (u32 *)FRAME_BUFFER_ADDR);

	if ( !displayOn ) display_init();
	mlc_set_video_mode();

	//display_init();
	db_stopwatch_stop();
#endif

	load_cart_id();

	db_puts("Starting kernel...\n");
	cleanup_for_linux();
	/* jump to image (void, architecture ID, atags pointer) */
	((void(*)(int r0, int r1, unsigned int r2))image)
		(0, MACH_TYPE_LF1000, (unsigned int)params_buffer);

	/* never get here! */
	guru_med(0x000000F0,0);
	//die();
}
Esempio n. 14
0
static
void mips_r4k_init (ram_addr_t ram_size,
                    const char *boot_device,
                    const char *kernel_filename, const char *kernel_cmdline,
                    const char *initrd_filename, const char *cpu_model)
{
    char *filename;
    ram_addr_t ram_offset;
    ram_addr_t bios_offset;
    int bios_size;
    CPUState *env;
    ResetData *reset_info;
    int i;
    qemu_irq *i8259;
    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];
    DriveInfo *dinfo;
    int be;

    /* init CPUs */
    if (cpu_model == NULL) {
#ifdef TARGET_MIPS64
        cpu_model = "R4000";
#else
        cpu_model = "24Kf";
#endif
    }
    env = cpu_init(cpu_model);
    if (!env) {
        fprintf(stderr, "Unable to find CPU definition\n");
        exit(1);
    }
    reset_info = qemu_mallocz(sizeof(ResetData));
    reset_info->env = env;
    reset_info->vector = env->active_tc.PC;
    qemu_register_reset(main_cpu_reset, reset_info);

    /* allocate RAM */
    if (ram_size > (256 << 20)) {
        fprintf(stderr,
                "qemu: Too much memory for this machine: %d MB, maximum 256 MB\n",
                ((unsigned int)ram_size / (1 << 20)));
        exit(1);
    }
    ram_offset = qemu_ram_alloc(NULL, "mips_r4k.ram", ram_size);

    cpu_register_physical_memory(0, ram_size, ram_offset | IO_MEM_RAM);

    if (!mips_qemu_iomemtype) {
        mips_qemu_iomemtype = cpu_register_io_memory(mips_qemu_read,
                                                     mips_qemu_write, NULL,
                                                     DEVICE_NATIVE_ENDIAN);
    }
    cpu_register_physical_memory(0x1fbf0000, 0x10000, mips_qemu_iomemtype);

    /* Try to load a BIOS image. If this fails, we continue regardless,
       but initialize the hardware ourselves. When a kernel gets
       preloaded we also initialize the hardware, since the BIOS wasn't
       run. */
    if (bios_name == NULL)
        bios_name = BIOS_FILENAME;
    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);
    if (filename) {
        bios_size = get_image_size(filename);
    } else {
        bios_size = -1;
    }
#ifdef TARGET_WORDS_BIGENDIAN
    be = 1;
#else
    be = 0;
#endif
    if ((bios_size > 0) && (bios_size <= BIOS_SIZE)) {
        bios_offset = qemu_ram_alloc(NULL, "mips_r4k.bios", BIOS_SIZE);
	cpu_register_physical_memory(0x1fc00000, BIOS_SIZE,
                                     bios_offset | IO_MEM_ROM);

        load_image_targphys(filename, 0x1fc00000, BIOS_SIZE);
    } else if ((dinfo = drive_get(IF_PFLASH, 0, 0)) != NULL) {
        uint32_t mips_rom = 0x00400000;
        bios_offset = qemu_ram_alloc(NULL, "mips_r4k.bios", mips_rom);
        if (!pflash_cfi01_register(0x1fc00000, bios_offset,
                                   dinfo->bdrv, sector_len,
                                   mips_rom / sector_len,
                                   4, 0, 0, 0, 0, be)) {
            fprintf(stderr, "qemu: Error registering flash memory.\n");
	}
    }
    else {
	/* not fatal */
        fprintf(stderr, "qemu: Warning, could not load MIPS bios '%s'\n",
		bios_name);
    }
    if (filename) {
        qemu_free(filename);
    }

    if (kernel_filename) {
        loaderparams.ram_size = ram_size;
        loaderparams.kernel_filename = kernel_filename;
        loaderparams.kernel_cmdline = kernel_cmdline;
        loaderparams.initrd_filename = initrd_filename;
        reset_info->vector = load_kernel();
    }

    /* Init CPU internal devices */
    cpu_mips_irq_init_cpu(env);
    cpu_mips_clock_init(env);

    /* The PIC is attached to the MIPS CPU INT0 pin */
    i8259 = i8259_init(env->irq[2]);
    isa_bus_new(NULL);
    isa_bus_irqs(i8259);

    rtc_init(2000, NULL);

    /* Register 64 KB of ISA IO space at 0x14000000 */
    isa_mmio_init(0x14000000, 0x00010000);
    isa_mem_base = 0x10000000;

    pit = pit_init(0x40, i8259[0]);

    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
        if (serial_hds[i]) {
            serial_isa_init(i, serial_hds[i]);
        }
    }

    isa_vga_init();

    if (nd_table[0].vlan)
        isa_ne2000_init(0x300, 9, &nd_table[0]);

    if (drive_get_max_bus(IF_IDE) >= MAX_IDE_BUS) {
        fprintf(stderr, "qemu: too many IDE bus\n");
        exit(1);
    }

    for(i = 0; i < MAX_IDE_BUS * MAX_IDE_DEVS; i++) {
        hd[i] = drive_get(IF_IDE, i / MAX_IDE_DEVS, i % MAX_IDE_DEVS);
    }

    for(i = 0; i < MAX_IDE_BUS; i++)
        isa_ide_init(ide_iobase[i], ide_iobase2[i], ide_irq[i],
                     hd[MAX_IDE_DEVS * i],
		     hd[MAX_IDE_DEVS * i + 1]);

    isa_create_simple("i8042");
}
Esempio n. 15
0
static void riscv_board_init(QEMUMachineInitArgs *args)
{
    ram_addr_t ram_size = args->ram_size;
    const char *cpu_model = args->cpu_model;
    const char *kernel_filename = args->kernel_filename;
    const char *kernel_cmdline = args->kernel_cmdline;
    const char *initrd_filename = args->initrd_filename;
    MemoryRegion *system_memory = get_system_memory();
    MemoryRegion *main_mem = g_new(MemoryRegion, 1);
    RISCVCPU *cpu;
    CPURISCVState *env;
    int i;
#ifdef CONFIG_RISCV_HTIF
    DriveInfo *htifbd_drive;
    char *htifbd_fname; // htif block device filename
#endif

    DeviceState *dev = qdev_create(NULL, TYPE_RISCV_BOARD);

    object_property_set_bool(OBJECT(dev), true, "realized", NULL);

    /* Make sure the first 3 serial ports are associated with a device. */
    for(i = 0; i < 3; i++) {
        if (!serial_hds[i]) {
            char label[32];
            snprintf(label, sizeof(label), "serial%d", i);
            serial_hds[i] = qemu_chr_new(label, "null", NULL);
        }
    }

    /* init CPUs */
    if (cpu_model == NULL) {
        cpu_model = "riscv-generic";
    }

    for (i = 0; i < smp_cpus; i++) {
        cpu = cpu_riscv_init(cpu_model);
        if (cpu == NULL) {
            fprintf(stderr, "Unable to find CPU definition\n");
            exit(1);
        }
        env = &cpu->env;

        /* Init internal devices */
        cpu_riscv_irq_init_cpu(env);
        cpu_riscv_clock_init(env);
        qemu_register_reset(main_cpu_reset, cpu);
    }
    cpu = RISCV_CPU(first_cpu);
    env = &cpu->env;

    /* register system main memory (actual RAM) */
    memory_region_init_ram(main_mem, NULL, "riscv_board.ram", ram_size);
    vmstate_register_ram_global(main_mem);
    memory_region_add_subregion(system_memory, 0x0, main_mem);

    if (kernel_filename) {
        /* Write a small bootloader to the flash location. */
        loaderparams.ram_size = ram_size;
        loaderparams.kernel_filename = kernel_filename;
        loaderparams.kernel_cmdline = kernel_cmdline;
        loaderparams.initrd_filename = initrd_filename;
        load_kernel();
    }

    // write memory amount in MiB to 0x0
    stl_p(memory_region_get_ram_ptr(main_mem), loaderparams.ram_size >> 20);

#ifdef CONFIG_RISCV_HTIF
    serial_mm_init(system_memory, 0x3f8, 0, env->irq[4], 1843200/16, serial_hds[0],
        DEVICE_NATIVE_ENDIAN);

    // setup HTIF Block Device if one is specified as -hda FILENAME
    htifbd_drive = drive_get_by_index(IF_IDE, 0);
    if (NULL == htifbd_drive) {
        htifbd_fname = NULL;
    } else {
        htifbd_fname = (*(htifbd_drive->bdrv)).filename;
    }

    // add htif device 0x400 - 0x410
    htif_mm_init(system_memory, 0x400, env->irq[0], main_mem, htifbd_fname);
#else
    // add serial device 0x3f8-0x3ff
    serial_mm_init(system_memory, 0x3f8, 0, env->irq[1], 1843200/16, serial_hds[0],
        DEVICE_NATIVE_ENDIAN);

    /* Create MMIO transports, to which virtio backends created by the
     * user are automatically connected as needed.  If no backend is
     * present, the transport simply remains harmlessly idle.
     * Each memory-mapped region is 0x200 bytes in size.
     */
    sysbus_create_simple("virtio-mmio", 0x400, env->irq[2]);
    sysbus_create_simple("virtio-mmio", 0x600, env->irq[3]);
    sysbus_create_simple("virtio-mmio", 0x800, env->irq[4]);
#endif

    /* Init internal devices */
    cpu_riscv_irq_init_cpu(env);
    cpu_riscv_clock_init(env);
}
Esempio n. 16
0
int
main(int argc, char *argv[])
{
	int port = 2344;
	const char *config = "sys161.conf";
	const char *kernel = NULL;
	int usetcp=0;
	char *argstr = NULL;
	int j, opt;
	size_t argsize=0;
	int debugwait=0;
	int pass_signals=0;
#ifdef USE_TRACE
	int profiling=0;
#endif
	int use_second_console=0;
	const char *second_console = NULL;
	unsigned ncpus;

	/* This must come absolutely first so msg() can be used. */
	console_earlyinit();
	
	if (sizeof(u_int32_t)!=4) {
		/*
		 * Just in case.
		 */
		msg("sys161 requires sizeof(u_int32_t)==4");
		die();
	}

	while ((opt = mygetopt(argc, argv, "c:f:p:Pst:wk:"))!=-1) {
		switch (opt) {
		    case 'c': config = myoptarg; break;
		    case 'f':
#ifdef USE_TRACE
			set_tracefile(myoptarg);
#endif
			break;
		    case 'p': port = atoi(myoptarg); usetcp=1; break;
		    case 'P':
#ifdef USE_TRACE
			profiling = 1;
#endif
			break;
		    case 's': pass_signals = 1; break;
		    case 't': 
#ifdef USE_TRACE
			set_traceflags(myoptarg); 
#endif
			break;
		    case 'w': debugwait = 1; break;
		    case 'k':
		    use_second_console = 1;
		    second_console = myoptarg;
		    break;
		    default: usage(); break;
		}
	}
	if (myoptind==argc) {
		usage();
	}
	kernel = argv[myoptind++];
	
	for (j=myoptind; j<argc; j++) {
		argsize += strlen(argv[j])+1;
	}
	argstr = malloc(argsize+1);
	if (!argstr) {
		msg("malloc failed");
		die();
	}
	*argstr = 0;
	for (j=myoptind; j<argc; j++) {
		strcat(argstr, argv[j]);
		if (j<argc-1) strcat(argstr, " ");
	}

	/* This must come before bus_config in case a network card needs it */
	mkdir(".sockets", 0700);
	
	console_init(pass_signals, use_second_console, second_console);
	clock_init();
	ncpus = bus_config(config);

	initstats(ncpus);
	cpu_init(ncpus);

	if (usetcp) {
		gdb_inet_init(port);
	}
	else {
		unlink(".sockets/gdb");
		gdb_unix_init(".sockets/gdb");
	}

	unlink(".sockets/meter");
	meter_init(".sockets/meter");

	load_kernel(kernel, argstr);

	msg("System/161 %s, compiled %s %s", VERSION, __DATE__, __TIME__);
#ifdef USE_TRACE
	print_traceflags();
	if (profiling) {
		prof_setup();
	}
#endif

	if (debugwait) {
		stoploop();
	}
	
	run();

#ifdef USE_TRACE
	if (profiling) {
		prof_write();
	}
#endif

	bus_cleanup();
	console_cleanup();
	clock_cleanup();
	
	return 0;
}
Esempio n. 17
0
static void
mips_mipssim_init (ram_addr_t ram_size,
                   const char *boot_device,
                   const char *kernel_filename, const char *kernel_cmdline,
                   const char *initrd_filename, const char *cpu_model)
{
    char *filename;
    ram_addr_t ram_offset;
    ram_addr_t bios_offset;
    CPUState *env;
    ResetData *reset_info;
    int bios_size;

    /* Init CPUs. */
    if (cpu_model == NULL) {
#ifdef TARGET_MIPS64
        cpu_model = "5Kf";
#else
        cpu_model = "24Kf";
#endif
    }
    env = cpu_init(cpu_model);
    if (!env) {
        fprintf(stderr, "Unable to find CPU definition\n");
        exit(1);
    }
    reset_info = qemu_mallocz(sizeof(ResetData));
    reset_info->env = env;
    reset_info->vector = env->active_tc.PC;
    qemu_register_reset(main_cpu_reset, reset_info);

    /* Allocate RAM. */
    ram_offset = qemu_ram_alloc(NULL, "mips_mipssim.ram", ram_size);
    bios_offset = qemu_ram_alloc(NULL, "mips_mipssim.bios", BIOS_SIZE);

    cpu_register_physical_memory(0, ram_size, ram_offset | IO_MEM_RAM);

    /* Map the BIOS / boot exception handler. */
    cpu_register_physical_memory(0x1fc00000LL,
                                 BIOS_SIZE, bios_offset | IO_MEM_ROM);
    /* Load a BIOS / boot exception handler image. */
    if (bios_name == NULL)
        bios_name = BIOS_FILENAME;
    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);
    if (filename) {
        bios_size = load_image_targphys(filename, 0x1fc00000LL, BIOS_SIZE);
        qemu_free(filename);
    } else {
        bios_size = -1;
    }
    if ((bios_size < 0 || bios_size > BIOS_SIZE) && !kernel_filename) {
        /* Bail out if we have neither a kernel image nor boot vector code. */
        fprintf(stderr,
                "qemu: Could not load MIPS bios '%s', and no -kernel argument was specified\n",
                filename);
        exit(1);
    } else {
        /* We have a boot vector start address. */
        env->active_tc.PC = (target_long)(int32_t)0xbfc00000;
    }

    if (kernel_filename) {
        loaderparams.ram_size = ram_size;
        loaderparams.kernel_filename = kernel_filename;
        loaderparams.kernel_cmdline = kernel_cmdline;
        loaderparams.initrd_filename = initrd_filename;
        reset_info->vector = load_kernel();
    }

    /* Init CPU internal devices. */
    cpu_mips_irq_init_cpu(env);
    cpu_mips_clock_init(env);

    /* Register 64 KB of ISA IO space at 0x1fd00000. */
    isa_mmio_init(0x1fd00000, 0x00010000);

    /* A single 16450 sits at offset 0x3f8. It is attached to
       MIPS CPU INT2, which is interrupt 4. */
    if (serial_hds[0])
        serial_init(0x3f8, env->irq[4], 115200, serial_hds[0]);

    if (nd_table[0].vlan)
        /* MIPSnet uses the MIPS CPU INT0, which is interrupt 2. */
        mipsnet_init(0x4200, env->irq[2], &nd_table[0]);
}
Esempio n. 18
0
unsigned int gapmis_one_to_many_opt_gpu ( const char * p1, const char ** t, const struct gapmis_params * in, struct gapmis_align * out )
{
	const char * p[] = { p1, NULL};

	if ( in -> scoring_matrix > 1 )
	{
		errno = MATRIX;
		return ( 0 );
	}

	unsigned int 	pats = get_number_of_sequences (p);
	unsigned int 	txts = get_number_of_sequences (t);
	unsigned int	maxPatLen = get_max_length (pats, p);
	unsigned int	minTxtLen = get_min_length (txts, t);

	if (check_sequences(pats,p,in->scoring_matrix)==0)
	{
		errno = BADCHAR;
      		return ( 0 );
	}

	if (check_sequences(txts,t,in->scoring_matrix)==0)
	{
		errno = BADCHAR;
      		return ( 0 );
	}

	if(maxPatLen > minTxtLen)
	{
		errno = LENGTH;
      		return ( 0 );
	}

	if ( in -> max_gap >= minTxtLen )
	{
		errno = MAXGAP; 
		return ( 0 );
	}

	int err = -1;

	/* get the GPU id */
	cl_platform_id gpu_id = get_gpu_id(&err);	
	if(err)
	{	
	 	errno = NOGPU;
      		return ( 0 );
	}

        /* get the device id */
	cl_device_id dev_id = get_dev_id(gpu_id, &err);
	if(err)
	{	
	 	errno = NOGPU;
      		return ( 0 );
	}

	/* create the context using dev_id */
	cl_context context = create_context(dev_id, &err);
	if(err)
	{	
	 	errno = GPUERROR;
      		return ( 0 );
	}

	/* create a list with the commands to be executed by GPU */
	cl_command_queue cmd_queue = create_cmd_queue (dev_id, context, &err);
	if(err)
	{	
	 	errno = GPUERROR;
      		return ( 0 );
	}

	/* create a kernel */
	cl_kernel kernel;

	/* load the kernel ``kernel_dna.cl'' with name ``gapmis_kernel''*/
	if(in->scoring_matrix==0)
		kernel = load_kernel ("kernel_dna.cl", "gapmis_kernel", dev_id, context, &err);
	else
		kernel = load_kernel ("kernel_pro.cl", "gapmis_kernel", dev_id, context, &err);

	if(err)
	{	
	 	errno = KERNEL;
      		return ( 0 );
	}

	const unsigned int patGroupSize = 1;
	const unsigned int txtGroupSize = 768;
	unsigned int i, j;	
	unsigned int patGroups = get_number_of_groups (pats, patGroupSize);
	unsigned int txtGroups = get_number_of_groups (txts, txtGroupSize);	

	const char * groupPatterns[patGroupSize+1];
	set_null (groupPatterns, patGroupSize+1);

	const char * groupTexts[txtGroupSize+1];
	set_null (groupTexts, txtGroupSize+1);

	float * groupScores;
        groupScores = calloc (patGroupSize*txtGroupSize, sizeof(float) );

	int groupMatch [patGroupSize];
	float groupMatchScores [patGroupSize];
	set_invalid(groupMatch,patGroupSize);
	set_minimum(groupMatchScores,patGroupSize);	

	for(i=0;i<patGroups;i++)
	{
		set_null (groupPatterns, patGroupSize+1);
		initialize_pointers (groupPatterns,i,patGroupSize,p,pats);
		set_invalid(groupMatch,patGroupSize);
		set_minimum(groupMatchScores,patGroupSize);
		
		for(j=0;j<txtGroups;j++)
		{			
			set_null (groupTexts, txtGroupSize+1);
			initialize_pointers (groupTexts,j,txtGroupSize,t,txts);

			if( ! ( kernel_launch (kernel, context, cmd_queue, groupPatterns, groupTexts, in, groupScores) ))
				return ( 0 );			

			update_group_match (groupScores,groupMatch,groupMatchScores,patGroupSize,txtGroupSize, pats, txts, i, j);
		
		}

		for(j=0;j<patGroupSize;j++)
		{
			if(i*patGroupSize+j<pats)
			{
				groupPatterns[0] = p[i*patGroupSize+j];
				groupPatterns[1] = NULL;

				groupTexts[0] = t[groupMatch[j]];
				groupTexts[1] = NULL;
				
				if( !( kernel_launch_l (kernel, context, cmd_queue, groupPatterns, groupTexts, in, groupScores,&out[i*patGroupSize+j] ) ) )
					return ( 0 );				
			}
		}
	}

        free ( groupScores );
        clReleaseContext ( context );
	clReleaseCommandQueue ( cmd_queue );
        clReleaseKernel(kernel);

	return ( 1 );
 }
Esempio n. 19
0
void main(void)
{
	u32 rootfs;
	char *rfs_txt;
	u32 image = 0;
	struct jffs2_raw_inode *node, *mfg_node;
	char *cmdline = 0, *altcmdline = 0;
	u32 kernel_nand_addr = 0, alt_kernel_nand_addr = 0;
	int board_id;
	int done = 0;
	u32 ret = 0;

#ifdef CPU_LF1000
	/* disable the USB controller */
	BIT_SET(REG16(LF1000_UDC_BASE+UDC_PCR), PCE);
#endif
	adc_init();
	board_id = load_board_id();
	display_backlight(board_id);
	clock_init();
	db_init();
	display_init();
	fbcon_init();
	db_displaytee(1);
	
	db_puts("************************************************\n");
	db_puts("*                                              *\n");
	db_puts("* OpenDidj lightning-boot 1.1  /  12 Mar 2010  *\n");
	db_puts("*                                              *\n");
	db_puts("************************************************\n");
	db_puts("\n\n");
	

#ifdef CONFIG_MACH_LF_LF1000
	/* now that backlight is on, see if we have enough battery to boot */
	if(gpio_get_val(LOW_BATT_PORT, LOW_BATT_PIN) == 0 && 
		ADC_TO_MV(adc_get_reading(LF1000_ADC_VBATSENSE)) < BOOT_MIN_MV){
		db_puts("PANIC: battery voltage too low!\n");
		die();
	}
#endif /* CONFIG_MACH_LF_LF1000 */
#ifdef UBOOT_SUPPORT
	if(((REG32(LF1000_GPIO_BASE+GPIOCPAD) & BUTTON_MSK) == BUTTON_MSK)) {
		do {
			db_puts("xmodem download mode\n");
			timer_init();
			offset = 0;
			xmodemInit(db_putchar,db_getc_async);
			tmr_poll_start(2000);
			db_puts("Switch to 115200 baud and press any button\n");
			db_puts("to start XModem download...\n");
	/* set the baud rate */
#define UART16(r)       REG16(LF1000_SYS_UART_BASE+r)
	UART16(BRD) = 1; /* FIXME (for now "1"  sets 115200 baud , "11" sets 19200 baud) */
	UART16(UARTCLKGEN) = ((UARTDIV-1)<<UARTCLKDIV)|(UART_PLL<<UARTCLKSRCSEL);
			if(tfs_load_summary(sum_buffer, BOOT0_ADDR) != 0) {
				db_puts("trying BOOT1\n");
				if(tfs_load_summary(sum_buffer, BOOT1_ADDR)) {
					db_puts("u-boot not found\n");
					break;
				}
			}
			while (!done)
			{			
				if (tmr_poll_has_expired()){
					if(((REG32(LF1000_GPIO_BASE+GPIOCPAD) & BUTTON_MSK) != BUTTON_MSK)) 
					{
						db_displaytee(0);
						ret = xmodemReceive(ubcopy);
						db_displaytee(1);
						if ( ret >= 0 ) break;
					}
					if (ret == -1) 
					db_puts("XMODEM_ERROR : REMOTECANCEL\n");
					
					if (ret == -2)
					db_puts("XMODEM_ERROR : OUTOFSYNC\n");
					
					if (ret == -3)
					db_puts("XMODEM_ERROR : RETRYEXCEED\n");
					if ( ret < 0 ) continue;
	
					/*		
					db_puts("Loaded : ");
					db_int(ret);
					db_puts("bytes\n");
					*/
					}
			}
			
			db_puts("\n\nXModem download complete.\n");
			db_puts("Transferring control to U-Boot.\n");
		
			/* jump to u-boot */
			((void (*)( int r0, int r1, int r2))UBOOT_ADDR) 
				(0, MACH_TYPE_LF1000, 0);
			
			/* never get here! */
			die();
		} while(0);
	}
#endif /* UBOOT_SUPPORT */
 
	/* Set up the kernel command line */

	/* read entire /flags partition */
	nand_read(fs_buffer, BOOT_FLAGS_ADDR, BOOT_FLAGS_SIZE);

	/* find rootfs file */
	node = jffs2_cat((char *)fs_buffer, BOOT_FLAGS_SIZE, "rootfs");
	rootfs = RFS0;
	if(node == 0) {
		db_puts("warning: failed to find rootfs flags!\n");
	}
	else {
		rfs_txt = (char*)node+sizeof(struct jffs2_raw_inode)-4;
		if(!strncmp(rfs_txt, "RFS1", 4)) {
			db_puts("booting RFS1\n");
			rootfs = RFS1;
		} 
#ifdef NFS_SUPPORT
		else if(!strncmp(rfs_txt, "NFS0", 4)) {
			db_puts("booting NFS0\n");
			rootfs = NFS0;
		} 
		else if(!strncmp(rfs_txt, "NFS1", 4)) {
			db_puts("booting NFS1\n");
			rootfs = NFS1;
		} 
#endif /* NFS_SUPPORT */
		else {
			db_puts("booting RFS0\n");
		}
	}

	/* Find the mfcart file */
	mfg_node = jffs2_cat((char *)fs_buffer, BOOT_FLAGS_SIZE, "mfcart");
	if(mfg_node != 0) {
		db_puts("Booting with mfg cartridge layout.\n");
	}

	/* construct the command line */
	if(mfg_node == 0) {
		if(rootfs == RFS0) {
			cmdline = CMDLINE_BASE CMDLINE_RFS0 CMDLINE_UBI;
			altcmdline = CMDLINE_BASE CMDLINE_RFS1 CMDLINE_UBI;
			kernel_nand_addr = BOOT0_ADDR;
			alt_kernel_nand_addr = BOOT1_ADDR;
			
		} 
		else if(rootfs == RFS1) {
			cmdline = CMDLINE_BASE CMDLINE_RFS1 CMDLINE_UBI;
			altcmdline = CMDLINE_BASE CMDLINE_RFS0 CMDLINE_UBI;
			kernel_nand_addr = BOOT1_ADDR;
			alt_kernel_nand_addr = BOOT0_ADDR;
		}
#ifdef NFS_SUPPORT
		else if(rootfs == NFS0) {
			cmdline = CMDLINE_BASE CMDLINE_NFS CMDLINE_UBI;
			altcmdline = CMDLINE_BASE CMDLINE_NFS CMDLINE_UBI;
			kernel_nand_addr = BOOT0_ADDR;
			alt_kernel_nand_addr = BOOT1_ADDR;
			
		} 
		else if(rootfs == NFS1) {
			cmdline = CMDLINE_BASE CMDLINE_NFS CMDLINE_UBI;
			altcmdline = CMDLINE_BASE CMDLINE_NFS CMDLINE_UBI;
			kernel_nand_addr = BOOT1_ADDR;
			alt_kernel_nand_addr = BOOT0_ADDR;
			
		} 
#endif /* NFS_SUPPORT */
	} else {
		if(rootfs == RFS0) {
			cmdline = CMDLINE_BASE CMDLINE_RFS0 CMDLINE_MFG CMDLINE_UBI;
			altcmdline = CMDLINE_BASE CMDLINE_RFS1 CMDLINE_MFG CMDLINE_UBI;
			kernel_nand_addr = BOOT0_ADDR;
			alt_kernel_nand_addr = BOOT1_ADDR;
			
		} 
		else if(rootfs == RFS1) {
			cmdline = CMDLINE_BASE CMDLINE_RFS1 CMDLINE_MFG CMDLINE_UBI;
			altcmdline = CMDLINE_BASE CMDLINE_RFS0 CMDLINE_MFG CMDLINE_UBI;
			kernel_nand_addr = BOOT1_ADDR;
			alt_kernel_nand_addr = BOOT0_ADDR;
		}
#ifdef NFS_SUPPORT
		else if(rootfs == NFS0) {
			cmdline = CMDLINE_BASE CMDLINE_NFS CMDLINE_MFG CMDLINE_UBI;
			altcmdline = CMDLINE_BASE CMDLINE_NFS CMDLINE_MFG CMDLINE_UBI;
			kernel_nand_addr = BOOT0_ADDR;
			alt_kernel_nand_addr = BOOT1_ADDR;
			
		} 
		else if(rootfs == NFS1) {
			cmdline = CMDLINE_BASE CMDLINE_NFS CMDLINE_MFG CMDLINE_UBI;
			altcmdline = CMDLINE_BASE CMDLINE_NFS CMDLINE_MFG CMDLINE_UBI;
			kernel_nand_addr = BOOT1_ADDR;
			alt_kernel_nand_addr = BOOT0_ADDR;
		}
#endif /* NFS_SUPPORT */
	}
	
	if(tfs_load_summary(sum_buffer, kernel_nand_addr)) {
		db_puts("warning: booting alternative kernel!\n");
		if(tfs_load_summary(sum_buffer, alt_kernel_nand_addr)) {
			db_puts("PANIC: unable to load alt summary\n");
			die();
		}
	}

	db_stopwatch_start("LOAD KERNEL");
	image = load_kernel(cmdline);
	db_stopwatch_stop();
	if(image == 0) {
		db_puts("Warning: booting alternative kernel!\n");
		if(tfs_load_summary(sum_buffer, alt_kernel_nand_addr) != 0) {
			die();
		}
		image = load_kernel(altcmdline);
		if(image == 0) {
			db_puts("PANIC: nothing to boot\n");
			die();
		}
	}

#ifdef DISPLAY_SUPPORT
	db_stopwatch_start("SPLASH");
	db_puts("Loading bootsplash\n");
	tfs_load_file("bootsplash.rgb", (u32 *)FRAME_BUFFER_ADDR);
	display_init();
	db_stopwatch_stop();
#endif

	load_cart_id();

	db_puts("Starting the kernel...\n");
	cleanup_for_linux();
	/* jump to image (void, architecture ID, atags pointer) */
	((void(*)(int r0, int r1, unsigned int r2))image)
		(0, MACH_TYPE_LF1000, (unsigned int)params_buffer);

	/* never get here! */
	die();
}
Esempio n. 20
0
int start_simulation(void)
{
    cl_device_id *dev;
	cl_uint devc;
    cl_context context;
    cl_command_queue *cmd_queue;
    cl_mem src, dst, wdth, hght, *offy;
    cl_int err;
    cl_kernel kern;
    cl_program prog;
	cl_platform_id pform;
    size_t rows, columns, runs, print_each = 0, offsetx, offsety, *y, swapoffy;
	int gui_enabled, platform, device;
    unsigned int *buff0;
    unsigned int i;
	struct dispatcher_context *c;
	int random;
	char fname[1024];
	cl_uint cqc;
    
#if 1
    
	do
	{
		printf("Width: ");
		scanf(SZTF, &columns);
        
		if (columns % 32)
		{
			printf("Width must be a multiple of 32\n");
			continue;
		}
        
		if (columns == 0)
		{
			printf("Width must be > 0\n");
			continue;
		}
        
		break;
	}
	while (true);
    
	do
	{
		printf("Height: ");
		scanf(SZTF, &rows);
        
		if (rows == 0)
		{
			printf("Width must be > 0\n");
			continue;
		}
        
		break;
	}
	while (true);
    
    printf("Runs: ");
    scanf(SZTF, &runs);
    
	printf("Random? ");
	scanf("%d", &random);
    
	if (!random)
	{
		printf("File name: ");
		scanf("%s", fname);
        
		printf("Offset X: ");
		scanf(SZTF, &offsetx);
        
		printf("Offset Y: ");
		scanf(SZTF, &offsety);
	}
    
	printf("GUI? ");
	scanf("%d", &gui_enabled);
    
	if (!gui_enabled)
	{
		printf("Print after run: ");
		scanf(SZTF, &print_each);
	}
    
	printf("Platform index: ");
	scanf("%d", &platform);
    
	printf("Device index (-1 for all): ");
	scanf("%d", &device);
    
	do
	{
		printf("Swap offset: ");
		scanf(SZTF, &swapoffy);
        
		if (swapoffy == 0) swapoffy = rows;
        
		if (rows % swapoffy != 0)
		{
			printf("Swap offset must be a factor of the row count\n");
			continue;
		}
        
		break;
	}
	while (true);
#else
    columns = 512;
    rows = 512;
    runs = 1000;
	gui_enabled = 1;
    print_each = 0;
	random = 1;
    offsetx = 0;
    offsety = 0;
	platform = 0;
	device = 0;
	swapoffy = rows;
#endif
    
    err = get_devices(&dev, &devc, &pform, platform, device);
    if (err)
        return err;
    
    err = initialize_context_cmd_queue(dev, devc, pform, &context, &cmd_queue, &cqc);
    if (err)
        return err;
    
    err = load_kernel(context, dev, devc, &prog, &kern);
    if (err)
        return err;
    
    buff0 = (unsigned int*)malloc(rows * (columns / 8));
    if (!buff0)
        return -1;
    
	if (random)
	{
		srand((unsigned int)time(NULL));
		for (i = 0; i < (rows * (columns / 8)) / 4; i++)
		{
		    buff0[i] = rand() | (rand() << 16);
		}
	}
	else
	{
		memset(buff0, 0, rows * (columns / 8));
		if (!load_file_to_buffer(buff0, fname, offsetx, offsety, columns, rows))
			return -1;
	}
    
	err = compute_buffer_sizes(context, cmd_queue, cqc, kern, columns, rows, swapoffy, &y);
	if (err)
		return err;
    
    err = create_buffers(context, swapoffy * (columns / 8), columns, 
		swapoffy, &src, &dst, &wdth, &hght, &offy, y, buff0, devc);
    if (err)
        return err;
    
	if (gui_enabled)
	{
		if (!initialize_window())
			return -1;
	}
    
	c = (struct dispatcher_context *)malloc(sizeof(*c));
	if (!c)
		return -1;
    
	c->cmd_queue = cmd_queue;
	c->cqc = cqc;
	c->kern = kern;
	c->columns = columns;
	c->rows = rows;
	c->print_each = print_each;
	c->runs = runs;
	c->gui_enabled = gui_enabled;
	c->buff0 = buff0;
	c->src = src;
	c->dst = dst;
	c->wdth = wdth;
	c->hght = hght;
	c->offy = offy;
	c->y = y;
	c->swapoffy = swapoffy;
	c->context = context;
    c->win_height = rows;
    
	return start_dispatcher(c);
}
Esempio n. 21
0
static void riscv_sifive_board_init(MachineState *args)
{
    ram_addr_t ram_size = args->ram_size;
    const char *cpu_model = args->cpu_model;
    const char *kernel_filename = args->kernel_filename;
    const char *kernel_cmdline = args->kernel_cmdline;
    const char *initrd_filename = args->initrd_filename;
    MemoryRegion *system_memory = get_system_memory();
    MemoryRegion *main_mem = g_new(MemoryRegion, 1);
    RISCVCPU *cpu;
    CPURISCVState *env;
    int i;
    DeviceState *dev = qdev_create(NULL, TYPE_RISCV_SIFIVE_BOARD);
    object_property_set_bool(OBJECT(dev), true, "realized", NULL);

    /* Make sure the first 3 serial ports are associated with a device. */
    for (i = 0; i < 3; i++) {
        if (!serial_hds[i]) {
            char label[32];
            snprintf(label, sizeof(label), "serial%d", i);
            serial_hds[i] = qemu_chr_new(label, "null", NULL);
        }
    }

    /* init CPUs */
    if (cpu_model == NULL) {
        cpu_model = "any";
    }

    for (i = 0; i < smp_cpus; i++) {
        cpu = cpu_riscv_init(cpu_model);
        if (cpu == NULL) {
            fprintf(stderr, "Unable to find CPU definition\n");
            exit(1);
        }
        env = &cpu->env;

        /* Init internal devices */
        cpu_riscv_irq_init_cpu(env);
        cpu_riscv_clock_init(env);
        qemu_register_reset(main_cpu_reset, cpu);
    }
    cpu = RISCV_CPU(first_cpu);
    env = &cpu->env;

    /* register system main memory (actual RAM) */
    memory_region_init_ram(main_mem, NULL, "riscv_sifive_board.ram", 2147483648ll +
                           ram_size, &error_fatal);
    /* for phys mem size check in page table walk */
    env->memsize = ram_size;
    vmstate_register_ram_global(main_mem);
    memory_region_add_subregion(system_memory, 0x0, main_mem);

    if (kernel_filename) {
        loaderparams.ram_size = ram_size;
        loaderparams.kernel_filename = kernel_filename;
        loaderparams.kernel_cmdline = kernel_cmdline;
        loaderparams.initrd_filename = initrd_filename;
        load_kernel();
    }

    uint32_t reset_vec[8] = {
        0x297 + 0x80000000 - 0x1000, /* reset vector */
        0x00028067,                  /* jump to DRAM_BASE */
        0x00000000,                  /* reserved */
        0x0,                         /* config string pointer */
        0, 0, 0, 0                   /* trap vector */
    };
    reset_vec[3] = 0x1000 + sizeof(reset_vec); /* config string pointer */

    /* part one of config string - before memory size specified */
    const char *config_string1 = "platform {\n"
                                 "  vendor ucb;\n"
                                 "  arch spike;\n"
                                 "};\n"
                                 "plic { \n"
                                 "  interface \"plic\"; \n"
                                 "  ndevs 2; \n"
                                 "  priority { mem { 0x60000000 0x60000fff; }; }; \n"
                                 "  pending  { mem { 0x60001000 0x6000107f; }; }; \n"
                                 "  0 { \n"
                                 "    0 { \n"
                                 "      m { \n"
                                 "        ie  { mem { 0x60002000 0x6000207f; }; }; \n"
                                 "        ctl { mem { 0x60200000 0x60200007; }; }; \n"
                                 "      }; \n"
                                 "      s { \n"
                                 "        ie  { mem { 0x60002080 0x600020ff; }; }; \n"
                                 "        ctl { mem { 0x60201000 0x60201007; }; }; \n"
                                 "      }; \n"
                                 "    }; \n"
                                 "  }; \n"
                                 "}; \n"
                                 "rtc {\n"
                                 "  addr 0x" "40000000" ";\n"
                                 "};\n"
                                 "uart {\n"
                                 "  addr 0x40002000;\n"
                                 "};\n"
                                 "ram {\n"
                                 "  0 {\n"
                                 "    addr 0x" "80000000" ";\n"
                                 "    size 0x";


    /* part two of config string - after memory size specified */
    const char *config_string2 =  ";\n"
                                  "  };\n"
                                  "};\n"
                                  "core {\n"
                                  "  0" " {\n"
                                  "    " "0 {\n"
                                  "      isa " "rv64imafd" ";\n"
                                  "      timecmp 0x" "40000008" ";\n"
                                  "      ipi 0x" "40001000" ";\n"
                                  "    };\n"
                                  "  };\n"
                                  "};\n";

    /* build config string with supplied memory size */
    uint64_t rsz = ram_size;
    char *ramsize_as_hex_str = malloc(17);
    sprintf(ramsize_as_hex_str, "%016" PRIx64, rsz);
    char *config_string = malloc(strlen(config_string1) +
                                 strlen(ramsize_as_hex_str) +
                                 strlen(config_string2) + 1);
    config_string[0] = 0;
    strcat(config_string, config_string1);
    strcat(config_string, ramsize_as_hex_str);
    strcat(config_string, config_string2);

    /* copy in the reset vec and configstring */
    int q;
    for (q = 0; q < sizeof(reset_vec) / sizeof(reset_vec[0]); q++) {
        stl_p(memory_region_get_ram_ptr(main_mem) + 0x1000 + q * 4,
              reset_vec[q]);
    }

    int confstrlen = strlen(config_string);
    for (q = 0; q < confstrlen; q++) {
        stb_p(memory_region_get_ram_ptr(main_mem) + reset_vec[3] + q,
              config_string[q]);
    }

    sifive_uart_create(0x40002000, serial_hds[0]);

    /* timer device at 0x40000000, as specified in the config string above */
    timer_mm_init(system_memory, 0x40000000, env);

    /* TODO: VIRTIO */
}
Esempio n. 22
0
int main(int argc, char **argv)
{
	int vmmflags = VMM_VMCALL_PRINTF;
	uint64_t entry = 0;
	int ret;
	struct vm_trapframe *vm_tf;
	int c;
	int option_index;
	static struct option long_options[] = {
		{"debug",         no_argument,       0, 'd'},
		{"vmmflags",      required_argument, 0, 'v'},
		{"memsize",       required_argument, 0, 'm'},
		{"memstart",      required_argument, 0, 'M'},
		{"stack",         required_argument, 0, 'S'},
		{"cmdline_extra", required_argument, 0, 'c'},
		{"greedy",        no_argument,       0, 'g'},
		{"scp",           no_argument,       0, 's'},
		{"help",          no_argument,       0, 'h'},
		{0, 0, 0, 0}
	};

	fprintf(stderr, "%p %p %p %p\n", PGSIZE, PGSHIFT, PML1_SHIFT,
			PML1_PTE_REACH);

	if ((uintptr_t)__procinfo.program_end >= MinMemory) {
		fprintf(stderr,
		        "Panic: vmrunkernel binary extends into guest memory\n");
		exit(1);
	}

	while ((c = getopt_long(argc, argv, "dv:m:M:S:gsh", long_options,
	                        &option_index)) != -1) {
		switch (c) {
			case 'd':
				debug++;
				break;
			case 'v':
				vmmflags = strtoull(optarg, 0, 0);
				break;
			case 'm':
				memsize = strtoull(optarg, 0, 0);
				break;
			case 'M':
				memstart = strtoull(optarg, 0, 0);
				break;
			case 'S':
				stack = strtoull(optarg, 0, 0);
				break;
			case 'g':	/* greedy */
				parlib_never_yield = TRUE;
				break;
			case 's':	/* scp */
				parlib_wants_to_be_mcp = FALSE;
				break;
			case 'h':
			default:
				// Sadly, the getopt_long struct does
				// not have a pointer to help text.
				for (int i = 0;
				    i < sizeof(long_options)/sizeof(long_options[0]) - 1;
				    i++) {
					struct option *l = &long_options[i];

					fprintf(stderr, "%s or %c%s\n", l->name, l->val,
						l->has_arg ? " <arg>" : "");
				}
				exit(0);
		}
	}
	argc -= optind;
	argv += optind;
	if (argc < 1) {
		fprintf(stderr, "Usage: %s vmimage [-n (no vmcall printf)]\n", argv[0]);
		exit(1);
	}

	if ((uintptr_t)(memstart + memsize) >= (uintptr_t)BRK_START) {
		fprintf(stderr,
		        "memstart 0x%lx memsize 0x%lx -> 0x%lx is too large; overlaps BRK_START at %p\n",
			memstart, memsize, memstart + memsize, BRK_START);
		exit(1);
	}

	ram = mmap((void *)memstart, memsize,
	           PROT_READ | PROT_WRITE | PROT_EXEC,
	           MAP_POPULATE | MAP_ANONYMOUS, -1, 0);
	if (ram != (void *)memstart) {
		fprintf(stderr, "Could not mmap 0x%lx bytes at 0x%lx\n",
		        memsize, memstart);
		exit(1);
	}

	entry = load_kernel(argv[0]);
	if (entry == 0) {
		fprintf(stderr, "Unable to load kernel %s\n", argv[0]);
		exit(1);
	}

	vm->nr_gpcs = 1;
	vm->gpcis = &gpci;
	ret = vmm_init(vm, vmmflags);
	if (ret) {
		fprintf(stderr, "vmm_init failed: %r\n");
		exit(1);
	}

	/* Allocate 3 pages for page table pages: a page of 512 GiB
	 * PTEs with only one entry filled to point to a page of 1 GiB
	 * PTEs; a page of 1 GiB PTEs with only one entry filled to
	 * point to a page of 2 MiB PTEs; and a page of 2 MiB PTEs,
	 * all of which may be filled. For now, we don't handle
	 * starting addresses not aligned on 512 GiB boundaries or
	 * sizes > GiB */
	ret = posix_memalign((void **)&p512, PGSIZE, 3 * PGSIZE);
	if (ret) {
		perror("ptp alloc");
		exit(1);
	}

	/* Set up a 1:1 ("identity") page mapping from guest virtual
	 * to guest physical using the (host virtual)
	 * `kerneladdress`. This mapping may be used for only a short
	 * time, until the guest sets up its own page tables. Be aware
	 * that the values stored in the table are physical addresses.
	 * This is subtle and mistakes are easily disguised due to the
	 * identity mapping, so take care when manipulating these
	 * mappings. */
	p1 = &p512[NPTENTRIES];
	p2m = &p512[2 * NPTENTRIES];

	fprintf(stderr, "Map %p for %zu bytes\n", memstart, memsize);
	/* TODO: fix this nested loop so it's correct for more than
	 * one GiB. */
	for(uintptr_t p4 = memstart; p4 < memstart + memsize;
	    p4 += PML4_PTE_REACH) {
		p512[PML4(p4)] = (uint64_t)p1 | PTE_KERN_RW;
		for (uintptr_t p3 = p4; p3 < memstart + memsize;
		     p3 += PML3_PTE_REACH) {
			p1[PML3(p3)] = (uint64_t)p2m | PTE_KERN_RW;
			for (uintptr_t p2 = p3; p2 < memstart + memsize; p2 += PML2_PTE_REACH) {
				p2m[PML2(p2)] =
					(uint64_t)(p2) | PTE_KERN_RW | PTE_PS;
			}
		}
	}

	fprintf(stderr, "p512 %p p512[0] is 0x%lx p1 %p p1[0] is 0x%x\n", p512, p512[0], p1, p1[0]);

	vm_tf = gth_to_vmtf(vm->gths[0]);
	vm_tf->tf_cr3 = (uint64_t) p512;
	vm_tf->tf_rip = entry;
	vm_tf->tf_rsp = stack;
	vm_tf->tf_rsi = (uint64_t) 0;
	start_guest_thread(vm->gths[0]);

	uthread_sleep_forever();
	return 0;
}
Esempio n. 23
0
static int __cmd_trace(void)
{
	int ret, rc = EXIT_FAILURE;
	unsigned long offset = 0;
	unsigned long head = 0;
	struct stat perf_stat;
	event_t *event;
	uint32_t size;
	char *buf;

	trace_report();
	register_idle_thread(&threads, &last_match);

	input = open(input_name, O_RDONLY);
	if (input < 0) {
		perror("failed to open file");
		exit(-1);
	}

	ret = fstat(input, &perf_stat);
	if (ret < 0) {
		perror("failed to stat file");
		exit(-1);
	}

	if (!perf_stat.st_size) {
		fprintf(stderr, "zero-sized file, nothing to do!\n");
		exit(0);
	}
	header = perf_header__read(input);
	head = header->data_offset;
	sample_type = perf_header__sample_type(header);

	if (!(sample_type & PERF_SAMPLE_RAW))
		die("No trace sample to read. Did you call perf record "
		    "without -R?");

	if (load_kernel() < 0) {
		perror("failed to load kernel symbols");
		return EXIT_FAILURE;
	}

remap:
	buf = (char *)mmap(NULL, page_size * mmap_window, PROT_READ,
			   MAP_SHARED, input, offset);
	if (buf == MAP_FAILED) {
		perror("failed to mmap file");
		exit(-1);
	}

more:
	event = (event_t *)(buf + head);

	if (head + event->header.size >= page_size * mmap_window) {
		unsigned long shift = page_size * (head / page_size);
		int res;

		res = munmap(buf, page_size * mmap_window);
		assert(res == 0);

		offset += shift;
		head -= shift;
		goto remap;
	}

	size = event->header.size;

	if (!size || process_event(event, offset, head) < 0) {

		/*
		 * assume we lost track of the stream, check alignment, and
		 * increment a single u64 in the hope to catch on again 'soon'.
		 */

		if (unlikely(head & 7))
			head &= ~7ULL;

		size = 8;
	}

	head += size;

	if (offset + head < (unsigned long)perf_stat.st_size)
		goto more;

	rc = EXIT_SUCCESS;
	close(input);

	return rc;
}
Esempio n. 24
0
static
void mips_r4k_init(MachineState *machine)
{
    ram_addr_t ram_size = machine->ram_size;
    const char *cpu_model = machine->cpu_model;
    const char *kernel_filename = machine->kernel_filename;
    const char *kernel_cmdline = machine->kernel_cmdline;
    const char *initrd_filename = machine->initrd_filename;
    char *filename;
    MemoryRegion *address_space_mem = get_system_memory();
    MemoryRegion *ram = g_new(MemoryRegion, 1);
    MemoryRegion *bios;
    MemoryRegion *iomem = g_new(MemoryRegion, 1);
    MemoryRegion *isa_io = g_new(MemoryRegion, 1);
    MemoryRegion *isa_mem = g_new(MemoryRegion, 1);
    int bios_size;
    MIPSCPU *cpu;
    CPUMIPSState *env;
    ResetData *reset_info;
    int i;
    qemu_irq *i8259;
    ISABus *isa_bus;
    DriveInfo *hd[MAX_IDE_BUS * MAX_IDE_DEVS];
    DriveInfo *dinfo;
    int be;

    /* init CPUs */
    if (cpu_model == NULL) {
#ifdef TARGET_MIPS64
        cpu_model = "R4000";
#else
        cpu_model = "24Kf";
#endif
    }
    cpu = cpu_mips_init(cpu_model);
    if (cpu == NULL) {
        fprintf(stderr, "Unable to find CPU definition\n");
        exit(1);
    }
    env = &cpu->env;

    reset_info = g_malloc0(sizeof(ResetData));
    reset_info->cpu = cpu;
    reset_info->vector = env->active_tc.PC;
    qemu_register_reset(main_cpu_reset, reset_info);

    /* allocate RAM */
    if (ram_size > (256 << 20)) {
        fprintf(stderr,
                "qemu: Too much memory for this machine: %d MB, maximum 256 MB\n",
                ((unsigned int)ram_size / (1 << 20)));
        exit(1);
    }
    memory_region_allocate_system_memory(ram, NULL, "mips_r4k.ram", ram_size);

    memory_region_add_subregion(address_space_mem, 0, ram);

    memory_region_init_io(iomem, NULL, &mips_qemu_ops, NULL, "mips-qemu", 0x10000);
    memory_region_add_subregion(address_space_mem, 0x1fbf0000, iomem);

    /* Try to load a BIOS image. If this fails, we continue regardless,
       but initialize the hardware ourselves. When a kernel gets
       preloaded we also initialize the hardware, since the BIOS wasn't
       run. */
    if (bios_name == NULL)
        bios_name = BIOS_FILENAME;
    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);
    if (filename) {
        bios_size = get_image_size(filename);
    } else {
        bios_size = -1;
    }
#ifdef TARGET_WORDS_BIGENDIAN
    be = 1;
#else
    be = 0;
#endif
    if ((bios_size > 0) && (bios_size <= BIOS_SIZE)) {
        bios = g_new(MemoryRegion, 1);
        memory_region_init_ram(bios, NULL, "mips_r4k.bios", BIOS_SIZE,
                               &error_fatal);
        vmstate_register_ram_global(bios);
        memory_region_set_readonly(bios, true);
        memory_region_add_subregion(get_system_memory(), 0x1fc00000, bios);

        load_image_targphys(filename, 0x1fc00000, BIOS_SIZE);
    } else if ((dinfo = drive_get(IF_PFLASH, 0, 0)) != NULL) {
        uint32_t mips_rom = 0x00400000;
        if (!pflash_cfi01_register(0x1fc00000, NULL, "mips_r4k.bios", mips_rom,
                                   blk_by_legacy_dinfo(dinfo),
                                   sector_len, mips_rom / sector_len,
                                   4, 0, 0, 0, 0, be)) {
            fprintf(stderr, "qemu: Error registering flash memory.\n");
	}
    } else if (!qtest_enabled()) {
	/* not fatal */
        fprintf(stderr, "qemu: Warning, could not load MIPS bios '%s'\n",
		bios_name);
    }
    g_free(filename);

    if (kernel_filename) {
        loaderparams.ram_size = ram_size;
        loaderparams.kernel_filename = kernel_filename;
        loaderparams.kernel_cmdline = kernel_cmdline;
        loaderparams.initrd_filename = initrd_filename;
        reset_info->vector = load_kernel();
    }

    /* Init CPU internal devices */
    cpu_mips_irq_init_cpu(env);
    cpu_mips_clock_init(env);

    /* ISA bus: IO space at 0x14000000, mem space at 0x10000000 */
    memory_region_init_alias(isa_io, NULL, "isa-io",
                             get_system_io(), 0, 0x00010000);
    memory_region_init(isa_mem, NULL, "isa-mem", 0x01000000);
    memory_region_add_subregion(get_system_memory(), 0x14000000, isa_io);
    memory_region_add_subregion(get_system_memory(), 0x10000000, isa_mem);
    isa_bus = isa_bus_new(NULL, isa_mem, get_system_io(), &error_abort);

    /* The PIC is attached to the MIPS CPU INT0 pin */
    i8259 = i8259_init(isa_bus, env->irq[2]);
    isa_bus_irqs(isa_bus, i8259);

    rtc_init(isa_bus, 2000, NULL);

    pit = pit_init(isa_bus, 0x40, 0, NULL);

    serial_hds_isa_init(isa_bus, MAX_SERIAL_PORTS);

    isa_vga_init(isa_bus);

    if (nd_table[0].used)
        isa_ne2000_init(isa_bus, 0x300, 9, &nd_table[0]);

    ide_drive_get(hd, ARRAY_SIZE(hd));
    for(i = 0; i < MAX_IDE_BUS; i++)
        isa_ide_init(isa_bus, ide_iobase[i], ide_iobase2[i], ide_irq[i],
                     hd[MAX_IDE_DEVS * i],
		     hd[MAX_IDE_DEVS * i + 1]);

    isa_create_simple(isa_bus, "i8042");
}
Esempio n. 25
0
grub_err_t
grub_multiboot_load (grub_file_t file, const char *filename)
{
  char *buffer;
  grub_ssize_t len;
  struct multiboot_header *header;
  grub_err_t err;

  buffer = grub_malloc (MULTIBOOT_SEARCH);
  if (!buffer)
    return grub_errno;

  len = grub_file_read (file, buffer, MULTIBOOT_SEARCH);
  if (len < 32)
    {
      grub_free (buffer);
      if (!grub_errno)
	grub_error (GRUB_ERR_BAD_OS, N_("premature end of file %s"),
		    filename);
      return grub_errno;
    }

  header = find_header (buffer, len);

  if (header == 0)
    {
      grub_free (buffer);
      return grub_error (GRUB_ERR_BAD_ARGUMENT, "no multiboot header found");
    }

  if (header->flags & UNSUPPORTED_FLAGS)
    {
      grub_free (buffer);
      return grub_error (GRUB_ERR_UNKNOWN_OS,
			 "unsupported flag: 0x%x", header->flags);
    }

  err = load_kernel (file, filename, buffer, header);
  if (err)
    {
      grub_free (buffer);
      return err;
    }

  if (header->flags & MULTIBOOT_VIDEO_MODE)
    {
      switch (header->mode_type)
	{
	case 1:
	  err = grub_multiboot_set_console (GRUB_MULTIBOOT_CONSOLE_EGA_TEXT, 
					    GRUB_MULTIBOOT_CONSOLE_EGA_TEXT
					    | GRUB_MULTIBOOT_CONSOLE_FRAMEBUFFER,
					    0, 0, 0, 0);
	  break;
	case 0:
	  err = grub_multiboot_set_console (GRUB_MULTIBOOT_CONSOLE_FRAMEBUFFER,
					    GRUB_MULTIBOOT_CONSOLE_EGA_TEXT
					    | GRUB_MULTIBOOT_CONSOLE_FRAMEBUFFER,
					    header->width, header->height,
					    header->depth, 0);
	  break;
	default:
	  err = grub_error (GRUB_ERR_BAD_OS, 
			    "unsupported graphical mode type %d",
			    header->mode_type);
	  break;
	}
    }
  else
    err = grub_multiboot_set_console (GRUB_MULTIBOOT_CONSOLE_EGA_TEXT, 
				      GRUB_MULTIBOOT_CONSOLE_EGA_TEXT,
				      0, 0, 0, 0);
  return err;
}
Esempio n. 26
0
extern "C" int
main(stage2_args *args)
{
	TRACE(("boot(): enter\n"));

	if (heap_init(args) < B_OK)
		panic("Could not initialize heap!\n");

	TRACE(("boot(): heap initialized...\n"));

	// set debug syslog default
#if KDEBUG_ENABLE_DEBUG_SYSLOG
	gKernelArgs.keep_debug_output_buffer = true;
#endif

	add_stage2_driver_settings(args);

	platform_init_video();

	// the main platform dependent initialisation
	// has already taken place at this point.

	if (vfs_init(args) < B_OK)
		panic("Could not initialize VFS!\n");

	dprintf("Welcome to the Haiku boot loader!\n");

	bool mountedAllVolumes = false;

	Directory *volume = get_boot_file_system(args);

	if (volume == NULL || (platform_boot_options() & BOOT_OPTION_MENU) != 0) {
		if (volume == NULL)
			puts("\tno boot path found, scan for all partitions...\n");

		if (mount_file_systems(args) < B_OK) {
			// That's unfortunate, but we still give the user the possibility
			// to insert a CD-ROM or just rescan the available devices
			puts("Could not locate any supported boot devices!\n");
		}

		// ToDo: check if there is only one bootable volume!

		mountedAllVolumes = true;

		if (user_menu(&volume) < B_OK) {
			// user requested to quit the loader
			goto out;
		}
	}

	if (volume != NULL) {
		// we got a volume to boot from!
		status_t status;
		while ((status = load_kernel(args, volume)) < B_OK) {
			// loading the kernel failed, so let the user choose another
			// volume to boot from until it works
			volume = NULL;

			if (!mountedAllVolumes) {
				// mount all other file systems, if not already happened
				if (mount_file_systems(args) < B_OK)
					panic("Could not locate any supported boot devices!\n");

				mountedAllVolumes = true;
			}

			if (user_menu(&volume) < B_OK || volume == NULL) {
				// user requested to quit the loader
				goto out;
			}
		}

		// if everything is okay, continue booting; the kernel
		// is already loaded at this point and we definitely
		// know our boot volume, too
		if (status == B_OK) {
			register_boot_file_system(volume);

			if ((platform_boot_options() & BOOT_OPTION_DEBUG_OUTPUT) == 0)
				platform_switch_to_logo();

			load_modules(args, volume);
			load_driver_settings(args, volume);

			// apply boot settings
			apply_boot_settings();

			// set up kernel args version info
			gKernelArgs.kernel_args_size = sizeof(kernel_args);
			gKernelArgs.version = CURRENT_KERNEL_ARGS_VERSION;

			// clone the boot_volume KMessage into kernel accessible memory
			// note, that we need to 4 byte align the buffer and thus allocate
			// 3 more bytes
			void* buffer = kernel_args_malloc(gBootVolume.ContentSize() + 3);
			if (!buffer) {
				panic("Could not allocate memory for the boot volume kernel "
					"arguments");
			}

			buffer = (void*)(((addr_t)buffer + 3) & ~(addr_t)0x3);
			memcpy(buffer, gBootVolume.Buffer(), gBootVolume.ContentSize());
			gKernelArgs.boot_volume = buffer;
			gKernelArgs.boot_volume_size = gBootVolume.ContentSize();

			// ToDo: cleanup, heap_release() etc.
			platform_start_kernel();
		}
	}

out:
	heap_release(args);
	return 0;
}
Esempio n. 27
0
static void
mips_mipssim_init(MachineState *machine)
{
    ram_addr_t ram_size = machine->ram_size;
    const char *cpu_model = machine->cpu_model;
    const char *kernel_filename = machine->kernel_filename;
    const char *kernel_cmdline = machine->kernel_cmdline;
    const char *initrd_filename = machine->initrd_filename;
    char *filename;
    MemoryRegion *address_space_mem = get_system_memory();
    MemoryRegion *isa = g_new(MemoryRegion, 1);
    MemoryRegion *ram = g_new(MemoryRegion, 1);
    MemoryRegion *bios = g_new(MemoryRegion, 1);
    MIPSCPU *cpu;
    CPUMIPSState *env;
    ResetData *reset_info;
    int bios_size;

    /* Init CPUs. */
    if (cpu_model == NULL) {
#ifdef TARGET_MIPS64
        cpu_model = "5Kf";
#else
        cpu_model = "24Kf";
#endif
    }
    cpu = cpu_mips_init(cpu_model);
    if (cpu == NULL) {
        fprintf(stderr, "Unable to find CPU definition\n");
        exit(1);
    }
    env = &cpu->env;

    reset_info = g_malloc0(sizeof(ResetData));
    reset_info->cpu = cpu;
    reset_info->vector = env->active_tc.PC;
    qemu_register_reset(main_cpu_reset, reset_info);

    /* Allocate RAM. */
    memory_region_allocate_system_memory(ram, NULL, "mips_mipssim.ram",
                                         ram_size);
    memory_region_init_ram(bios, NULL, "mips_mipssim.bios", BIOS_SIZE,
                           &error_fatal);
    vmstate_register_ram_global(bios);
    memory_region_set_readonly(bios, true);

    memory_region_add_subregion(address_space_mem, 0, ram);

    /* Map the BIOS / boot exception handler. */
    memory_region_add_subregion(address_space_mem, 0x1fc00000LL, bios);
    /* Load a BIOS / boot exception handler image. */
    if (bios_name == NULL)
        bios_name = BIOS_FILENAME;
    filename = qemu_find_file(QEMU_FILE_TYPE_BIOS, bios_name);
    if (filename) {
        bios_size = load_image_targphys(filename, 0x1fc00000LL, BIOS_SIZE);
        g_free(filename);
    } else {
        bios_size = -1;
    }
    if ((bios_size < 0 || bios_size > BIOS_SIZE) &&
            !kernel_filename && !qtest_enabled()) {
        /* Bail out if we have neither a kernel image nor boot vector code. */
        error_report("Could not load MIPS bios '%s', and no "
                     "-kernel argument was specified", bios_name);
        exit(1);
    } else {
        /* We have a boot vector start address. */
        env->active_tc.PC = (target_long)(int32_t)0xbfc00000;
    }

    if (kernel_filename) {
        loaderparams.ram_size = ram_size;
        loaderparams.kernel_filename = kernel_filename;
        loaderparams.kernel_cmdline = kernel_cmdline;
        loaderparams.initrd_filename = initrd_filename;
        reset_info->vector = load_kernel();
    }

    /* Init CPU internal devices. */
    cpu_mips_irq_init_cpu(cpu);
    cpu_mips_clock_init(cpu);

    /* Register 64 KB of ISA IO space at 0x1fd00000. */
    memory_region_init_alias(isa, NULL, "isa_mmio",
                             get_system_io(), 0, 0x00010000);
    memory_region_add_subregion(get_system_memory(), 0x1fd00000, isa);

    /* A single 16450 sits at offset 0x3f8. It is attached to
       MIPS CPU INT2, which is interrupt 4. */
    if (serial_hds[0])
        serial_init(0x3f8, env->irq[4], 115200, serial_hds[0],
                    get_system_io());

    if (nd_table[0].used)
        /* MIPSnet uses the MIPS CPU INT0, which is interrupt 2. */
        mipsnet_init(0x4200, env->irq[2], &nd_table[0]);
}
Esempio n. 28
0
int
load_kernel_and_config(struct loader_info *li)
{
	EFI_HANDLE handles[128];
	EFI_BLOCK_IO *blkio;
	UINTN i, nparts = sizeof(handles);
	EFI_STATUS status;
	EFI_DEVICE_PATH *devpath;
	unsigned char buf[512];
	EFI_LBA head;
	UINTN size;

	status = systab->BootServices->LocateHandle(ByProtocol, &BlockIoGUID, NULL, &nparts, handles);
	nparts /= sizeof(handles[0]);

	for (i = 0; i < nparts; i++) {

		status = systab->BootServices->HandleProtocol(handles[i], &DevicePathGUID, (void **)&devpath); 
		if (EFI_ERROR(status))
			continue;

		while (!IsDevicePathEnd(NextDevicePathNode(devpath)))
			devpath = NextDevicePathNode(devpath);

		status = systab->BootServices->HandleProtocol(handles[i], &BlockIoGUID, (void **)&blkio); 
		if (EFI_ERROR(status))
			continue;

		if (!blkio->Media->LogicalPartition)
			continue;

		status = blkio->ReadBlocks(blkio, blkio->Media->MediaId, 0, 512, buf);
		if (EFI_ERROR(status))
			continue;

		if (buf[0] != 0xeb && buf[0] != 0xe9)
			continue;

		if (buf[510] != 0x55 || buf[511] != 0xaa)
			continue;

		/* ここまできたら blkio は FAT ファイルシステム */

		if (search_kernel(blkio, &head, &size))
			continue;

		if (load_kernel(blkio, &head, &size, li))
			return -1;

		printstr("KERNEL BASE: ");
		printhex64(li->kernel_base);
		putchar('\n');
		printstr("KERNEL SIZE: ");
		printhex64(li->kernel_size);
		putchar('\n');

		if (search_config(blkio, &head, &size)
		  || (size == 0)
		  || load_config(blkio, &head, &size, li)) {
			li->config_base = 0;
			li->config_size = 0;
		}

		printstr("CONFIG BASE: ");
		printhex64(li->config_base);
		putchar('\n');
		printstr("CONFIG SIZE: ");
		printhex64(li->config_size);
		putchar('\n');

		/* 正常完了 */
		return 0;
	}

	/* 失敗 */
	return -1;
}
Esempio n. 29
0
File: mips_r4k.c Progetto: CPFL/gxen
static
void mips_r4k_init (ram_addr_t ram_size, int vga_ram_size,
                    const char *boot_device,
                    const char *kernel_filename, const char *kernel_cmdline,
                    const char *initrd_filename, const char *cpu_model)
{
    char buf[1024];
    unsigned long bios_offset;
    int bios_size;
    CPUState *env;
    RTCState *rtc_state;
    int i;
    qemu_irq *i8259;
    int index;
    BlockDriverState *hd[MAX_IDE_BUS * MAX_IDE_DEVS];

    /* init CPUs */
    if (cpu_model == NULL) {
#ifdef TARGET_MIPS64
        cpu_model = "R4000";
#else
        cpu_model = "24Kf";
#endif
    }
    env = cpu_init(cpu_model);
    if (!env) {
        fprintf(stderr, "Unable to find CPU definition\n");
        exit(1);
    }
    qemu_register_reset(main_cpu_reset, env);

    /* allocate RAM */
    if (ram_size > (256 << 20)) {
        fprintf(stderr,
                "qemu: Too much memory for this machine: %d MB, maximum 256 MB\n",
                ((unsigned int)ram_size / (1 << 20)));
        exit(1);
    }
    cpu_register_physical_memory(0, ram_size, IO_MEM_RAM);

    if (!mips_qemu_iomemtype) {
        mips_qemu_iomemtype = cpu_register_io_memory(0, mips_qemu_read,
                                                     mips_qemu_write, NULL);
    }
    cpu_register_physical_memory(0x1fbf0000, 0x10000, mips_qemu_iomemtype);

    /* Try to load a BIOS image. If this fails, we continue regardless,
       but initialize the hardware ourselves. When a kernel gets
       preloaded we also initialize the hardware, since the BIOS wasn't
       run. */
    bios_offset = ram_size + vga_ram_size;
    if (bios_name == NULL)
        bios_name = BIOS_FILENAME;
    snprintf(buf, sizeof(buf), "%s/%s", bios_dir, bios_name);
    bios_size = load_image(buf, phys_ram_base + bios_offset);
    if ((bios_size > 0) && (bios_size <= BIOS_SIZE)) {
	cpu_register_physical_memory(0x1fc00000,
				     BIOS_SIZE, bios_offset | IO_MEM_ROM);
    } else if ((index = drive_get_index(IF_PFLASH, 0, 0)) > -1) {
        uint32_t mips_rom = 0x00400000;
        cpu_register_physical_memory(0x1fc00000, mips_rom,
	                     qemu_ram_alloc(mips_rom) | IO_MEM_ROM);
        if (!pflash_cfi01_register(0x1fc00000, qemu_ram_alloc(mips_rom),
            drives_table[index].bdrv, sector_len, mips_rom / sector_len,
            4, 0, 0, 0, 0)) {
            fprintf(stderr, "qemu: Error registering flash memory.\n");
	}
    }
    else {
	/* not fatal */
        fprintf(stderr, "qemu: Warning, could not load MIPS bios '%s'\n",
		buf);
    }

    if (kernel_filename) {
        loaderparams.ram_size = ram_size;
        loaderparams.kernel_filename = kernel_filename;
        loaderparams.kernel_cmdline = kernel_cmdline;
        loaderparams.initrd_filename = initrd_filename;
        load_kernel (env);
    }

    /* Init CPU internal devices */
    cpu_mips_irq_init_cpu(env);
    cpu_mips_clock_init(env);

    /* The PIC is attached to the MIPS CPU INT0 pin */
    i8259 = i8259_init(env->irq[2]);

    rtc_state = rtc_init(0x70, i8259[8], 2000);

    /* Register 64 KB of ISA IO space at 0x14000000 */
    isa_mmio_init(0x14000000, 0x00010000);
    isa_mem_base = 0x10000000;

    pit = pit_init(0x40, i8259[0]);

    for(i = 0; i < MAX_SERIAL_PORTS; i++) {
        if (serial_hds[i]) {
            serial_init(serial_io[i], i8259[serial_irq[i]], 115200,
                        serial_hds[i]);
        }
    }

    isa_vga_init(phys_ram_base + ram_size, ram_size,
                 vga_ram_size);

    if (nd_table[0].vlan)
        isa_ne2000_init(0x300, i8259[9], &nd_table[0]);

    if (drive_get_max_bus(IF_IDE) >= MAX_IDE_BUS) {
        fprintf(stderr, "qemu: too many IDE bus\n");
        exit(1);
    }

    for(i = 0; i < MAX_IDE_BUS * MAX_IDE_DEVS; i++) {
        index = drive_get_index(IF_IDE, i / MAX_IDE_DEVS, i % MAX_IDE_DEVS);
        if (index != -1)
            hd[i] = drives_table[index].bdrv;
        else
            hd[i] = NULL;
    }

    for(i = 0; i < MAX_IDE_BUS; i++)
        isa_ide_init(ide_iobase[i], ide_iobase2[i], i8259[ide_irq[i]],
                     hd[MAX_IDE_DEVS * i],
		     hd[MAX_IDE_DEVS * i + 1]);

    i8042_init(i8259[1], i8259[12], 0x60);
}
Esempio n. 30
0
int main(int argc, const char** argv)
{
	size_t x = 512, y = 250000; //y has to be a multiple of ciDeviceCount!
	struct svm_node* px = (struct svm_node*)malloc((x+1)*sizeof(struct svm_node));
	gen_data(px, x, 1, 3);
	struct svm_node* py = (struct svm_node*)malloc((x+1)*y*sizeof(struct svm_node));
	for(size_t i = 0; i < y; ++i) {
		struct svm_node* tmp = py+i*(x+1);
		gen_data(tmp, x, 3,2);
	}
	dtype* result = (dtype*)malloc(y*sizeof(dtype));
	int* pyLength = (int*)malloc(y*sizeof(int));
	
	for(size_t i = 0; i < y; ++i)
	{
		for(size_t j = 0; py[i*(x+1)+j].index >= 0; ++j)
			pyLength[i] = py[i*(x+1)+j].index;
		++pyLength[i];
	}
	
	cl_int err = CL_SUCCESS;
//	cl_platform_id platform = NULL;
//	cl_uint ciDeviceCount = 0;
//	cl_device_id *device = NULL;

	// retrieve devices
	cl_platform_id platform;
	err = clGetPlatformIDs(1, &platform, NULL);
	cl_device_id device;
	err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_CPU, 1, &device, NULL);

	size_t localDim  = 256l;
	size_t globalDim = localDim*y;
/*	
	device = (cl_device_id *)malloc(ciDeviceCount * sizeof(cl_device_id) );
	err = clGetDeviceIDs(platform, CL_DEVICE_TYPE_ALL, ciDeviceCount, device, NULL);
	if (err != CL_SUCCESS)
	{
		printf("Failed to get devices:\n%s\n", oclErrorString(err));
		return -1;
	}
	*/
	//Create the context
	cl_context context1 = clCreateContext(0, 1, &device, NULL, NULL, &err);
	if(err != CL_SUCCESS)
	{
		printf("Context creation failed:\n%d\n", err);
		return -1;
	}										 

	// create a command queue for first device the context reported
	cl_command_queue queue = clCreateCommandQueue(context1, device, 0, 0);
	
	// load program from disk
	char *tmp = strdup(argv[0]);
	char* my_dir = dirname(tmp);

//	size_t program_length;
	char path[256];
  	snprintf(path, PATH_MAX - 1, "%s/vecops.cl", my_dir);
 
	cl_program vecops = load_kernel(path, context1);

	if(err != CL_SUCCESS)
	{
		printf("Program creation failed:\n%d\n", (err));
		return -1;
	}
 
	err = clBuildProgram(vecops, 0, NULL, "-I.", NULL, NULL);
	if(err != CL_SUCCESS)
	{
			err = clGetProgramBuildInfo(vecops, device, CL_PROGRAM_BUILD_LOG, 8192, buffer, NULL);
			if(err != CL_SUCCESS)
				printf("Cannot get build info: %d\n", (err));

			printf("Build log:\n%s\n", buffer);
	}
	
	// create kernel
	cl_kernel sparsedot_kernel;
	
#if version == 1
	sparsedot_kernel = clCreateKernel(vecops, "sparsedot1_kernel", &err);
#endif
#if version == 2
	sparsedot_kernel = clCreateKernel(vecops, "sparsedot4_kernel", &err);
#endif
#if version == 3
	sparsedot_kernel = clCreateKernel(vecops, "sparsedot3_kernel", &err);
#endif
	if (err != CL_SUCCESS)
	{
		printf("Kernel creation failed:\n%d\n", (err));
		return -1;
	}
	
	 
	// allocate memory on the devices
	cl_mem px_d, py_d, result_d, pyLength_d;
	
#if version == 1
	px_d = clCreateBuffer(context1,
							 CL_MEM_READ_ONLY,
							 (x+1) * sizeof(struct svm_node),
							 0, &err);
#endif
#if version == 2 || version == 3
	//unpack px
	int size = px[x-1].index+1;

	for(size_t i = 0; i < y; ++i)
		size = size > pyLength[i] ? size : pyLength[i];

	dtype* px_u = (dtype*)calloc(size, sizeof(dtype));

	unpack(px, px_u);
	printf("px size: %d\n", size);
#endif
#if version == 3
	size_t height, width;
	clGetDeviceInfo(device, CL_DEVICE_IMAGE2D_MAX_HEIGHT, sizeof(size_t), &height, 0);
	clGetDeviceInfo(Device, CL_DEVICE_IMAGE2D_MAX_WIDTH, sizeof(size_t), &width, 0);

	size_t region[3];
	region[2] = 1;

	region[0] = min(4, size);
	region[1] = (size+2-1) / 4;
		

	cl_image_format px_format;
	px_format.image_channel_order = CL_R;
	px_format.image_channel_data_type = CL_FLOAT;
#endif
#if version == 2
	px_d = clCreateBuffer(context1,
				 CL_MEM_READ_ONLY,
				 size * sizeof(dtype),
				 0, &err);
#endif
#if version == 3
	 px_d = clCreateImage2D(context1, CL_MEM_READ_ONLY, &px_format,
				  region[0], region[1], 0, 0, &err);

#endif
	if(err != CL_SUCCESS)
	{
		printf("Failed to allocate px:\n%d\n", (err));
		return -1;
	}
	py_d = clCreateBuffer(context1,
		 CL_MEM_READ_ONLY,
		 (x+1) * y * sizeof(struct svm_node),
		 0, &err);
	if(err != CL_SUCCESS)
	{
		printf("Failed to allocate px:\n%d\n", (err));
		return -1;
	}
	result_d = clCreateBuffer(context1,
		CL_MEM_WRITE_ONLY,
		y * sizeof(dtype),
		0, 0);
	pyLength_d = clCreateBuffer(context1,
		CL_MEM_READ_ONLY,
		y * sizeof(int),
		0, 0);
	

#if bench
	//start time measurement
	start_timer(0);
#endif

	// copy host vectors to device
	err = CL_SUCCESS;
   
    err |= clEnqueueWriteBuffer(queue, py_d, CL_FALSE, 0, 
								(x+1) * y * sizeof(struct svm_node), py, 0, NULL, NULL);
									

	err |= clEnqueueWriteBuffer(queue, pyLength_d, CL_FALSE, 0, 
								y * sizeof(int), pyLength, 0, NULL, NULL);

#if version == 1
	err |= clEnqueueWriteBuffer(queue, px_d, CL_FALSE, 0, 
								(x+1) * sizeof(struct svm_node), px, 0, NULL, NULL);
#endif
#if version == 2
	err |= clEnqueueWriteBuffer(queue, px_d, CL_FALSE, 0, 
								size * sizeof(dtype), px_u, 0, NULL, NULL);
#endif
#if version == 3
	size_t offset[] = {0,0,0};
	err |= clEnqueueWriteImage(queue, px_d, CL_TRUE, offset, region, sizeof(dtype), 0, 
							   px_u, 0, 0, NULL);
#endif
	clFinish(queue);

	 
	if(err != CL_SUCCESS)
	{
		printf("Data transfer to GPU failed:\n%d\n", (err));
		return -1;
	}

#if bench
	stop_timer(0);
	start_timer(1);
#endif
	// set kernel arguments

	clSetKernelArg(sparsedot_kernel, 0, sizeof(cl_mem), (void *) &px_d);
	clSetKernelArg(sparsedot_kernel, 1, sizeof(cl_mem), (void *) &py_d);
	clSetKernelArg(sparsedot_kernel, 2, sizeof(cl_mem), (void *) &result_d);
	clSetKernelArg(sparsedot_kernel, 3, sizeof(cl_mem), (void *) &pyLength_d);
	clSetKernelArg(sparsedot_kernel, 4, sizeof(cl_ulong), (void *) &x);
	clSetKernelArg(sparsedot_kernel, 5, sizeof(cl_ulong), (void *) &y);
//	clSetKernelArg(sparsedot_kernel, 6, sizeof(cl_float8)*localDim, 0);
#if version == 3
		clSetKernelArg(sparsedot_kernel, 7, sizeof(cl_long), (void *) &region[1]) ;		
		clSetKernelArg(sparsedot_kernel, 8, sizeof(cl_long), (void *) &region[0]) ;		
#endif
	clFlush(queue);

	// start kernel
	err = clEnqueueNDRangeKernel(queue, sparsedot_kernel, 1, 0, &globalDim, &localDim,
					   0, NULL, 0);

	if(err != CL_SUCCESS)
	{
		printf("Kernel launch failed:\n%d\n", (err));
		return -1;
	}

	clFinish(queue);
	
#if bench	
	stop_timer(1);
	start_timer(2);
#endif

	cl_event result_gather;
	 
	// Non-blocking copy of result from device to host
	err = clEnqueueReadBuffer(queue, result_d, CL_FALSE, 0, y * sizeof(dtype), 
						result, 0, NULL, &result_gather);
	
	if(err != CL_SUCCESS)
	{
		printf("Reading result failed:\n%d\n", (err));
		return -1;
	}

	// CPU sync with GPU
	clWaitForEvents(1, &result_gather);

#if bench	
	// stop GPU time measurement
	stop_timer(2);
#endif
	//check result
/*	for(size_t i = 0; i < y; ++i)
	{
		printf("%f ", result[i]);
	}
	printf("\n");
  */  

#if bench
	start_timer(3);
#endif
	bool correct = validate(px, py, result, x, y);
#if bench
	stop_timer(3);
	printf("v%i; x: %lu, y: %lu\n", version, x, y);
	printf("CPU: %f, upcpy: %f DeviceCalc: %f, downcpy: %f\n", 
		   get_secs(3), get_secs(0), get_secs(1), get_secs(2));
#endif
	
	if(correct)
		printf("SUCCESS!\n");
		
	//cleenup

	clReleaseKernel(sparsedot_kernel);
	clReleaseCommandQueue(queue);
	clReleaseEvent(result_gather);
	clReleaseMemObject(px_d);
	clReleaseMemObject(py_d);
	clReleaseMemObject(result_d);
	clReleaseMemObject(pyLength_d);
//	clReleaseDevice(device);

	free(px);
#if version == 2 || version == 3
	free(px_u);
#endif
	free(py);
	free(result);

	return 0;
}