Exemplo n.º 1
0
int do_boota (cmd_tbl_t * cmdtp, int flag, int argc, char *argv[])
{
	unsigned char *load_address = (unsigned char *) CONFIG_SYS_LOAD_ADDR;
	unsigned char *base_address;
	unsigned long offset;

	unsigned long part_number = 0;
	block_dev_desc_t *boot_disk;
	char *s;
	struct bootcode_block *boot_code;

	/* Get parameters */

	switch (argc) {
	case 2:
		load_address = (unsigned char *) simple_strtol (argv[1], NULL, 16);
		part_number = 0;
		break;
	case 3:
		load_address = (unsigned char *) simple_strtol (argv[1], NULL, 16);
		part_number = simple_strtol (argv[2], NULL, 16);
		break;
	}

	base_address = load_address;

	PRINTF ("Loading boot code from disk %d to %p\n", part_number,
			load_address);

	/* Find the appropriate disk device */
	boot_disk = ide_get_dev (part_number);
	if (!boot_disk) {
		PRINTF ("Unknown disk %d\n", part_number);
		return 1;
	}

	/* Find the bootcode block */
	boot_code = get_bootcode (boot_disk);
	if (!boot_code) {
		PRINTF ("Not a bootable disk %d\n", part_number);
		return 1;
	}

	/* Only use the offset from the first block */
	offset = boot_code->load_data[0];
	memcpy (load_address, &boot_code->load_data[1], 122 * 4);
	load_address += 122 * 4;

	/* Setup for the loop */
	bblk.next = boot_code->next;
	boot_code = &bblk;

	/* Scan the chain, and copy the loader succesively into the destination area */
	while (0xffffffff != boot_code->next) {
		PRINTF ("Loading block %d\n", boot_code->next);

		/* Load block */
		if (1 !=
			boot_disk->block_read (boot_disk->dev, boot_code->next, 1,
								   (ulong *) & bblk)) {
			PRINTF ("Read error\n");
			return 1;
		}

		/* check sum */
		if (sum_block ((struct block_header *) (ulong *) & bblk) != 0) {
			PRINTF ("Checksum error\n");
			return 1;
		}

		/* Ok, concatenate it to the already loaded code */
		memcpy (load_address, boot_code->load_data, 123 * 4);
		load_address += 123 * 4;
	}

	printf ("Bootcode loaded to %p (size %d)\n", base_address,
			load_address - base_address);
	printf ("Entry point at %p\n", base_address + offset);

	flush_cache (base_address, load_address - base_address);


	s = getenv ("autostart");
	if (s && strcmp (s, "yes") == 0) {
		void (*boot) (bd_t *, char *, block_dev_desc_t *);
		char *args;

		boot = (void (*)(bd_t *, char *, block_dev_desc_t *)) (base_address + offset);
		boot (gd->bd, getenv ("amiga_bootargs"), boot_disk);
	}


	return 0;
}
Exemplo n.º 2
0
int main(int argc, char * argv[])
{
#ifdef DEBUG
  open_debug();
#endif
  init_static_control_simple();
  void ask(addr_t addr)
    {
      char str[DEFAULT_TRANSFER];
      struct args args = { .log_addr = addr, .log_len = DEFAULT_TRANSFER, .phys_addr = (unsigned long)str, .direction = direct_read };
      root_strategy->ops[0][opcode_trans]((void*)root_strategy, &args, "");
      if(args.success) {
	 printf("%s", str);
      }
    }
  bool cmd(addr_t addr, char * str, char * param)
    {
      struct args args = { .log_addr = addr, .log_len = strlen(str), .phys_addr = (unsigned long)str, .direction = direct_write };
      root_strategy->ops[0][opcode_trans]((void*)root_strategy, &args, param);
      return args.success;
    }
  addr_t boot(char * str, char * param)
    {
      struct args args = { .log_len = DEFAULT_TRANSFER, .reader = FALSE, .exclu = TRUE, .action = action_wait, .melt = TRUE, .try_len = DEFAULT_TRANSFER, .op_code = opcode_gadr };
      root_strategy->ops[0][opcode_gadr]((void*)root_strategy, &args, param);
      if(!args.success) {
        printf("!!!!! gadrcreateget failed\n");
	exit(-1);
      }
      args.log_len = strlen(str);
      args.phys_addr = (unsigned long)str;
      args.direction = direct_write;
      args.op_code = opcode_trans;
      root_strategy->ops[0][opcode_trans]((void*)root_strategy, &args, param);
      if(!args.success) {
        printf("!!!!! trans '%s' failed\n", str);
	exit(-1);
      }
      return args.log_addr;
    }
  char str[256];
  addr_t control = DEFAULT_TRANSFER;
  cmd(control, "output:=control\n", "");
  // basic level
#if 0
  addr_t dev = boot("brick:=device_dummy_linux\n output:=out", "testfile");
  sprintf(str, "brick:=buffer_dummy_linux\n \n connect dev:=%llx:out\n output:=out {\n", dev);
  addr_t buffer = boot(str, "");
  sprintf(str, "brick:=map_simple\n connect in:=%llx:out\noutput:=out", buffer);
#else
  sprintf(str, "brick:=map_dummy\n output:=out{\n");
#endif
  addr_t map = boot(str, "");
  sprintf(str, "brick:=adapt_meta\n connect in:=%llx:out\n output:=out\n", map);
  addr_t meta = boot(str, "");
#if 0
  sprintf(str, "brick:=spy_trace\n connect in:=%llx:out\n output:=out\n", meta);
  meta = boot(str, "spylog");
#endif
  // create root hook
  cmd(0, "output:=_root", "");
  cmd(meta, "connect hook:=0:_root", "");
  // strategy level
  sprintf(str, "brick:=fs_simple\n connect strat:=%llx:control\n output:=control{\n", control);
  addr_t fs = boot(str, "_root");
  // testing
  sprintf(str, "brick:=bench_fs\n connect strat:=%llx:control\n", fs);
  addr_t bench = boot(str, "");
#if 1
  ask(0);
  ask(DEFAULT_TRANSFER);
  ask(0x3000);
#endif
  printf("================== STARTING BENCH ================\n");
  cmd(bench, "output:=dummy", "1000");
  printf("================== END BENCH ================\n");
#ifdef MOVE_COUNT
  extern void print_counts(void);
  print_counts();
  printf("------------------------------------\n");
  printf("_makespace: shortcuts: %d count1: %d count2: %d\n", count_0, count_1, count_2);
  printf("creates (count_c1) = %d, triggering creates (count_c2) = %d\n", count_c1, count_c2);
#endif
  cmd(meta, "brick/=adapt_meta", "");
  cmd(map, "brick/=map_dummy", "");
#ifdef DEBUG
  close_debug();
#endif
  return 0;
}
Exemplo n.º 3
0
int main(int argc, char **argv) {
    uint64_t t;
    int myargc = 2;
    ///char **myargv;
    //	printf("\n argc val =%d",argc);
    ///	argc = 2;
    ////	argv[0] = "myself";
    //char *name = "/home/prajakta/praj_multi2sim_RandD/guestos_multi2sim/mytest/simple";
    //printf("\n The length of the hardcoded complete path of simple file is : %d\n", strlen(name));
    //argv[1] = "/home/prajakta/praj_multi2sim_RandD/guestos_multi2sim/mytest/simple";


    fprintf(stderr, "********************************************************");
    fprintf(stderr, "\n WELCOME TO GUESTOS\n");
    fprintf(stderr, "********************************************************\n");
    //Subhajit Changes

    /* Options */
    opt_init();
    sim_reg_options();
    ///////////////////////////////////////
    /////	p_reg_options();
    ///	cache_system_reg_options();
    ////	opt_check_options(&argc, argv);

    /////////////////////////////////////////////





    /* Initialize */
    ke_init();
    
	boot();

    /////	install_sighandler();
    //	printf("\n enter path:");
    //	fgets(user_prog_path,200,stdin);
    //for( ii=0;ii<strlen(user_prog_path);ii++)
    //	argv[1][ii]=user_prog_path[ii];
    //char * origargv= argv;
    //argv=argv++;
    //argv[1]=(char *)user_prog_path;
    //The following lines are written to take the file path from the user and removing the last string terminating character....
    /*	argv[1] = (char *)malloc(strlen( (user_prog_path) - 1) * sizeof(char));
            for(i = 0; i < strlen(user_prog_path) - 1;i++)
                    argv[1][i] = user_prog_path[i];*/
    //argv=origargv;

    //argv=argv++;
    //// argv=user_prog_path;
    //argv=origargv;
    ///fgets(user_prog_path,max_path_length,stdin);
    shell();
    if (*configfile) {
        ///		printf("\n Entered inside checking\n\n")	;
        opt_check_config(configfile);
    }
    //////////printf("\n User entered path of binary in main : %s",user_prog_path);
    //strncpy(*(argv+1),user_prog_path,max_path_length);
    //	strncpy(myargv[0],user_prog_path,200);
    //	strcpy(argv[1],user_prog_path);
    //printf("\nafter strcpy");
    //argv[1] = user_prog_path;
    //printf("\n\n\\nnnnnnnnnnnnnnnnnnnnnnnn");
    //	printf("\n Value of argv[1] is : %s\n\n\n", argv[1]);
    //	printf("\n Length of file name in argv[1] = %d\n", strlen(argv[1]));
    //strncpy(argv[1],user_prog_path,max_path_length);
    ///////strcpy(argv[0],user_prog_path);
    ///printf("\n the rcvd pa ths is %s \n",user_prog_path);

    ///printf("\n the rcvd pa ths is %s \n",user_prog_path);
    ///printf("\n the rcvd pa ths is %s \n",user_prog_path);
    /* Load programs from configuration file and command line. */
    ///////	if (*ctxconfig)
    srand(time(NULL));
    swap_initialize();
    ld_load_prog_from_ctxconfig(ctxconfig);
    ///////////////////if (argc >= 1)
    ///		ld_load_prog_from_cmdline(argc - 1, user_prog_path );
    ////////////		ld_load_prog_from_cmdline(argc - 1, argv + 1);
    ///		ld_load_prog_from_cmdline(argc - 1, myargv);

    /* Simulation loop */
    signal(SIGINT, &sim_signal_handler);
    signal(SIGABRT, &sim_signal_handler);
    signal(SIGFPE, &sim_signal_handler);
    signal(SIGUSR2, &sim_signal_handler);
    //raise(8);
    //raise(10);
    //raise(12);
    while (!sigint_received) {

        /* Break point */
        if (break_point && ke->context_list_head->regs->eip == break_point) {
            regs_dump(ke->context_list_head->regs, stdout);
            break;
        }

        /* Run an instruction from each running context */
        ke_run();
        sim_inst += ke->running_count;
        if (!ke->context_list_head){
		//	printf("Moving out of while loop ke_run\n");
			break;
		}
            

        /* Stop conditions */
        sim_cycle++;
        if ((sim_cycle >= max_cycles && max_cycles) ||
                (sim_inst >= max_inst && max_inst)) {
            regs_dump(isa_regs, stdout);
            ke_dump(stdout);
            break;
        }
        if (sim_cycle == inst_reset && inst_reset)
            isa_inst_stat_reset();

        if (*inst_stop && !strcmp(isa_inst.format, inst_stop))
            panic("instruction '%s' found", inst_stop);


    }

    /* Finalization */
    ke_done();
    ///opt_done();
    ///debug_done();
    mhandle_done();
    return 0;
}
Exemplo n.º 4
0
int main(void)
{
	NetbootParam *param;

	// Initialize some consoles.
	serial_console_init();
	cbmem_console_init();
	video_console_init();
	input_init();

	printf("\n\nStarting netboot on " CONFIG_BOARD "...\n");

	timestamp_init();

	if (run_init_funcs())
		halt();

	// Make sure graphics are available if they aren't already.
	enable_graphics();

	dc_usb_initialize();

	srand(timer_raw_value());

	printf("Looking for network device... ");
	while (!net_get_device())
		usb_poll();
	printf("done.\n");

	printf("Waiting for link... ");
	int ready = 0;
	while (!ready) {
		if (net_ready(&ready))
			halt();
	}
	mdelay(200);	// some dongles need more time than they think
	printf("done.\n");

	// Start up the network stack.
	uip_init();

	// Plug in the MAC address.
	const uip_eth_addr *mac_addr = net_get_mac();
	if (!mac_addr)
		halt();
	printf("MAC: ");
	print_mac_addr(mac_addr);
	printf("\n");
	uip_setethaddr(*mac_addr);

	// Find out who we are.
	uip_ipaddr_t my_ip, next_ip, server_ip;
	const char *dhcp_bootfile;
	while (dhcp_request(&next_ip, &server_ip, &dhcp_bootfile))
		printf("Dhcp failed, retrying.\n");

	printf("My ip is ");
	uip_gethostaddr(&my_ip);
	print_ip_addr(&my_ip);
	printf("\nThe DHCP server ip is ");
	print_ip_addr(&server_ip);
	printf("\n");

	// Retrieve settings from the shared data area.
	FmapArea shared_data;
	if (fmap_find_area("SHARED_DATA", &shared_data)) {
		printf("Couldn't find the shared data area.\n");
		halt();
	}
	void *data = flash_read(shared_data.offset, shared_data.size);
	netboot_params_init(data, shared_data.size);

	// Get TFTP server IP and file name from params with DHCP as fallback
	uip_ipaddr_t *tftp_ip = NULL;
	param = netboot_params_val(NetbootParamIdTftpServerIp);
	if (param->data && param->size >= sizeof(uip_ipaddr_t)) {
		tftp_ip = (uip_ipaddr_t *)param->data;
		printf("TFTP server IP set from firmware parameters: ");
	} else {
		tftp_ip = &next_ip;
		printf("TFTP server IP supplied by DHCP server: ");
	}
	print_ip_addr(tftp_ip);
	printf("\n");

	const char *bootfile = NULL;
	param = netboot_params_val(NetbootParamIdBootfile);
	if (param->data && param->size > 0 && strnlen((const char *)param->data,
			param->size) < param->size) {
		bootfile = (const char *)param->data;
		printf("Bootfile set from firmware parameters: %s\n", bootfile);
	} else {
		bootfile = dhcp_bootfile;
		printf("Bootfile supplied by DHCP server: %s\n", bootfile);
	}

	// Download the bootfile.
	uint32_t size;
	if (tftp_read(payload, tftp_ip, bootfile, &size, MaxPayloadSize)) {
		printf("Tftp failed.\n");
		if (dhcp_release(server_ip))
			printf("Dhcp release failed.\n");
		halt();
	}
	printf("The bootfile was %d bytes long.\n", size);

	// Use command line from params when present (added to the default).
	param = netboot_params_val(NetbootParamIdKernelArgs);
	if (param->data && param->size > 0 && *(char *)param->data != '\0') {
		cmd_line[sizeof(def_cmd_line) - 1] = ' ';
		strncpy(&cmd_line[sizeof(def_cmd_line)], param->data,
			sizeof(cmd_line) - sizeof(def_cmd_line));
		printf("Command line set from firmware parameters.\n");
	// Otherwise, try to fetch it dynamically as a TFTP file.
	} else if (!(tftp_read(cmd_line, tftp_ip, "cmdline." CONFIG_BOARD,
			       &size, sizeof(cmd_line) - 1))) {
		while (cmd_line[size - 1] <= ' ')  // strip trailing whitespace
			if (!--size) break;	   // and control chars (\n, \r)
		cmd_line[size] = '\0';
		while (size--)			   // replace inline control
			if (cmd_line[size] < ' ')  // chars with spaces
				cmd_line[size] = ' ';
		printf("Command line loaded dynamically from TFTP server.\n");
	// If the file doesn't exist, finally fall back to built-in default.
	} else {
		printf("No command line from TFTP, falling back to default.\n");
	}
	cmd_line[sizeof(cmd_line) - 1] = '\0';

	// We're done on the network, so release our IP.
	if (dhcp_release(server_ip)) {
		printf("Dhcp release failed.\n");
		halt();
	}

	// Add tftp server IP into command line.
	static const char def_tftp_cmdline[] = " tftpserverip=xxx.xxx.xxx.xxx";
	const int tftp_cmdline_def_size = sizeof(def_tftp_cmdline) - 1;
	int cmd_line_size = strlen(cmd_line);
	if (cmd_line_size + tftp_cmdline_def_size >= sizeof(cmd_line)) {
		printf("Out of space adding TFTP server IP to the command line.\n");
		return 1;
	}
	sprintf(&cmd_line[cmd_line_size], " tftpserverip=%d.%d.%d.%d",
		uip_ipaddr1(tftp_ip), uip_ipaddr2(tftp_ip),
		uip_ipaddr3(tftp_ip), uip_ipaddr4(tftp_ip));
	printf("The command line is: %s\n", cmd_line);

	// Boot.
	boot(payload, cmd_line, NULL, NULL);

	// We should never get here.
	printf("Got to the end!\n");
	halt();
	return 0;
}
Exemplo n.º 5
0
 worldClass::worldClass()
 {
     boot("Default");
 }
Exemplo n.º 6
0
static void
boot_fromfs(void)
{
    union {
	Elf64_Ehdr eh;
    } hdr;
    static Elf64_Phdr ep[2];
#if 0
    static Elf64_Shdr es[2];
#endif
    caddr_t p;
    ufs_ino_t ino;
    uint64_t addr;
    int i, j;

    if (!(ino = lookup(kname))) {
	if (!ls)
	    printf("No %s\n", kname);
	return;
    }
    if (xfsread(ino, &hdr, sizeof(hdr)))
	return;

    if (IS_ELF(hdr.eh)) {
	fs_off = hdr.eh.e_phoff;
	for (j = i = 0; i < hdr.eh.e_phnum && j < 2; i++) {
	    if (xfsread(ino, ep + j, sizeof(ep[0])))
		return;
	    if (ep[j].p_type == PT_LOAD)
		j++;
	}
	for (i = 0; i < 2; i++) {
	    p = (caddr_t)ep[i].p_paddr;
	    fs_off = ep[i].p_offset;
	    if (xfsread(ino, p, ep[i].p_filesz))
		return;
	}
	p += roundup2(ep[1].p_memsz, PAGE_SIZE);
#if 0
	bootinfo.bi_symtab = VTOP(p);
	if (hdr.eh.e_shnum == hdr.eh.e_shstrndx + 3) {
	    fs_off = hdr.eh.e_shoff + sizeof(es[0]) *
		(hdr.eh.e_shstrndx + 1);
	    if (xfsread(ino, &es, sizeof(es)))
		return;
	    for (i = 0; i < 2; i++) {
		*(Elf32_Word *)p = es[i].sh_size;
		p += sizeof(es[i].sh_size);
		fs_off = es[i].sh_offset;
		if (xfsread(ino, p, es[i].sh_size))
		    return;
		p += es[i].sh_size;
	    }
	}
#endif
	addr = hdr.eh.e_entry;
#if 0
	bootinfo.bi_esymtab = VTOP(p);
#endif
    } else {
	printf("Invalid %s\n", "format");
	return;
    }
    boot((void *)addr, beri_argc, beri_argv, beri_envv);
}
Exemplo n.º 7
0
Buzzer::Buzzer(MyDigitalOut* buzzer)
{
    this->_buzzer = buzzer;
    boot();
}
Exemplo n.º 8
0
Arquivo: boot.c Projeto: RP7/misoc
void serialboot(void)
{
	struct sfl_frame frame;
	int failed;
	unsigned int cmdline_adr, initrdstart_adr, initrdend_adr;
	static const char str[SFL_MAGIC_LEN+1] = SFL_MAGIC_REQ;
	const char *c;

	printf("Booting from serial...\n");

	c = str;
	while(*c) {
		uart_write(*c);
		c++;
	}
	if(!check_ack()) {
		printf("Timeout\n");
		return;
	}

	failed = 0;
	cmdline_adr = initrdstart_adr = initrdend_adr = 0;
	while(1) {
		int i;
		int actualcrc;
		int goodcrc;

		/* Grab one frame */
		frame.length = uart_read();
		frame.crc[0] = uart_read();
		frame.crc[1] = uart_read();
		frame.cmd = uart_read();
		for(i=0;i<frame.length;i++)
			frame.payload[i] = uart_read();

		/* Check CRC */
		actualcrc = ((int)frame.crc[0] << 8)|(int)frame.crc[1];
		goodcrc = crc16(&frame.cmd, frame.length+1);
		if(actualcrc != goodcrc) {
			failed++;
			if(failed == MAX_FAILED) {
				printf("Too many consecutive errors, aborting");
				return;
			}
			uart_write(SFL_ACK_CRCERROR);
			continue;
		}

		/* CRC OK */
		switch(frame.cmd) {
			case SFL_CMD_ABORT:
				failed = 0;
				uart_write(SFL_ACK_SUCCESS);
				return;
			case SFL_CMD_LOAD: {
				char *writepointer;

				failed = 0;
				writepointer = (char *)(
					 ((unsigned int)frame.payload[0] << 24)
					|((unsigned int)frame.payload[1] << 16)
					|((unsigned int)frame.payload[2] << 8)
					|((unsigned int)frame.payload[3] << 0));
				for(i=4;i<frame.length;i++)
					*(writepointer++) = frame.payload[i];
				uart_write(SFL_ACK_SUCCESS);
				break;
			}
			case SFL_CMD_JUMP: {
				unsigned int addr;

				failed = 0;
				addr =  ((unsigned int)frame.payload[0] << 24)
					|((unsigned int)frame.payload[1] << 16)
					|((unsigned int)frame.payload[2] << 8)
					|((unsigned int)frame.payload[3] << 0);
				uart_write(SFL_ACK_SUCCESS);
				boot(cmdline_adr, initrdstart_adr, initrdend_adr, addr);
				break;
			}
			case SFL_CMD_CMDLINE:
				failed = 0;
				cmdline_adr =  ((unsigned int)frame.payload[0] << 24)
					      |((unsigned int)frame.payload[1] << 16)
					      |((unsigned int)frame.payload[2] << 8)
					      |((unsigned int)frame.payload[3] << 0);
				uart_write(SFL_ACK_SUCCESS);
				break;
			case SFL_CMD_INITRDSTART:
				failed = 0;
				initrdstart_adr =  ((unsigned int)frame.payload[0] << 24)
					          |((unsigned int)frame.payload[1] << 16)
					          |((unsigned int)frame.payload[2] << 8)
					          |((unsigned int)frame.payload[3] << 0);
				uart_write(SFL_ACK_SUCCESS);
				break;
			case SFL_CMD_INITRDEND:
				failed = 0;
				initrdend_adr =  ((unsigned int)frame.payload[0] << 24)
					        |((unsigned int)frame.payload[1] << 16)
					        |((unsigned int)frame.payload[2] << 8)
					        |((unsigned int)frame.payload[3] << 0);
				uart_write(SFL_ACK_SUCCESS);
				break;
			default:
				failed++;
				if(failed == MAX_FAILED) {
					printf("Too many consecutive errors, aborting");
					return;
				}
				uart_write(SFL_ACK_UNKNOWN);
				break;
		}
	}
}
Exemplo n.º 9
0
int main(int argc, char * argv[])
{
#ifdef DEBUG
  open_debug();
#endif
  init_static_control_simple();
  bool cmd(addr_t addr, char * str, char * param)
    {
      struct args args = { .log_addr = addr, .log_len = strlen(str), .phys_addr = (unsigned long)str, .direction = direct_write };
      root_strategy->ops[0][opcode_trans]((void*)root_strategy, &args, param);
      return args.success;
    }
  addr_t boot(char * str, char * param)
    {
      struct args args = { .log_len = DEFAULT_TRANSFER, .reader = FALSE, .exclu = TRUE, .action = action_wait, .melt = TRUE, .try_len = DEFAULT_TRANSFER, .op_code = opcode_gadr };
      root_strategy->ops[0][opcode_gadr]((void*)root_strategy, &args, param);
      if(!args.success) {
        printf("!!!!! gadr failed\n");
	exit(-1);
      }
      args.log_len = strlen(str);
      args.phys_addr = (unsigned long)str;
      args.direction = direct_write;
      args.op_code = opcode_trans;
      root_strategy->ops[0][opcode_trans]((void*)root_strategy, &args, param);
      if(!args.success) {
        printf("!!!!! trans '%s' failed\n", str);
	exit(-1);
      }
      return args.log_addr;
    }
  char str[256];
  addr_t control = DEFAULT_TRANSFER;
  // basic level
#if 0
  addr_t dev = boot("brick:=device_dummy_linux\n output:=out", "testfile");
  sprintf(str, "brick:=buffer_dummy_linux\n \n connect dev:=%llx:out\n output:=out {\n", dev);
  addr_t buffer = boot(str, "");
  sprintf(str, "brick:=map_simple\n connect in:=%llx:out\noutput:=out", buffer);
#else
  sprintf(str, "brick:=map_dummy\n output:=out{\n");
#endif
  addr_t map = boot(str, "");
  sprintf(str, "brick:=adapt_meta\n connect in:=%llx:out\n output:=out\n", map);
  addr_t meta = boot(str, "");
  // create root hook
  cmd(0, "output:=_root", "");
  cmd(meta, "connect hook:=0:_root", "");
  // strategy level
  sprintf(str, "brick:=fs_simple\n connect strat:=%llx:control\n output:=control{\n", control);
  addr_t fs = boot(str, "_root");
  // testing

  sprintf(str, "brick:=bench_fs\n connect strat:=%llx:control\n", fs);
  addr_t bench = boot(str, "");

  printf("================== STARTING BENCH ================\n");
  cmd(bench, "output:=dummy", "1");
  printf("================== END BENCH ================\n");

  cmd(meta, "brick/=adapt_meta", "");
  printf("------------------------------------\n");
  printf("size_input=%u\n", (unsigned) sizeof(struct input));
  printf("size_output=%u\n", (unsigned) sizeof(struct output));
  printf("size_conn=%u\n", (unsigned) sizeof(struct connector_header));
  printf("size_brick=%u\n", (unsigned) sizeof(struct brick_header));

  struct timespec t0, t1;
  printf("------------------------------------\n");

  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t0);
  int i;
  for(i = 0; i < 1000000; i++) {
	  getpid();
	  getpid();
  }
  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t1);
  printf("getpid time=%11lld\n", ((long long)t1.tv_sec-(long long)t0.tv_sec)*1000LL + ((long long)t1.tv_nsec-(long long)t0.tv_nsec)/1000000LL);
  printf("------------------------------------\n");

  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t0);
  for(i = 0; i < 1000000; i++) {
	  int fd = open("/etc/passwd", O_RDONLY);
	  close(fd);
  }
  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t1);
  printf("open   time=%11lld\n", ((long long)t1.tv_sec-(long long)t0.tv_sec)*1000LL + ((long long)t1.tv_nsec-(long long)t0.tv_nsec)/1000000LL);
  printf("------------------------------------\n");

  int fd = open("/etc/services", O_RDONLY);
  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t0);
  for(i = 0; i < 1000000; i++) {
	  char buf[4096];
	  lseek(fd, 0, SEEK_SET);
	  read(fd, buf, 4096);
  }
  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t1);
  close(fd);
  printf("read   time=%11lld\n", ((long long)t1.tv_sec-(long long)t0.tv_sec)*1000LL + ((long long)t1.tv_nsec-(long long)t0.tv_nsec)/1000000LL);
  printf("------------------------------------\n");
  sprintf(str, "brick:=adapt_meta\n connect in:=%llx:out\n", map);
  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t0);
  for(i = 0; i < 1000000; i++) {
    struct conn_info conn1 = { .conn_addr = meta, .conn_name = "in" };
    struct conn_info conn2 = { .conn_addr = map, .conn_name = "out" };
    struct args args = { .log_addr = meta, .name = "adapt_meta", .conn1 = &conn1, .conn2 = &conn2 };
    root_strategy->ops[0][opcode_instbrick]((void*)root_strategy, &args, "");
    root_strategy->ops[0][opcode_connect]((void*)root_strategy, &args, "");
    root_strategy->ops[0][opcode_deinstbrick]((void*)root_strategy, &args, "");
#if 0
	  addr_t adr = cmd(meta, str, "");
	  cmd(meta, "brick/=adapt_meta\n", "");
#endif
  }
  clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t1);
  printf("inst   time=%11lld\n", ((long long)t1.tv_sec-(long long)t0.tv_sec)*1000LL + ((long long)t1.tv_nsec-(long long)t0.tv_nsec)/1000000LL);
  printf("------------------------------------\n");
  cmd(map, "brick/=map_dummy", "");
#ifdef DEBUG
  close_debug();
#endif
  return 0;
}
Exemplo n.º 10
0
bool FolderImage::readSector(quint16 sector, QByteArray &data)
{
    /* Boot */

    QFile boot(dir.path() + "/$boot.bin");
    data = QByteArray(128, 0);
    int bootFileSector;

    if (sector == 1) {
         if (!boot.open(QFile::ReadOnly)) {
             data[1] = 0x01;
             data[3] = 0x07;
             data[4] = 0x40;
             data[5] = 0x15;
             data[6] = 0x4c;
             data[7] = 0x14;
             data[8] = 0x07;     // JMP 0x0714
             data[0x14] = 0x38;  // SEC
             data[0x15] = 0x60;  // RTS
         } else {
             data = boot.read(128);
             buildDirectory();
             for(int i=0; i<64; i++) {
                 // AtariDOS, MyDos, SmartDOS  and DosXL
                 if(atariFiles[i].longName.toUpper() == "DOS.SYS") {
                     bootFileSector = 369 + i;
                     data[15] = bootFileSector % 256;
                     data[16] = bootFileSector / 256;
                     break;
                 }
                 // MyPicoDOS
                 if(atariFiles[i].longName.toUpper() == "PICODOS.SYS") {
                     bootFileSector = 369 + i;
                     if(g_disablePicoHiSpeed) {
                         data[15] = 0;
                         QFile boot(dir.path() + "/$boot.bin");
                         QByteArray speed;
                         boot.open(QFile::ReadWrite);
                         boot.seek(15);
                         speed = boot.read(1);
                         speed[0] = '\x30';
                         boot.seek(15);
                         boot.write(speed);
                         boot.close();
                     }
                     data[9] = bootFileSector % 256;
                     data[10] = bootFileSector / 256;
                     // Create the piconame.txt file
                     QFile picoName(dir.path() + "/piconame.txt");
                     picoName.open(QFile::WriteOnly);
                     QByteArray nameLine;
                     nameLine.append(dir.dirName() + '\x9B');
                     picoName.write(nameLine);
                     for(int i=0; i<64; i++){
                     if(atariFiles[i].exists) {
                         if(atariFiles[i].longName != "$boot.bin") {
                                 nameLine.clear();
                                 nameLine.append(atariFiles[i].atariName);
                                 QByteArray space;
                                 int size;
                                 size = atariFiles[i].atariName.size();
                                 for(int j=0; j<=8-size-1; j++) {
                                     space[j] = '\x20';
                                 }
                                 nameLine.append(space);
                                 nameLine.append(atariFiles[i].atariExt);
                                 nameLine.append('\x20');
                                 nameLine.append(atariFiles[i].longName.mid(0, atariFiles[i].longName.indexOf(".", -1)-1));
                                 nameLine.append('\x9B');
                                 picoName.write(nameLine);
                         }
                      } else {
                             picoName.close();
                             break;
                      }
                     }
                     break;
                 }
                 // SpartaDOS, force it to change to AtariDOS format after the boot
                 if(atariFiles[i].longName.toUpper() == "X32.DOS") {
                     QFile x32Dos(dir.path() + "/x32.dos");
                     x32Dos.open(QFile::ReadOnly);
                     QByteArray flag;
                     flag = x32Dos.readAll();
                     if(flag[0] == '\xFF') {
                         flag[0] = '\x00';
                         data[1] = 0x01;
                         data[3] = 0x07;
                         data[4] = 0x40;
                         data[5] = 0x15;
                         data[6] = 0x4c;
                         data[7] = 0x14;
                         data[8] = 0x07;
                         data[0x14] = 0x38;
                         data[0x15] = 0x60;
                     }
                   break;
                 }
             }
         }
         return true;
    }
    if (sector == 2) {
        boot.open(QFile::ReadOnly);
        boot.seek(128);
        data = boot.read(128);
        return true;
    }
    if (sector == 3) {
        boot.open(QFile::ReadOnly);
        boot.seek(256);
        data = boot.read(128);
        return true;
    }
    // SpartaDOS Boot
    if ((sector >= 32 && sector <= 134) ||
        sector == 5 || sector == 6) {
        boot.open(QFile::ReadOnly);
        boot.seek((sector-1)*128);
        data = boot.read(128);
        if(sector == 134) {
            QFile x32Dos(dir.path() + "/x32.dos");
            x32Dos.open(QFile::ReadWrite);
            QByteArray flag;
            flag = x32Dos.readAll();
            if(flag[0] == '\x00') {
                flag[0] = '\xFF';
                x32Dos.seek(0);
                x32Dos.write(flag);
                x32Dos.close();
            }
        }
        return true;
    }

    /* VTOC */
    if (sector == 360) {
        data = QByteArray(128, 0);
        data[0] = 2;
        data[1] = 1010 % 256;
        data[2] = 1010 / 256;
        data[10] = 0x7F;
        for (int i = 11; i < 100; i++) {
            data[i] = 0xff;
        }
        return true;
    }

    /* Directory sectors */
    if (sector >= 361 && sector <=368) {
        if (sector == 361) {
            buildDirectory();
        }
        data.resize(0);
        for (int i = (sector - 361) * 8; i < (sector - 360) * 8; i++) {
            QByteArray entry;
            if (!atariFiles[i].exists) {
                entry = QByteArray(16, 0);
            } else {
                entry = "";
                entry[0] = 0x42;
                QFileInfo info = atariFiles[i].original;;
                int size = (info.size() + 124) / 125;
                if (size > 999) {
                    size = 999;
                }
                entry[1] = size % 256;
                entry[2] = size / 256;
                int first = 369 + i;
                entry[3] = first % 256;
                entry[4] = first / 256;
                entry += atariFiles[i].atariName.toLatin1();
                while (entry.count() < 13) {
                    entry += 32;
                }
                entry += atariFiles[i].atariExt.toLatin1();
                while (entry.count() < 16) {
                    entry += 32;
                }
            }
            data += entry;
        }
        return true;
    }

    /* Data sectors */

    /* First sector of the file */
        int size, next;
        if  (sector >= 369 && sector <= 432) {
            atariFileNo = sector - 369;
            if (!atariFiles[atariFileNo].exists) {
                data = QByteArray(128, 0);
                return true;
            }
            QFile file(atariFiles[atariFileNo].original.absoluteFilePath());
            file.open(QFile::ReadOnly);
            data = file.read(125);
            size = data.size();
            data.resize(128);
            if (file.atEnd()) {
                next = 0;
            }
            else {
                next = 433;
            }
            data[125] = (atariFileNo * 4) | (next / 256);
            data[126] = next % 256;
            data[127] = size;
            return true;
        }

    /* Rest of the file sectors */
        if ((sector >= 433 && sector <= 1023)) {
            QFile file(atariFiles[atariFileNo].original.absoluteFilePath());
            file.open(QFile::ReadOnly);
            atariFiles[atariFileNo].pos = (125+((sector-433)*125))+(atariFiles[atariFileNo].sectPass*73875);
            file.seek(atariFiles[atariFileNo].pos);
            data = file.read(125);
            next = sector + 1;
            if (sector == 1023) {
                next = 433;
                atariFiles[atariFileNo].sectPass += 1;
            }
            size = data.size();
            data.resize(128);
            atariFiles[atariFileNo].lastSector = sector;
            if (file.atEnd()) {
                next = 0;
            }
            data[125] = (atariFileNo * 4) | (next / 256);
            data[126] = next % 256;
            data[127] = size;
            return true;
        }

    /* Any other sector */

        data = QByteArray(128, 0);
        return true;
}
Exemplo n.º 11
0
void flashboot(void)
{
	unsigned int *flashbase;
	unsigned int length;
	unsigned int crc;
#ifdef FIXME
	unsigned int got_crc;
	int r = 0;
#endif
	int lzma;
	//int i;

	
	if(rescue) {
	    printf("G: Booting from flash (rescue)...\n");
		flashbase = (unsigned int *)FLASH_OFFSET_RESCUE_APP;
	}
	else {
	    //printf("F: Booting from flash...\n");
		flashbase = (unsigned int *)FLASH_OFFSET_REGULAR_APP;
	}
	length = *flashbase++;
	if(length & 0x80000000) {
		length &= 0x7fffffff;
		lzma = 1;
		printf("E: LZMA mode enable\n");
	} else
		lzma = 0;
	crc = *flashbase++;
	
    length = 2628328;
    
	if(length < 32) {
		printf("E: Invalid flash boot image length: length < 32\n");
		return;
	}
	if(length > 4*1024*1024) {
		printf("E: Invalid flash boot image length: length > 4*1024*1024\n");
		return;
	}

	if(lzma) {
	printf("D: Decompressing LZMA\n");
#ifdef FIXME
		printf("I: Decompressing %d bytes from flash...\n", length);
		got_crc = crc32((unsigned char *)flashbase, length);
		if(crc != got_crc) {
			printf("E: CRC failed (expected %08x, got %08x)\n", crc, got_crc);
			return;
		}

		r = unlzma((unsigned char *)flashbase, length, NULL, NULL, (void *)SDRAM_BASE, NULL, lzma_error);

		if(r < 0)
			return;
#endif
	} else {
		//printf("I: Loading %d bytes from flash...\n", length);
        //printf("A: Start Loading bytes from flash...\n");
		if((memcpy((void *)SDRAM_BASE, flashbase, length)) == NULL)
		    printf("C: memcpy return NULL.\n");
	   // printf("B: Loading bytes from flash over...\n");
#ifdef FIXME
		got_crc = crc32((unsigned char *)SDRAM_BASE, length);
		if(crc != got_crc) {
			printf("E: CRC failed (expected %08x, got %08x)\n", crc, got_crc);
			return;
		}
#endif
	}

	//printf("H: Booting...\n");
	boot(0, 0, 0, rescue, SDRAM_BASE);
}
Exemplo n.º 12
0
MAIN_QTHREAD(int, argc, char **, argv) { // macro to enable multithreaded gui
#else
  int main(int argc, char **argv) { // regular main without gui
#endif
    try {
      // check input parameters
      if ((argc != 2) && (argc != 3) ) {
	cerr << "warning: wrong number of parameters." << endl;
	cerr << "usage: detect <config file> [directory or file]" << endl;
	//	return -1;
      }
#ifdef __LINUX__
      feenableexcept(FE_DIVBYZERO | FE_INVALID); // enable float exceptions
#endif
      // load configuration
      configuration	conf(argv[1], true, true, false);
      if (conf.exists_true("fixed_randomization"))
	cout << "Using fixed seed: " << fixed_init_drand() << endl;
      else
	cout << "Using random seed: " << dynamic_init_drand(argc, argv) << endl;
      if (!conf.exists("root2") || !conf.exists("current_dir")) {
	string dir;
	dir << dirname(argv[1]) << "/";
	cout << "Looking for trained files in: " << dir << endl;
	conf.set("root2", dir.c_str());
	conf.set("current_dir", dir.c_str());
      }
      conf.set("run_type", "detect"); // tell conf that we are in detect mode
      conf.resolve(); // manual call to resolving variable
      bool              silent        = conf.exists_true("silent");
      if (conf.exists_true("show_conf") && !silent) conf.pretty();
      // output synchronization
      bool sync = conf.exists_true("sync_outputs");
      mutex out_mutex;
      mutex_ostream mutout(std::cout, &out_mutex, "Thread M");
      mutex_ostream muterr(std::cerr, &out_mutex, "Thread M");
      ostream &mout = sync ? mutout : cout;
      ostream &merr = sync ? muterr : cerr;
      bootstrapping<t_net> boot(conf);
      // output dir
      string outdir = detection_thread<t_net>::get_output_directory(conf);
      mout << "Saving outputs to " << outdir << endl;
      // save conf to output dir
      string cname = outdir;
      cname << filename(argv[1]);
      if (conf.write(cname.c_str()))
	mout << "Wrote configuration to " << cname << endl;
      // load classes of network
      idx<ubyte> classes(1,1);
      vector<string> sclasses;
      try { // try loading classes names but do not stop upon failure
	load_matrix<ubyte>(classes, conf.get_cstring("classes"));
      } catch(string &err) { merr << "warning: " << err << endl; }
      sclasses = ubyteidx_to_stringvector(classes);
      t_bbox_saving bbsaving = bbox_none;
      if (conf.exists("bbox_saving"))
	bbsaving = (t_bbox_saving) conf.get_int("bbox_saving");
      bboxes boxes(bbsaving, &outdir, mout, merr);

      uint              ipp_cores     = 1;
      if (conf.exists("ipp_cores")) ipp_cores = conf.get_uint("ipp_cores");
      ipp_init(ipp_cores); // limit IPP (if available) to 1 core
      bool		save_video    = conf.exists_true("save_video");
      bool              save_detections = conf.exists_true("save_detections");
      int		height        = -1;
      int		width         = -1;
      if (conf.exists("input_height")) height = conf.get_int("input_height");
      if (conf.exists("input_width")) width = conf.get_int("input_width");
      bool              input_random  = conf.exists_true("input_random");
      uint              npasses       = 1;
      char              next_on_key   = 0;
      if (conf.exists("next_on_key")) {
	next_on_key = conf.get_char("next_on_key");
	mout << "Press " << next_on_key << " to process next frame." << endl;
      }
      uint skip_frames = conf.try_get_uint("skip_frames", 0);
      if (conf.exists("input_npasses"))
	npasses = conf.get_uint("input_npasses");
      string viddir;
      if (save_video) {
	viddir << outdir << "video/";
	mkdir_full(viddir);
      }
      bool precomputed_boxes = conf.exists("bbox_file");
      uint save_bbox_period = conf.try_get_uint("save_bbox_period", 500);
      idxdim crop(1, 1, 1);
      if (conf.exists("input_crop"))
	crop = string_to_idxdim(conf.get_string("input_crop"));

      string		cam_type;
#ifdef __LINUX__ // default camera for linux if not defined
      cam_type = "v4l2";
#endif
      if (conf.exists("camera"))
	cam_type = conf.get_string("camera");

      // allocate threads
      uint nthreads = 1;
      bool updated = false;
      idx<ubyte> detframe; // frame returned by detection thread
      uint frame_id = 0;
      svector<midx<t_net> > all_samples, samples; // extracted samples
      bboxes all_bbsamples, bbsamples; // boxes corresponding to samples
      if (conf.exists("nthreads"))
	nthreads = (std::max)((uint) 1, conf.get_uint("nthreads"));
      list<detection_thread<t_net>*>  threads;
      list<detection_thread<t_net>*>::iterator ithreads;
      idx<uint> total_saved(nthreads);
      idx_clear(total_saved);
      mout << "Initializing " << nthreads << " detection threads." << endl;
      for (uint i = 0; i < nthreads; ++i) {
	detection_thread<t_net> *dt =
	  new detection_thread<t_net>(conf, &out_mutex, NULL, NULL, sync);
	threads.push_back(dt);
	dt->start();
      }
      // image search can be configured with a search pattern
      const char *fpattern = IMAGE_PATTERN_MAT;
      if (conf.exists("file_pattern"))
	fpattern = conf.get_cstring("file_pattern");

      // initialize camera (opencv, directory, shmem or video)
      idx<ubyte> frame(std::max(height, 1), std::max(width, 1), 3);
      camera<ubyte> *cam = NULL, *cam2 = NULL;
      if (!strcmp(cam_type.c_str(), "directory")) {
	string dir;
	if (argc >= 3) // read input dir from command line
	  dir = argv[2];
	else if (conf.exists("input_dir"))
	  dir = conf.get_string("input_dir");
	// given list
	list<string> files;
	if (conf.exists("input_list")) {
	  files = string_to_stringlist(conf.get_string("input_list"));
	  cam = new camera_directory<ubyte>(dir.c_str(), height, width,
					    input_random, npasses, mout, merr,
					    fpattern, &files);
	} else // given directory only
	  cam = new camera_directory<ubyte>(dir.c_str(), height, width,
					    input_random, npasses, mout, merr,
					    fpattern, &files);
      } else if (!strcmp(cam_type.c_str(), "opencv"))
	cam = new camera_opencv<ubyte>(-1, height, width);
#ifdef __LINUX__
      else if (!strcmp(cam_type.c_str(), "v4l2"))
	cam = new camera_v4l2<ubyte>(conf.get_cstring("device"),
				     height, width,
				     conf.exists_true("camera_grayscale"),
                                     conf.exists_true("camera_rgb"));
      else if (!strcmp(cam_type.c_str(), "mac"))
	cam = new camera_mac<ubyte>(conf.get_cstring("device"),
				     height, width,
				     conf.exists_true("camera_grayscale"),
                                     conf.exists_true("camera_rgb"));
      else if (!strcmp(cam_type.c_str(), "mcams")) {
        vector<string> devices = conf.get_all_strings("device");
	cam = new camera_mcams<ubyte>(conf, devices, height, width,
                                      conf.exists_true("camera_grayscale"),
                                      conf.exists_true("camera_rgb"));
      }
#endif
#ifdef __KINECT__
      else if (!strcmp(cam_type.c_str(), "kinect"))
	cam = new camera_kinect<ubyte>(height, width);
#endif
      else if (!strcmp(cam_type.c_str(), "shmem"))
	cam = new camera_shmem<ubyte>("shared-mem", height, width);
      else if (!strcmp(cam_type.c_str(), "video")) {
	if (argc >= 3)
	  cam = new camera_video<ubyte>
	    (argv[2], height, width, conf.get_uint("input_video_sstep"),
	     conf.get_uint("input_video_max_duration"));
	else eblerror("expected 2nd argument");
      } else if (!strcmp(cam_type.c_str(), "datasource")) {
        cam = new camera_datasource<ubyte,int>(conf);
      } else eblerror("unknown camera type, set \"camera\" in your .conf");
      // a camera directory may be used first, then switching to regular cam
      if (conf.exists_true("precamera"))
	cam2 = new camera_directory<ubyte>(conf.get_cstring("precamdir"),
					   height, width, input_random,
					   npasses, mout, merr, fpattern);
      if (conf.exists_true("camera_grayscale")) cam->set_grayscale();
      if (conf.exists_true("silent")) cam->set_silent();

      // answer variables & initializations
      bboxes bb;

      // gui
#ifdef __GUI__
      bool              bkey_msg      = false; // display key message
      bool display	     = conf.exists_bool("display");
      bool show_parts        = conf.exists_true("show_parts");
      bool bbox_show_conf = !conf.exists_false("bbox_show_conf");
      bool bbox_show_class = !conf.exists_false("bbox_show_class");
      // mindisplay     = conf.exists_bool("minimal_display");
      uint display_sleep  = 0;
      if (conf.exists("display_sleep"))
	display_sleep = conf.get_uint("display_sleep");
      // display_states = conf.exists_bool("display_states");
      // uint qstep1 = 0, qheight1 = 0, qwidth1 = 0,
      // 	qheight2 = 0, qwidth2 = 0, qstep2 = 0;
      // if (conf.exists_bool("queue1")) {
      // 	qstep1 = conf.get_uint("qstep1");
      // 	qheight1 = conf.get_uint("qheight1");
      // 	qwidth1 = conf.get_uint("qwidth1"); }
      // if (conf.exists_bool("queue2")) {
      // 	qstep2 = conf.get_uint("qstep2");
      // 	qheight2 = conf.get_uint("qheight2");
      // 	qwidth2 = conf.get_uint("qwidth2"); }
      // wid_states  = display_states ? new_window("network states"):0;
      // night_mode();
      uint wid  = display ? new_window("eblearn object recognition") : 0;
      night_mode();
      float display_transp = 0.0;
      if (conf.exists("display_bb_transparency"))
	display_transp = conf.get_float("display_bb_transparency");
      detector_gui<t_net> dgui(conf.exists_true("show_extracted"));
#endif
      // timing variables
      timer tpass, toverall, tstop;
      uint cnt = 0;
      bool stop = false, finished = false;

      // loop
      toverall.start();
      while (!finished) {
	// check for results and send new image for each thread
	uint i = 0;
	finished = true;
	for (ithreads = threads.begin();
	     ithreads != threads.end(); ++ithreads, ++i) {
	  // do nothing if thread is finished already
	  if ((*ithreads)->finished()) continue ;
	  finished = false; // a thread is not finished
	  string processed_fname;
	  uint processed_id = 0;
	  // retrieve new data if present
	  bool skipped = false;
	  updated = (*ithreads)->get_data
	    (bb, detframe, *(total_saved.idx_ptr() + i), processed_fname,
	     &processed_id, &samples, &bbsamples, &skipped);
	  if (skipped) cnt++; // a new skipped frame was received
	  // save bounding boxes
	  if (updated) {
	    idxdim d(detframe);
	    if (boot.activated()) bb.clear();
	    if (bbsaving != bbox_none) {
              if (!silent)
                mout << "Adding " << bb.size() << " boxes into new group: "
                     << processed_fname << " with id " << processed_id << endl;
	      boxes.new_group(d, &processed_fname, processed_id);
	      boxes.add(bb, d, &processed_fname, processed_id);
	      if (cnt % save_bbox_period == 0) boxes.save();
	      // avoid sample accumulation if not using bootstrapping
	      if (boot.activated())
		mout << "Received " << samples.size()
		     << " bootstrapping samples." << endl;
	    }
	    if (conf.exists_true("bootstrapping_save")) {
	      all_samples.push_back_new(samples);
	      all_bbsamples.push_back_new(bbsamples);
	    }
            // datasource mode, check and log answers
            if (dynamic_cast<camera_datasource<ubyte,int>*>(cam)) {
              camera_datasource<ubyte,int>* dscam =
                  (camera_datasource<ubyte,int>*) cam;
              dscam->log_answers(bb);
            }
	    cnt++;
	    // display processed frame
#ifdef __GUI__
	    if (display) {
	      select_window(wid);
	      disable_window_updates();
	      clear_resize_window();
	      set_window_title(processed_fname.c_str());
	      uint h = 0, w = 0;
	      // display frame with resulting boxes
	      dgui.display_minimal
		(detframe, bb, ((*ithreads)->pdetect ?
				(*ithreads)->pdetect->get_labels() : sclasses),
		 h, w, 1, 0, 255, wid, show_parts, display_transp,
		 bbox_show_class, bbox_show_conf, &bbsamples);
	      // display extracted samples
	      if (boot.activated()) {
		dgui.display_preprocessed
		  (samples, bbsamples, ((*ithreads)->pdetect ?
					(*ithreads)->pdetect->get_labels() : sclasses),
		   h, w, 1, -1, 1);
	      }
	      enable_window_updates();
	      if (save_video && display) {
		string fname;
		fname << viddir << processed_fname;
		save_window(fname.c_str());
		if (!silent) mout << "saved " << fname << endl;
	      }
	    }
	    // sleep display
	    if (display_sleep > 0) {
	      mout << "sleeping for " << display_sleep << "ms." << endl;
	      millisleep(display_sleep);
	    }
#endif
            if (!silent) {
              // output info
              uint k = cnt, tot = cam->size() - cnt; // progress variables
              if (conf.exists("save_max")) tot = conf.get_uint("save_max");
              if (!silent) {
                if (save_detections) {
                  mout << "total_saved=" << idx_sum(total_saved);
                  if (conf.exists("save_max")) mout << " / " << tot;
                  mout << endl;
                }
              }
              if (boot.activated())
                mout << "total_bootstrapping=" << all_samples.size() << endl;
              mout << "remaining=" << (cam->size() - cnt)
                   << " elapsed=" << toverall.elapsed();
              if (cam->size() > 0)
                mout << " ETA=" << toverall.eta(cnt, cam->size());
              if (conf.exists("save_max") && save_detections) {
                k = idx_sum(total_saved);
                mout << " save_max_ETA=" << toverall.eta(k, tot);
              }
              mout << endl;
              mout << "i=" << cnt << " processing: " << tpass.elapsed_ms()
                   << " fps: " << cam->fps() << endl;
              // save progress
              if (!conf.exists_false("save_progress"))
                job::write_progress(k, tot);
            }
	  }
	  // check if ready
	  if ((*ithreads)->available()) {
	    if (stop)
	      (*ithreads)->ask_stop(); // stop but let thread finish
	    else {
	      // grab a new frame if available
	      if (cam->empty()) {
		stop = true;
		tstop.start(); // start countdown timer
		(*ithreads)->ask_stop(); // ask this thread to stop
		millisleep(50);
	      } else {
#ifdef __GUI__
		int key = gui.pop_key_pressed();
		// if thread has already received data, wait for next key
		if ((*ithreads)->fed() && next_on_key) {
		  if ((int)next_on_key != key && (int)next_on_key != key + 32) {
		    if (!bkey_msg)
		      mout << "Press " << next_on_key
			   << " to process next frame." << endl;
		    bkey_msg = true;
		    continue ; // pause until key is pressed
		  } else {
		    mout << "Key pressed (" << key
			 << ") allowing next frame to process." << endl;
		    bkey_msg = false;
		    tpass.restart();
		  }
		}
#endif
		bool frame_grabbed = false;
		frame_id = cam->frame_id();
		// if the pre-camera is defined use it until empty
		if (cam2 && !cam2->empty())
		  frame = cam2->grab();
		else { // empty pre-camera, use regular camera
		  if (skip_frames > 0)
		    cam->skip(skip_frames); // skip frames if skip_frames > 0
		  if (cam->empty()) continue ;
		  if (precomputed_boxes && !save_video)
		    cam->next(); // move to next frame but without grabbing
		  else if (dynamic_cast<camera_directory<ubyte>*>(cam)) {
		    cam->grab_filename(); // just get the filename, no data
		  } else { // actually grab the frame
		    frame = cam->grab();
		    frame_grabbed = true;
		    // cropping
		    if (crop.nelements() > crop.order()) {
		      cout << "cropping frame from " << frame;
		      for (uint i = 0; i < crop.order(); ++i)
			if (crop.dim(i) > 1)
			  frame = frame.narrow(i, crop.dim(i), 0);
		      cout << " to " << frame << endl;
		    }
		  }
		}
		// send new frame to this thread
		string ffname = cam->frame_fullname();
		string fname = cam->frame_name();
		if (frame_grabbed) {
		  while (!(*ithreads)->set_data(frame, ffname, fname, frame_id))
		  millisleep(5);
		} else {
		  while (!(*ithreads)->set_data(ffname, fname, frame_id))
		    millisleep(5);
		}
		// we just sent a new frame
		tpass.restart();
	      }
	    }
	  }
	}
	if ((conf.exists("save_max") && !stop &&
	     idx_sum(total_saved) > conf.get_uint("save_max"))
	    || (boot.activated()
		&& (intg) all_samples.size() > boot.max_size())) {
	  mout << "Reached max number of detections, exiting." << endl;
	  stop = true; // limit number of detection saves
	  tstop.start(); // start countdown timer
	}
	// sleep a bit between each iteration
	millisleep(5);
	// check if stop countdown reached 0
	if (stop && tstop.elapsed_minutes() >= 20) {
	  cerr << "threads did not all return 20 min after request, stopping"
	       << endl;
	  break ; // program too long to stop, force exit
	}
      }
      // saving boxes
      if (bbsaving != bbox_none) boxes.save();
      mout << "Execution time: " << toverall.elapsed() << endl;
      if (save_video)
	cam->stop_recording(conf.exists_bool("use_original_fps") ?
			    cam->fps() : conf.get_uint("save_video_fps"),
			    outdir.c_str());
      // saving bootstrapping
      if (conf.exists_true("bootstrapping_save") && boot.activated())
	boot.save_dataset(all_samples, all_bbsamples, outdir, classes);
      // free variables
      if (cam) delete cam;
      for (ithreads = threads.begin(); ithreads != threads.end(); ++ithreads) {
	if (!(*ithreads)->finished())
	  (*ithreads)->stop(); // stop thread without waiting
	delete *ithreads;
      }
#ifdef __GUI__
      if (!conf.exists_true("no_gui_quit") && !conf.exists("next_on_key")) {
	mout << "Closing windows..." << endl;
	quit_gui(); // close all windows
	mout << "Windows closed." << endl;
      }
#endif
      job::write_finished(); // declare job finished
      mout << "Detection finished." << endl;
      // evaluation of bbox
      if (conf.exists_true("evaluate") && conf.exists("evaluate_cmd")) {
	string cmd;
	cmd << "cd " << outdir << " && " << conf.get_string("evaluate_cmd");
	int res = std::system(cmd.c_str());
	if (res != 0)
	  cerr << "bbox evaluation failed with command " << cmd << endl;
      }
    } eblcatcherror();
  return 0;
}