Ejemplo n.º 1
0
void board_init(void)
{
	bd_t *bd;
	int i;

	gd = (gd_t *)CONFIG_SYS_GBL_DATA_ADDR;

	memset((void *)gd, 0, GENERATED_GBL_DATA_SIZE);

	gd->bd = (bd_t *)(gd+1);	/* At end of global data */
	gd->baudrate = CONFIG_BAUDRATE;
	gd->cpu_clk = CONFIG_SYS_CLK_FREQ;

	bd = gd->bd;
	bd->bi_memstart = CONFIG_SYS_SDRAM_BASE;
	bd->bi_memsize = CONFIG_SYS_SDRAM_SIZE;
#ifndef CONFIG_SYS_NO_FLASH
	bd->bi_flashstart = CONFIG_SYS_FLASH_BASE;
#endif
#if	defined(CONFIG_SYS_SRAM_BASE) && defined(CONFIG_SYS_SRAM_SIZE)
	bd->bi_sramstart = CONFIG_SYS_SRAM_BASE;
	bd->bi_sramsize = CONFIG_SYS_SRAM_SIZE;
#endif
	bd->bi_baudrate = CONFIG_BAUDRATE;

	for (i = 0; i < ARRAY_SIZE(init_sequence); i++) {
		WATCHDOG_RESET();
		if (init_sequence[i]())
			hang();
	}

	WATCHDOG_RESET();

	/* The Malloc area is immediately below the monitor copy in RAM */
	mem_malloc_init(CONFIG_SYS_MALLOC_BASE, CONFIG_SYS_MALLOC_LEN);

#ifndef CONFIG_SYS_NO_FLASH
	WATCHDOG_RESET();
	bd->bi_flashsize = flash_init();
#endif

#ifdef CONFIG_CMD_NAND
	puts("NAND:  ");
	nand_init();
#endif

#ifdef CONFIG_GENERIC_MMC
	puts("MMC:   ");
	mmc_initialize(bd);
#endif

	WATCHDOG_RESET();
	env_relocate();

	WATCHDOG_RESET();
	stdio_init();
	jumptable_init();
	console_init_r();

	WATCHDOG_RESET();
	interrupt_init();

#if defined(CONFIG_BOARD_LATE_INIT)
	board_late_init();
#endif

#if defined(CONFIG_CMD_NET)
	puts("NET:   ");
	eth_initialize(bd);
#endif

	/* main_loop */
	for (;;) {
		WATCHDOG_RESET();
		main_loop();
	}
}
Ejemplo n.º 2
0
int main( int argc, char *argv[] ){
  Socket **localsocks;
  CamConfig *camcfg;
  char *shm_segment, tmpbuf[ 1024 ], cfg_path[ MAXPATHLEN ];
  int fd, shm_alloc, donecfg;
  extern int errno;

  donecfg = 0;
  if (argc >= 2) {
    strncpy( cfg_path, argv[ 1 ], sizeof( cfg_path ) );
    cfg_path[ sizeof( cfg_path ) - 1 ] = '\0';
    camserv_log( "main", "Trying to read config file \"%s\": ", cfg_path);
    if( (camcfg = read_ccfg( cfg_path )) == NULL ){
      camserv_log( "main", "Error reading config \"%s\": %s", cfg_path,
		   strerror( errno ));
    } else {
      camserv_log( "main", "Success reading config \"%s\"", cfg_path);
      donecfg=1;
    }
  } else {
    fprintf( stderr, "camserv v%s - by Jon Travis ([email protected])\n", 
	     VERSION );
    fprintf( stderr, "Syntax: %s <cfg file>\n", argv[0] );
    fprintf( stderr, "Will try %s/camserv.cfg\n", DATDIR);
   
    if (!donecfg) {
      snprintf( cfg_path, sizeof( cfg_path ), "%s/camserv.cfg", DATDIR );
      cfg_path[ sizeof( cfg_path ) - 1 ] = '\0';
      camserv_log( "main", "Trying to read config file \"%s\": ", cfg_path);
      if( (camcfg = read_ccfg( cfg_path )) == NULL ){
	camserv_log( "main", "Error reading config \"%s\": %s", cfg_path,
		     strerror( errno ));
      } else {
	camserv_log( "main", "Success reading config \"%s\"", cfg_path);
	donecfg=1;
      }
    }
  }

  if (!donecfg) {
    camserv_log( "main", "Error finding config file, exit!");
    return(-1);
  }

  /* If we took a single snapshot, we are all done */
  if( snap_single( camcfg )) 
    return 0;

  if( (localsocks = socket_unix_pair( SOCK_DGRAM )) == NULL ){
    camserv_log( "main", "Error creating communication sockets between procs");
    return -1;
  }
  
  /* Setup a temp file for making our shm */
  strcpy( tmpbuf, "/tmp/CAMSERV_XXXXXX" );
  if( (fd = mkstemp( tmpbuf )) == -1 ){
    camserv_log( "main", "Couldn't create temporary file: %s", tmpbuf );
    strcpy( tmpbuf, argv[ 0 ] ); /* Last resort */
  } else {
    close( fd );
  }

  shm_alloc = camconfig_query_def_int( camcfg, SEC_MAIN, "shm_alloc", 
				       PICTURE_MALLOC );

  if( shm_alloc < PICTURE_MALLOC )
    camserv_log( "main", "Allocated %d bytes for SHM [RISKY RISKY!]",
		 shm_alloc);

  if( (Shmid = shm_setup( tmpbuf,
			  /* Allocate generous ammount */
			  shm_alloc,
			  &shm_segment) ) == -1 ){

    socket_unix_pair_dest( localsocks );
    return -1;
  }
  unlink( tmpbuf );

/* Start the picture taker thread */
  CPid = picture_taker( shm_segment, PICTURE_MALLOC, camcfg, localsocks[ 0 ]); 
  if( CPid == -1 ){
    /* Failure setting up camerastuffs */
    camserv_log( "main",  "Picture taker could not be created!");
    socket_unix_pair_dest( localsocks );
    return -1;
  }
    
  if( main_loop( camcfg, localsocks[ 1 ], shm_segment ) == -1 ){
    camserv_log( "main", "Main loop exited abnormally");
    socket_unix_pair_dest( localsocks );
    if( CPid != -1 ) kill( CPid, SIGINT );
    return -1;
  }

  socket_unix_pair_dest( localsocks );
  return 0;
}
Ejemplo n.º 3
0
int loop (void) {
  on_start ();
  if (binlog_enabled) {
    double t = get_double_time ();
    logprintf ("replay log start\n");
    replay_log ();
    logprintf ("replay log end in %lf seconds\n", get_double_time () - t);
    write_binlog ();
    #ifdef USE_LUA
      lua_binlog_end ();
    #endif
  } else {
    read_auth_file ();
  }
  update_prompt ();

  assert (DC_list[dc_working_num]);
  if (!DC_working || !DC_working->auth_key_id) {
//  if (auth_state == 0) {
    DC_working = DC_list[dc_working_num];
    assert (!DC_working->auth_key_id);
    dc_authorize (DC_working);
    assert (DC_working->auth_key_id);
    auth_state = 100;
    write_auth_file ();
  }
  
  if (verbosity) {
    logprintf ("Requesting info about DC...\n");
  }
  do_help_get_config ();
  net_loop (0, mcs);
  if (verbosity) {
    logprintf ("DC_info: %d new DC got\n", new_dc_num);
  }
  int i;
  for (i = 0; i <= MAX_DC_NUM; i++) if (DC_list[i] && !DC_list[i]->auth_key_id) {
    dc_authorize (DC_list[i]);
    assert (DC_list[i]->auth_key_id);
    write_auth_file ();
  }

  if (auth_state == 100 || !(DC_working->has_auth)) {
    if (!default_username) {
      size_t size = 0;
      char *user = 0;

      if (!user) {
        printf ("Telephone number (with '+' sign): ");         
        if (net_getline (&user, &size) == -1) {
          perror ("getline()");
          exit (EXIT_FAILURE);
        }
        set_default_username (user);
      }
    }
    int res = do_auth_check_phone (default_username);
    assert (res >= 0);
    logprintf ("%s\n", res > 0 ? "phone registered" : "phone not registered");
    if (res > 0 && !register_mode) {
      do_send_code (default_username);
      char *code = 0;
      size_t size = 0;
      printf ("Code from sms: ");
      while (1) {
        if (net_getline (&code, &size) == -1) {
          perror ("getline()");
          exit (EXIT_FAILURE);
        }
        if (do_send_code_result (code) >= 0) {
          break;
        }
        printf ("Invalid code. Try again: ");
        tfree_str (code);
      }
      auth_state = 300;
    } else {
      printf ("User is not registered. Do you want to register? [Y/n] ");
      char *code;
      size_t size;
      if (net_getline (&code, &size) == -1) {
        perror ("getline()");
        exit (EXIT_FAILURE);
      }
      if (!*code || *code == 'y' || *code == 'Y') {
        printf ("Ok, starting registartion.\n");
      } else {
        printf ("Then try again\n");
        exit (EXIT_SUCCESS);
      }
      char *first_name;
      printf ("Name: ");
      if (net_getline (&first_name, &size) == -1) {
        perror ("getline()");
        exit (EXIT_FAILURE);
      }
      char *last_name;
      printf ("Name: ");
      if (net_getline (&last_name, &size) == -1) {
        perror ("getline()");
        exit (EXIT_FAILURE);
      }

      int dc_num = do_get_nearest_dc ();
      assert (dc_num >= 0 && dc_num <= MAX_DC_NUM && DC_list[dc_num]);
      dc_working_num = dc_num;
      DC_working = DC_list[dc_working_num];
      
      do_send_code (default_username);
      printf ("Code from sms: ");
      while (1) {
        if (net_getline (&code, &size) == -1) {
          perror ("getline()");
          exit (EXIT_FAILURE);
        }
        if (do_send_code_result_auth (code, first_name, last_name) >= 0) {
          break;
        }
        printf ("Invalid code. Try again: ");
        tfree_str (code);
      }
      auth_state = 300;
    }
  }

  for (i = 0; i <= MAX_DC_NUM; i++) if (DC_list[i] && !DC_list[i]->has_auth) {
    do_export_auth (i);
    do_import_auth (i);
    bl_do_dc_signed (i);
    write_auth_file ();
  }
  write_auth_file ();

  fflush (stdout);
  fflush (stderr);

  read_state_file ();
  read_secret_chat_file ();

  set_interface_callbacks ();

  do_get_difference ();
  net_loop (0, dgot);
  #ifdef USE_LUA
    lua_diff_end ();
  #endif
  send_all_unsent ();


  do_get_dialog_list ();
  if (wait_dialog_list) {
    dialog_list_got = 0;
    net_loop (0, dlgot);
  }

  return main_loop ();
}
Ejemplo n.º 4
0
/*---------------------------------------------------------------------------*/
#if WITH_TINYOS_AUTO_IDS
uint16_t TOS_NODE_ID = 0x1234; /* non-zero */
uint16_t TOS_LOCAL_ADDRESS = 0x1234; /* non-zero */
#endif /* WITH_TINYOS_AUTO_IDS */
int
main(void)
{
  /* Set stack overflow address for detecting overflow in runtime */
  vAHI_SetStackOverflow(TRUE, ((uint32_t *)&heap_location)[0]);

  /* Initialize random with a seed from the SoC random generator.
   * This must be done before selecting the high-precision external oscillator.
   */
  vAHI_StartRandomNumberGenerator(E_AHI_RND_SINGLE_SHOT, E_AHI_INTS_DISABLED);
  random_init(u16AHI_ReadRandomNumber());

  clock_init();
  rtimer_init();

#if JN516X_EXTERNAL_CRYSTAL_OSCILLATOR
  /* initialize the 32kHz crystal and wait for ready */
  xosc_init();
  /* need to reinitialize because the wait-for-ready process uses system timers */
  clock_init();
  rtimer_init();
#endif

  watchdog_init();
  leds_init();
  leds_on(LEDS_ALL);
  init_node_mac();

  energest_init();
  ENERGEST_ON(ENERGEST_TYPE_CPU);

  node_id_restore();

#if WITH_TINYOS_AUTO_IDS
  node_id = TOS_NODE_ID;
#endif /* WITH_TINYOS_AUTO_IDS */
  /* for setting "hardcoded" IEEE 802.15.4 MAC addresses */
#ifdef IEEE_802154_MAC_ADDRESS
  {
    uint8_t ieee[] = IEEE_802154_MAC_ADDRESS;
    memcpy(node_mac, ieee, sizeof(uip_lladdr.addr));
    node_mac[7] = node_id & 0xff;
  }
#endif

  process_init();
  ctimer_init();
  uart0_init(UART_BAUD_RATE); /* Must come before first PRINTF */

#if NETSTACK_CONF_WITH_IPV4
  slip_arch_init(UART_BAUD_RATE);
#endif /* NETSTACK_CONF_WITH_IPV4 */

  /* check for reset source */
  if(bAHI_WatchdogResetEvent()) {
    PRINTF("Init: Watchdog timer has reset device!\r\n");
  }
  process_start(&etimer_process, NULL);
  set_linkaddr();
  netstack_init();

#if NETSTACK_CONF_WITH_IPV6
#if UIP_CONF_IPV6_RPL
  PRINTF(CONTIKI_VERSION_STRING " started with IPV6, RPL\n");
#else
  PRINTF(CONTIKI_VERSION_STRING " started with IPV6\n");
#endif
#elif NETSTACK_CONF_WITH_IPV4
  PRINTF(CONTIKI_VERSION_STRING " started with IPV4\n");
#else
  PRINTF(CONTIKI_VERSION_STRING " started\n");
#endif

  if(node_id > 0) {
    PRINTF("Node id is set to %u.\n", node_id);
  } else {
    PRINTF("Node id is not set.\n");
  }
#if NETSTACK_CONF_WITH_IPV6
  memcpy(&uip_lladdr.addr, node_mac, sizeof(uip_lladdr.addr));
  queuebuf_init();
#endif /* NETSTACK_CONF_WITH_IPV6 */

  PRINTF("%s %s %s\n", NETSTACK_LLSEC.name, NETSTACK_MAC.name, NETSTACK_RDC.name);

#if !NETSTACK_CONF_WITH_IPV4 && !NETSTACK_CONF_WITH_IPV6
  uart0_set_input(serial_line_input_byte);
  serial_line_init();
#endif

#if TIMESYNCH_CONF_ENABLED
  timesynch_init();
  timesynch_set_authority_level((linkaddr_node_addr.u8[0] << 4) + 16);
#endif /* TIMESYNCH_CONF_ENABLED */

#if NETSTACK_CONF_WITH_IPV4
  process_start(&tcpip_process, NULL);
  process_start(&uip_fw_process, NULL); /* Start IP output */
  process_start(&slip_process, NULL);

  slip_set_input_callback(set_gateway);

  {
    uip_ipaddr_t hostaddr, netmask;

    uip_init();

    uip_ipaddr(&hostaddr, 172, 16,
               linkaddr_node_addr.u8[0], linkaddr_node_addr.u8[1]);
    uip_ipaddr(&netmask, 255, 255, 0, 0);
    uip_ipaddr_copy(&meshif.ipaddr, &hostaddr);

    uip_sethostaddr(&hostaddr);
    uip_setnetmask(&netmask);
    uip_over_mesh_set_net(&hostaddr, &netmask);
    /*    uip_fw_register(&slipif);*/
    uip_over_mesh_set_gateway_netif(&slipif);
    uip_fw_default(&meshif);
    uip_over_mesh_init(UIP_OVER_MESH_CHANNEL);
    PRINTF("uIP started with IP address %d.%d.%d.%d\n",
           uip_ipaddr_to_quad(&hostaddr));
  }
#endif /* NETSTACK_CONF_WITH_IPV4 */

  watchdog_start();
  NETSTACK_LLSEC.init();

#if NETSTACK_CONF_WITH_IPV6
  start_uip6();
#endif /* NETSTACK_CONF_WITH_IPV6 */

  /* need this to reliably generate the first rtimer callback and callbacks in other 
     auto-start processes */
  (void)u32AHI_Init();

  start_autostart_processes();

  leds_off(LEDS_ALL);

  main_loop();

  return -1;
}
Ejemplo n.º 5
0
int main(int argc, const char * argv[]) {
    main_loop(argc, argv);
    return 0;
}
Ejemplo n.º 6
0
/**
 * Main routine, start of the program execution.
 * \param argc the number of arguments
 * \param argv pointer to the arguments array
 * \return don't return on sucess, -1 on error
 * \see main_loop
 */
int main(int argc, char** argv)
{
	/* configure by default logging to syslog */
	int cfg_log_stderr = 0;
	FILE* cfg_stream;
	int c,r;
	char *tmp;
	int tmp_len;
	int port;
	int proto;
	char *options;
	int ret;
	unsigned int seed;
	int rfd;

	/*init*/
	ret=-1;
	my_argc=argc; my_argv=argv;

	/* process pkg mem size from command line */
	opterr=0;
	options="f:cCm:M:b:l:n:N:rRvdDFETSVhw:t:u:g:P:G:W:o:";

	while((c=getopt(argc,argv,options))!=-1){
		switch(c){
			case 'M':
					pkg_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024;
					if (tmp &&(*tmp)){
						LM_ERR("bad pkgmem size number: -m %s\n", optarg);
						goto error00;
					};

					break;
		}
	}
	/*init pkg mallocs (before parsing cfg but after parsing cmd line !)*/
	if (init_pkg_mallocs()==-1)
		goto error00;

	init_route_lists();
	/* process command line (get port no, cfg. file path etc) */
	/* first reset getopt */
	optind = 1;
	while((c=getopt(argc,argv,options))!=-1){
		switch(c){
			case 'f':
					cfg_file=optarg;
					break;
			case 'C':
					config_check |= 2;
			case 'c':
					if (config_check==3)
						break;
					config_check |= 1;
					cfg_log_stderr=1; /* force stderr logging */
					break;
			case 'm':
					shm_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024;
					if (tmp &&(*tmp)){
						LM_ERR("bad shmem size number: -m %s\n", optarg);
						goto error00;
					};

					break;
			case 'M':
					/* ignoring it, parsed previously */

					break;
			case 'b':
					maxbuffer=strtol(optarg, &tmp, 10);
					if (tmp &&(*tmp)){
						LM_ERR("bad max buffer size number: -b %s\n", optarg);
						goto error00;
					}
					break;
			case 'l':
					if (parse_phostport(optarg, strlen(optarg), &tmp, &tmp_len,
											&port, &proto)<0){
						LM_ERR("bad -l address specifier: %s\n", optarg);
						goto error00;
					}
					tmp[tmp_len]=0; /* null terminate the host */
					/* add a new addr. to our address list */
					if (add_listen_iface(tmp, port, proto, 0, 0, 0,0 )!=0){
						LM_ERR("failed to add new listen address\n");
						goto error00;
					}
					break;
			case 'n':
					children_no=strtol(optarg, &tmp, 10);
					if ((tmp==0) ||(*tmp)){
						LM_ERR("bad process number: -n %s\n", optarg);
						goto error00;
					}
					break;
			case 'v':
					check_via=1;
					break;
			case 'r':
					received_dns|=DO_DNS;
					break;
			case 'R':
					received_dns|=DO_REV_DNS;
			case 'd':
#ifdef CHANGEABLE_DEBUG_LEVEL
					(*debug)++;
#else
					debug++;
#endif
					break;
			case 'D':
					dont_fork=1;
					break;
			case 'F':
					no_daemon_mode=1;
					break;
			case 'E':
					cfg_log_stderr=1;
					break;
			case 'T':
#ifdef USE_TCP
					tcp_disable=1;
#else
					LM_WARN("tcp support not compiled in\n");
#endif
					break;
			case 'S':
#ifdef USE_SCTP
					sctp_disable=1;
#else
					LM_WARN("sctp support not compiled in\n");
#endif
			break;
			case 'N':
#ifdef USE_TCP
					tcp_children_no=strtol(optarg, &tmp, 10);
					if ((tmp==0) ||(*tmp)){
						LM_ERR("bad process number: -N %s\n", optarg);
						goto error00;
					}
#else
					LM_WARN("tcp support not compiled in\n");
#endif
					break;
			case 'W':
#ifdef USE_TCP
					tcp_poll_method=get_poll_type(optarg);
					if (tcp_poll_method==POLL_NONE){
						LM_ERR("bad poll method name: -W %s\ntry "
							"one of %s.\n", optarg, poll_support);
						goto error00;
					}
#else
					LM_WARN("tcp support not compiled in\n");
#endif
					break;
			case 'V':
					printf("version: %s\n", version);
					printf("flags: %s\n", flags );
					print_ct_constants();
					printf("%s\n",id);
					printf("%s compiled on %s with %s\n", __FILE__,
							compiled, COMPILER );
					
					exit(0);
					break;
			case 'h':
					printf("version: %s\n", version);
					printf("%s",help_msg);
					exit(0);
					break;
			case 'w':
					working_dir=optarg;
					break;
			case 't':
					chroot_dir=optarg;
					break;
			case 'u':
					user=optarg;
					break;
			case 'g':
					group=optarg;
					break;
			case 'P':
					pid_file=optarg;
					break;
			case 'G':
					pgid_file=optarg;
					break;
			case 'o':
					if (add_arg_var(optarg) < 0)
						LM_ERR("cannot add option %s\n", optarg);
					break;
			case '?':
					if (isprint(optopt))
						LM_ERR("Unknown option `-%c`.\n", optopt);
					else
						LM_ERR("Unknown option character `\\x%x`.\n", optopt);
					goto error00;
			case ':':
					LM_ERR("Option `-%c` requires an argument.\n", optopt);
					goto error00;
			default:
					abort();
		}
	}

	log_stderr = cfg_log_stderr;

	/* fill missing arguments with the default values*/
	if (cfg_file==0) cfg_file=CFG_FILE;

	/* load config file or die */
	cfg_stream=fopen (cfg_file, "r");
	if (cfg_stream==0){
		LM_ERR("loading config file(%s): %s\n", cfg_file,
				strerror(errno));
		goto error00;
	}

	/* seed the prng, try to use /dev/urandom if possible */
	/* no debugging information is logged, because the standard
	   log level prior the config file parsing is L_NOTICE */
	seed=0;
	if ((rfd=open("/dev/urandom", O_RDONLY))!=-1){
try_again:
		if (read(rfd, (void*)&seed, sizeof(seed))==-1){
			if (errno==EINTR) goto try_again; /* interrupted by signal */
			LM_WARN("could not read from /dev/urandom (%d)\n", errno);
		}
		LM_DBG("initialize the pseudo random generator from "
			"/dev/urandom\n");
		LM_DBG("read %u from /dev/urandom\n", seed);
			close(rfd);
	}else{
		LM_WARN("could not open /dev/urandom (%d)\n", errno);
		LM_WARN("using a unsafe seed for the pseudo random number generator");
	}
	seed+=getpid()+time(0);
	LM_DBG("seeding PRNG with %u\n", seed);
	srand(seed);
	LM_DBG("test random number %u\n", rand());

	/*register builtin  modules*/
	register_builtin_modules();

#ifdef USE_TLS
	/* initialize default TLS domains,
	   must be done before reading the config */
	if (pre_init_tls()<0){
		LM_CRIT("could not pre_init_tls, exiting...\n");
		goto error00;
	}
#endif /* USE_TLS */

	if (preinit_black_lists()!=0) {
		LM_CRIT("failed to alloc black list's anchor\n");
		goto error00;
	}

	/* init avps */
	if (init_global_avps() != 0) {
		LM_ERR("error while initializing avps\n");
		goto error;
	}


	/* parse the config file, prior to this only default values
	   e.g. for debugging settings will be used */
	yyin=cfg_stream;
	if ((yyparse()!=0)||(cfg_errors)){
		LM_ERR("bad config file (%d errors)\n", cfg_errors);
		goto error00;
	}

	if (config_check>1 && check_rls()!=0) {
		LM_ERR("bad function call in config file\n");
		return ret;
	}
#ifdef EXTRA_DEBUG
	print_rl();
#endif

	if (no_daemon_mode+dont_fork > 1) {
		LM_ERR("cannot use -D (fork=no) and -F together\n");
		return ret;
	}

	/* init the resolver, before fixing the config */
	resolv_init();

	/* fix parameters */
	if (port_no<=0) port_no=SIP_PORT;
#ifdef USE_TLS
	if (tls_port_no<=0) tls_port_no=SIPS_PORT;
#endif
	
	
	if (children_no<=0) children_no=CHILD_NO;
#ifdef USE_TCP
	if (!tcp_disable){
		if (tcp_children_no<=0) tcp_children_no=children_no;
	}
#endif
	
	if (working_dir==0) working_dir="/";

	/* get uid/gid */
	if (user){
		if (user2uid(&uid, &gid, user)<0){
			LM_ERR("bad user name/uid number: -u %s\n", user);
			goto error00;
		}
	}
	if (group){
		if (group2gid(&gid, group)<0){
			LM_ERR("bad group name/gid number: -u %s\n", group);
			goto error00;
		}
	}
	if (fix_all_socket_lists()!=0){
		LM_ERR("failed to initialize list addresses\n");
		goto error00;
	}
	/* print all the listen addresses */
	printf("Listening on \n");
	print_all_socket_lists();
	printf("Aliases: \n");
	/*print_aliases();*/
	print_aliases();
	printf("\n");
	
	if (dont_fork){
		LM_WARN("no fork mode %s\n", 
				(udp_listen)?(
				(udp_listen->next)?" and more than one listen address found"
				"(will use only the first one)":""
				):"and no udp listen address found" );
	}
	if (config_check){
		LM_NOTICE("config file ok, exiting...\n");
		return 0;
	}


	time(&startup_time);

	/*init shm mallocs
	 *  this must be here 
	 *     -to allow setting shm mem size from the command line
	 *       => if shm_mem should be settable from the cfg file move
	 *       everything after
	 *     -it must be also before init_timer and init_tcp
	 *     -it must be after we know uid (so that in the SYSV sems case,
	 *        the sems will have the correct euid)
	 * --andrei */
	if (init_shm_mallocs()==-1)
		goto error;
	/*init timer, before parsing the cfg!*/
	if (init_timer()<0){
		LM_CRIT("could not initialize timer, exiting...\n");
		goto error;
	}
	
#ifdef USE_TCP
	if (!tcp_disable){
		/*init tcp*/
		if (init_tcp()<0){
			LM_CRIT("could not initialize tcp, exiting...\n");
			goto error;
		}
	}
#ifdef USE_TLS
	if (!tls_disable){
		/* init tls*/
		if (init_tls()<0){
			LM_CRIT("could not initialize tls, exiting...\n");
			goto error;
		}
	}
#endif /* USE_TLS */
#endif /* USE_TCP */

	/* init_daemon? */
	if (!dont_fork){
		if ( daemonize((log_name==0)?argv[0]:log_name, &own_pgid) <0 )
			goto error;
	}

	/* install signal handlers */
	if (install_sigs() != 0){
		LM_ERR("could not install the signal handlers\n");
		goto error;
	}

#ifdef CHANGEABLE_DEBUG_LEVEL
#ifdef SHM_MEM
	debug=shm_malloc(sizeof(int));
	if (debug==0) {
		LM_ERR("ERROR: out of memory\n");
		goto error;
	}
	*debug = debug_init;
#else
	LM_WARN("no shm mem support compiled -> changeable debug "
		"level turned off\n");
#endif
#endif

	if (disable_core_dump) set_core_dump(0, 0);
	else set_core_dump(1, shm_mem_size+pkg_mem_size+4*1024*1024);
	if (open_files_limit>0){
		if(increase_open_fds(open_files_limit)<0){ 
			LM_ERR("ERROR: error could not increase file limits\n");
			goto error;
		}
	}

	/* print OpenSIPS version to log for history tracking */
	LM_NOTICE("version: %s\n", version);
	
	/* print some data about the configuration */
#ifdef SHM_MEM
	LM_INFO("using %ld Mb shared memory\n", ((shm_mem_size/1024)/1024));
#endif
	LM_INFO("using %ld Mb private memory per process\n", ((pkg_mem_size/1024)/1024));

	/* init serial forking engine */
	if (init_serialization()!=0) {
		LM_ERR("failed to initialize serialization\n");
		goto error;
	}
	/* Init statistics */
	if (init_stats_collector()<0) {
		LM_ERR("failed to initialize statistics\n");
		goto error;
	}
	/* Init MI */
	if (init_mi_core()<0) {
		LM_ERR("failed to initialize MI core\n");
		goto error;
	}

	/* Register core events */
	if (evi_register_core() != 0) {
		LM_ERR("failed register core events\n");
		goto error;
	}

	/* init black list engine */
	if (init_black_lists()!=0) {
		LM_CRIT("failed to init black lists\n");
		goto error;
	}
	/* init resolver's blacklist */
	if (resolv_blacklist_init()!=0) {
		LM_CRIT("failed to create DNS blacklist\n");
		goto error;
	}

	/* init modules */
	if (init_modules() != 0) {
		LM_ERR("error while initializing modules\n");
		goto error;
	}

	/* register route timers */
	if(register_route_timers() < 0) {
		LM_ERR("Failed to register timer\n");
		goto error;
	}

	/* check pv context list */
	if(pv_contextlist_check() != 0) {
		LM_ERR("used pv context that was not defined\n");
		goto error;
	}

	/* init query list now in shm
	 * so all processes that will be forked from now on
	 * will have access to it 
	 *
	 * if it fails, give it a try and carry on */
	if (init_ql_support() != 0) {
		LM_ERR("failed to initialise buffering query list\n");
		query_buffer_size = 0;
		*query_list = NULL;
	}

	/* init multi processes support */
	if (init_multi_proc_support()!=0) {
		LM_ERR("failed to init multi-proc support\n");
		goto error;
	}

	#ifdef PKG_MALLOC
	/* init stats support for pkg mem */
	if (init_pkg_stats(counted_processes)!=0) {
		LM_ERR("failed to init stats for pkg\n");
		goto error;
	}
	#endif

	/* init avps */
	if (init_extra_avps() != 0) {
		LM_ERR("error while initializing avps\n");
		goto error;
	}

	/* fix routing lists */
	if ( (r=fix_rls())!=0){
		LM_ERR("failed to fix configuration with err code %d\n", r);
		goto error;
	};

	ret=main_loop();

error:

	/*kill everything*/
	kill_all_children(SIGTERM);
	/*clean-up*/
	cleanup(0);
error00:
	return ret;
}
Ejemplo n.º 7
0
int main(int argc, char *argv[])
{
    int ii;
    int ret_val;
    double x_orig, y_orig;
    static int rand1 = 12345;
    static int rand2 = 67891;
    struct GModule *module;

    G_gisinit(argv[0]);

    module = G_define_module();
    G_add_keyword(_("raster"));
    G_add_keyword(_("hydrology"));
    module->description =
	_("Overland flow hydrologic simulation using "
	  "path sampling method (SIMWE).");

    parm.elevin = G_define_standard_option(G_OPT_R_ELEV);
    
    parm.dxin = G_define_standard_option(G_OPT_R_INPUT);
    parm.dxin->key = "dx";
    parm.dxin->description = _("Name of x-derivatives raster map [m/m]");

    parm.dyin = G_define_standard_option(G_OPT_R_INPUT);
    parm.dyin->key = "dy";
    parm.dyin->description = _("Name of y-derivatives raster map [m/m]");

    parm.rain = G_define_standard_option(G_OPT_R_INPUT);
    parm.rain->key = "rain";
    parm.rain->required = NO;
    parm.rain->description =
	_("Name of rainfall excess rate (rain-infilt) raster map [mm/hr]");
    parm.rain->guisection = _("Input");
    
    parm.rainval = G_define_option();
    parm.rainval->key = "rain_value";
    parm.rainval->type = TYPE_DOUBLE;
    parm.rainval->answer = RAINVAL;
    parm.rainval->required = NO;
    parm.rainval->description =
	_("Rainfall excess rate unique value [mm/hr]");
    parm.rainval->guisection = _("Input");

    parm.infil = G_define_standard_option(G_OPT_R_INPUT);
    parm.infil->key = "infil";
    parm.infil->required = NO;
    parm.infil->description =
	_("Name of runoff infiltration rate raster map [mm/hr]");
    parm.infil->guisection = _("Input");

    parm.infilval = G_define_option();
    parm.infilval->key = "infil_value";
    parm.infilval->type = TYPE_DOUBLE;
    parm.infilval->answer = INFILVAL;
    parm.infilval->required = NO;
    parm.infilval->description =
	_("Runoff infiltration rate unique value [mm/hr]");
    parm.infilval->guisection = _("Input");

    parm.manin = G_define_standard_option(G_OPT_R_INPUT);
    parm.manin->key = "man";
    parm.manin->required = NO;
    parm.manin->description = _("Name of mannings n raster map");
    parm.manin->guisection = _("Input");

    parm.maninval = G_define_option();
    parm.maninval->key = "man_value";
    parm.maninval->type = TYPE_DOUBLE;
    parm.maninval->answer = MANINVAL;
    parm.maninval->required = NO;
    parm.maninval->description = _("Mannings n unique value");
    parm.maninval->guisection = _("Input");

    parm.traps = G_define_standard_option(G_OPT_R_INPUT);
    parm.traps->key = "traps";
    parm.traps->required = NO;
    parm.traps->description =
	_("Name of flow controls raster map (permeability ratio 0-1)");
    parm.traps->guisection = _("Input");

    parm.observation = G_define_standard_option(G_OPT_V_INPUT);
    parm.observation->key = "observation";
    parm.observation->required = NO;
    parm.observation->description =
	_("Name of the sampling locations vector points map");
    parm.observation->guisection = _("Input_options");

    parm.logfile = G_define_standard_option(G_OPT_F_OUTPUT);
    parm.logfile->key = "logfile";
    parm.logfile->required = NO;
    parm.logfile->description =
	_("Name of the sampling points output text file. For each observation vector point the time series of water depth is stored.");
    parm.logfile->guisection = _("Output");

    parm.depth = G_define_standard_option(G_OPT_R_OUTPUT);
    parm.depth->key = "depth";
    parm.depth->required = NO;
    parm.depth->description = _("Name for output water depth raster map [m]");
    parm.depth->guisection = _("Output");

    parm.disch = G_define_standard_option(G_OPT_R_OUTPUT);
    parm.disch->key = "disch";
    parm.disch->required = NO;
    parm.disch->description = _("Name for output water discharge raster map [m3/s]");
    parm.disch->guisection = _("Output");

    parm.err = G_define_standard_option(G_OPT_R_OUTPUT);
    parm.err->key = "err";
    parm.err->required = NO;
    parm.err->description = _("Name for output simulation error raster map [m]");
    parm.err->guisection = _("Output");

    parm.outwalk = G_define_standard_option(G_OPT_V_OUTPUT);
    parm.outwalk->key = "outwalk";
    parm.outwalk->required = NO;
    parm.outwalk->description =
	_("Base name of the output walkers vector points map");
    parm.outwalk->guisection = _("Output_options");

    parm.nwalk = G_define_option();
    parm.nwalk->key = "nwalk";
    parm.nwalk->type = TYPE_INTEGER;
    parm.nwalk->required = NO;
    parm.nwalk->description =
	_("Number of walkers, default is twice the no. of cells");
    parm.nwalk->guisection = _("Parameters");

    parm.niter = G_define_option();
    parm.niter->key = "niter";
    parm.niter->type = TYPE_INTEGER;
    parm.niter->answer = NITER;
    parm.niter->required = NO;
    parm.niter->description = _("Time used for iterations [minutes]");
    parm.niter->guisection = _("Parameters");

    parm.outiter = G_define_option();
    parm.outiter->key = "outiter";
    parm.outiter->type = TYPE_INTEGER;
    parm.outiter->answer = ITEROUT;
    parm.outiter->required = NO;
    parm.outiter->description =
	_("Time interval for creating output maps [minutes]");
    parm.outiter->guisection = _("Parameters");

/*
    parm.density = G_define_option();
    parm.density->key = "density";
    parm.density->type = TYPE_INTEGER;
    parm.density->answer = DENSITY;
    parm.density->required = NO;
    parm.density->description = _("Density of output walkers");
    parm.density->guisection = _("Parameters");
*/

    parm.diffc = G_define_option();
    parm.diffc->key = "diffc";
    parm.diffc->type = TYPE_DOUBLE;
    parm.diffc->answer = DIFFC;
    parm.diffc->required = NO;
    parm.diffc->description = _("Water diffusion constant");
    parm.diffc->guisection = _("Parameters");

    parm.hmax = G_define_option();
    parm.hmax->key = "hmax";
    parm.hmax->type = TYPE_DOUBLE;
    parm.hmax->answer = HMAX;
    parm.hmax->required = NO;
    parm.hmax->label =
	_("Threshold water depth [m]");
    parm.hmax->description = _("Diffusion increases after this water depth is reached");
    parm.hmax->guisection = _("Parameters");

    parm.halpha = G_define_option();
    parm.halpha->key = "halpha";
    parm.halpha->type = TYPE_DOUBLE;
    parm.halpha->answer = HALPHA;
    parm.halpha->required = NO;
    parm.halpha->description = _("Diffusion increase constant");
    parm.halpha->guisection = _("Parameters");

    parm.hbeta = G_define_option();
    parm.hbeta->key = "hbeta";
    parm.hbeta->type = TYPE_DOUBLE;
    parm.hbeta->answer = HBETA;
    parm.hbeta->required = NO;
    parm.hbeta->description =
	_("Weighting factor for water flow velocity vector");
    parm.hbeta->guisection = _("Parameters");

    flag.tserie = G_define_flag();
    flag.tserie->key = 't';
    flag.tserie->description = _("Time-series output");

    if (G_parser(argc, argv))
	exit(EXIT_FAILURE);

    G_get_set_window(&cellhd);

    conv = G_database_units_to_meters_factor();

    mixx = conv * cellhd.west;
    maxx = conv * cellhd.east;
    miyy = conv * cellhd.south;
    mayy = conv * cellhd.north;

    stepx = cellhd.ew_res * conv;
    stepy = cellhd.ns_res * conv;
    /*  step = amin1(stepx,stepy); */
    step = (stepx + stepy) / 2.;
    mx = cellhd.cols;
    my = cellhd.rows;
    x_orig = cellhd.west * conv;
    y_orig = cellhd.south * conv;	/* do we need this? */
    xmin = 0.;
    ymin = 0.;
    xp0 = xmin + stepx / 2.;
    yp0 = ymin + stepy / 2.;
    xmax = xmin + stepx * (float)mx;
    ymax = ymin + stepy * (float)my;

    ts = flag.tserie->answer;

    elevin = parm.elevin->answer;
    dxin = parm.dxin->answer;
    dyin = parm.dyin->answer;
    rain = parm.rain->answer;
    infil = parm.infil->answer;
    traps = parm.traps->answer;
    manin = parm.manin->answer;
    depth = parm.depth->answer;
    disch = parm.disch->answer;
    err = parm.err->answer;
    outwalk = parm.outwalk->answer; 

    sscanf(parm.niter->answer, "%d", &timesec);
    sscanf(parm.outiter->answer, "%d", &iterout);
    sscanf(parm.diffc->answer, "%lf", &frac);
    sscanf(parm.hmax->answer, "%lf", &hhmax);
    sscanf(parm.halpha->answer, "%lf", &halpha);
    sscanf(parm.hbeta->answer, "%lf", &hbeta);

    /* if no rain map input, then: */
    if (parm.rain->answer == NULL) {
	/*Check for Rain Unique Value Input */
	/* if no rain unique value input */
	if (parm.rainval->answer == NULL) {
	    /*No rain input so use default */
	    sscanf(RAINVAL, "%lf", &rain_val);
	    /* if rain unique input exist, load it */
	}
	else {
	    /*Unique value input only */
	    sscanf(parm.rainval->answer, "%lf", &rain_val);
	}
	/* if Rain map exists */
    }
    else {
	/*Map input, so set rain_val to -999.99 */
	if (parm.rainval->answer == NULL) {
	    rain_val = -999.99;
	}
	else {
	    /*both map and unique value exist */
	    /*Choose the map, discard the unique value */
	    rain_val = -999.99;
	}
    }
    /* Report the final value of rain_val */
    G_debug(3, "rain_val is set to: %f\n", rain_val);

    /* if no Mannings map, then: */
    if (parm.manin->answer == NULL) {
	/*Check for Manin Unique Value Input */
	/* if no Mannings unique value input */
	if (parm.maninval->answer == NULL) {
	    /*No Mannings input so use default */
	    sscanf(MANINVAL, "%lf", &manin_val);
	    /* if mannings unique input value exists, load it */
	}
	else {
	    /*Unique value input only */
	    sscanf(parm.maninval->answer, "%lf", &manin_val);
	}
	/* if Mannings map exists */
    }
    else {
	/* Map input, set manin_val to -999.99 */
	if (parm.maninval->answer == NULL) {
	    manin_val = -999.99;
	}
	else {
	    /*both map and unique value exist */
	    /*Choose map, discard the unique value */
	    manin_val = -999.99;
	}
    }
    /* Report the final value of manin_val */
    G_debug(1, "manin_val is set to: %f\n", manin_val);

    /* if no infiltration map, then: */
    if (parm.infil->answer == NULL) {
	/*Check for Infil Unique Value Input */
	/*if no infiltration unique value input */
	if (parm.infilval->answer == NULL) {
	    /*No infiltration unique value so use default */
	    sscanf(INFILVAL, "%lf", &infil_val);
	    /* if infiltration unique value exists, load it */
	}
	else {
	    /*unique value input only */
	    sscanf(parm.infilval->answer, "%lf", &infil_val);
	}
	/* if infiltration map exists */
    }
    else {
	/* Map input, set infil_val to -999.99 */
	if (parm.infilval->answer == NULL) {
	    infil_val = -999.99;
	}
	else {
	    /*both map and unique value exist */
	    /*Choose map, discard the unique value */
	    infil_val = -999.99;
	}
    }
    /* Report the final value of infil_val */
    G_debug(1, "infil_val is set to: %f\n", infil_val);

    /* Recompute timesec from user input in minutes
     * to real timesec in seconds */
    timesec = timesec * 60.0;
    iterout = iterout * 60.0;
    if ((timesec / iterout) > 100.0)
	G_message(_("More than 100 files are going to be created !!!!!"));

    /* compute how big the raster is and set this to appr 2 walkers per cell */
    if (parm.nwalk->answer == NULL) {
	maxwa = mx * my * 2;
	rwalk = (double)(mx * my * 2.);
	G_message(_("default nwalk=%d, rwalk=%f"), maxwa, rwalk);
    }
    else {
	sscanf(parm.nwalk->answer, "%d", &maxwa);
	rwalk = (double)maxwa;
    }

    /*      rwalk = (double) maxwa; */

    if (conv != 1.0)
	G_message(_("Using metric conversion factor %f, step=%f"), conv,
		  step);

 if ((depth == NULL) && (disch == NULL) && (err == NULL))
        G_warning(_("You are not outputting any raster maps"));
    ret_val = input_data();
    if (ret_val != 1)
        G_fatal_error(_("Input failed"));


    /* memory allocation for output grids */
    G_debug(1, "beginning memory allocation for output grids");

    gama = G_alloc_matrix(my, mx);
    if (err != NULL)
	gammas = G_alloc_matrix(my, mx);
    dif = G_alloc_fmatrix(my, mx);

    G_debug(1, "seeding randoms");
    seeds(rand1, rand2);
    grad_check();
    main_loop();

    if (ts == 0) {
	ii = output_data(0, 1.);
	if (ii != 1)
	    G_fatal_error(_("Cannot write raster maps"));
    }

    /* Exit with Success */
    exit(EXIT_SUCCESS);
}
Ejemplo n.º 8
0
int
main(int argc, char **argv)
{
    char *codeset = NULL;

    rootuid = get_user_uid_safe(ROOTNAME);
    rootgid = get_group_gid_safe(ROOTGROUP);

    /* we set it to 022 in order to get a pidfile readable by fcrontab
     * (will be set to 066 later) */
    saved_umask = umask(022);

    /* parse options */

    if (strrchr(argv[0], '/') == NULL)
        prog_name = argv[0];
    else
        prog_name = strrchr(argv[0], '/') + 1;

    {
        uid_t daemon_uid;
        if ((daemon_uid = getuid()) != rootuid)
            die("Fcron must be executed as root");
    }

    /* we have to set daemon_pid before the fork because it's
     * used in die() and die_e() functions */
    daemon_pid = getpid();

    /* save the value of the TZ env variable (used for option timezone) */
    orig_tz_envvar = strdup2(getenv("TZ"));

    parseopt(argc, argv);

    /* read fcron.conf and update global parameters */
    read_conf();

    /* initialize the logs before we become a daemon */
    xopenlog();

    /* change directory */

    if (chdir(fcrontabs) != 0)
        die_e("Could not change dir to %s", fcrontabs);

    /* Get the default locale character set for the mail
     * "Content-Type: ...; charset=" header */
    setlocale(LC_ALL, "");      /* set locale to system defaults or to
                                 * that specified by any  LC_* env vars */
    /* Except that "US-ASCII" is preferred to "ANSI_x3.4-1968" in MIME,
     * even though "ANSI_x3.4-1968" is the official charset name. */
    if ((codeset = nl_langinfo(CODESET)) != 0L &&
        strcmp(codeset, "ANSI_x3.4-1968") != 0)
        strncpy(default_mail_charset, codeset, sizeof(default_mail_charset));
    else
        strcpy(default_mail_charset, "US-ASCII");

    if (freopen("/dev/null", "r", stdin) == NULL)
        error_e("Could not open /dev/null as stdin");

    if (foreground == 0) {

        /* close stdout and stderr.
         * close unused descriptors
         * optional detach from controlling terminal */

        int fd;
        pid_t pid;

        switch (pid = fork()) {
        case -1:
            die_e("fork");
            break;
        case 0:
            /* child */
            break;
        default:
            /* parent */
/*  	    printf("%s[%d] " VERSION_QUOTED " : started.\n", */
/*  		   prog_name, pid); */
            exit(0);
        }

        daemon_pid = getpid();

        if ((fd = open("/dev/tty", O_RDWR)) >= 0) {
#ifndef _HPUX_SOURCE
            ioctl(fd, TIOCNOTTY, 0);
#endif
            xclose_check(&fd, "/dev/tty");
        }

        if (freopen("/dev/null", "w", stdout) == NULL)
            error_e("Could not open /dev/null as stdout");
        if (freopen("/dev/null", "w", stderr) == NULL)
            error_e("Could not open /dev/null as stderr");

        /* close most other open fds */
        xcloselog();
        for (fd = 3; fd < 250; fd++)
            /* don't use xclose_check() as we do expect most of them to fail */
            (void)close(fd);

        /* finally, create a new session */
        if (setsid() == -1)
            error("Could not setsid()");

    }

    /* check if another fcron daemon is running, create pid file and lock it */
    get_lock();

    /* this program belongs to root : we set default permission mode
     * to  600 for security reasons, but we reset them to the saved
     * umask just before we run a job */
    umask(066);

    explain("%s[%d] " VERSION_QUOTED " started", prog_name, daemon_pid);

#ifdef HAVE_SIGNAL
    signal(SIGTERM, sigterm_handler);
    signal(SIGHUP, sighup_handler);
    siginterrupt(SIGHUP, 0);
    signal(SIGCHLD, sigchild_handler);
    siginterrupt(SIGCHLD, 0);
    signal(SIGUSR1, sigusr1_handler);
    siginterrupt(SIGUSR1, 0);
    signal(SIGUSR2, sigusr2_handler);
    siginterrupt(SIGUSR2, 0);
    /* we don't want SIGPIPE to kill fcron, and don't need to handle it */
    signal(SIGPIPE, SIG_IGN);
#elif HAVE_SIGSET
    sigset(SIGTERM, sigterm_handler);
    sigset(SIGHUP, sighup_handler);
    sigset(SIGCHLD, sigchild_handler);
    sigset(SIGUSR1, sigusr1_handler);
    sigset(SIGUSR2, sigusr2_handler);
    sigset(SIGPIPE, SIG_IGN);
#endif

    /* initialize job database */
    next_id = 0;

    /* initialize exe_array */
    exe_list = exe_list_init();

    /* initialize serial_array */
    serial_running = 0;
    serial_array_index = 0;
    serial_num = 0;
    serial_array_size = SERIAL_INITIAL_SIZE;
    serial_array =
        alloc_safe(serial_array_size * sizeof(cl_t *), "serial_array");

    /* initialize lavg_array */
    lavg_list = lavg_list_init();
    lavg_list->max_entries = lavg_queue_max;
    lavg_serial_running = 0;

#ifdef FCRONDYN
    /* initialize socket */
    init_socket();
#endif

    /* initialize random number generator :
     * WARNING : easy to guess !!! */
    /* we use the hostname and tv_usec in order to get different seeds
     * on two different machines starting fcron at the same moment */
    {
        char hostname[50];
        int i;
        unsigned int seed;
#ifdef HAVE_GETTIMEOFDAY
        struct timeval tv;      /* we use usec field to get more precision */
        gettimeofday(&tv, NULL);
        seed = ((unsigned int)tv.tv_usec) ^ ((unsigned int)tv.tv_sec);
#else
        seed = (unsigned int)time(NULL);
#endif
        gethostname(hostname, sizeof(hostname));

        for (i = 0; i < sizeof(hostname) - sizeof(seed); i += sizeof(seed))
            seed ^= (unsigned int)*(hostname + i);

        srand(seed);
    }

    main_loop();

    /* never reached */
    return EXIT_OK;
}
Ejemplo n.º 9
0
int main(int argc, char **argv) {

    main_loop();
    return 0;
}
Ejemplo n.º 10
0
/*
 *			M A I N
 */
int
main(int argc, char **argv)
{
#define PORTSZ 32
    char	portname[PORTSZ];

    max_fd = 0;

    /* No disk files on remote machine */
    _fb_disk_enable = 0;
    memset((void *)clients, 0, sizeof(struct pkg_conn *) * MAX_CLIENTS);

#ifdef SIGALRM
    (void)signal( SIGPIPE, SIG_IGN );
    (void)signal( SIGALRM, sigalarm );
#endif
    /*alarm(1)*/

    FD_ZERO(&select_list);
    fb_server_select_list = &select_list;
    fb_server_max_fd = &max_fd;

#ifndef _WIN32
    /*
     * Inetd Daemon.
     * Check to see if we were invoked by /etc/inetd.  If so
     * we will have an open network socket on fd=0.  Become
     * a Transient PKG server if this is so.
     */
    netfd = 0;
    if ( is_socket(netfd) ) {
	init_syslog();
	new_client( pkg_transerver( fb_server_pkg_switch, comm_error ) );
	max_fd = 8;
	once_only = 1;
	main_loop();
	bu_exit(0, NULL);
    }
#endif

    /* for now, make them set a port_num, for usage message */
    if ( !get_args( argc, argv ) || !port_set ) {
	(void)fputs(usage, stderr);
	bu_exit( 1, NULL );
    }

    /* Single-Frame-Buffer Server */
    if ( framebuffer != NULL ) {
	fb_server_retain_on_close = 1;	/* don't ever close the frame buffer */

	/* open a frame buffer */
	if ( (fb_server_fbp = fb_open(framebuffer, width, height)) == FBIO_NULL )
	    bu_exit(1, NULL);
	if ( fb_server_fbp->if_selfd > 0 )  {
	    FD_SET(fb_server_fbp->if_selfd, &select_list);
	    max_fd = fb_server_fbp->if_selfd;
	}

	/* check/default port */
	if ( port_set ) {
	    if ( port < 1024 )
		port += 5559;
	}
	snprintf(portname, PORTSZ, "%d", port);

	/*
	 * Hang an unending listen for PKG connections
	 */
	if ( (netfd = pkg_permserver(portname, 0, 0, comm_error)) < 0 )
	    bu_exit(-1, NULL);
	FD_SET(netfd, &select_list);
	if (netfd > max_fd)
	    max_fd = netfd;

	main_loop();
	bu_exit(0, NULL);
    }

#ifndef _WIN32
    /*
     * Stand-Alone Daemon
     */
    /* check/default port */
    if ( port_set ) {
	if ( port < 1024 )
	    port += 5559;
	sprintf(portname, "%d", port);
    } else {
	snprintf(portname, PORTSZ, "%s", "remotefb");
    }

    init_syslog();
    while ( (netfd = pkg_permserver(portname, 0, 0, comm_error)) < 0 ) {
	static int error_count=0;
	sleep(1);
	if (error_count++ < 60) {
	    continue;
	}
	comm_error("Unable to start the stand-alone framebuffer daemon after 60 seconds, giving up.");
	bu_exit(1, NULL);
    }

    while (1) {
	int stat;
	struct pkg_conn	*pcp;

	pcp = pkg_getclient( netfd, fb_server_pkg_switch, comm_error, 0 );
	if ( pcp == PKC_ERROR )
	    break;		/* continue is unlikely to work */

	if ( fork() == 0 )  {
	    /* 1st level child process */
	    (void)close(netfd);	/* Child is not listener */

	    /* Create 2nd level child process, "double detatch" */
	    if ( fork() == 0 )  {
		/* 2nd level child -- start work! */
		new_client( pcp );
		once_only = 1;
		main_loop();
		bu_exit(0, NULL);
	    } else {
		/* 1st level child -- vanish */
		bu_exit(1, NULL);
	    }
	} else {
	    /* Parent: lingering server daemon */
	    pkg_close(pcp);	/* Daemon is not the server */
	    /* Collect status from 1st level child */
	    (void)wait( &stat );
	}
    }
#endif  /* _WIN32 */

    bu_exit(2, NULL);	/* ERROR exit */
}
Ejemplo n.º 11
0
int main(int argc, char **argv)
{
	char *ptr;
	int c, i, j, cpu_tmp, opt_index, ops_touched = 0, vals[4] = {0};
	bool prio_high = false, setsockmem = true;
	void (*main_loop)(struct ctx *ctx) = NULL;
	struct ctx ctx;

	init_ctx(&ctx);
	srand(time(NULL));

	while ((c = getopt_long(argc, argv, short_options, long_options,
				&opt_index)) != EOF) {
		switch (c) {
		case 'd':
		case 'i':
			ctx.device_in = xstrdup(optarg);
			break;
		case 'o':
			ctx.device_out = xstrdup(optarg);
			break;
		case 'P':
			ctx.prefix = xstrdup(optarg);
			break;
		case 'R':
			ctx.link_type = LINKTYPE_IEEE802_11;
			ctx.rfraw = 1;
			break;
		case 'r':
			ctx.randomize = true;
			break;
		case 'J':
			ctx.jumbo = true;
			break;
		case 'T':
			ctx.magic = (uint32_t) strtoul(optarg, NULL, 0);
			pcap_check_magic(ctx.magic);
			break;
		case 'f':
			ctx.filter = xstrdup(optarg);
			break;
		case 'M':
			ctx.promiscuous = false;
			break;
		case 'A':
			setsockmem = false;
			break;
		case 'u':
			ctx.uid = strtoul(optarg, NULL, 0);
			ctx.enforce = true;
			break;
		case 'g':
			ctx.gid = strtoul(optarg, NULL, 0);
			ctx.enforce = true;
			break;
		case 't':
			if (!strncmp(optarg, "host", strlen("host")))
				ctx.packet_type = PACKET_HOST;
			else if (!strncmp(optarg, "broadcast", strlen("broadcast")))
				ctx.packet_type = PACKET_BROADCAST;
			else if (!strncmp(optarg, "multicast", strlen("multicast")))
				ctx.packet_type = PACKET_MULTICAST;
			else if (!strncmp(optarg, "others", strlen("others")))
				ctx.packet_type = PACKET_OTHERHOST;
			else if (!strncmp(optarg, "outgoing", strlen("outgoing")))
				ctx.packet_type = PACKET_OUTGOING;
			else
				ctx.packet_type = -1;
			break;
		case 'S':
			ptr = optarg;
			ctx.reserve_size = 0;

			for (j = i = strlen(optarg); i > 0; --i) {
				if (!isdigit(optarg[j - i]))
					break;
				ptr++;
			}

			if (!strncmp(ptr, "KiB", strlen("KiB")))
				ctx.reserve_size = 1 << 10;
			else if (!strncmp(ptr, "MiB", strlen("MiB")))
				ctx.reserve_size = 1 << 20;
			else if (!strncmp(ptr, "GiB", strlen("GiB")))
				ctx.reserve_size = 1 << 30;
			else
				panic("Syntax error in ring size param!\n");

			ctx.reserve_size *= strtoul(optarg, NULL, 0);
			break;
		case 'b':
			cpu_tmp = strtol(optarg, NULL, 0);

			cpu_affinity(cpu_tmp);
			if (ctx.cpu != -2)
				ctx.cpu = cpu_tmp;
			break;
		case 'H':
			prio_high = true;
			break;
		case 'c':
			ctx.pcap = PCAP_OPS_RW;
			ops_touched = 1;
			break;
		case 'm':
			ctx.pcap = PCAP_OPS_MM;
			ops_touched = 1;
			break;
		case 'G':
			ctx.pcap = PCAP_OPS_SG;
			ops_touched = 1;
			break;
		case 'Q':
			ctx.cpu = -2;
			break;
		case 's':
			ctx.print_mode = PRINT_NONE;
			break;
		case 'q':
			ctx.print_mode = PRINT_LESS;
			break;
		case 'X':
			ctx.print_mode =
				(ctx.print_mode == PRINT_ASCII) ?
				 PRINT_HEX_ASCII : PRINT_HEX;
			break;
		case 'l':
			ctx.print_mode =
				(ctx.print_mode == PRINT_HEX) ?
				 PRINT_HEX_ASCII : PRINT_ASCII;
			break;
		case 'k':
			ctx.kpull = strtoul(optarg, NULL, 0);
			break;
		case 'n':
			frame_count_max = strtoul(optarg, NULL, 0);
			break;
		case 'F':
			ptr = optarg;
			ctx.dump_interval = 0;

			for (j = i = strlen(optarg); i > 0; --i) {
				if (!isdigit(optarg[j - i]))
					break;
				ptr++;
			}

			if (!strncmp(ptr, "KiB", strlen("KiB"))) {
				ctx.dump_interval = 1 << 10;
				ctx.dump_mode = DUMP_INTERVAL_SIZE;
			} else if (!strncmp(ptr, "MiB", strlen("MiB"))) {
				ctx.dump_interval = 1 << 20;
				ctx.dump_mode = DUMP_INTERVAL_SIZE;
			} else if (!strncmp(ptr, "GiB", strlen("GiB"))) {
				ctx.dump_interval = 1 << 30;
				ctx.dump_mode = DUMP_INTERVAL_SIZE;
			} else if (!strncmp(ptr, "sec", strlen("sec"))) {
				ctx.dump_interval = 1;
				ctx.dump_mode = DUMP_INTERVAL_TIME;
			} else if (!strncmp(ptr, "min", strlen("min"))) {
				ctx.dump_interval = 60;
				ctx.dump_mode = DUMP_INTERVAL_TIME;
			} else if (!strncmp(ptr, "hrs", strlen("hrs"))) {
				ctx.dump_interval = 60 * 60;
				ctx.dump_mode = DUMP_INTERVAL_TIME;
			} else if (!strncmp(ptr, "s", strlen("s"))) {
				ctx.dump_interval = 1;
				ctx.dump_mode = DUMP_INTERVAL_TIME;
			} else {
				panic("Syntax error in time/size param!\n");
			}

			ctx.dump_interval *= strtoul(optarg, NULL, 0);
			break;
		case 'V':
			ctx.verbose = 1;
			break;
		case 'B':
			ctx.dump_bpf = true;
			break;
		case 'D':
			pcap_dump_type_features();
			die();
			break;
		case 'U':
			update_geoip();
			die();
			break;
		case 'v':
			version();
			break;
		case 'h':
			help();
			break;
		case '?':
			switch (optopt) {
			case 'd':
			case 'i':
			case 'o':
			case 'f':
			case 't':
			case 'P':
			case 'F':
			case 'n':
			case 'S':
			case 'b':
			case 'k':
			case 'T':
			case 'u':
			case 'g':
			case 'e':
				panic("Option -%c requires an argument!\n",
				      optopt);
			default:
				if (isprint(optopt))
					printf("Unknown option character `0x%X\'!\n", optopt);
				die();
			}
		default:
			break;
		}
	}

	if (!ctx.filter && optind != argc) {
		int ret;
		off_t offset = 0;

		for (i = optind; i < argc; ++i) {
			size_t alen = strlen(argv[i]) + 2;
			size_t flen = ctx.filter ? strlen(ctx.filter) : 0;

			ctx.filter = xrealloc(ctx.filter, 1, flen + alen);
			ret = slprintf(ctx.filter + offset, strlen(argv[i]) + 2, "%s ", argv[i]);
			if (ret < 0)
				panic("Cannot concatenate filter string!\n");
			else
				offset += ret;
		}
	}

	if (!ctx.device_in)
		ctx.device_in = xstrdup("any");

	register_signal(SIGINT, signal_handler);
	register_signal(SIGQUIT, signal_handler);
	register_signal(SIGTERM, signal_handler);
	register_signal(SIGHUP, signal_handler);

	tprintf_init();

	if (prio_high) {
		set_proc_prio(-20);
		set_sched_status(SCHED_FIFO, sched_get_priority_max(SCHED_FIFO));
	}

	if (ctx.device_in && (device_mtu(ctx.device_in) ||
	    !strncmp("any", ctx.device_in, strlen(ctx.device_in)))) {
		if (!ctx.rfraw)
			ctx.link_type = pcap_devtype_to_linktype(ctx.device_in);
		if (!ctx.device_out) {
			ctx.dump = 0;
			main_loop = recv_only_or_dump;
		} else if (device_mtu(ctx.device_out)) {
			register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
			main_loop = receive_to_xmit;
		} else {
			ctx.dump = 1;
			register_signal_f(SIGALRM, timer_next_dump, SA_SIGINFO);
			main_loop = recv_only_or_dump;
			if (!ops_touched)
				ctx.pcap = PCAP_OPS_SG;
		}
	} else {
		if (ctx.device_out && device_mtu(ctx.device_out)) {
			register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);
			main_loop = pcap_to_xmit;
			if (!ops_touched)
				ctx.pcap = PCAP_OPS_MM;
		} else {
			main_loop = read_pcap;
			if (!ops_touched)
				ctx.pcap = PCAP_OPS_SG;
		}
	}

	bug_on(!main_loop);

	init_geoip(0);
	if (setsockmem)
		set_system_socket_memory(vals, array_size(vals));
	if (!ctx.enforce)
		xlockme();

	if (ctx.verbose)
		printf("pcap file I/O method: %s\n", pcap_ops_group_to_str[ctx.pcap]);

	main_loop(&ctx);

	if (!ctx.enforce)
		xunlockme();
	if (setsockmem)
		reset_system_socket_memory(vals, array_size(vals));
	destroy_geoip();

	device_restore_irq_affinity_list();
	tprintf_cleanup();

	destroy_ctx(&ctx);
	return 0;
}
Ejemplo n.º 12
0
int main (int argc, char **argv) {
  int c;

  program_name = argv[0];
  long long int msec = 0;// start timecode in ms from 00:00:00.00
  long int date = 0;// bcd: 201012 = 20 Oct 2012
  long int tzoff = 0;// time-zone in minuteswest
  int custom_user_bits = 0;

  while ((c = getopt_long (argc, argv,
	   "h"	/* help */
	   "f:"	/* fps */
	   "d:"	/* date */
	   "g:"	/* gain^wvolume */
	   "l:"	/* duration */
	   "r"	/* reverse */
	   "s:"	/* samplerate */
	   "t:"	/* timecode */
	   "z:"	/* timezone */
	   "m:"	/* timezone */
	   "u:" /* free format user bits */
	   "V",	/* version */
	   long_options, (int *) 0)) != EOF)
  {
      switch (c) {
	case 'V':
	  printf ("%s %s\n\n",basename(argv[0]), VERSION);
	  printf (
		  "Copyright (C) 2012 Robin Gareus <*****@*****.**>\n"
		  "This is free software; see the source for copying conditions.  There is NO\n"
		  "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\n"
		  );
	  exit (0);

	case 'h':
	  usage (0);

	case 'f':
	  parse_fps(optarg);
	  break;

	case 'd':
	  {
	    date=atoi(optarg);
	    char *tmp = optarg;
	    if (tmp && (tmp = strchr(tmp, '/'))) date=date*100+(atoi(++tmp)*10000);
	    if (tmp) {
	      if ((tmp = strchr(tmp, '/'))) date+=atoi(++tmp);
	      else date+=12;// 2012
	    }
	  }
	  break;

	case 'g':
	  volume_dbfs = atof(optarg);
	  if (volume_dbfs > 0) volume_dbfs=0;
	  if (volume_dbfs < -96.0) volume_dbfs=-96.0;
	  printf("Output volume %.2f dBfs\n", volume_dbfs);
	  break;

	case 'm':
	  tzoff=atoi(optarg); //minuteswest
	  break;

	case 'r':
	  reverse = 1;
	  break;

	case 's':
	  samplerate=atoi(optarg);
	  break;

	case 'z':
	  {
	    int hh = atoi(optarg)/100;
	    tzoff= 60*hh + ((atoi(optarg)-(100*hh))%60); // HHMM
	  }
	  break;

	case 'l':
	  {
	    int bcd[SMPTE_LAST];
	    parse_string(rint(fps_num/(double)fps_den), bcd, optarg);
	    duration = bcdarray_to_framecnt(bcd) * 1000.0 / (((double)fps_num)/(double)fps_den);
	  }
	  break;

	case 't':
	  {
	    sync_now=0;
	    int bcd[SMPTE_LAST];
	    parse_string(rint(fps_num/(double)fps_den), bcd, optarg);
	    msec = bcdarray_to_framecnt(bcd) * 1000.0 / (((double)fps_num)/(double)fps_den);
	  }
	  break;

	case 'u':
	  {
	    custom_user_bits = 1;
	    parse_user_bits(user_bit_array, optarg);
	    /* Free format user bits, so reset any date/timezone settings. */
	    date = 0;
	    tzoff = 0;
	  }
	  break;

	default:
	  usage (EXIT_FAILURE);
      }
  }

  if (optind >= argc) {
    usage (EXIT_FAILURE);
  }

  fps_sanity_checks();

  {
    SF_INFO sfnfo;
    memset(&sfnfo, 0, sizeof(SF_INFO));
    sfnfo.samplerate = samplerate;
    sfnfo.channels = 1;
    sfnfo.format = SF_FORMAT_WAV | sf_format;
    sf = sf_open(argv[optind], SFM_WRITE, &sfnfo);
    if (!sf) {
      fprintf(stderr, "cannot open output file '%s'\n", argv[optind]);
      return 1;
    }
  }
  printf("writing to '%s'\n", argv[optind]);
  printf("samplerate: %d, duration %.1f ms\n", samplerate, duration);

  encoder_setup(fps_num, fps_den, ltc_tv, samplerate,
      ((date != 0) ? LTC_USE_DATE : 0) | ((sync_now) ? (LTC_USE_DATE|LTC_TC_CLOCK) : 0)
      );

  if (sync_now==0) {
#if 0 // DEBUG
    printf("date: %06ld (DDMMYY)\n", date);
    printf("time: %lldms\n", msec);
    printf("zone: %c%02d%02d = %ld minutes west\n", tzoff<0?'-':'+', abs(tzoff/60),abs(tzoff%60), tzoff);
#endif
    set_encoder_time(1000.0*msec, date, tzoff, fps_num, fps_den, 1);
  } else {
    struct timespec t;
    long int sync_msec;
    my_clock_gettime(&t);
    sync_msec = (t.tv_sec%86400)*1000 + (t.tv_nsec/1000000);

    time_t now = t.tv_sec;
    struct tm gm;
    long int sync_date = 0;
    if (gmtime_r(&now, &gm))
      sync_date = gm.tm_mday*10000 + (gm.tm_mon + 1)*100 + (gm.tm_year % 100);
    sync_msec += 1000.0 * ltc_frame_alignment(samplerate * fps_den / (double) fps_num, ltc_tv) / samplerate;
    set_encoder_time(1000.0*sync_msec, custom_user_bits ? 0 : sync_date, 0, fps_num, fps_den, 1);
  }

  if (custom_user_bits)
    set_user_bits(user_bit_array);

  signal(SIGINT, endnow);

  if (reverse)
    main_loop_reverse();
  else
    main_loop();

  if (sf) sf_close(sf);
  if (enc_buf) free(enc_buf);
  if (encoder) ltc_encoder_free(encoder);
  return(0);
}
Ejemplo n.º 13
0
void board_init_r(gd_t *new_gd, ulong dest_addr)
{
#ifndef CONFIG_ENV_IS_NOWHERE
    extern char * env_name_spec;
#endif
    bd_t *bd;

    gd = new_gd;
    bd = gd->bd;

    gd->flags |= GD_FLG_RELOC;
    gd->reloc_off = dest_addr - CONFIG_SYS_MONITOR_BASE;

    /* Enable the MMU so that we can keep u-boot simple */
    mmu_init_r(dest_addr);

    board_early_init_r();

    monitor_flash_len = _edata - _text;

#if defined(CONFIG_NEEDS_MANUAL_RELOC)
    /*
     * We have to relocate the command table manually
     */
    fixup_cmdtable(ll_entry_start(cmd_tbl_t, cmd),
                   ll_entry_count(cmd_tbl_t, cmd));
#endif /* defined(CONFIG_NEEDS_MANUAL_RELOC) */

    /* there are some other pointer constants we must deal with */
#ifndef CONFIG_ENV_IS_NOWHERE
    env_name_spec += gd->reloc_off;
#endif

    timer_init();

    /* The malloc area is right below the monitor image in RAM */
    mem_malloc_init(CONFIG_SYS_MONITOR_BASE + gd->reloc_off -
                    CONFIG_SYS_MALLOC_LEN, CONFIG_SYS_MALLOC_LEN);
    dma_alloc_init();

    enable_interrupts();

    bd->bi_flashstart = 0;
    bd->bi_flashsize = 0;
    bd->bi_flashoffset = 0;

#ifndef CONFIG_SYS_NO_FLASH
    bd->bi_flashstart = CONFIG_SYS_FLASH_BASE;
    bd->bi_flashsize = flash_init();
    bd->bi_flashoffset = (unsigned long)_edata - (unsigned long)_text;

    if (bd->bi_flashsize)
        display_flash_config();
#endif

    if (bd->bi_dram[0].size)
        display_dram_config();

    gd->bd->bi_boot_params = malloc(CONFIG_SYS_BOOTPARAMS_LEN);
    if (!gd->bd->bi_boot_params)
        puts("WARNING: Cannot allocate space for boot parameters\n");

    /* initialize environment */
    env_relocate();

    stdio_init();
    jumptable_init();
    console_init_r();

    /* Initialize from environment */
    load_addr = getenv_ulong("loadaddr", 16, load_addr);

#ifdef CONFIG_BITBANGMII
    bb_miiphy_init();
#endif
#if defined(CONFIG_CMD_NET)
    puts("Net:   ");
    eth_initialize(gd->bd);
#endif

#ifdef CONFIG_GENERIC_ATMEL_MCI
    mmc_initialize(gd->bd);
#endif
    for (;;) {
        main_loop();
    }
}
Ejemplo n.º 14
0
int main(int argc, char **argv){
   
    int gdb_fd, child_fd, slavefd, masterfd;

#if 0
   int c;
   read(0, &c ,1);
#endif

    if ( tty_cbreak(STDIN_FILENO, &term_attributes) == -1 )
        logger_write_pos ( logger, __FILE__, __LINE__, "tty_cbreak error");

    pty_pair = pty_pair_create ();
    if (!pty_pair)
      {
        fprintf ( stderr, "%s:%d Unable to create PTY pair", __FILE__, __LINE__); 
        exit(-1);
      }

    slavefd = pty_pair_get_slavefd (pty_pair);
    if (slavefd == -1)
      {
        fprintf ( stderr, "%s:%d Unable to get slavefd", __FILE__, __LINE__); 
        exit(-1);
      }

    masterfd = pty_pair_get_masterfd (pty_pair);
    if (masterfd == -1)
      {
        fprintf ( stderr, "%s:%d Unable to get masterfd", __FILE__, __LINE__); 
        exit(-1);
      }

    if (tty_off_xon_xoff (masterfd) == -1)
     exit(-1);
      
    rline = rline_initialize (slavefd, rlctx_send_user_command, tab_completion, getenv ("TERM"));

    if ( (tgdb = tgdb_initialize(NULL, argc-1, argv+1, &gdb_fd, &child_fd)) == NULL ) {
        logger_write_pos ( logger, __FILE__, __LINE__, "tgdb_start error");
        goto driver_end;
    }

	if ( tgdb_set_verbose_error_handling ( tgdb, 1 ) != 1 ) {
		logger_write_pos ( logger, __FILE__, __LINE__, "driver error");
		goto driver_end;
	}

	/* Ask TGDB to print error messages */
	if ( tgdb_set_verbose_gui_command_output ( tgdb, 1 ) != 1 ) {
		logger_write_pos ( logger, __FILE__, __LINE__, "driver error");
		goto driver_end;
	}

    set_up_signal();

    main_loop(gdb_fd, child_fd);

    if(tgdb_shutdown( tgdb ) == -1)
        logger_write_pos ( logger, __FILE__, __LINE__, "could not shutdown");

driver_end:

    if (tty_set_attributes (STDIN_FILENO, &term_attributes) == -1)
        logger_write_pos (logger, __FILE__, __LINE__, "tty_reset error");

    return 0;
}
Ejemplo n.º 15
0
int main(int argc, char **argv)
{
	bool slow = false, invoke_cpp = false, reseed = true;
	int c, opt_index, i, j, vals[4] = {0}, irq;
	char *confname = NULL, *ptr;
	unsigned long cpus_tmp, orig_num = 0;
	unsigned long long tx_packets, tx_bytes;
	struct ctx ctx;

	fmemset(&ctx, 0, sizeof(ctx));
	ctx.cpus = get_number_cpus_online();
	ctx.uid = getuid();
	ctx.gid = getgid();

	while ((c = getopt_long(argc, argv, short_options, long_options,
				&opt_index)) != EOF) {
		switch (c) {
		case 'h':
			help();
			break;
		case 'v':
			version();
			break;
		case 'e':
			example();
			break;
		case 'p':
			invoke_cpp = true;
			break;
		case 'V':
			ctx.verbose = true;
			break;
		case 'P':
			cpus_tmp = strtoul(optarg, NULL, 0);
			if (cpus_tmp > 0 && cpus_tmp < ctx.cpus)
				ctx.cpus = cpus_tmp;
			break;
		case 'd':
		case 'o':
			ctx.device = xstrndup(optarg, IFNAMSIZ);
			break;
		case 'r':
			ctx.rand = true;
			break;
		case 's':
			slow = true;
			ctx.cpus = 1;
			ctx.smoke_test = true;
			ctx.rhost = xstrdup(optarg);
			break;
		case 'R':
			ctx.rfraw = true;
			break;
		case 'J':
			ctx.jumbo_support = true;
			break;
		case 'c':
		case 'i':
			confname = xstrdup(optarg);
			if (!strncmp("-", confname, strlen("-")))
				ctx.cpus = 1;
			break;
		case 'u':
			ctx.uid = strtoul(optarg, NULL, 0);
			ctx.enforce = true;
			break;
		case 'g':
			ctx.gid = strtoul(optarg, NULL, 0);
			ctx.enforce = true;
			break;
		case 'k':
			ctx.kpull = strtoul(optarg, NULL, 0);
			break;
		case 'E':
			seed = strtoul(optarg, NULL, 0);
			reseed = false;
			break;
		case 'n':
			orig_num = strtoul(optarg, NULL, 0);
			ctx.num = orig_num;
			break;
		case 't':
			slow = true;
			ctx.gap = strtoul(optarg, NULL, 0);
			if (ctx.gap > 0)
				/* Fall back to single core to not
				 * mess up correct timing. We are slow
				 * anyway!
				 */
				ctx.cpus = 1;
			break;
		case 'S':
			ptr = optarg;
			ctx.reserve_size = 0;

			for (j = i = strlen(optarg); i > 0; --i) {
				if (!isdigit(optarg[j - i]))
					break;
				ptr++;
			}

			if (!strncmp(ptr, "KiB", strlen("KiB")))
				ctx.reserve_size = 1 << 10;
			else if (!strncmp(ptr, "MiB", strlen("MiB")))
				ctx.reserve_size = 1 << 20;
			else if (!strncmp(ptr, "GiB", strlen("GiB")))
				ctx.reserve_size = 1 << 30;
			else
				panic("Syntax error in ring size param!\n");
			*ptr = 0;

			ctx.reserve_size *= strtol(optarg, NULL, 0);
			break;
		case '?':
			switch (optopt) {
			case 'd':
			case 'c':
			case 'n':
			case 'S':
			case 's':
			case 'P':
			case 'o':
			case 'E':
			case 'i':
			case 'k':
			case 'u':
			case 'g':
			case 't':
				panic("Option -%c requires an argument!\n",
				      optopt);
			default:
				if (isprint(optopt))
					printf("Unknown option character `0x%X\'!\n", optopt);
				die();
			}
		default:
			break;
		}
	}

	if (argc < 5)
		help();
	if (ctx.device == NULL)
		panic("No networking device given!\n");
	if (confname == NULL)
		panic("No configuration file given!\n");
	if (device_mtu(ctx.device) == 0)
		panic("This is no networking device!\n");

	register_signal(SIGINT, signal_handler);
	register_signal(SIGHUP, signal_handler);
	register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);

	set_system_socket_memory(vals, array_size(vals));
	xlockme();

	if (ctx.rfraw) {
		ctx.device_trans = xstrdup(ctx.device);
		xfree(ctx.device);

		enter_rfmon_mac80211(ctx.device_trans, &ctx.device);
		sleep(0);
	}

	irq = device_irq_number(ctx.device);
	device_set_irq_affinity_list(irq, 0, ctx.cpus - 1);

	stats = setup_shared_var(ctx.cpus);

	for (i = 0; i < ctx.cpus; i++) {
		pid_t pid = fork();

		switch (pid) {
		case 0:
			if (reseed)
				seed = generate_srand_seed();
			srand(seed);

			cpu_affinity(i);
			main_loop(&ctx, confname, slow, i, invoke_cpp, orig_num);

			goto thread_out;
		case -1:
			panic("Cannot fork processes!\n");
		}
	}

	for (i = 0; i < ctx.cpus; i++) {
		int status;

		wait(&status);
		if (WEXITSTATUS(status) == EXIT_FAILURE)
			die();
	}

	if (ctx.rfraw)
		leave_rfmon_mac80211(ctx.device_trans, ctx.device);

	reset_system_socket_memory(vals, array_size(vals));

	for (i = 0, tx_packets = tx_bytes = 0; i < ctx.cpus; i++) {
		while ((__get_state(i) & CPU_STATS_STATE_RES) == 0)
			sched_yield();

		tx_packets += stats[i].tx_packets;
		tx_bytes   += stats[i].tx_bytes;
	}

	fflush(stdout);
	printf("\n");
	printf("\r%12llu packets outgoing\n", tx_packets);
	printf("\r%12llu bytes outgoing\n", tx_bytes);
	for (i = 0; i < ctx.cpus; i++) {
		printf("\r%12lu sec, %lu usec on CPU%d (%llu packets)\n",
		       stats[i].tv_sec, stats[i].tv_usec, i,
		       stats[i].tx_packets);
	}

thread_out:
	xunlockme();
	destroy_shared_var(stats, ctx.cpus);
	device_restore_irq_affinity_list();

	free(ctx.device);
	free(ctx.device_trans);
	free(ctx.rhost);
	free(confname);

	return 0;
}
Ejemplo n.º 16
0
int
main (int argc, char *argv[])
{
  static const char *options = "rv?";
  static const struct option long_options[] = {
    { "help", 0, 0, '?' },
    { "verbose", 0, 0, 'v' },
    { 0, 0, 0, 0 }
  };
  int c;
  char *cmdline;

  ignore_value (chdir ("/"));

  if (winsock_init () == -1)
    error (EXIT_FAILURE, 0, "winsock initialization failed");

#ifdef HAVE_REGISTER_PRINTF_SPECIFIER
  /* http://udrepper.livejournal.com/20948.html */
  register_printf_specifier ('Q', print_shell_quote, print_arginfo);
  register_printf_specifier ('R', print_sysroot_shell_quote, print_arginfo);
#else
#ifdef HAVE_REGISTER_PRINTF_FUNCTION
  register_printf_function ('Q', print_shell_quote, print_arginfo);
  register_printf_function ('R', print_sysroot_shell_quote, print_arginfo);
#else
#error "HAVE_REGISTER_PRINTF_{SPECIFIER|FUNCTION} not defined"
#endif
#endif

  /* XXX The appliance /init script sets LD_PRELOAD=../libSegFault.so.
   * However if we CHROOT_IN to the sysroot that file might not exist,
   * resulting in all commands failing.  What we'd really like to do
   * is to have LD_PRELOAD only set while outside the chroot.  I
   * suspect the proper way to solve this is to remove the
   * CHROOT_IN/_OUT hack and replace it properly (fork), but that is
   * for another day.
   */
  unsetenv ("LD_PRELOAD");

  struct stat statbuf;
  if (stat ("/", &statbuf) == 0)
    root_device = statbuf.st_dev;

  for (;;) {
    c = getopt_long (argc, argv, options, long_options, NULL);
    if (c == -1) break;

    switch (c) {
      /* The -r flag is used when running standalone.  It changes
       * several aspects of the daemon.
       */
    case 'r':
      sysroot = "";
      sysroot_len = 0;
      autosync_umount = 0;
      break;

    case 'v':
      verbose = 1;
      break;

    case '?':
      usage ();
      exit (EXIT_SUCCESS);

    default:
      fprintf (stderr, "guestfsd: unexpected command line option 0x%x\n", c);
      exit (EXIT_FAILURE);
    }
  }

  if (optind < argc) {
    usage ();
    exit (EXIT_FAILURE);
  }

  cmdline = read_cmdline ();

  /* Set the verbose flag. */
  verbose = verbose ||
    (cmdline && strstr (cmdline, "guestfs_verbose=1") != NULL);
  if (verbose)
    printf ("verbose daemon enabled\n");

  if (verbose) {
    if (cmdline)
      printf ("linux commmand line: %s\n", cmdline);
    else
      printf ("could not read linux command line\n");
  }

  enable_network = cmdline && strstr (cmdline, "guestfs_network=1") != NULL;

#ifndef WIN32
  /* Make sure SIGPIPE doesn't kill us. */
  struct sigaction sa;
  memset (&sa, 0, sizeof sa);
  sa.sa_handler = SIG_IGN;
  sa.sa_flags = 0;
  if (sigaction (SIGPIPE, &sa, NULL) == -1)
    perror ("sigaction SIGPIPE"); /* but try to continue anyway ... */
#endif

#ifdef WIN32
# define setenv(n,v,f) _putenv(n "=" v)
#endif
  /* Set up a basic environment.  After we are called by /init the
   * environment is essentially empty.
   * https://bugzilla.redhat.com/show_bug.cgi?id=502074#c5
   *
   * NOTE: if you change $PATH, you must also change 'prog_exists'
   * function below.
   */
  setenv ("PATH", "/sbin:/usr/sbin:/bin:/usr/bin", 1);
  setenv ("SHELL", "/bin/sh", 1);
  setenv ("LC_ALL", "C", 1);
  setenv ("TERM", "dumb", 1);

#ifndef WIN32
  /* We document that umask defaults to 022 (it should be this anyway). */
  umask (022);
#else
  /* This is the default for Windows anyway.  It's not even clear if
   * Windows ever uses this -- the MSDN documentation for the function
   * contains obvious errors.
   */
  _umask (0);
#endif

  /* Make a private copy of /etc/lvm so we can change the config (see
   * daemon/lvm-filter.c).
   */
  copy_lvm ();

  /* Connect to virtio-serial channel. */
  char *channel, *p;
  if (cmdline && (p = strstr (cmdline, "guestfs_channel=")) != NULL) {
    p += 16;
    channel = strndup (p, strcspn (p, " \n"));
  }
  else
    channel = strdup (VIRTIO_SERIAL_CHANNEL);
  if (!channel) {
    perror ("strdup");
    exit (EXIT_FAILURE);
  }

  if (verbose)
    printf ("trying to open virtio-serial channel '%s'\n", channel);

  int sock = open (channel, O_RDWR|O_CLOEXEC);
  if (sock == -1) {
    fprintf (stderr,
             "\n"
             "Failed to connect to virtio-serial channel.\n"
             "\n"
             "This is a fatal error and the appliance will now exit.\n"
             "\n"
             "Usually this error is caused by either QEMU or the appliance\n"
             "kernel not supporting the vmchannel method that the\n"
             "libguestfs library chose to use.  Please run\n"
             "'libguestfs-test-tool' and provide the complete, unedited\n"
             "output to the libguestfs developers, either in a bug report\n"
             "or on the libguestfs redhat com mailing list.\n"
             "\n");
    perror (channel);
    exit (EXIT_FAILURE);
  }

  /* If it's a serial-port like device then it probably has echoing
   * enabled.  Put it into complete raw mode.
   */
  if (STRPREFIX (channel, "/dev/ttyS"))
    makeraw (channel, sock);

  /* cmdline, channel not used after this point */
  free (cmdline);
  free (channel);

  /* Wait for udev devices to be created.  If you start libguestfs,
   * especially with disks that contain complex (eg. mdadm) data
   * already, then it is possible for the 'mdadm' and LVM commands
   * that the init script runs to have not completed by the time the
   * daemon starts executing library commands.  (This is very rare and
   * hard to test however, but we have seen it in 'brew').  Run
   * udev_settle, but do it as late as possible to minimize the chance
   * that we'll have to do any waiting here.
   */
  udev_settle ();

  /* Send the magic length message which indicates that
   * userspace is up inside the guest.
   */
  char lenbuf[4];
  XDR xdr;
  uint32_t len = GUESTFS_LAUNCH_FLAG;
  xdrmem_create (&xdr, lenbuf, sizeof lenbuf, XDR_ENCODE);
  xdr_u_int (&xdr, &len);

  if (xwrite (sock, lenbuf, sizeof lenbuf) == -1) {
    perror ("xwrite");
    exit (EXIT_FAILURE);
  }

  xdr_destroy (&xdr);

  /* Enter the main loop, reading and performing actions. */
  main_loop (sock);

  exit (EXIT_SUCCESS);
}
Ejemplo n.º 17
0
void start_armboot (void)
{
	init_fnc_t **init_fnc_ptr;
	char *s;
#if defined(CONFIG_VFD) || defined(CONFIG_LCD)
	unsigned long addr;
#endif

	/* Pointer is writable since we allocated a register for it */
	gd = (gd_t*)(_armboot_start - CONFIG_SYS_MALLOC_LEN - sizeof(gd_t));
	/* compiler optimization barrier needed for GCC >= 3.4 */
	__asm__ __volatile__("": : :"memory");

	memset ((void*)gd, 0, sizeof (gd_t));
	gd->bd = (bd_t*)((char*)gd - sizeof(bd_t));
	memset (gd->bd, 0, sizeof (bd_t));

	gd->flags |= GD_FLG_RELOC;

	monitor_flash_len = _bss_start - _armboot_start;

	for (init_fnc_ptr = init_sequence; *init_fnc_ptr; ++init_fnc_ptr) {
		if ((*init_fnc_ptr)() != 0) {
			hang ();
		}
	}

	/* ADD by jhkim to extern heap length */
#if defined(CONFIG_SYS_HEAP_LEN)
	#if defined(CONFIG_SYS_HEAP_BASE)
	mem_malloc_init(CONFIG_SYS_HEAP_BASE, CONFIG_SYS_HEAP_LEN);
	#else
	mem_malloc_init((uint)_bss_end, CONFIG_SYS_HEAP_LEN);
	#endif
#else
	/* armboot_start is defined in the board-specific linker script */
	mem_malloc_init (_armboot_start - CONFIG_SYS_MALLOC_LEN,
			CONFIG_SYS_MALLOC_LEN);
#endif

#ifndef CONFIG_SYS_NO_FLASH
	/* configure available FLASH banks */
	display_flash_config (flash_init ());
#endif /* CONFIG_SYS_NO_FLASH */

#ifdef CONFIG_VFD
#	ifndef PAGE_SIZE
#	  define PAGE_SIZE 4096
#	endif
	/*
	 * reserve memory for VFD display (always full pages)
	 */
	/* bss_end is defined in the board-specific linker script */
	addr = (_bss_end + (PAGE_SIZE - 1)) & ~(PAGE_SIZE - 1);
	vfd_setmem (addr);
	gd->fb_base = addr;
#endif /* CONFIG_VFD */

#ifdef CONFIG_LCD
	/* board init may have inited fb_base */
	if (!gd->fb_base) {
#		ifndef PAGE_SIZE
#		  define PAGE_SIZE 4096
#		endif
		/*
		 * reserve memory for LCD display (always full pages)
		 */
		/* bss_end is defined in the board-specific linker script */
		addr = (_bss_end + (PAGE_SIZE - 1)) & ~(PAGE_SIZE - 1);
		lcd_setmem (addr);
		gd->fb_base = addr;
	}
#endif /* CONFIG_LCD */

#if defined(CONFIG_CMD_NAND)
	puts ("NAND:  ");
	nand_init();		/* go init the NAND */
#endif

#if defined(CONFIG_CMD_ONENAND)
	onenand_init();
#endif

#ifdef CONFIG_HAS_DATAFLASH
	AT91F_DataflashInit();
	dataflash_print_info();
#endif

	// psw0523 add for mmc env
#ifdef CONFIG_ENV_IS_IN_MMC
#if defined(CONFIG_MISC_INIT_R)
	/* miscellaneous platform dependent initialisations */
	misc_init_r ();
#endif
	puts ("MMC:   ");
	mmc_initialize (gd->bd);
#endif

	/* initialize environment */
	env_relocate ();

#ifdef CONFIG_VFD
	/* must do this after the framebuffer is allocated */
	drv_vfd_init();
#endif /* CONFIG_VFD */

#ifdef CONFIG_SERIAL_MULTI
	serial_initialize();
#endif

	/* IP Address */
	gd->bd->bi_ip_addr = getenv_IPaddr ("ipaddr");

	stdio_init ();	/* get the devices list going. */

	jumptable_init ();

#if defined(CONFIG_API)
	/* Initialize API */
	api_init ();
#endif

	console_init_r ();	/* fully init console as a device */

#if defined(CONFIG_ARCH_MISC_INIT)
	/* miscellaneous arch dependent initialisations */
	arch_misc_init ();
#endif
	// psw0523 fix for mmc env
#ifndef CONFIG_ENV_IS_IN_MMC
#if defined(CONFIG_MISC_INIT_R)
	/* miscellaneous platform dependent initialisations */
	misc_init_r ();
#endif
#endif

	/* enable exceptions */
	enable_interrupts ();

	/* Perform network card initialisation if necessary */
#ifdef CONFIG_DRIVER_TI_EMAC
	/* XXX: this needs to be moved to board init */
extern void davinci_eth_set_mac_addr (const u_int8_t *addr);
	if (getenv ("ethaddr")) {
		uchar enetaddr[6];
		eth_getenv_enetaddr("ethaddr", enetaddr);
		davinci_eth_set_mac_addr(enetaddr);
	}
#endif

#if defined(CONFIG_DRIVER_SMC91111) || defined (CONFIG_DRIVER_LAN91C96)
	/* XXX: this needs to be moved to board init */
	if (getenv ("ethaddr")) {
		uchar enetaddr[6];
		eth_getenv_enetaddr("ethaddr", enetaddr);
		smc_set_mac_addr(enetaddr);
	}
#endif /* CONFIG_DRIVER_SMC91111 || CONFIG_DRIVER_LAN91C96 */

	/* Initialize from environment */
	if ((s = getenv ("loadaddr")) != NULL) {
		load_addr = simple_strtoul (s, NULL, 16);
	}
#if defined(CONFIG_CMD_NET)
	if ((s = getenv ("bootfile")) != NULL) {
		copy_filename (BootFile, s, sizeof (BootFile));
	}
#endif

#ifdef BOARD_LATE_INIT
	board_late_init ();
#endif

	// psw0523 fix for mmc env
#ifndef CONFIG_ENV_IS_IN_MMC
#ifdef CONFIG_GENERIC_MMC
//	puts ("MMC:   ");
//	mmc_initialize (gd->bd);
#endif
#endif

#ifdef CONFIG_BITBANGMII
	bb_miiphy_init();
#endif
#if defined(CONFIG_CMD_NET)
#if defined(CONFIG_NET_MULTI)
	puts ("Net:   ");
#endif
	eth_initialize(gd->bd);
#if defined(CONFIG_RESET_PHY_R)
	debug ("Reset Ethernet PHY\n");
	reset_phy();
#endif
#endif
	/* main_loop() can return to retry autoboot, if so just run it again. */
	for (;;) {
		main_loop ();
	}

	/* NOTREACHED - no way out of command loop except booting */
}
Ejemplo n.º 18
0
void start_UI(pDataStruct workingData){
	puts("Welcome to SPIFFS (Somewhat Poorly Implemented Fast File System)");
	workingData->date = get_time();
	main_loop(workingData);
	return;
}
Ejemplo n.º 19
0
void board_init_f(ulong bootflag)
{
	bd_t *bd;
	init_fnc_t **init_fnc_ptr;
	int j;

#ifndef CONFIG_SYS_NO_FLASH
	ulong flash_size;
#endif

	gd = (gd_t *) (CONFIG_SYS_GBL_DATA_OFFSET);

	/* Clear initial global data */
	memset((void *)gd, 0, sizeof(gd_t));

	gd->bd = (bd_t *) (gd + 1);	/* At end of global data */
	gd->baudrate = CONFIG_BAUDRATE;
	gd->cpu_clk = CONFIG_SYS_CLK_FREQ;

	bd = gd->bd;
	bd->bi_memstart = CONFIG_SYS_RAM_BASE;
	bd->bi_memsize = CONFIG_SYS_RAM_SIZE;
	bd->bi_flashstart = CONFIG_SYS_FLASH_BASE;
#if	defined(CONFIG_SYS_SRAM_BASE) && defined(CONFIG_SYS_SRAM_SIZE)
	bd->bi_sramstart = CONFIG_SYS_SRAM_BASE;
	bd->bi_sramsize = CONFIG_SYS_SRAM_SIZE;
#endif
	bd->bi_baudrate = CONFIG_BAUDRATE;
	bd->bi_bootflags = bootflag;	/* boot / reboot flag (for LynxOS)    */

	gd->flags |= GD_FLG_RELOC;	/* tell others: relocation done */
	gd->reloc_off = CONFIG_SYS_RELOC_MONITOR_BASE - CONFIG_SYS_MONITOR_BASE;

	for (init_fnc_ptr = init_sequence, j = 0; *init_fnc_ptr;
	     ++init_fnc_ptr, j++) {
#ifdef DEBUG_INIT_SEQUENCE
		if (j > 9)
			str_init_seq[9] = '0' + (j / 10);
		str_init_seq[10] = '0' + (j - (j / 10) * 10);
		serial_puts(str_init_seq);
#endif
		if ((*init_fnc_ptr + gd->reloc_off) () != 0) {
			hang();
		}
	}
#ifdef DEBUG_INIT_SEQUENCE
	serial_puts(str_init_seq_done);
#endif

	/*
	 * Now that we have DRAM mapped and working, we can
	 * relocate the code and continue running from DRAM.
	 *
	 * Reserve memory at end of RAM for (top down in that order):
	 *  - kernel log buffer
	 *  - protected RAM
	 *  - LCD framebuffer
	 *  - monitor code
	 *  - board info struct
	 */
#ifdef DEBUG_MEM_LAYOUT
	printf("CONFIG_SYS_MONITOR_BASE:       0x%lx\n", CONFIG_SYS_MONITOR_BASE);
	printf("CONFIG_ENV_ADDR:           0x%lx\n", CONFIG_ENV_ADDR);
	printf("CONFIG_SYS_RELOC_MONITOR_BASE: 0x%lx (%d)\n", CONFIG_SYS_RELOC_MONITOR_BASE,
	       CONFIG_SYS_MONITOR_LEN);
	printf("CONFIG_SYS_MALLOC_BASE:        0x%lx (%d)\n", CONFIG_SYS_MALLOC_BASE,
	       CONFIG_SYS_MALLOC_LEN);
	printf("CONFIG_SYS_INIT_SP_OFFSET:     0x%lx (%d)\n", CONFIG_SYS_INIT_SP_OFFSET,
	       CONFIG_SYS_STACK_SIZE);
	printf("CONFIG_SYS_PROM_OFFSET:        0x%lx (%d)\n", CONFIG_SYS_PROM_OFFSET,
	       CONFIG_SYS_PROM_SIZE);
	printf("CONFIG_SYS_GBL_DATA_OFFSET:    0x%lx (%d)\n", CONFIG_SYS_GBL_DATA_OFFSET,
	       GENERATED_GBL_DATA_SIZE);
#endif

#ifdef CONFIG_POST
	post_bootmode_init();
	post_run(NULL, POST_ROM | post_bootmode_get(0));
#endif

#if defined(CONFIG_NEEDS_MANUAL_RELOC)
	/*
	 * We have to relocate the command table manually
	 */
	fixup_cmdtable(&__u_boot_cmd_start,
		(ulong)(&__u_boot_cmd_end - &__u_boot_cmd_start));
#endif /* defined(CONFIG_NEEDS_MANUAL_RELOC) */

#if defined(CONFIG_CMD_AMBAPP) && defined(CONFIG_SYS_AMBAPP_PRINT_ON_STARTUP)
	puts("AMBA:\n");
	do_ambapp_print(NULL, 0, 0, NULL);
#endif

	/* initialize higher level parts of CPU like time base and timers */
	cpu_init_r();

	/* start timer */
	timer_interrupt_init();

	/*
	 * Enable Interrupts before any calls to udelay,
	 * the flash driver may use udelay resulting in
	 * a hang if not timer0 IRQ is enabled.
	 */
	interrupt_init();

	/* The Malloc area is immediately below the monitor copy in RAM */
	mem_malloc_init(CONFIG_SYS_MALLOC_BASE,
			CONFIG_SYS_MALLOC_END - CONFIG_SYS_MALLOC_BASE);
	malloc_bin_reloc();

#if !defined(CONFIG_SYS_NO_FLASH)
	puts("Flash: ");

	if ((flash_size = flash_init()) > 0) {
# ifdef CONFIG_SYS_FLASH_CHECKSUM
		print_size(flash_size, "");
		/*
		 * Compute and print flash CRC if flashchecksum is set to 'y'
		 *
		 * NOTE: Maybe we should add some WATCHDOG_RESET()? XXX
		 */
		s = getenv("flashchecksum");
		if (s && (*s == 'y')) {
			printf("  CRC: %08lX",
			       crc32(0, (const unsigned char *)CONFIG_SYS_FLASH_BASE,
				     flash_size)
			    );
		}
		putc('\n');
# else				/* !CONFIG_SYS_FLASH_CHECKSUM */
		print_size(flash_size, "\n");
# endif				/* CONFIG_SYS_FLASH_CHECKSUM */
	} else {
		puts(failed);
		hang();
	}

	bd->bi_flashstart = CONFIG_SYS_FLASH_BASE;	/* update start of FLASH memory    */
	bd->bi_flashsize = flash_size;	/* size of FLASH memory (final value) */
#if CONFIG_SYS_MONITOR_BASE == CONFIG_SYS_FLASH_BASE
	bd->bi_flashoffset = monitor_flash_len;	/* reserved area for startup monitor  */
#else
	bd->bi_flashoffset = 0;
#endif
#else				/* CONFIG_SYS_NO_FLASH */
	bd->bi_flashsize = 0;
	bd->bi_flashstart = 0;
	bd->bi_flashoffset = 0;
#endif				/* !CONFIG_SYS_NO_FLASH */

#ifdef CONFIG_SPI
# if !defined(CONFIG_ENV_IS_IN_EEPROM)
	spi_init_f();
# endif
	spi_init_r();
#endif

	/* relocate environment function pointers etc. */
	env_relocate();

#if defined(CONFIG_BOARD_LATE_INIT)
	board_late_init();
#endif

#ifdef CONFIG_ID_EEPROM
	mac_read_from_eeprom();
#endif

#if defined(CONFIG_PCI)
	/*
	 * Do pci configuration
	 */
	pci_init();
#endif

	/* Initialize stdio devices */
	stdio_init();

	/* Initialize the jump table for applications */
	jumptable_init();

	/* Initialize the console (after the relocation and devices init) */
	console_init_r();

#ifdef CONFIG_STATUS_LED
	status_led_set(STATUS_LED_BOOT, STATUS_LED_BLINKING);
#endif

	udelay(20);

	/* Initialize from environment */
	load_addr = getenv_ulong("loadaddr", 16, load_addr);

	WATCHDOG_RESET();

#if defined(CONFIG_CMD_DOC)
	WATCHDOG_RESET();
	puts("DOC:   ");
	doc_init();
#endif

#ifdef CONFIG_BITBANGMII
	bb_miiphy_init();
#endif
#if defined(CONFIG_CMD_NET)
	WATCHDOG_RESET();
	puts("Net:   ");
	eth_initialize(bd);
#endif

#if defined(CONFIG_CMD_NET) && defined(CONFIG_RESET_PHY_R)
	WATCHDOG_RESET();
	debug("Reset Ethernet PHY\n");
	reset_phy();
#endif

#ifdef CONFIG_POST
	post_run(NULL, POST_RAM | post_bootmode_get(0));
#endif

#if defined(CONFIG_CMD_IDE)
	WATCHDOG_RESET();
	puts("IDE:   ");
	ide_init();
#endif /* CONFIG_CMD_IDE */

#ifdef CONFIG_LAST_STAGE_INIT
	WATCHDOG_RESET();
	/*
	 * Some parts can be only initialized if all others (like
	 * Interrupts) are up and running (i.e. the PC-style ISA
	 * keyboard).
	 */
	last_stage_init();
#endif

#ifdef CONFIG_PS2KBD
	puts("PS/2:  ");
	kbd_init();
#endif
	prom_init();

	/* main_loop */
	for (;;) {
		WATCHDOG_RESET();
		main_loop();
	}

}
Ejemplo n.º 20
0
int main(int argc, char** argv) {
    int i, retval;
    bool one_pass = false;

    check_stop_daemons();

    int j=1;
    for (i=1; i<argc; i++) {
        if (is_arg(argv[i], "one_pass")) {
            one_pass = true;
        } else if (is_arg(argv[i], "variety")) {
            if (!argv[++i]) {
                log_messages.printf(MSG_CRITICAL,
                    "%s requires an argument\n\n", argv[--i]
                );
                usage(argv[0]);
                exit(1);
            }
            safe_strcpy(variety, argv[i]);
        } else if (!strcmp(argv[i], "-d")) {
            if (!argv[++i]) {
                log_messages.printf(MSG_CRITICAL,
                    "%s requires an argument\n\n", argv[--i]
                    
                );
                usage(argv[0]);
                exit(1);
            }
            int dl = atoi(argv[i]);
            log_messages.set_debug_level(dl);
            if (dl == 4) g_print_queries = true;
        } else if (!strcmp(argv[i], "-v") || !strcmp(argv[i], "--version")) {
            printf("%s\n", SVN_VERSION);
            exit(0);
        } else if (!strcmp(argv[i], "-h") || !strcmp(argv[i], "--help")) {
            usage(argv[0]);
            exit(0);
        } else {
            // unknown arg - pass to handler
            argv[j++] = argv[i];
        }
    }
    retval = config.parse_file();
    if (retval) {
        log_messages.printf(MSG_CRITICAL,
            "Can't parse config.xml: %s\n", boincerror(retval)
        );
        exit(1);
    }

    retval = boinc_db.open(
        config.db_name, config.db_host, config.db_user, config.db_passwd
    );
    if (retval) {
        log_messages.printf(MSG_CRITICAL,
            "boinc_db.open failed: %s\n", boincerror(retval)
        );
        exit(1);
    }

    argv[j] = 0;
    retval = handle_trickle_init(j, argv);
    if (retval) exit(1);

    log_messages.printf(MSG_NORMAL, "Starting trickle handler\n");

    install_stop_signal_handler();

    main_loop(one_pass);
}
Ejemplo n.º 21
0
void board_init_r(gd_t *id, ulong dest_addr)
{
	ulong malloc_start;
#if !defined(CONFIG_SYS_NO_FLASH)
	ulong flash_size;
#endif

	gd = id;

	gd->flags |= GD_FLG_RELOC;	/* tell others: relocation done */
	bootstage_mark_name(BOOTSTAGE_ID_START_UBOOT_R, "board_init_r");

	monitor_flash_len = _end_ofs;

	/* Enable caches */
	enable_caches();

	debug("monitor flash len: %08lX\n", monitor_flash_len);
	board_init();	/* Setup chipselects */
	/*
	 * TODO: printing of the clock inforamtion of the board is now
	 * implemented as part of bdinfo command. Currently only support for
	 * davinci SOC's is added. Remove this check once all the board
	 * implement this.
	 */
#ifdef CONFIG_CLOCKS
	set_cpu_clk_info(); /* Setup clock information */
#endif
#ifdef CONFIG_SERIAL_MULTI
	serial_initialize();
#endif

	debug("Now running in RAM - U-Boot at: %08lx\n", dest_addr);

#ifdef CONFIG_LOGBUFFER
	logbuff_init_ptrs();
#endif
#ifdef CONFIG_POST
	post_output_backlog();
#endif

	/* The Malloc area is immediately below the monitor copy in DRAM */
	malloc_start = dest_addr - TOTAL_MALLOC_LEN;
	mem_malloc_init (malloc_start, TOTAL_MALLOC_LEN);

#if !defined(CONFIG_SYS_NO_FLASH)
	puts("Flash: ");

	flash_size = flash_init();
	if (flash_size > 0) {
# ifdef CONFIG_SYS_FLASH_CHECKSUM
		char *s = getenv("flashchecksum");

		print_size(flash_size, "");
		/*
		 * Compute and print flash CRC if flashchecksum is set to 'y'
		 *
		 * NOTE: Maybe we should add some WATCHDOG_RESET()? XXX
		 */
		if (s && (*s == 'y')) {
			printf("  CRC: %08X", crc32(0,
				(const unsigned char *) CONFIG_SYS_FLASH_BASE,
				flash_size));
		}
		putc('\n');
# else	/* !CONFIG_SYS_FLASH_CHECKSUM */
		print_size(flash_size, "\n");
# endif /* CONFIG_SYS_FLASH_CHECKSUM */
	} else {
		puts(failed);
		hang();
	}
#endif

#if defined(CONFIG_CMD_NAND)
	puts("NAND:  ");
	nand_init();		/* go init the NAND */
#endif

#if defined(CONFIG_CMD_ONENAND)
	onenand_init();
#endif

#ifdef CONFIG_HAS_DATAFLASH
	AT91F_DataflashInit();
	dataflash_print_info();
#endif

	/* initialize environment */
	env_relocate();

#if defined(CONFIG_CMD_PCI) || defined(CONFIG_PCI)
	arm_pci_init();
#endif

	stdio_init();	/* get the devices list going. */

	jumptable_init();

#if defined(CONFIG_API)
	/* Initialize API */
	api_init();
#endif

	console_init_r();	/* fully init console as a device */

#if defined(CONFIG_ARCH_MISC_INIT)
	/* miscellaneous arch dependent initialisations */
	arch_misc_init();
#endif
#if defined(CONFIG_MISC_INIT_R)
	/* miscellaneous platform dependent initialisations */
	misc_init_r();
#endif

	 /* set up exceptions */
	interrupt_init();
	/* enable exceptions */
	enable_interrupts();

	/* Perform network card initialisation if necessary */
#if defined(CONFIG_DRIVER_SMC91111) || defined (CONFIG_DRIVER_LAN91C96)
	/* XXX: this needs to be moved to board init */
	if (getenv("ethaddr")) {
		uchar enetaddr[6];
		eth_getenv_enetaddr("ethaddr", enetaddr);
		smc_set_mac_addr(enetaddr);
	}
#endif /* CONFIG_DRIVER_SMC91111 || CONFIG_DRIVER_LAN91C96 */

	/* Initialize from environment */
	load_addr = getenv_ulong("loadaddr", 16, load_addr);

#ifdef CONFIG_BOARD_LATE_INIT
	board_late_init();
#endif

#ifdef CONFIG_BITBANGMII
	bb_miiphy_init();
#endif
#if defined(CONFIG_CMD_NET)
	puts("Net:   ");
	eth_initialize(gd->bd);
#if defined(CONFIG_RESET_PHY_R)
	debug("Reset Ethernet PHY\n");
	reset_phy();
#endif
#endif

#ifdef CONFIG_GENERIC_MMC
       puts("MMC:   ");
       mmc_initialize(gd->bd);
#endif

#ifdef CONFIG_POST
	post_run(NULL, POST_RAM | post_bootmode_get(0));
#endif

#if defined(CONFIG_PRAM) || defined(CONFIG_LOGBUFFER)
	/*
	 * Export available size of memory for Linux,
	 * taking into account the protected RAM at top of memory
	 */
	{
		ulong pram = 0;
		uchar memsz[32];

#ifdef CONFIG_PRAM
		pram = getenv_ulong("pram", 10, CONFIG_PRAM);
#endif
#ifdef CONFIG_LOGBUFFER
#ifndef CONFIG_ALT_LB_ADDR
		/* Also take the logbuffer into account (pram is in kB) */
		pram += (LOGBUFF_LEN + LOGBUFF_OVERHEAD) / 1024;
#endif
#endif
		sprintf((char *)memsz, "%ldk", (gd->ram_size / 1024) - pram);
		setenv("mem", (char *)memsz);
	}
#endif

	/* main_loop() can return to retry autoboot, if so just run it again. */
	for (;;) {
		main_loop();
	}

	/* NOTREACHED - no way out of command loop except booting */
}
Ejemplo n.º 22
0
void board_init_r(gd_t *id, ulong dest_addr)
{
#if defined(CONFIG_CMD_NET)
	char *s;
#endif
#ifndef CONFIG_SYS_NO_FLASH
	ulong size;
#endif
	static bd_t bd_data;
	static gd_t gd_data;
	init_fnc_t **init_fnc_ptr;

	show_boot_progress(0x21);

	/* Global data pointer is now writable */
	gd = &gd_data;
	memcpy(gd, id, sizeof(gd_t));

	/* compiler optimization barrier needed for GCC >= 3.4 */
	__asm__ __volatile__("" : : : "memory");

	gd->bd = &bd_data;
	memset(gd->bd, 0, sizeof(bd_t));
	show_boot_progress(0x22);

	gd->baudrate =  CONFIG_BAUDRATE;

	mem_malloc_init((((ulong)dest_addr - CONFIG_SYS_MALLOC_LEN)+3)&~3,
			CONFIG_SYS_MALLOC_LEN);

	for (init_fnc_ptr = init_sequence_r; *init_fnc_ptr; ++init_fnc_ptr) {
		if ((*init_fnc_ptr)() != 0)
			hang();
	}
	show_boot_progress(0x23);

#ifdef CONFIG_SERIAL_MULTI
	serial_initialize();
#endif

#ifndef CONFIG_SYS_NO_FLASH
	/* configure available FLASH banks */
	size = flash_init();
	display_flash_config(size);
	show_boot_progress(0x24);
#endif

	show_boot_progress(0x25);

	/* initialize environment */
	env_relocate();
	show_boot_progress(0x26);


#ifdef CONFIG_CMD_NET
	/* IP Address */
	bd_data.bi_ip_addr = getenv_IPaddr("ipaddr");
#endif

#if defined(CONFIG_PCI)
	/*
	 * Do pci configuration
	 */
	pci_init();
#endif

	show_boot_progress(0x27);


	stdio_init();

	jumptable_init();

	/* Initialize the console (after the relocation and devices init) */
	console_init_r();

#ifdef CONFIG_MISC_INIT_R
	/* miscellaneous platform dependent initialisations */
	misc_init_r();
#endif

#if defined(CONFIG_CMD_PCMCIA) && !defined(CONFIG_CMD_IDE)
	WATCHDOG_RESET();
	puts("PCMCIA:");
	pcmcia_init();
#endif

#if defined(CONFIG_CMD_KGDB)
	WATCHDOG_RESET();
	puts("KGDB:  ");
	kgdb_init();
#endif

	/* enable exceptions */
	enable_interrupts();
	show_boot_progress(0x28);

#ifdef CONFIG_STATUS_LED
	status_led_set(STATUS_LED_BOOT, STATUS_LED_BLINKING);
#endif

	udelay(20);

	/* Initialize from environment */
	load_addr = getenv_ulong("loadaddr", 16, load_addr);
#if defined(CONFIG_CMD_NET)
	s = getenv("bootfile");

	if (s != NULL)
		copy_filename(BootFile, s, sizeof(BootFile));
#endif

	WATCHDOG_RESET();

#if defined(CONFIG_CMD_IDE)
	WATCHDOG_RESET();
	puts("IDE:   ");
	ide_init();
#endif

#if defined(CONFIG_CMD_SCSI)
	WATCHDOG_RESET();
	puts("SCSI:  ");
	scsi_init();
#endif

#if defined(CONFIG_CMD_DOC)
	WATCHDOG_RESET();
	puts("DOC:   ");
	doc_init();
#endif

#ifdef CONFIG_BITBANGMII
	bb_miiphy_init();
#endif
#if defined(CONFIG_CMD_NET)
	WATCHDOG_RESET();
	puts("Net:   ");
	eth_initialize(gd->bd);
#endif

#if (defined(CONFIG_CMD_NET)) && (0)
	WATCHDOG_RESET();
# ifdef DEBUG
	puts("Reset Ethernet PHY\n");
# endif
	reset_phy();
#endif

#ifdef CONFIG_LAST_STAGE_INIT
	WATCHDOG_RESET();
	/*
	 * Some parts can be only initialized if all others (like
	 * Interrupts) are up and running (i.e. the PC-style ISA
	 * keyboard).
	 */
	last_stage_init();
#endif


#ifdef CONFIG_POST
	post_run(NULL, POST_RAM | post_bootmode_get(0));
#endif

	show_boot_progress(0x29);

	/* main_loop() can return to retry autoboot, if so just run it again. */
	for (;;)
		main_loop();

	/* NOTREACHED - no way out of command loop except booting */
}
Ejemplo n.º 23
0
static void
main_loop(void)
{
  int r;
  clock_time_t time_to_etimer;
  rtimer_clock_t ticks_to_rtimer;

  while(1) {
    do {
      /* Reset watchdog. */
      watchdog_periodic();
      r = process_run();
    } while(r > 0);
    /*
     * Idle processing.
     */
    watchdog_stop();

#if DCOSYNCH_CONF_ENABLED
    /* Calibrate the DCO every DCOSYNCH_PERIOD
     * if we have more than 500uSec until next rtimer
     * PS: Calibration disables interrupts and blocks for 200uSec.
     *  */
    if(clock_seconds() - last_dco_calibration_time > DCOSYNCH_PERIOD) {
      if(rtimer_arch_time_to_rtimer() > RTIMER_SECOND / 2000) {
        /* PRINTF("ContikiMain: Calibrating the DCO\n"); */
        eAHI_AttemptCalibration();
        /* Patch to allow CpuDoze after calibration */
        vREG_PhyWrite(REG_PHY_IS, REG_PHY_INT_VCO_CAL_MASK);
        last_dco_calibration_time = clock_seconds();
      }
    }
#endif /* DCOSYNCH_CONF_ENABLED */

    /* flush standard output before sleeping */
    uart_driver_flush(E_AHI_UART_0, TRUE, FALSE);

    /* calculate the time to the next etimer and rtimer */
    time_to_etimer = clock_arch_time_to_etimer();
    ticks_to_rtimer = rtimer_arch_time_to_rtimer();

#if JN516X_SLEEP_ENABLED
    /* we can sleep only up to the next rtimer/etimer */
    rtimer_clock_t max_sleep_time = ticks_to_rtimer;
    if(max_sleep_time >= JN516X_MIN_SLEEP_TIME) {
      /* also take into account etimers */
      uint64_t ticks_to_etimer = ((uint64_t)time_to_etimer * RTIMER_SECOND) / CLOCK_SECOND;
      max_sleep_time = MIN(ticks_to_etimer, ticks_to_rtimer);
    }

    if(max_sleep_time >= JN516X_MIN_SLEEP_TIME) {
      max_sleep_time -= JN516X_SLEEP_GUARD_TIME;
      /* bound the sleep time to 1 second */
      max_sleep_time = MIN(max_sleep_time, JN516X_MAX_SLEEP_TIME);

#if !RTIMER_USE_32KHZ
      /* convert to 32.768 kHz oscillator ticks */
      max_sleep_time = (uint64_t)max_sleep_time * JN516X_XOSC_SECOND / RTIMER_SECOND;
#endif
      vAHI_WakeTimerEnable(WAKEUP_TIMER, TRUE);
      /* sync with the tick timer */
      WAIT_FOR_EDGE(sleep_start);
      sleep_start_ticks = u32AHI_TickTimerRead();

      vAHI_WakeTimerStartLarge(WAKEUP_TIMER, max_sleep_time);
      ENERGEST_SWITCH(ENERGEST_TYPE_CPU, ENERGEST_TYPE_EXTRA_LPM);
      vAHI_Sleep(E_AHI_SLEEP_OSCON_RAMON);
    } else {
#else
    {
#endif /* JN516X_SLEEP_ENABLED */
      clock_arch_schedule_interrupt(time_to_etimer, ticks_to_rtimer);
      ENERGEST_SWITCH(ENERGEST_TYPE_CPU, ENERGEST_TYPE_LPM);
      vAHI_CpuDoze();
      watchdog_start();
      ENERGEST_SWITCH(ENERGEST_TYPE_LPM, ENERGEST_TYPE_CPU);
    }
  }
}
/*---------------------------------------------------------------------------*/
void
AppColdStart(void)
{
  /* After reset or sleep with memory off */
  main();
}
/*---------------------------------------------------------------------------*/
void
AppWarmStart(void)
{
  /* Wakeup after sleep with memory on.
   * Need to initialize devices but not the application state.
   * Note: the actual time this function is called is
   * ~8 ticks (32kHz timer) later than the scheduled sleep end time.
   */
  uint32_t sleep_ticks;
  uint64_t sleep_end;
  rtimer_clock_t sleep_ticks_rtimer;

  clock_arch_calibrate();
  leds_init();
  uart0_init(UART_BAUD_RATE); /* Must come before first PRINTF */
  NETSTACK_RADIO.init();
  watchdog_init();
  watchdog_stop();

  WAIT_FOR_EDGE(sleep_end);
  sleep_ticks = (uint32_t)(sleep_start - sleep_end) + 1;

#if RTIMER_USE_32KHZ
  sleep_ticks_rtimer = sleep_ticks;
#else
  {
    static uint32_t remainder;
    uint64_t t = (uint64_t)sleep_ticks * RTIMER_SECOND + remainder;
    sleep_ticks_rtimer = (uint32_t)(t / JN516X_XOSC_SECOND);
    remainder = t - sleep_ticks_rtimer * JN516X_XOSC_SECOND;
  }
#endif

  /* reinitialize rtimers */
  rtimer_arch_reinit(sleep_start_ticks, sleep_ticks_rtimer);

  ENERGEST_SWITCH(ENERGEST_TYPE_EXTRA_LPM, ENERGEST_TYPE_CPU);

  watchdog_start();

  /* reinitialize clock */
  clock_arch_init(1);
  /* schedule etimer interrupt */
  clock_arch_schedule_interrupt(clock_arch_time_to_etimer(), rtimer_arch_time_to_rtimer());

#if DCOSYNCH_CONF_ENABLED
  /* The radio is recalibrated on wakeup */
  last_dco_calibration_time = clock_seconds();
#endif

  main_loop();
}
Ejemplo n.º 24
0
//extern new_heap_t* n_heap;
asmlinkage void _start(struct multiboot_info *boot_info)
{
    boot_informations = boot_info;
	main_loop(boot_info);
	while(1);
}
Ejemplo n.º 25
0
/*{{{ main() */
int
main (int argc, char *argv[])
{
  int i;
  char *val, **cmd_argv = NULL;
  /* "WINDOWID=\0" = 10 chars, UINT_MAX = 10 chars */
  static char windowid_string[20], *display_string;

  for (i = 0; i < argc; i++)
    {
      if (!strcmp (argv[i], "-e"))
	{
	  argc = i;
	  argv[argc] = NULL;
	  if (argv[argc + 1] != NULL)
	    {
	      cmd_argv = (argv + argc + 1);
	      if (cmd_argv[0] != NULL)
		rs_iconName = rs_title = my_basename (cmd_argv[0]);
	    }
	  break;
	}
    }

  rs_name = my_basename (argv[0]);

  /*
   * Open display, get options/resources and create the window
   */
  if ((display_name = getenv ("DISPLAY")) == NULL)
    display_name = ":0";

  get_options (argc, argv);

  Xdisplay = XOpenDisplay (display_name);
  if (!Xdisplay)
    {
      print_error ("can't open display %s", display_name);
      exit (EXIT_FAILURE);
    }
  extract_resources (Xdisplay, rs_name);

  /*
   * set any defaults not already set
   */
  if (!rs_title)
    rs_title = rs_name;
  if (!rs_iconName)
    rs_iconName = rs_name;
  if (!rs_saveLines || (TermWin.saveLines = atoi (rs_saveLines)) < 0)
    TermWin.saveLines = SAVELINES;

  /* no point having a scrollbar without having any scrollback! */
  if (!TermWin.saveLines)
    Options &= ~Opt_scrollBar;

#ifdef PRINTPIPE
  if (!rs_print_pipe)
    rs_print_pipe = PRINTPIPE;
#endif
  if (!rs_cutchars)
    rs_cutchars = CUTCHARS;

#ifndef NO_BOLDFONT
  if (rs_font[0] == NULL && rs_boldFont != NULL)
    {
      rs_font[0] = rs_boldFont;
      rs_boldFont = NULL;
    }
#endif
  for (i = 0; i < NFONTS; i++)
    {
      if (!rs_font[i])
	rs_font[i] = def_fontName[i];
#ifdef KANJI
      if (!rs_kfont[i])
	rs_kfont[i] = def_kfontName[i];
#endif
    }

#ifdef XTERM_REVERSE_VIDEO
  /* this is how xterm implements reverseVideo */
  if (Options & Opt_reverseVideo)
    {
      if (!rs_color[fgColor])
	rs_color[fgColor] = def_colorName[bgColor];
      if (!rs_color[bgColor])
	rs_color[bgColor] = def_colorName[fgColor];
    }
#endif

  for (i = 0; i < NRS_COLORS; i++)
    if (!rs_color[i])
      rs_color[i] = def_colorName[i];

#ifndef XTERM_REVERSE_VIDEO
  /* this is how we implement reverseVideo */
  if (Options & Opt_reverseVideo)
    {
      const char *name;
      /* swap foreground/background colors */

      name = rs_color[fgColor];
      rs_color[fgColor] = rs_color[bgColor];
      rs_color[bgColor] = name;

      name = def_colorName[fgColor];
      def_colorName[fgColor] = def_colorName[bgColor];
      def_colorName[bgColor] = name;
    }
#endif

  /* convenient aliases for setting fg/bg to colors */
  color_aliases (fgColor);
  color_aliases (bgColor);
#ifndef NO_CURSORCOLOR
  color_aliases (cursorColor);
  color_aliases (cursorColor2);
#endif /* NO_CURSORCOLOR */
#ifndef NO_BOLDUNDERLINE
  color_aliases (colorBD);
  color_aliases (colorUL);
#endif /* NO_BOLDUNDERLINE */

  Create_Windows (argc, argv);
  scr_reset ();			/* initialize screen */
  Gr_reset ();			/* reset graphics */

  /* add scrollBar, do it directly to avoid resize() */
  scrollbar_mapping (Options & Opt_scrollBar);

#ifdef DEBUG_X
  XSynchronize (Xdisplay, True);
  XSetErrorHandler ((XErrorHandler) abort);
#else
  XSetErrorHandler ((XErrorHandler) xerror_handler);
#endif

#ifdef DISPLAY_IS_IP
  /* Fixup display_name for export over pty to any interested terminal
   * clients via "ESC[7n" (e.g. shells).  Note we use the pure IP number
   * (for the first non-loopback interface) that we get from
   * network_display().  This is more "name-resolution-portable", if you
   * will, and probably allows for faster x-client startup if your name
   * server is beyond a slow link or overloaded at client startup.  Of
   * course that only helps the shell's child processes, not us.
   *
   * Giving out the display_name also affords a potential security hole
   */
  val = display_name = network_display (display_name);
  if (val == NULL)
#endif /* DISPLAY_IS_IP */
    val = XDisplayString (Xdisplay);
  if (display_name == NULL)
    display_name = val;		/* use broken `:0' value */

  i = strlen (val);
  display_string = MALLOC ((i + 9) * sizeof (char), "display_string");

  sprintf (display_string, "DISPLAY=%s", val);
  sprintf (windowid_string, "WINDOWID=%u", (unsigned int) TermWin.parent);

  /* add entries to the environment:
   * @ DISPLAY:   in case we started with -display
   * @ WINDOWID:  X window id number of the window
   * @ COLORTERM: terminal sub-name and also indicates its color
   * @ TERM:      terminal name
   */
  putenv (display_string);
  putenv (windowid_string);
  if (Xdepth <= 2)
    {
      putenv ("COLORTERM=" COLORTERMENV "-mono");
      putenv ("TERM=" TERMENV);
    }
  else
    {
#ifdef XPM_BACKGROUND
      putenv ("COLORTERM=" COLORTERMENV "-xpm");
#else
      putenv ("COLORTERM=" COLORTERMENV);
#endif
#ifdef DEFINE_XTERM_COLOR
      putenv ("TERM=" TERMENV "-color");
#else
      putenv ("TERM=" TERMENV);
#endif
    }

  init_command (cmd_argv);
  main_loop ();			/* main processing loop */
  return EXIT_SUCCESS;
}
Ejemplo n.º 26
0
/**
 * Main routine, start of the program execution.
 * \param argc the number of arguments
 * \param argv pointer to the arguments array
 * \return don't return on sucess, -1 on error
 * \see main_loop
 */
int main(int argc, char** argv)
{
	/* configure by default logging to syslog */
	int cfg_log_stderr = 1;
	FILE* cfg_stream;
	int c,r;
	char *tmp;
	int tmp_len;
	int port;
	int proto;
	char *options;
	int ret;
	unsigned int seed;
	int rfd;

	/*init*/
	ret=-1;
	my_argc=argc; my_argv=argv;

	/* process pkg mem size from command line */
	opterr=0;
	options="f:cCm:M:b:l:n:N:rRvdDFETSVhw:t:u:g:P:G:W:o:";

	while((c=getopt(argc,argv,options))!=-1){
		switch(c){
			case 'M':
					pkg_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024;
					if (tmp &&(*tmp)){
						LM_ERR("bad pkgmem size number: -m %s\n", optarg);
						goto error00;
					};

					break;
		}
	}
	/*init pkg mallocs (before parsing cfg but after parsing cmd line !)*/
	if (init_pkg_mallocs()==-1)
		goto error00;

	init_route_lists();

	/* process command line (get port no, cfg. file path etc) */
	/* first reset getopt */
	optind = 1;
	while((c=getopt(argc,argv,options))!=-1){
		switch(c){
			case 'f':
					cfg_file=optarg;
					break;
			case 'C':
					config_check |= 2;
			case 'c':
					if (config_check==3)
						break;
					config_check |= 1;
					cfg_log_stderr=1; /* force stderr logging */
					break;
			case 'm':
					shm_mem_size=strtol(optarg, &tmp, 10) * 1024 * 1024;
					if (tmp &&(*tmp)){
						LM_ERR("bad shmem size number: -m %s\n", optarg);
						goto error00;
					};
					break;
			case 'M':
					/* ignoring it, parsed previously */
					break;
			case 'b':
					maxbuffer=strtol(optarg, &tmp, 10);
					if (tmp &&(*tmp)){
						LM_ERR("bad max buffer size number: -b %s\n", optarg);
						goto error00;
					}
					break;
			case 'l':
					if (parse_phostport(optarg, strlen(optarg), &tmp, &tmp_len,
											&port, &proto)<0){
						LM_ERR("bad -l address specifier: %s\n", optarg);
						goto error00;
					}
					tmp[tmp_len]=0; /* null terminate the host */
					/* add a new addr. to our address list */
					if (add_cmd_listener(tmp, port, proto)!=0){
						LM_ERR("failed to add new listen address\n");
						goto error00;
					}
					break;
			case 'n':
					children_no=strtol(optarg, &tmp, 10);
					if ((tmp==0) ||(*tmp)){
						LM_ERR("bad process number: -n %s\n", optarg);
						goto error00;
					}
					break;
			case 'v':
					check_via=1;
					break;
			case 'r':
					received_dns|=DO_DNS;
					break;
			case 'R':
					received_dns|=DO_REV_DNS;
				    break;
			case 'd':
					*log_level = debug_mode ? L_DBG : (*log_level)+1;
					break;
			case 'D':
					debug_mode=1;
					*log_level = L_DBG;
					break;
			case 'F':
					no_daemon_mode=1;
					break;
			case 'E':
					cfg_log_stderr=1;
					break;
			case 'N':
					tcp_children_no=strtol(optarg, &tmp, 10);
					if ((tmp==0) ||(*tmp)){
						LM_ERR("bad process number: -N %s\n", optarg);
						goto error00;
					}
					break;
			case 'W':
					io_poll_method=get_poll_type(optarg);
					if (io_poll_method==POLL_NONE){
						LM_ERR("bad poll method name: -W %s\ntry "
							"one of %s.\n", optarg, poll_support);
						goto error00;
					}
					break;
			case 'V':
					printf("version: %s\n", version);
					printf("flags: %s\n", flags );
					print_ct_constants();
					printf("%s compiled on %s with %s\n", __FILE__,
							compiled, COMPILER );
					exit(0);
					break;
			case 'h':
					printf("version: %s\n", version);
					printf("%s",help_msg);
					exit(0);
					break;
			case 'w':
					working_dir=optarg;
					break;
			case 't':
					chroot_dir=optarg;
					break;
			case 'u':
					user=optarg;
					break;
			case 'g':
					group=optarg;
					break;
			case 'P':
					pid_file=optarg;
					break;
			case 'G':
					pgid_file=optarg;
					break;
			case 'o':
					if (add_arg_var(optarg) < 0)
						LM_ERR("cannot add option %s\n", optarg);
					break;
			case '?':
					if (isprint(optopt))
						LM_ERR("Unknown option `-%c`.\n", optopt);
					else
						LM_ERR("Unknown option character `\\x%x`.\n", optopt);
					goto error00;
			case ':':
					LM_ERR("Option `-%c` requires an argument.\n", optopt);
					goto error00;
			default:
					abort();
		}
	}

	log_stderr = cfg_log_stderr;

	/* fill missing arguments with the default values*/
	if (cfg_file==0) cfg_file=CFG_FILE;

	/* load config file or die */
	cfg_stream=fopen (cfg_file, "r");
	if (cfg_stream==0){
		LM_ERR("loading config file(%s): %s\n", cfg_file,
				strerror(errno));
		goto error00;
	}

	/* seed the prng, try to use /dev/urandom if possible */
	/* no debugging information is logged, because the standard
	   log level prior the config file parsing is L_NOTICE */
	seed=0;
	if ((rfd=open("/dev/urandom", O_RDONLY))!=-1){
try_again:
		if (read(rfd, (void*)&seed, sizeof(seed))==-1){
			if (errno==EINTR) goto try_again; /* interrupted by signal */
			LM_WARN("could not read from /dev/urandom (%d)\n", errno);
		}
		LM_DBG("initialize the pseudo random generator from "
			"/dev/urandom\n");
		LM_DBG("read %u from /dev/urandom\n", seed);
			close(rfd);
	}else{
		LM_WARN("could not open /dev/urandom (%d)\n", errno);
		LM_WARN("using a unsafe seed for the pseudo random number generator");
	}
	seed+=getpid()+time(0);
	LM_DBG("seeding PRNG with %u\n", seed);
	srand(seed);
	LM_DBG("test random number %u\n", rand());

	/*register builtin  modules*/
	register_builtin_modules();

	/* init avps */
	if (init_global_avps() != 0) {
		LM_ERR("error while initializing avps\n");
		goto error;
	}

	/* used for parser debugging */
#ifdef DEBUG_PARSER
	yydebug = 1;
#endif

	/*
	 * initializes transport interfaces - we initialize them here because we
	 * can have listening interfaces declared in the command line
	 */
	if (trans_init() < 0) {
		LM_ERR("cannot initialize transport interface\n");
		goto error;
	}

		/* get uid/gid */
	if (user){
		if (user2uid(&uid, &gid, user)<0){
			LM_ERR("bad user name/uid number: -u %s\n", user);
			goto error00;
		}
	}
	if (group){
		if (group2gid(&gid, group)<0){
			LM_ERR("bad group name/gid number: -u %s\n", group);
			goto error00;
		}
	}

		/*init shm mallocs
	 *  this must be here
	 *     -to allow setting shm mem size from the command line
	 *     -it must be also before init_timer and init_tcp
	 *     -it must be after we know uid (so that in the SYSV sems case,
	 *        the sems will have the correct euid)
	 * --andrei */
	if (init_shm_mallocs()==-1)
		goto error;

	if (init_stats_collector() < 0) {
		LM_ERR("failed to initialize statistics\n");
		goto error;
	}

	/* parse the config file, prior to this only default values
	   e.g. for debugging settings will be used */
	yyin=cfg_stream;
	if ((yyparse()!=0)||(cfg_errors)){
		LM_ERR("bad config file (%d errors)\n", cfg_errors);
		goto error00;
	}

	if (config_check>1 && check_rls()!=0) {
		LM_ERR("bad function call in config file\n");
		return ret;
	}

	if (solve_module_dependencies(modules) != 0) {
		LM_ERR("failed to solve module dependencies\n");
		return -1;
	}

	/* init the resolver, before fixing the config */
	resolv_init();

	fix_poll_method( &io_poll_method );

	/* fix temporary listeners added in the cmd line */
	if (fix_cmd_listeners() < 0) {
		LM_ERR("cannot add temproray listeners\n");
		return ret;
	}

	/* load transport protocols */
	if (trans_load() < 0) {
		LM_ERR("cannot load transport protocols\n");
		goto error;
	}

	/* fix parameters */
	if (working_dir==0) working_dir="/";

	if (fix_all_socket_lists()!=0){
		LM_ERR("failed to initialize list addresses\n");
		goto error00;
	}
	/* print all the listen addresses */
	printf("Listening on \n");
	print_all_socket_lists();
	printf("Aliases: \n");
	/*print_aliases();*/
	print_aliases();
	printf("\n");

	if (config_check){
		LM_NOTICE("config file ok, exiting...\n");
		return 0;
	}

	time(&startup_time);

	/* Init statistics */
	init_shm_statistics();

	/*init UDP networking layer*/
	if (udp_init()<0){
		LM_CRIT("could not initialize tcp\n");
		goto error;
	}
	/*init TCP networking layer*/
	if (tcp_init()<0){
		LM_CRIT("could not initialize tcp\n");
		goto error;
	}

	if (create_status_pipe() < 0) {
		LM_ERR("failed to create status pipe\n");
		goto error;
	}

	if (debug_mode) {

		LM_NOTICE("DEBUG MODE activated\n");
		if (no_daemon_mode==0) {
			LM_NOTICE("disabling daemon mode (found enabled)\n");
			no_daemon_mode = 1;
		}
		if (log_stderr==0) {
			LM_NOTICE("enabling logging to standard error (found disabled)\n");
			log_stderr = 1;
		}
		if (*log_level<L_DBG) {
			LM_NOTICE("setting logging to debug level (found on %d)\n",
				*log_level);
			*log_level = L_DBG;
		}
		if (disable_core_dump) {
			LM_NOTICE("enabling core dumping (found off)\n");
			disable_core_dump = 0;
		}
		if (udp_count_processes()!=0) {
			if (children_no!=2) {
				LM_NOTICE("setting UDP children to 2 (found %d)\n",
					children_no);
				children_no = 2;
			}
		}
		if (tcp_count_processes()!=0) {
			if (tcp_children_no!=2) {
				LM_NOTICE("setting TCP children to 2 (found %d)\n",
					tcp_children_no);
				tcp_children_no = 2;
			}
		}

	} else { /* debug_mode */

		/* init_daemon */
		if ( daemonize((log_name==0)?argv[0]:log_name, &own_pgid) <0 )
			goto error;

	}

	/* install signal handlers */
	if (install_sigs() != 0){
		LM_ERR("could not install the signal handlers\n");
		goto error;
	}

	if (disable_core_dump) set_core_dump(0, 0);
	else set_core_dump(1, shm_mem_size+pkg_mem_size+4*1024*1024);
	if (open_files_limit>0) {
		if(set_open_fds_limit()<0){
			LM_ERR("ERROR: error could not increase file limits\n");
			goto error;
		}
	}

	/* print OpenSIPS version to log for history tracking */
	LM_NOTICE("version: %s\n", version);

	/* print some data about the configuration */
	LM_INFO("using %ld Mb shared memory\n", ((shm_mem_size/1024)/1024));
	LM_INFO("using %ld Mb private memory per process\n",
		((pkg_mem_size/1024)/1024));

	/* init async reactor */
	if (init_reactor_size()<0) {
		LM_CRIT("failed to init internal reactor, exiting...\n");
		goto error;
	}

	/* init timer */
	if (init_timer()<0){
		LM_CRIT("could not initialize timer, exiting...\n");
		goto error;
	}

	/* init serial forking engine */
	if (init_serialization()!=0) {
		LM_ERR("failed to initialize serialization\n");
		goto error;
	}
	/* Init MI */
	if (init_mi_core()<0) {
		LM_ERR("failed to initialize MI core\n");
		goto error;
	}

	/* Register core events */
	if (evi_register_core() != 0) {
		LM_ERR("failed register core events\n");
		goto error;
	}

	/* init black list engine */
	if (init_black_lists()!=0) {
		LM_CRIT("failed to init blacklists\n");
		goto error;
	}
	/* init resolver's blacklist */
	if (resolv_blacklist_init()!=0) {
		LM_CRIT("failed to create DNS blacklist\n");
		goto error;
	}

	/* init modules */
	if (init_modules() != 0) {
		LM_ERR("error while initializing modules\n");
		goto error;
	}

	/* register route timers */
	if(register_route_timers() < 0) {
		LM_ERR("Failed to register timer\n");
		goto error;
	}

	/* check pv context list */
	if(pv_contextlist_check() != 0) {
		LM_ERR("used pv context that was not defined\n");
		goto error;
	}

	/* init query list now in shm
	 * so all processes that will be forked from now on
	 * will have access to it
	 *
	 * if it fails, give it a try and carry on */
	if (init_ql_support() != 0) {
		LM_ERR("failed to initialise buffering query list\n");
		query_buffer_size = 0;
		*query_list = NULL;
	}

	/* init multi processes support */
	if (init_multi_proc_support()!=0) {
		LM_ERR("failed to init multi-proc support\n");
		goto error;
	}

	#ifdef PKG_MALLOC
	/* init stats support for pkg mem */
	if (init_pkg_stats(counted_processes)!=0) {
		LM_ERR("failed to init stats for pkg\n");
		goto error;
	}
	#endif

	/* init avps */
	if (init_extra_avps() != 0) {
		LM_ERR("error while initializing avps\n");
		goto error;
	}

	/* fix routing lists */
	if ( (r=fix_rls())!=0){
		LM_ERR("failed to fix configuration with err code %d\n", r);
		goto error;
	}

	if (init_log_level() != 0) {
		LM_ERR("failed to init logging levels\n");
		goto error;
	}

	if (trans_init_all_listeners()<0) {
		LM_ERR("failed to init all SIP listeners, aborting\n");
		goto error;
	}

	/* all processes should have access to all the sockets (for sending)
	 * so we open all first*/
	if (do_suid(uid, gid)==-1)
		goto error;

	ret = main_loop();

error:
	/*kill everything*/
	kill_all_children(SIGTERM);
	/*clean-up*/
	cleanup(0);
error00:
	LM_NOTICE("Exiting....\n");
	return ret;
}
Ejemplo n.º 27
0
int main(int argc, char** argv) {
    int i, retval;

    const char *usage = 
      "\nUsage: %s --app <app-name> [OPTIONS]\n"
      "Start validator for application <app-name>\n\n"
      "Optional arguments:\n"
      "  --one_pass_N_WU N       Validate at most N WUs, then exit\n"
      "  --one_pass              Make one pass through WU table, then exit\n"
      "  --mod n i               Process only WUs with (id mod n) == i\n"
      "  --max_claimed_credit X  If a result claims more credit than this, mark it as invalid\n"
      "  --max_granted_credit X  Grant no more than this amount of credit to a result\n"
      "  --grant_claimed_credit  Grant the claimed credit, regardless of what other results for this workunit claimed\n"
      "  --update_credited_job   Add record to credited_job table after granting credit\n"
      "  --credit_from_wu        Credit is specified in WU XML\n"
      "  --sleep_interval n      Set sleep-interval to n\n"
      "  -d n, --debug_level n   Set log verbosity level, 1-4\n"
      "  -h | --help             Show this\n"
      "  -v | --version          Show version information\n";

    if ((argc > 1) && (!strcmp(argv[1], "-h") || !strcmp(argv[1], "--help"))) {
        printf (usage, argv[0] );
        exit(0);
    }

    check_stop_daemons();

    for (i=1; i<argc; i++) {
        if (is_arg(argv[i], "one_pass_N_WU")) {
            one_pass_N_WU = atoi(argv[++i]);
            one_pass = true;
        } else if (is_arg(argv[i], "sleep_interval")) {
            sleep_interval = atoi(argv[++i]);
        } else if (is_arg(argv[i], "one_pass")) {
            one_pass = true;
        } else if (is_arg(argv[i], "app")) {
            strcpy(app_name, argv[++i]);
        } else if (is_arg(argv[i], "d") || is_arg(argv[i], "debug_level")) {
            debug_level = atoi(argv[++i]);
            log_messages.set_debug_level(debug_level);
            if (debug_level == 4) g_print_queries = true;
        } else if (is_arg(argv[i], "mod")) {
            wu_id_modulus = atoi(argv[++i]);
            wu_id_remainder = atoi(argv[++i]);
        } else if (is_arg(argv[i], "max_granted_credit")) {
            max_granted_credit = atof(argv[++i]);
        } else if (is_arg(argv[i], "max_claimed_credit")) {
            max_claimed_credit = atof(argv[++i]);
        } else if (is_arg(argv[i], "grant_claimed_credit")) {
            grant_claimed_credit = true;
        } else if (is_arg(argv[i], "update_credited_job")) {
            update_credited_job = true;
        } else if (is_arg(argv[i], "credit_from_wu")) {
            credit_from_wu = true;
        } else if (is_arg(argv[i], "v") || is_arg(argv[i], "version")) {
            printf("%s\n", SVN_VERSION);
            exit(0);
        } else {
            fprintf(stderr,
                "Invalid option '%s'\nTry `%s --help` for more information\n",
                argv[i], argv[0]
            );
            log_messages.printf(MSG_CRITICAL, "unrecognized arg: %s\n", argv[i]);
            exit(1);
        }
    }

    if (app_name[0] == 0) {
        log_messages.printf(MSG_CRITICAL,
            "must use '--app' to specify an application\n"
        );
        printf (usage, argv[0] );
        exit(1);      
    }

    retval = config.parse_file();
    if (retval) {
        log_messages.printf(MSG_CRITICAL,
            "Can't parse config.xml: %s\n", boincerror(retval)
        );
        exit(1);
    }

    log_messages.printf(MSG_NORMAL,
        "Starting validator, debug level %d\n", log_messages.debug_level
    );
    if (wu_id_modulus) {
        log_messages.printf(MSG_NORMAL,
            "Modulus %d, remainder %d\n", wu_id_modulus, wu_id_remainder
        );
    }

    install_stop_signal_handler();

    main_loop();
}
Ejemplo n.º 28
0
/*
 ************************************************************************
 *
 * This is the next part if the initialization sequence: we are now
 * running from RAM and have a "normal" C environment, i. e. global
 * data can be written, BSS has been cleared, the stack size in not
 * that critical any more, etc.
 *
 ************************************************************************
 */
void board_init_r(gd_t *id, ulong dest_addr)
{
	char *s;
	//bd_t *bd;
	ulong malloc_start;
#ifdef CONFIG_NONCACHE_MEMORY
	uint  malloc_noncache_start;
#endif
#if !defined(CONFIG_SYS_NO_FLASH)
	ulong flash_size;
#endif
	int workmode;
	int ret;
#ifdef CONFIG_SUNXI_HDCP_IN_SECURESTORAGE
	int hdcpkey_enable=0;
#endif
	gd = id;
	//bd = gd->bd;

	gd->flags |= GD_FLG_RELOC;	/* tell others: relocation done */

	monitor_flash_len = _end_ofs;

	malloc_start = dest_addr - TOTAL_MALLOC_LEN - sizeof(struct spare_boot_head_t);
#ifdef CONFIG_NONCACHE_MEMORY_SIZE
	malloc_start &= (~(0x00100000 -1));
	malloc_noncache_start = malloc_start - CONFIG_NONCACHE_MEMORY_SIZE;
	gd->malloc_noncache_start = malloc_noncache_start;
#endif
	/* Enable caches */
	enable_caches();
	debug("monitor flash len: %08lX\n", monitor_flash_len);
	board_init();	/* Setup chipselects */
#ifdef CONFIG_SERIAL_MULTI
	serial_initialize();
#endif
	debug("Now running in RAM - U-Boot at: %08lx\n", dest_addr);

#ifdef CONFIG_LOGBUFFER
	logbuff_init_ptrs();
#endif
#ifdef CONFIG_POST
	post_output_backlog();
#endif

	/* The Malloc area is immediately below the monitor copy in DRAM */
	mem_malloc_init (malloc_start, TOTAL_MALLOC_LEN);
#ifdef CONFIG_SMALL_MEMSIZE
        save_config();
#endif
#ifdef CONFIG_NONCACHE_MEMORY
	mem_noncache_malloc_init(malloc_noncache_start, CONFIG_NONCACHE_MEMORY_SIZE);
#endif

#if defined(CONFIG_ARCH_HOMELET)
	check_physical_key_early();
#endif

	workmode = uboot_spare_head.boot_data.work_mode;
	debug("work mode %d\n", workmode);

	axp_reinit();
	//uboot_spare_head.boot_data.work_mode = WORK_MODE_CARD_PRODUCT;

#if defined(CONFIG_CPUS_STANDBY) //目前只在homelet上使用
	do_box_standby();
#endif

#ifdef 	CONFIG_ARCH_HOMELET
	gpio_control();
#endif
#if 0
#if !defined(CONFIG_SYS_NO_FLASH)
	puts("Flash: ");

	flash_size = flash_init();
	if (flash_size > 0) {
# ifdef CONFIG_SYS_FLASH_CHECKSUM
		print_size(flash_size, "");
		/*
		 * Compute and print flash CRC if flashchecksum is set to 'y'
		 *
		 * NOTE: Maybe we should add some WATCHDOG_RESET()? XXX
		 */
		s = getenv("flashchecksum");
		if (s && (*s == 'y')) {
			printf("  CRC: %08X", crc32(0,
				(const unsigned char *) CONFIG_SYS_FLASH_BASE,
				flash_size));
		}
		putc('\n');
# else	/* !CONFIG_SYS_FLASH_CHECKSUM */
		print_size(flash_size, "\n");
# endif /* CONFIG_SYS_FLASH_CHECKSUM */
	} else {
		puts(failed);
		hang();
	}
#endif
#endif
	/* set up exceptions */
	interrupt_init();
	/* enable exceptions */
	enable_interrupts();
	sunxi_dma_init();
#ifdef DEBUG
    puts("ready to config storage\n");
#endif

#ifdef CONFIG_ARCH_HOMELET	//for homlet to use one-key-recovery
	ret = sunxi_flash_handle_init();
	if(!ret)
	{
		sunxi_partition_init();
	}
#endif

	if((workmode == WORK_MODE_BOOT) || (workmode == WORK_MODE_CARD_PRODUCT) || (workmode == WORK_MODE_SPRITE_RECOVERY))
	{
#if (defined(CONFIG_SUNXI_DISPLAY) || defined(CONFIG_SUN7I_DISPLAY))
	    drv_disp_init();
#endif
#ifdef CONFIG_SUNXI_HDCP_IN_SECURESTORAGE
		ret = script_parser_fetch("hdmi_para", "hdmi_hdcp_enable", &hdcpkey_enable, 1);
		if((ret) || (hdcpkey_enable != 1))
		{
			board_display_device_open();
			board_display_layer_request();
		}
#else
		board_display_device_open();
		board_display_layer_request();
#endif
	}

#ifndef CONFIG_ARCH_HOMELET	//for pad used
	ret = sunxi_flash_handle_init();
	if(!ret)
	{
		sunxi_partition_init();
	}
#endif

#ifdef CONFIG_SUNXI_HDCP_IN_SECURESTORAGE
		//here: write key to hardware
		if(hdcpkey_enable==1)
		{
			char buffer[4096];
			int data_len;
			int ret0;

			memset(buffer, 0, 4096);
			ret0 = sunxi_secure_storage_init();
			if(ret0)
			{
				printf("sunxi init secure storage failed\n");
			}
			else
			{
				ret0 = sunxi_secure_storage_read("hdcpkey", buffer, 4096, &data_len);
				if(ret0)
				{
					printf("probe hdcp key failed\n");
				}
				else
				{
					ret0 = smc_aes_bssk_decrypt_to_keysram(buffer, data_len);
					if(ret0)
					{
						printf("push hdcp key failed\n");
					}
					else
					{
						board_display_device_open();
						board_display_layer_request();
					}
				}
			}
		}
#endif

#ifdef  CONFIG_BOOT_A15
	if(sunxi_sprite_download_boot0_simple())
	{
		printf("rewrite boot0 to save boot cpu failed\n");
	}
#endif
#ifndef CONFIG_SUNXI_SPINOR_PLATFORM
	sunxi_keydata_burn_by_usb();
#endif
//#else
//#if defined(CONFIG_CMD_NAND)
//	if(!storage_type){
//		puts("NAND:  ");
//		nand_init();        /* go init the NAND */
//	}
//#endif/*CONFIG_CMD_NAND*/
//
//#if defined(CONFIG_GENERIC_MMC)
//	if(storage_type){
//		puts("MMC:   ");
//		mmc_initialize(bd);
//	}
//#endif/*CONFIG_GENERIC_MMC*/

#ifdef CONFIG_HAS_DATAFLASH
	AT91F_DataflashInit();
	dataflash_print_info();
#endif

	/* initialize environment */
	env_relocate();
#if defined(CONFIG_CMD_PCI) || defined(CONFIG_PCI)
	arm_pci_init();
#endif

	/* IP Address */
	gd->bd->bi_ip_addr = getenv_IPaddr("ipaddr");
	stdio_init();	/* get the devices list going. */
	jumptable_init();
#if defined(CONFIG_API)
	/* Initialize API */
	api_init();
#endif

	console_init_r();	/* fully init console as a device */
#if defined(CONFIG_ARCH_MISC_INIT)
	/* miscellaneous arch dependent initialisations */
	arch_misc_init();
#endif
#if defined(CONFIG_MISC_INIT_R)
	/* miscellaneous platform dependent initialisations */
	misc_init_r();
#endif
	/* Perform network card initialisation if necessary */
#if defined(CONFIG_DRIVER_SMC91111) || defined (CONFIG_DRIVER_LAN91C96)
	/* XXX: this needs to be moved to board init */
	if (getenv("ethaddr")) {
		uchar enetaddr[6];
		eth_getenv_enetaddr("ethaddr", enetaddr);
		smc_set_mac_addr(enetaddr);
	}
#endif /* CONFIG_DRIVER_SMC91111 || CONFIG_DRIVER_LAN91C96 */

	/* Initialize from environment */
	s = getenv("loadaddr");
	if (s != NULL)
		load_addr = simple_strtoul(s, NULL, 16);
#if defined(CONFIG_CMD_NET)
	s = getenv("bootfile");
	if (s != NULL)
		copy_filename(BootFile, s, sizeof(BootFile));
#endif
#ifdef BOARD_LATE_INIT
	board_late_init();
#endif
#ifdef CONFIG_BITBANGMII
	bb_miiphy_init();
#endif
#if defined(CONFIG_CMD_NET)
#if defined(CONFIG_NET_MULTI)
	puts("Net:   ");
#endif
	eth_initialize(gd->bd);
#if defined(CONFIG_RESET_PHY_R)
	debug("Reset Ethernet PHY\n");
	reset_phy();
#endif
#endif

#ifdef CONFIG_POST
	post_run(NULL, POST_RAM | post_bootmode_get(0));
#endif

#if defined(CONFIG_PRAM) || defined(CONFIG_LOGBUFFER)
	/*
	 * Export available size of memory for Linux,
	 * taking into account the protected RAM at top of memory
	 */
	{
		ulong pram;
		uchar memsz[32];
#ifdef CONFIG_PRAM
		char *s;

		s = getenv("pram");
		if (s != NULL)
			pram = simple_strtoul(s, NULL, 10);
		else
			pram = CONFIG_PRAM;
#else
		pram = 0;
#endif
#ifdef CONFIG_LOGBUFFER
#ifndef CONFIG_ALT_LB_ADDR
		/* Also take the logbuffer into account (pram is in kB) */
		pram += (LOGBUFF_LEN + LOGBUFF_OVERHEAD) / 1024;
#endif
#endif
		sprintf((char *)memsz, "%ldk", (gd->ram_size / 1024) - pram);
		setenv("mem", (char *)memsz);
	}
#endif
	//sprite_cartoon_test();
	if(workmode == WORK_MODE_BOOT)
    {
#if defined(CONFIG_SUNXI_SCRIPT_REINIT)
		{
			FATFS script_mount;
			int  ret;
			uint read_bytes = 0;
			FILE  script_fs;
			uchar  *buf = NULL;

			f_mount_ex(0, &script_mount, 0);
			ret = f_open (&script_fs, "0:script.bin", FA_OPEN_EXISTING | FA_READ | FA_WRITE );
			if(ret)
			{
				printf("cant open script.bin, maybe it is not exist\n");
			}
			else
			{
				buf = (uchar *)malloc(100 * 1024);
				memset(buf, 0, 100 * 1024);

				if(!f_read(&script_fs, buf, 100 * 1024, &read_bytes))
				{
					printf("f_read read bytes = %d\n", read_bytes);
				}
				f_close(&script_fs);
				puts("try to unlink file ");
				printf("%d\n", f_unlink("0:script.bin"));
			}
			f_mount(0, NULL, NULL);
			if(read_bytes > 0)
			{
				char *tmp_target_buffer = (char *)(CONFIG_SYS_TEXT_BASE - 0x01000000);

				sunxi_flash_exit(1);

				memcpy(tmp_target_buffer + uboot_spare_head.boot_head.uboot_length, buf, read_bytes);
				sunxi_sprite_download_uboot(tmp_target_buffer, uboot_spare_head.boot_data.storage_type, 1);

				reset_cpu(0);
			}
			if(buf)
			{
				free(buf);
			}
		}
#endif
    	printf("WORK_MODE_BOOT\n");
#if (defined(CONFIG_SUNXI_DISPLAY) || defined(CONFIG_SUN7I_DISPLAY))
		if(!ret)
		{
#ifndef CONFIG_ARCH_HOMELET
			printf("board_status_probe\n");
			board_status_probe(0);
#endif
                    if(!gd->chargemode)
                    {
			printf("sunxi_bmp_logo_display\n");
			sunxi_bmp_display("bootlogo.bmp");
                    }
                    else
                    {
                        printf("sunxi_bmp_charger_display\n");
                        sunxi_bmp_display("bat\\battery_charge.bmp");
                    }
		}
#endif
#ifdef CONFIG_READ_LOGO_FOR_KERNEL
	    sunxi_read_bootlogo("bootlogo");
#endif

	}
	/* main_loop() can return to retry autoboot, if so just run it again. */
	for (;;)
	{
		main_loop();
	}
	hang();
	/* NOTREACHED - no way out of command loop except booting */
}
Ejemplo n.º 29
0
int main (int argc, char** argv) {
  DfaSet * dfaSet = stasis_calloc(1, DfaSet);
  /*  callback_fcn* callbacks[MAX_MESSAGE_COUNT]; */
  
  Transition * transitions = stasis_malloc(3, Transition);

  State * states = stasis_malloc(MAX_STATE_COUNT, State);
  /*  StateMachine initial_sm1_stack; */
  StateMachine * initial_sm1;
  int transition_count;

  /*  dfaSet->monoTree.buffer = stasis_calloc(DFA_MACHINE_COUNT, StateMachine);
      dfa_initialize_new (dfaSet, 10001, DFA_MACHINE_COUNT); */
  /*   dfaSet->monoTree.buffer = stasis_calloc(100, StateMachine); */
  dfa_initialize_new (dfaSet, 10001, 100);
  
  /*  initial_sm1 = allocMachine(&(dfaSet->monoTree)); */
  initial_sm1 = allocSmash(dfaSet->smash);
  assert(NULL != initial_sm1);
  //(initial_sm1 = allocSmash(dfaSet->smash)));
  
  initial_sm1->message.from_machine_id = initial_sm1->machine_id;
  initial_sm1->message.to_machine_id   = NULL_MACHINE;
  initial_sm1->message.type = NULL_STATE;
  /* What to do here ???? 
     initial_sm1->message.machine_id = initial_sm2->machine_id;
     initial_sm2->message.machine_id = initial_sm1->machine_id;
  */
  
  printf("sm1 %ld\n", initial_sm1->machine_id);

  initial_sm1->current_state = START_STATE;
    
  initial_sm1->last_transition = (time_t)0;
  
  strcpy(initial_sm1->message_recipient, "127.0.0.1:10001");

  setSmash(dfaSet->smash, initial_sm1->machine_id);
  
  states[0].name      = FORKED;
  states[0].retry_fcn = NULL;
  states[0].abort_fcn = NULL;

  transitions[0].remote_state = NULL_STATE;
  transitions[0].pre_state    = NULL_STATE;
  transitions[0].post_state   = START_STATE;
  transitions[0].fcn_ptr      = &recv_new;
  transitions[0].force        = 0;

  transitions[1].remote_state = START_STATE;
  transitions[1].pre_state    = START_STATE;
  transitions[1].post_state   = FORKED;
  transitions[1].fcn_ptr      = &recv_ack;
  transitions[1].force        = 0;

  transitions[2].remote_state = START_STATE;
  transitions[2].pre_state    = FORKED;
  transitions[2].post_state   = NULL_STATE;
  transitions[2].fcn_ptr      = &recv_ack;
  transitions[2].force        = 0;

  /* Needed for bootstrap... */

  transitions[3].remote_state = START_STATE;
  transitions[3].pre_state    = NULL_STATE;
  transitions[3].post_state   = START_STATE;
  transitions[3].fcn_ptr      = &recv_new;
  transitions[3].force        = 0;

  transition_count = 4;

  if(dfa_reinitialize(dfaSet, "127.0.0.1:10001", transitions, transition_count, states, 1) < 0) {
    printf("Error.  Exiting.\n");
  }

  main_loop(dfaSet);


  return 0;
}
Ejemplo n.º 30
0
int main(int argc, char **argv) {
  char *uuid; /* This host's uuid */
  int i, c;
  char uuid_lock_path[PATH_MAX];
  char tmp_path[PATH_MAX];
  char fence_path[PATH_MAX];
  char **other_lock_files;

  while (1) {
    int option_index = 0;
    static struct option long_options[] = {
      {"uuid",    required_argument, 0,  'u' },
      {"verbose", no_argument,       0,  'v' },
      {0,         0,                 0,  0 }
    };

    c = getopt_long(argc, argv, "u:f:v", long_options, &option_index);
    if (c == -1)
      break;

    switch (c) {
      case 'u':
        uuid = strdup(optarg);
        break;
      case 'v':
        verbose = 1;
        break;
      default:
        fprintf(stderr, "unexpected return from getopt: %d\n", c);
    }
  }

  if (!uuid) {
    fprintf(stderr, "Please supply a host uuid with --uuid <uuid>\n");
    exit(1);
  }

  if ((mkdir(".ha", 0755) == -1) && (errno != EEXIST)) {
    perror("Failed to mkdir .ha");
  }
  if ((mkdir(".ha/master", 0755) == -1) && (errno != EEXIST)) {
    perror("Failed to mkdir .ha/master");
  }
  if ((mkdir(".ha/host", 0755) == -1) && (errno != EEXIST)) {
    perror("Failed to mkdir .ha/host");
  }

  snprintf(tmp_path, sizeof(tmp_path), ".ha/host/%s", uuid);
  if ((mkdir(tmp_path, 0755) == -1) && (errno != EEXIST)) {
    perror("Failed to mkdir .ha/host/<uuid>");
  }
  snprintf(uuid_lock_path, sizeof(uuid_lock_path), ".ha/host/%s/lock", uuid);
  snprintf(fence_path, sizeof(fence_path), ".ha/host/%s/self-fence", uuid);
  if ((mkdir(fence_path, 0755) == -1) && (errno != EEXIST)) {
    perror("Failed to mkdir fence_path");
  }

  other_lock_files = (char **)malloc(sizeof(char *) * (argc - optind));
  if (!other_lock_files)
    abort();  
  for (i = 0; i < (argc - optind); i++) {
    snprintf(tmp_path, sizeof(tmp_path), ".ha/host/%s", argv[optind + i]);
    if ((mkdir(tmp_path, 0755) == -1) && (errno != EEXIST)) {
      perror("Failed to mkdir fence_path");
    }
    snprintf(tmp_path, sizeof(tmp_path), ".ha/host/%s/self-fence", argv[optind + i]);
    if ((mkdir(tmp_path, 0755) == -1) && (errno != EEXIST)) {
      perror("Failed to mkdir fence_path");
    }

    int bytes = snprintf(NULL, 0, ".ha/host/%s/lock", argv[optind + i]);
    char *path = malloc(bytes + 1);
    snprintf(path, bytes + 1, ".ha/host/%s/lock", argv[optind + i]);
    *(other_lock_files + i) = path;
  }

  main_loop(uuid_lock_path, ".ha/master/lock", fence_path, other_lock_files, argc - optind);
  return 0;
}