示例#1
0
/*------------------------------------------------------------------------*/
int get_uuids(char **uuids, int max)
{
	int count,n;
	api_cmd_t sock_cmd;
        api_cmd_t *api_cmd=&sock_cmd;

	if (api_init(socket_path)==-1) {
		exit(-1);
	}
	api_cmd->cmd=API_GET_NC_NUM;
	api_cmd->magic = MCLI_MAGIC;
	api_cmd->version = MCLI_VERSION;
        API_WAIT_RESPONSE(api_cmd);
	if(api_cmd->magic != MCLI_MAGIC || api_cmd->version != MCLI_VERSION) {
		err("API version mismatch!\n");
	}
	count=api_cmd->parm[API_PARM_NC_NUM];
	
	for(n=0;n<max && n<count;n++) {
		api_cmd->cmd=API_GET_NC_INFO;
                api_cmd->parm[API_PARM_NC_NUM]=n;
                API_WAIT_RESPONSE(api_cmd);
                if(api_cmd->u.nc_info.magic != MCLI_MAGIC || api_cmd->u.nc_info.version != MCLI_VERSION) {
                	err("API version mismatch!\n");
                }
                
		uuids[n]=strdup(api_cmd->u.nc_info.uuid);
		versions[n]=strdup(api_cmd->u.nc_info.FirmwareVersion);		
	}
	return count;
}
示例#2
0
文件: punter.c 项目: ecks/harry
int main(int argc, char **argv)
{
  struct thread thread;
  struct addrinfo *ai;

  if(optind != argc-1)
  {
    printf("usage: punter <hostname>\n");
    exit(1);
  }
  
  /* thread master */
  master = thread_master_create();

  host = argv[optind];
 
  api_init();
 
  punter_ctrl_init(host);

  while(thread_fetch(master, &thread))
  {
    thread_call(&thread);
  }

}
示例#3
0
int main(int argc, char *argv[])
{
    api_init();

    if (API_OK != api_loop_run(proxy_server, 0, 0))
        return 1;

    return 0;
}
示例#4
0
mapi_proc api_get_proc_address(const char *proc_name)
{
   if (!proc_name || proc_name[0] != 'v' || proc_name[1] != 'g')
      return NULL;
   proc_name += 2;

   api_init();
   return mapi_get_proc_address(proc_name);
}
示例#5
0
struct mapi_table *api_create_dispatch(void)
{
   struct mapi_table *tbl;

   api_init();

   tbl = mapi_table_create();
   if (tbl)
      mapi_table_fill(tbl, vega_procs);

   return tbl;
}
示例#6
0
文件: beagle.c 项目: dzz/ctt2
unsigned int initPython() {
    api_set_screensize( SCREEN_WIDTH, SCREEN_HEIGHT );
    //Py_SetProgramName("ctt2_py");
    if( api_init() == API_FAILURE ) {
        log_message( CTT2_RT_MODULE_PYTHON, LOG_LEVEL_ERROR, "Error booting python environment.");
        if(PyErr_Occurred()) {
            PyErr_Print();
        }
        return MODULE_FAILURE;
    } 
    return MODULE_LOADED;
}
示例#7
0
文件: api.c 项目: troglobit/toolbox
static int api_do(int cmd, int id, char *label, int timeout, int ack, int *next)
{
	int sd;
	api_t a = {
		.cmd     = cmd,
		.pid     = getpid(),
		.timeout = timeout,
	};
	
	sd = api_init(0);
	if (-1 == sd)
		return errno;

	printf("API: Got cmd %d\n", cmd);
	if (API_SUBSCRIBE_CMD == cmd) {
		if (!label || !label[0])
			label = __progname;
		strncpy(a.label, label, sizeof(a.label));
	} else {
		a.id  = id;
		a.ack = ack;
	}

	printf("API: Sending to D ...\n");
	if (sock_poll(sd, POLLOUT)) {
		if (write(sd, &a, sizeof(a)) != sizeof(a))
			goto error;
	}

	printf("API: Receiving from D ...\n");
	if (sock_poll(sd, POLLIN)) {
		if (read(sd, &a, sizeof(a)) != sizeof(a))
			goto error;
	}

	*next = a.next_ack;
	printf("API: All OK, next ACK %d!\n", *next);

	close(sd);

	if (API_SUBSCRIBE_CMD == cmd)
		return a.id;

	return 0;
error:
	printf("API: ERROR!\n");
	close(sd);
	return -errno;
}
示例#8
0
文件: api.c 项目: troglobit/toolbox
/* Used by client to check if server is up */
int api_ping(void)
{
	int sd;
	fd_set fdset;
	struct timeval tv;
	int so_error = ENOTCONN;
	socklen_t len = sizeof(so_error);

	sd = api_init(0);
	if (-1 == sd)
		return 1;

	if (sock_poll(sd, POLLIN | POLLOUT))
		getsockopt(sd, SOL_SOCKET, SO_ERROR, &so_error, &len);

	close(sd);

	return errno != 0;
}
示例#9
0
文件: test-conhash.c 项目: mymmsc/api
int main(int argc, char* argv[])
{
	api_init();
	{
		int n = 0x01fffc;
		printf("n has [%d]<=>[%d] 1.\n", api_bitset_count(n), api_bitset_count(0x01) + api_bitset_count(0xff) + api_bitset_count(0xfc));
	}
	int rc = 0;
	{
		char s1[1024];
		memset(s1, 0x00, sizeof(s1));
		strcpy(s1, "log path is <${MSF_LOGS}>-<${MSF_LOGS}>${MSF_RUNTIME}");
		api_strfilter(s1, NULL, NULL);
		printf("s1 = [%s]\n", s1);
	}
	api_conhash_t *conhash = calloc(1, sizeof(api_conhash_t));
	rc = api_conhash_init(conhash, API_SIZE_FROM_MB(32), 100);
	do_assert(rc == API_SUCCESS);
	int index = 0;
	char serverId[100];
	for(index = 0; index < 3; index++)
	{
		memset(serverId, 0x00, sizeof(serverId));
		snprintf(serverId, sizeof(serverId), "10.1.15.1%d", index);
		printf(">>>>>>>>>>>>>>>>>>>>>>>>>>> %s\n", serverId);
		api_conhash_add_node(conhash, (uint8_t *)serverId, api_strlen(serverId), NULL);
	}

	
	//char serverId[100];
	api_vector_t *slist = api_vector_new(1);
	char *str = NULL;
	for(index = 0; index < 10; index++)
	{
		memset(serverId, 0x00, sizeof(serverId));
		snprintf(serverId, sizeof(serverId), "cookie:%d", 9 - index);
		str = strdup(serverId);
		api_vector_push(slist, str);
		printf("cookie: [%s]\t", serverId);
		api_conhash_lookup_node(conhash, (uint8_t *)serverId, api_strlen(serverId), server_get, NULL);
	}
	printf("----------------------------------------------------------------\n");
	api_vector_sort(slist, (int (*) (const void *, const void *)) str_sort);
	api_vector_remove(slist, 0);
	for(index = 0; index < api_vector_size(slist); index++)
	{
		str = api_vector_get(slist, index);
		printf("cookie: [%s]\n", str);
	}
	printf("----------------------------------------------------------------\n");
	for(index = 0; index < 1; index++)
	{
		memset(serverId, 0x00, sizeof(serverId));
		snprintf(serverId, sizeof(serverId), "10.1.15.1%d", index + 2);
		api_conhash_del_node(conhash, (uint8_t *)serverId, api_strlen(serverId));
	}
	printf("----------------------------------------------------------------\n");
	for(index = 0; index < 10; index++)
	{
		memset(serverId, 0x00, sizeof(serverId));
		snprintf(serverId, sizeof(serverId), "cookie:%d", index);
		printf("cookie: [%s]\t", serverId);
		api_conhash_lookup_node(conhash, (uint8_t *)serverId, api_strlen(serverId), server_get, NULL);
	}
	printf("----------------------------------------------------------------\n");
	api_safefree(conhash);
	return 0;
}
示例#10
0
文件: finit.c 项目: jonasj76/finit
int main(int argc, char* argv[])
{
	char *path;
	char cmd[256];
	int udev = 0;
	uev_t timer;	       /* Bootstrap timer, on timeout call finalize() */
	uev_ctx_t loop;

	/*
	 * finit/init/telinit client tool uses /dev/initctl pipe
	 * for compatibility but initctl client tool uses socket
	 */
	if (getpid() != 1)
		return client(argc, argv);

	/*
	 * Initalize event context.
	 */
	uev_init(&loop);
	ctx = &loop;

	/*
	 * Set PATH and SHELL early to something sane
	 */
	setenv("PATH", _PATH_STDPATH, 1);
	setenv("SHELL", _PATH_BSHELL, 1);

	/*
	 * Mount base file system, kernel is assumed to run devtmpfs for /dev
	 */
	chdir("/");
	umask(0);
	mount("none", "/proc", "proc", 0, NULL);
	mount("none", "/sys", "sysfs", 0, NULL);
	if (fisdir("/proc/bus/usb"))
		mount("none", "/proc/bus/usb", "usbfs", 0, NULL);

	/*
	 * Parse kernel command line (debug, rescue, splash, etc.)
	 * Also calls log_init() to set correct log level
	 */
	conf_parse_cmdline();

	/* Set up canvas */
	if (!rescue && !log_is_debug())
		screen_init();

	/*
	 * In case of emergency.
	 */
	emergency_shell();

	/*
	 * Initial setup of signals, ignore all until we're up.
	 */
	sig_init();

	/*
	 * Load plugins early, finit.conf may contain references to
	 * features implemented by plugins.
	 */
	plugin_init(&loop);

	/*
	 * Hello world.
	 */
	banner();

	/*
	 * Check file filesystems in /etc/fstab
	 */
	for (int pass = 1; pass < 10 && !rescue; pass++) {
		if (fsck(pass))
			break;
	}

	/*
	 * Initialize .conf system and load static /etc/finit.conf
	 * Also initializes global_rlimit[] for udevd, below.
	 */
	conf_init();

	/*
	 * Some non-embedded systems without an initramfs may not have /dev mounted yet
	 * If they do, check if system has udevadm and perform cleanup from initramfs
	 */
	if (!fismnt("/dev"))
		mount("udev", "/dev", "devtmpfs", MS_RELATIME, "size=10%,nr_inodes=61156,mode=755");
	else if (whichp("udevadm"))
		run_interactive("udevadm info --cleanup-db", "Cleaning up udev db");

	/* Some systems use /dev/pts */
	makedir("/dev/pts", 0755);
	mount("devpts", "/dev/pts", "devpts", 0, "gid=5,mode=620");

	/*
	 * Some systems rely on us to both create /dev/shm and, to mount
	 * a tmpfs there.  Any system with dbus needs shared memory, so
	 * mount it, unless its already mounted, but not if listed in
	 * the /etc/fstab file already.
	 */
	makedir("/dev/shm", 0755);
	if (!fismnt("/dev/shm") && !ismnt("/etc/fstab", "/dev/shm"))
		mount("shm", "/dev/shm", "tmpfs", 0, NULL);

	/*
	 * New tmpfs based /run for volatile runtime data
	 * For details, see http://lwn.net/Articles/436012/
	 */
	if (fisdir("/run") && !fismnt("/run"))
		mount("tmpfs", "/run", "tmpfs", MS_NODEV, "mode=0755,size=10%");
	umask(022);

	/* Bootstrap conditions, needed for hooks */
	cond_init();

	/*
	 * Populate /dev and prepare for runtime events from kernel.
	 * Prefer udev if mdev is also available on the system.
	 */
	path = which("udevd");
	if (!path)
		path = which("/lib/systemd/systemd-udevd");
	if (path) {
		/* Desktop and server distros usually have a variant of udev */
		udev = 1;

		/* Register udevd as a monitored service */
		snprintf(cmd, sizeof(cmd), "[S12345789] pid:udevd %s -- Device event managing daemon", path);
		if (service_register(SVC_TYPE_SERVICE, cmd, global_rlimit, NULL)) {
			_pe("Failed registering %s", path);
			udev = 0;
		} else {
			snprintf(cmd, sizeof(cmd), ":1 [S] <svc%s> "
				 "udevadm trigger -c add -t devices "
				 "-- Requesting device events", path);
			service_register(SVC_TYPE_RUN, cmd, global_rlimit, NULL);

			snprintf(cmd, sizeof(cmd), ":2 [S] <svc%s> "
				 "udevadm trigger -c add -t subsystems "
				 "-- Requesting subsystem events", path);
			service_register(SVC_TYPE_RUN, cmd, global_rlimit, NULL);
		}
		free(path);
	} else {
		path = which("mdev");
		if (path) {
			/* Embedded Linux systems usually have BusyBox mdev */
			if (log_is_debug())
				touch("/dev/mdev.log");

			snprintf(cmd, sizeof(cmd), "%s -s", path);
			free(path);

			run_interactive(cmd, "Populating device tree");
		}
	}

	/*
	 * Start built-in watchdog as soon as possible, if enabled
	 */
	wdogpid = watchdog(argv[0]);

	/*
	 * Mount filesystems
	 */
	if (!rescue) {
#ifdef REMOUNT_ROOTFS
		run("mount -n -o remount,rw /");
#endif
#ifdef SYSROOT
		mount(SYSROOT, "/", NULL, MS_MOVE, NULL);
#endif
	}

	if (!rescue) {
		_d("Root FS up, calling hooks ...");
		plugin_run_hooks(HOOK_ROOTFS_UP);

		umask(0);
		if (run_interactive("mount -na", "Mounting filesystems"))
			plugin_run_hooks(HOOK_MOUNT_ERROR);

		_d("Calling extra mount hook, after mount -a ...");
		plugin_run_hooks(HOOK_MOUNT_POST);

		run("swapon -ea");
		umask(0022);
	}

	/* Base FS up, enable standard SysV init signals */
	sig_setup(&loop);

	if (!rescue) {
		_d("Base FS up, calling hooks ...");
		plugin_run_hooks(HOOK_BASEFS_UP);
	}

	/*
	 * Set up inotify watcher for /etc/finit.d and read all .conf
	 * files to figure out how to bootstrap the system.
	 */
	conf_monitor(&loop);

	/*
	 * Initalize state machine and start all bootstrap tasks
	 * NOTE: no network available!
	 */
	sm_init(&sm);
	sm_step(&sm);

	/* Debian has this little script to copy generated rules while the system was read-only */
	if (udev && fexist("/lib/udev/udev-finish"))
		run_interactive("/lib/udev/udev-finish", "Finalizing udev");

	/* Start new initctl API responder */
	api_init(&loop);
	umask(022);

	/*
	 * Wait for all SVC_TYPE_RUNTASK to have completed their work in
	 * [S], or timeout, before calling finalize()
	 */
	_d("Starting bootstrap finalize timer ...");
	uev_timer_init(&loop, &timer, service_bootstrap_cb, finalize, 1000, 1000);

	/*
	 * Enter main loop to monior /dev/initctl and services
	 */
	_d("Entering main loop ...");
	return uev_run(&loop, 0);
}
api::api(HINSTANCE hInstance): wnd(hInstance, WndProc, (LPCWSTR)L"myClass")
{
	api_init(hInstance);
}
示例#12
0
int
main(int argc, char **argv)
{
  int i;
  sigset_t set;
#if ENABLE_LINUXDVB
  uint32_t adapter_mask;
#endif
  int  log_level   = LOG_INFO;
  int  log_options = TVHLOG_OPT_MILLIS | TVHLOG_OPT_STDERR | TVHLOG_OPT_SYSLOG;
  const char *log_debug = NULL, *log_trace = NULL;
  char buf[512];

  main_tid = pthread_self();

  /* Setup global mutexes */
  pthread_mutex_init(&ffmpeg_lock, NULL);
  pthread_mutex_init(&fork_lock, NULL);
  pthread_mutex_init(&global_lock, NULL);
  pthread_mutex_init(&atomic_lock, NULL);
  pthread_cond_init(&gtimer_cond, NULL);

  /* Defaults */
  tvheadend_webui_port      = 9981;
  tvheadend_webroot         = NULL;
  tvheadend_htsp_port       = 9982;
  tvheadend_htsp_port_extra = 0;

  /* Command line options */
  int         opt_help         = 0,
              opt_version      = 0,
              opt_fork         = 0,
              opt_firstrun     = 0,
              opt_stderr       = 0,
              opt_syslog       = 0,
              opt_uidebug      = 0,
              opt_abort        = 0,
              opt_noacl        = 0,
              opt_fileline     = 0,
              opt_threadid     = 0,
              opt_ipv6         = 0,
              opt_tsfile_tuner = 0,
              opt_dump         = 0;
  const char *opt_config       = NULL,
             *opt_user         = NULL,
             *opt_group        = NULL,
             *opt_logpath      = NULL,
             *opt_log_debug    = NULL,
             *opt_log_trace    = NULL,
             *opt_pidpath      = "/var/run/tvheadend.pid",
#if ENABLE_LINUXDVB
             *opt_dvb_adapters = NULL,
#endif
             *opt_bindaddr     = NULL,
             *opt_subscribe    = NULL;
  str_list_t  opt_tsfile       = { .max = 10, .num = 0, .str = calloc(10, sizeof(char*)) };
  cmdline_opt_t cmdline_opts[] = {
    {   0, NULL,        "Generic Options",         OPT_BOOL, NULL         },
    { 'h', "help",      "Show this page",          OPT_BOOL, &opt_help    },
    { 'v', "version",   "Show version infomation", OPT_BOOL, &opt_version },

    {   0, NULL,        "Service Configuration",   OPT_BOOL, NULL         },
    { 'c', "config",    "Alternate config path",   OPT_STR,  &opt_config  },
    { 'f', "fork",      "Fork and run as daemon",  OPT_BOOL, &opt_fork    },
    { 'u', "user",      "Run as user",             OPT_STR,  &opt_user    },
    { 'g', "group",     "Run as group",            OPT_STR,  &opt_group   },
    { 'p', "pid",       "Alternate pid path",      OPT_STR,  &opt_pidpath },
    { 'C', "firstrun",  "If no user account exists then create one with\n"
	                      "no username and no password. Use with care as\n"
	                      "it will allow world-wide administrative access\n"
	                      "to your Tvheadend installation until you edit\n"
	                      "the access-control from within the Tvheadend UI",
      OPT_BOOL, &opt_firstrun },
#if ENABLE_LINUXDVB
    { 'a', "adapters",  "Only use specified DVB adapters (comma separated)",
      OPT_STR, &opt_dvb_adapters },
#endif
    {   0, NULL,         "Server Connectivity",    OPT_BOOL, NULL         },
    { '6', "ipv6",       "Listen on IPv6",         OPT_BOOL, &opt_ipv6    },
    { 'b', "bindaddr",   "Specify bind address",   OPT_STR,  &opt_bindaddr},
    {   0, "http_port",  "Specify alternative http port",
      OPT_INT, &tvheadend_webui_port },
    {   0, "http_root",  "Specify alternative http webroot",
      OPT_STR, &tvheadend_webroot },
    {   0, "htsp_port",  "Specify alternative htsp port",
      OPT_INT, &tvheadend_htsp_port },
    {   0, "htsp_port2", "Specify extra htsp port",
      OPT_INT, &tvheadend_htsp_port_extra },

    {   0, NULL,        "Debug Options",           OPT_BOOL, NULL         },
    { 'd', "stderr",    "Enable debug on stderr",  OPT_BOOL, &opt_stderr  },
    { 's', "syslog",    "Enable debug to syslog",  OPT_BOOL, &opt_syslog  },
    { 'l', "logfile",   "Enable debug to file",    OPT_STR,  &opt_logpath },
    {   0, "debug",     "Enable debug subsystems", OPT_STR,  &opt_log_debug },
#if ENABLE_TRACE
    {   0, "trace",     "Enable trace subsystems", OPT_STR,  &opt_log_trace },
#endif
    {   0, "fileline",  "Add file and line numbers to debug", OPT_BOOL, &opt_fileline },
    {   0, "threadid",  "Add the thread ID to debug", OPT_BOOL, &opt_threadid },
    {   0, "uidebug",   "Enable webUI debug (non-minified JS)", OPT_BOOL, &opt_uidebug },
    { 'A', "abort",     "Immediately abort",       OPT_BOOL, &opt_abort   },
    { 'D', "dump",      "Enable coredumps for daemon", OPT_BOOL, &opt_dump },
    {   0, "noacl",     "Disable all access control checks",
      OPT_BOOL, &opt_noacl },
    { 'j', "join",      "Subscribe to a service permanently",
      OPT_STR, &opt_subscribe },


    { 0, NULL, "TODO: testing", OPT_BOOL, NULL },
    { 0, "tsfile_tuners", "Number of tsfile tuners", OPT_INT, &opt_tsfile_tuner },
    { 0, "tsfile", "tsfile input (mux file)", OPT_STR_LIST, &opt_tsfile },

  };

  /* Get current directory */
  tvheadend_cwd = dirname(dirname(tvh_strdupa(argv[0])));

  /* Set locale */
  setlocale(LC_ALL, "");
  setlocale(LC_NUMERIC, "C");

  /* make sure the timezone is set */
  tzset();

  /* Process command line */
  for (i = 1; i < argc; i++) {

    /* Find option */
    cmdline_opt_t *opt
      = cmdline_opt_find(cmdline_opts, ARRAY_SIZE(cmdline_opts), argv[i]);
    if (!opt)
      show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts),
                 "invalid option specified [%s]", argv[i]);

    /* Process */
    if (opt->type == OPT_BOOL)
      *((int*)opt->param) = 1;
    else if (++i == argc)
      show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts),
                 "option %s requires a value", opt->lopt);
    else if (opt->type == OPT_INT)
      *((int*)opt->param) = atoi(argv[i]);
    else if (opt->type == OPT_STR_LIST) {
      str_list_t *strl = opt->param;
      if (strl->num < strl->max)
        strl->str[strl->num++] = argv[i];
    }
    else
      *((char**)opt->param) = argv[i];

    /* Stop processing */
    if (opt_help)
      show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts), NULL);
    if (opt_version)
      show_version(argv[0]);
  }

  /* Additional cmdline processing */
#if ENABLE_LINUXDVB
  if (!opt_dvb_adapters) {
    adapter_mask = ~0;
  } else {
    char *p, *e;
    char *r = NULL;
    char *dvb_adapters = strdup(opt_dvb_adapters);
    adapter_mask = 0x0;
    p = strtok_r(dvb_adapters, ",", &r);
    while (p) {
      int a = strtol(p, &e, 10);
      if (*e != 0 || a < 0 || a > 31) {
        tvhlog(LOG_ERR, "START", "Invalid adapter number '%s'", p);
        free(dvb_adapters);
        return 1;
      }
      adapter_mask |= (1 << a);
      p = strtok_r(NULL, ",", &r);
    }
    free(dvb_adapters);
    if (!adapter_mask) {
      tvhlog(LOG_ERR, "START", "No adapters specified!");
      return 1;
    }
  }
#endif
  if (tvheadend_webroot) {
    char *tmp;
    if (*tvheadend_webroot == '/')
      tmp = strdup(tvheadend_webroot);
    else {
      tmp = malloc(strlen(tvheadend_webroot)+2);
      *tmp = '/';
      strcpy(tmp+1, tvheadend_webroot);
    }
    if (tmp[strlen(tmp)-1] == '/')
      tmp[strlen(tmp)-1] = '\0';
    tvheadend_webroot = tmp;
  }
  tvheadend_webui_debug = opt_uidebug;

  /* Setup logging */
  if (isatty(2))
    log_options |= TVHLOG_OPT_DECORATE;
  if (opt_stderr || opt_syslog || opt_logpath) {
    if (!opt_log_trace && !opt_log_debug)
      log_debug      = "all";
    log_level      = LOG_DEBUG;
    if (opt_stderr)
      log_options   |= TVHLOG_OPT_DBG_STDERR;
    if (opt_syslog)
      log_options   |= TVHLOG_OPT_DBG_SYSLOG;
    if (opt_logpath)
      log_options   |= TVHLOG_OPT_DBG_FILE;
  }
  if (opt_fileline)
    log_options |= TVHLOG_OPT_FILELINE;
  if (opt_threadid)
    log_options |= TVHLOG_OPT_THREAD;
  if (opt_log_trace) {
    log_level  = LOG_TRACE;
    log_trace  = opt_log_trace;
  }
  if (opt_log_debug)
    log_debug  = opt_log_debug;
    
  tvhlog_init(log_level, log_options, opt_logpath);
  tvhlog_set_debug(log_debug);
  tvhlog_set_trace(log_trace);
 
  signal(SIGPIPE, handle_sigpipe); // will be redundant later

  /* Daemonise */
  if(opt_fork) {
    const char *homedir;
    gid_t gid;
    uid_t uid;
    struct group  *grp = getgrnam(opt_group ?: "video");
    struct passwd *pw  = opt_user ? getpwnam(opt_user) : NULL;
    FILE   *pidfile    = fopen(opt_pidpath, "w+");

    if(grp != NULL) {
      gid = grp->gr_gid;
    } else {
      gid = 1;
    }

    if (pw != NULL) {
      if (getuid() != pw->pw_uid) {
        gid_t glist[10];
        int gnum;
        gnum = get_user_groups(pw, glist, 10);
        if (setgroups(gnum, glist)) {
          tvhlog(LOG_ALERT, "START",
                 "setgroups() failed, do you have permission?");
          return 1;
        }
      }
      uid     = pw->pw_uid;
      homedir = pw->pw_dir;
      setenv("HOME", homedir, 1);
    } else {
      uid = 1;
    }
    if ((getgid() != gid) && setgid(gid)) {
      tvhlog(LOG_ALERT, "START",
             "setgid() failed, do you have permission?");
      return 1;
    }
    if ((getuid() != uid) && setuid(uid)) {
      tvhlog(LOG_ALERT, "START",
             "setuid() failed, do you have permission?");
      return 1;
    }

    if(daemon(0, 0)) {
      exit(2);
    }
    if(pidfile != NULL) {
      fprintf(pidfile, "%d\n", getpid());
      fclose(pidfile);
    }

    /* Make dumpable */
    if (opt_dump) {
#ifdef PLATFORM_LINUX
      if (chdir("/tmp"))
        tvhwarn("START", "failed to change cwd to /tmp");
      prctl(PR_SET_DUMPABLE, 1);
#else
      tvhwarn("START", "Coredumps not implemented on your platform");
#endif
    }

    umask(0);
  }

  tvheadend_running = 1;

  /* Start log thread (must be done post fork) */
  tvhlog_start();

  /* Alter logging */
  if (opt_fork)
    tvhlog_options &= ~TVHLOG_OPT_STDERR;
  if (!isatty(2))
    tvhlog_options &= ~TVHLOG_OPT_DECORATE;
  
  /* Initialise clock */
  pthread_mutex_lock(&global_lock);
  time(&dispatch_clock);

  /* Signal handling */
  sigfillset(&set);
  sigprocmask(SIG_BLOCK, &set, NULL);
  trap_init(argv[0]);
  
  /* Initialise configuration */
  uuid_init();
  idnode_init();
  config_init(opt_config);

  /**
   * Initialize subsystems
   */
  
  api_init();

  fsmonitor_init();

#if ENABLE_LIBAV
  libav_init();
  transcoding_init();
#endif

  imagecache_init();

  service_init();

#if ENABLE_TSFILE
  if(opt_tsfile.num) {
    tsfile_init(opt_tsfile_tuner ?: opt_tsfile.num);
    for (i = 0; i < opt_tsfile.num; i++)
      tsfile_add_file(opt_tsfile.str[i]);
  }
#endif
#if ENABLE_MPEGTS_DVB
  dvb_network_init();
#endif
#if ENABLE_IPTV
  iptv_init();
#endif
#if ENABLE_LINUXDVB
  linuxdvb_init(adapter_mask);
#endif

  channel_init();

  subscription_init();

  access_init(opt_firstrun, opt_noacl);

#if ENABLE_TIMESHIFT
  timeshift_init();
#endif

  http_client_init();
  tcp_server_init(opt_ipv6);
  http_server_init(opt_bindaddr);
  webui_init();

  service_mapper_init();

  descrambler_init();

  epggrab_init();
  epg_init();

  dvr_init();

  htsp_init(opt_bindaddr);


  if(opt_subscribe != NULL)
    subscription_dummy_join(opt_subscribe, 1);

  avahi_init();

  epg_updated(); // cleanup now all prev ref's should have been created

  pthread_mutex_unlock(&global_lock);

  /**
   * Wait for SIGTERM / SIGINT, but only in this thread
   */

  sigemptyset(&set);
  sigaddset(&set, SIGTERM);
  sigaddset(&set, SIGINT);

  signal(SIGTERM, doexit);
  signal(SIGINT, doexit);

  pthread_sigmask(SIG_UNBLOCK, &set, NULL);

  tvhlog(LOG_NOTICE, "START", "HTS Tvheadend version %s started, "
         "running as PID:%d UID:%d GID:%d, CWD:%s CNF:%s",
         tvheadend_version,
         getpid(), getuid(), getgid(), getcwd(buf, sizeof(buf)),
         hts_settings_get_root());

  if(opt_abort)
    abort();

  mainloop();

  tvhftrace("main", htsp_done);
  tvhftrace("main", http_server_done);
  tvhftrace("main", webui_done);
  tvhftrace("main", http_client_done);
  tvhftrace("main", fsmonitor_done);
#if ENABLE_MPEGTS_DVB
  tvhftrace("main", dvb_network_done);
#endif
#if ENABLE_IPTV
  tvhftrace("main", iptv_done);
#endif
#if ENABLE_LINUXDVB
  tvhftrace("main", linuxdvb_done);
#endif
#if ENABLE_TSFILE
  tvhftrace("main", tsfile_done);
#endif

  // Note: the locking is obviously a bit redundant, but without
  //       we need to disable the gtimer_arm call in epg_save()
  pthread_mutex_lock(&global_lock);
  tvhftrace("main", epg_save);

#if ENABLE_TIMESHIFT
  tvhftrace("main", timeshift_term);
#endif
  pthread_mutex_unlock(&global_lock);

  tvhftrace("main", epggrab_done);
  tvhftrace("main", tcp_server_done);
  tvhftrace("main", descrambler_done);
  tvhftrace("main", service_mapper_done);
  tvhftrace("main", service_done);
  tvhftrace("main", channel_done);
  tvhftrace("main", dvr_done);
  tvhftrace("main", subscription_done);
  tvhftrace("main", access_done);
  tvhftrace("main", epg_done);
  tvhftrace("main", avahi_done);
  tvhftrace("main", imagecache_done);
  tvhftrace("main", idnode_done);
  tvhftrace("main", lang_code_done);
  tvhftrace("main", api_done);
  tvhftrace("main", config_done);
  tvhftrace("main", hts_settings_done);
  tvhftrace("main", dvb_done);
  tvhftrace("main", lang_str_done);

  tvhlog(LOG_NOTICE, "STOP", "Exiting HTS Tvheadend");
  tvhlog_end();

  if(opt_fork)
    unlink(opt_pidpath);
    
  free(opt_tsfile.str);

  return 0;
}
示例#13
0
/*
 *  ======== dsp_init ========
 *  	Allocates bridge resources. Loads a base image onto DSP, if specified.
 */
u32 dsp_init(u32 *init_status)
{
	char dev_node[MAXREGPATHLENGTH] = "TIOMAP1510";
	int status = -EPERM;
	struct drv_object *drv_obj = NULL;
	u32 device_node;
	u32 device_node_string;

	if (!api_init())
		goto func_cont;

	status = drv_create(&drv_obj);
	if (status) {
		api_exit();
		goto func_cont;
	}

	/* End drv_create */
	/* Request Resources */
	status = drv_request_resources((u32) &dev_node, &device_node_string);
	if (!status) {
		/* Attempt to Start the Device */
		status = dev_start_device((struct cfg_devnode *)
					  device_node_string);
		if (status)
			(void)drv_release_resources
			    ((u32) device_node_string, drv_obj);
	} else {
		dev_dbg(bridge, "%s: drv_request_resources Failed\n", __func__);
		status = -EPERM;
	}

	/* Unwind whatever was loaded */
	if (status) {
		/* irrespective of the status of dev_remove_device we conitinue
		 * unloading. Get the Driver Object iterate through and remove.
		 * Reset the status to E_FAIL to avoid going through
		 * api_init_complete2. */
		for (device_node = drv_get_first_dev_extension();
		     device_node != 0;
		     device_node = drv_get_next_dev_extension(device_node)) {
			(void)dev_remove_device((struct cfg_devnode *)
						device_node);
			(void)drv_release_resources((u32) device_node, drv_obj);
		}
		/* Remove the Driver Object */
		(void)drv_destroy(drv_obj);
		drv_obj = NULL;
		api_exit();
		dev_dbg(bridge, "%s: Logical device failed init\n", __func__);
	}			/* Unwinding the loaded drivers */
func_cont:
	/* Attempt to Start the Board */
	if (!status) {
		/* BRD_AutoStart could fail if the dsp execuetable is not the
		 * correct one. We should not propagate that error
		 * into the device loader. */
		(void)api_init_complete2();
	} else {
		dev_dbg(bridge, "%s: Failed\n", __func__);
	}			/* End api_init_complete2 */
	DBC_ENSURE((!status && drv_obj != NULL) ||
		   (status && drv_obj == NULL));
	*init_status = status;
	/* Return the Driver Object */
	return (u32) drv_obj;
}
示例#14
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;

	extern void malloc_bin_reloc(void);

	gd = id;
	bd = gd->bd;

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

	monitor_flash_len = &_end - &_start;
	debug("monitor flash len: %08lX\n", monitor_flash_len);

	board_init();	/* Setup chipselects */

#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) */

#ifdef CONFIG_SERIAL_MULTI
	serial_initialize();
#endif

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

	/* 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);
	malloc_bin_reloc();

#ifndef CONFIG_SYS_NO_FLASH
	/* configure available FLASH banks */
	gd->bd->bi_flashstart = CONFIG_SYS_FLASH_BASE;
	gd->bd->bi_flashsize = flash_init();
	gd->bd->bi_flashoffset = CONFIG_SYS_FLASH_BASE + gd->bd->bi_flashsize;

	if (gd->bd->bi_flashsize)
			display_flash_config(gd->bd->bi_flashsize);
#endif /* CONFIG_SYS_NO_FLASH */

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

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

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

	/* initialize environment */
	env_relocate();

#if defined(CONFIG_CMD_PCI) || defined(CONFIG_PCI)
	nds32_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

#if defined(CONFIG_USE_IRQ)
	/* set up exceptions */
	interrupt_init();
	/* enable exceptions */
	enable_interrupts();
#endif

	/* 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

#ifdef BOARD_LATE_INIT
	board_late_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

	/* 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 */
}
示例#15
0
static int initr_api(void)
{
	/* Initialize API */
	api_init();
	return 0;
}
示例#16
0
void start_armboot (void)
{
	init_fnc_t **init_fnc_ptr;
	char *s;
	int mmc_exist = 0;
#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 ();
		}
	}

	/* armboot_start is defined in the board-specific linker script */
	mem_malloc_init (_armboot_start - CONFIG_SYS_MALLOC_LEN,
			CONFIG_SYS_MALLOC_LEN);

#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_GENERIC_MMC
	puts ("MMC:   ");
	mmc_exist = mmc_initialize (gd->bd);
	if (mmc_exist != 0)
	{
		puts ("0 MB\n");
	}

#endif


#ifdef CONFIG_HAS_DATAFLASH
	AT91F_DataflashInit();
	dataflash_print_info();
#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
#if defined(CONFIG_MISC_INIT_R)
	/* miscellaneous platform dependent initialisations */
	misc_init_r ();
#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

#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 */
}
示例#17
0
/**
 * RESCH APIs are called through write() system call.
 * See api.h for details.
 * Do not use timespec_to_jiffies(), since it rounds up the value.
 */
static ssize_t resch_write
(struct file *file, const char *buf, size_t count, loff_t *offset)
{
	int res = RES_SUCCESS;
	struct api_struct a;
	unsigned long us;

	/* copy data to kernel buffer. */
	if (copy_from_user(&a, buf, count)) {
		printk(KERN_WARNING "RESCH: failed to copy data.\n");
		return -EFAULT;
	}
	
	switch (a.api) {
		/* PORT I: preemptive periodic real-time scheduling.*/
	case API_INIT:
		res = api_init();
		break;
	
	case API_EXIT:
		res = api_exit(a.rid);
		break;

	case API_RUN:
		us = timespec_to_usecs(&a.arg.ts);
		res = api_run(a.rid, usecs_to_jiffies(us));
		break;

	case API_WAIT_PERIOD:
		res = api_wait_for_period(a.rid);
		break;

	case API_WAIT_INTERVAL:
		us = timespec_to_usecs(&a.arg.ts);
		res = api_wait_for_interval(a.rid, usecs_to_jiffies(us));
		break;

	case API_SET_PERIOD:
		us = timespec_to_usecs(&a.arg.ts);
		res = api_set_period(a.rid, usecs_to_jiffies(us));
		break;

	case API_SET_DEADLINE:
		us = timespec_to_usecs(&a.arg.ts);
		res = api_set_deadline(a.rid, usecs_to_jiffies(us));
		break;

	case API_SET_WCET:
		us = timespec_to_usecs(&a.arg.ts);
		res = api_set_wcet(a.rid, us);
		break;

	case API_SET_RUNTIME:
		us = timespec_to_usecs(&a.arg.ts);
		res = api_set_runtime(a.rid, us);
		break;

	case API_SET_PRIORITY:
		res = api_set_priority(a.rid, a.arg.val);
		break;

	case API_SET_SCHEDULER:
		res = api_set_scheduler(a.rid, a.arg.val);
		break;

	case API_BACKGROUND:
		res = api_background(a.rid);
		break;

		/* PORT II: event-driven asynchrous scheduling.*/
	case API_SLEEP:
		us = timespec_to_usecs(&a.arg.ts);
		res = api_sleep(a.rid, usecs_to_jiffies(us));
		break;

	case API_SUSPEND:
		res = api_suspend(a.rid);
		break;

	case API_WAKE_UP:
		res = api_wake_up(a.arg.val);
		break;

		/* PORT III: reservation-based scheduling.*/
	case API_RESERVE_START:
		us = timespec_to_usecs(&a.arg.ts);
		res = api_reserve_start(a.rid, usecs_to_jiffies(us), false);
		break;

	case API_RESERVE_START_XCPU:
		us = timespec_to_usecs(&a.arg.ts);
		res = api_reserve_start(a.rid, usecs_to_jiffies(us), true);
		break;

	case API_RESERVE_STOP:
		res = api_reserve_stop(a.rid);
		break;

	case API_RESERVE_EXPIRE:
		res = api_reserve_expire(a.rid);
		break;

	case API_SERVER_RUN:
		res = api_server_run(a.rid);
		break;

		/* PORT IV.*/
		/* PORT V: hierarchical scheduling.*/
	case API_COMPONENT_CREATE:
		res = api_component_create();
		break;

	case API_COMPONENT_DESTROY:
		res = api_component_destroy(a.arg.val);
		break;

	case API_COMPOSE:
		res = api_compose(a.rid, a.arg.val);
		break;

	case API_DECOMPOSE:
		res = api_decompose(a.rid);
		break;

	default: /* illegal api identifier. */
		res = RES_ILLEGAL;
		printk(KERN_WARNING "RESCH: illegal API identifier.\n");
		break;
	}
	
	return res;
}
示例#18
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
	char storage_type_buf[24] = {0};
	char boot_mmc_buf[24] = {0};
	
	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 CONFIG_USE_CIR	//����ӿڣ�Ŀǰֻ���ں��� A20
	if (uboot_spare_head.boot_data.work_mode == WORK_MODE_BOOT)
	{
		ir_setup();
	}
#endif
#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

#ifndef CONFIG_ARCH_SUN8IW8P1
	if((workmode == WORK_MODE_BOOT) || (workmode == WORK_MODE_CARD_PRODUCT) || (workmode == WORK_MODE_SPRITE_RECOVERY))
	{
#else
	if((workmode == WORK_MODE_CARD_PRODUCT) || (workmode == WORK_MODE_SPRITE_RECOVERY))
	{
#endif
#if (defined(CONFIG_SUNXI_DISPLAY) || defined(CONFIG_SUN7I_DISPLAY))
	    drv_disp_init();
#endif
#ifdef CONFIG_SUNXI_HDCP_IN_SECURESTORAGE
		int tmp = 0;
		tmp = script_parser_fetch("hdmi_para", "hdmi_hdcp_enable", &hdcpkey_enable, 1);
		if((tmp) || (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_object_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();

	/* setenv storage_type */
	sprintf(storage_type_buf, "%d", uboot_spare_head.boot_data.storage_type);
	if (setenv("storage_type", storage_type_buf))
		printf("set storage_type=%s fail\n", storage_type_buf);
	if (uboot_spare_head.boot_data.storage_type == 1)
		sprintf(boot_mmc_buf, "%s", "0");	
	else
		sprintf(boot_mmc_buf, "%s", "2");
	setenv("boot_mmc", boot_mmc_buf);
	
#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)
			{
				if(sunxi_advert_disp_probe())
				{
					printf("sunxi_bmp_logo_display\n");
					sunxi_bmp_display("bootlogo.bmp");
				}
				else
				{
					if(sunxi_advert_display("Reserve0", "advert.bmp"))
					{
						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("boot_logo");
#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 */
}

void hang(void)
{
	puts("### ERROR ### Please RESET the board ###\n");
	for (;;);
}
示例#19
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)
{
	bd_t *bd;
	ulong malloc_start;

#ifndef CONFIG_SYS_NO_FLASH
	ulong flash_size;
#endif

	gd = id;		/* initialize RAM version of global data */
	bd = gd->bd;

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

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

#if defined(CONFIG_MPC85xx) || defined(CONFIG_MPC86xx)
	/*
	 * The gd->arch.cpu pointer is set to an address in flash before
	 * relocation.  We need to update it to point to the same CPU entry
	 * in RAM.
	 */
	gd->arch.cpu += dest_addr - CONFIG_SYS_MONITOR_BASE;

	/*
	 * If we didn't know the cpu mask & # cores, we can save them of
	 * now rather than 'computing' them constantly
	 */
	fixup_cpu();
#endif

#ifdef CONFIG_SYS_EXTRA_ENV_RELOC
	/*
	 * Some systems need to relocate the env_addr pointer early because the
	 * location it points to will get invalidated before env_relocate is
	 * called.  One example is on systems that might use a L2 or L3 cache
	 * in SRAM mode and initialize that cache from SRAM mode back to being
	 * a cache in cpu_init_r.
	 */
	gd->env_addr += dest_addr - CONFIG_SYS_MONITOR_BASE;
#endif

	serial_initialize();

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

	WATCHDOG_RESET();

	/*
	 * Setup trap handlers
	 */
	trap_init(dest_addr);

#ifdef CONFIG_ADDR_MAP
	init_addr_map();
#endif

#if defined(CONFIG_BOARD_EARLY_INIT_R)
	board_early_init_r();
#endif

	monitor_flash_len = (ulong)&__init_end - dest_addr;

	WATCHDOG_RESET();

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

	WATCHDOG_RESET();

#if defined(CONFIG_SYS_DELAYED_ICACHE)
	icache_enable();	/* it's time to enable the instruction cache */
#endif

#if defined(CONFIG_SYS_INIT_RAM_LOCK) && defined(CONFIG_E500)
	unlock_ram_in_cache();	/* it's time to unlock D-cache in e500 */
#endif

#if defined(CONFIG_PCI) && defined(CONFIG_SYS_EARLY_PCI_INIT)
	/*
	 * Do early PCI configuration _before_ the flash gets initialised,
	 * because PCU ressources are crucial for flash access on some boards.
	 */
	pci_init();
#endif
#if defined(CONFIG_WINBOND_83C553)
	/*
	 * Initialise the ISA bridge
	 */
	initialise_w83c553f();
#endif

	asm("sync ; isync");

	mem_malloc_init(malloc_start, TOTAL_MALLOC_LEN);

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

	if (board_flash_wp_on()) {
		printf("Uninitialized - Write Protect On\n");
		/* Since WP is on, we can't find real size.  Set to 0 */
		flash_size = 0;
	} else 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
		 */
		if (getenv_yesno("flashchecksum") == 1) {
			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();
	}

	/* update start of FLASH memory    */
	bd->bi_flashstart = CONFIG_SYS_FLASH_BASE;
	/* size of FLASH memory (final value) */
	bd->bi_flashsize = flash_size;

#if defined(CONFIG_SYS_UPDATE_FLASH_SIZE)
	/* Make a update of the Memctrl. */
	update_flash_size(flash_size);
#endif


#if defined(CONFIG_OXC) || defined(CONFIG_RMU)
	/* flash mapped at end of memory map */
	bd->bi_flashoffset = CONFIG_SYS_TEXT_BASE + flash_size;
#elif CONFIG_SYS_MONITOR_BASE == CONFIG_SYS_FLASH_BASE
	bd->bi_flashoffset = monitor_flash_len;	/* reserved area for monitor */
#endif
#endif /* !CONFIG_SYS_NO_FLASH */

	WATCHDOG_RESET();

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

	WATCHDOG_RESET();

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

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

#ifdef CONFIG_GENERIC_MMC
/*
 * MMC initialization is called before relocating env.
 * Thus It is required that operations like pin multiplexer
 * be put in board_init.
 */
	WATCHDOG_RESET();
	puts("MMC:  ");
	mmc_initialize(bd);
#endif

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

	/*
	 * after non-volatile devices & environment is setup and cpu code have
	 * another round to deal with any initialization that might require
	 * full access to the environment or loading of some image (firmware)
	 * from a non-volatile device
	 */
	cpu_secondary_init_r();

	/*
	 * Fill in missing fields of bd_info.
	 * We do this here, where we have "normal" access to the
	 * environment; we used to do this still running from ROM,
	 * where had to use getenv_f(), which can be pretty slow when
	 * the environment is in EEPROM.
	 */

#if defined(CONFIG_SYS_EXTBDINFO)
#if defined(CONFIG_405GP) || defined(CONFIG_405EP)
#if defined(CONFIG_I2CFAST)
	/*
	 * set bi_iic_fast for linux taking environment variable
	 * "i2cfast" into account
	 */
	{
		if (getenv_yesno("i2cfast") == 1) {
			bd->bi_iic_fast[0] = 1;
			bd->bi_iic_fast[1] = 1;
		}
	}
#endif /* CONFIG_I2CFAST */
#endif /* CONFIG_405GP, CONFIG_405EP */
#endif /* CONFIG_SYS_EXTBDINFO */

#if defined(CONFIG_SC3)
	sc3_read_eeprom();
#endif

#if defined(CONFIG_ID_EEPROM) || defined(CONFIG_SYS_I2C_MAC_OFFSET)
	mac_read_from_eeprom();
#endif

#ifdef CONFIG_CMD_NET
	/* kept around for legacy kernels only ... ignore the next section */
	eth_getenv_enetaddr("ethaddr", bd->bi_enetaddr);
#ifdef CONFIG_HAS_ETH1
	eth_getenv_enetaddr("eth1addr", bd->bi_enet1addr);
#endif
#ifdef CONFIG_HAS_ETH2
	eth_getenv_enetaddr("eth2addr", bd->bi_enet2addr);
#endif
#ifdef CONFIG_HAS_ETH3
	eth_getenv_enetaddr("eth3addr", bd->bi_enet3addr);
#endif
#ifdef CONFIG_HAS_ETH4
	eth_getenv_enetaddr("eth4addr", bd->bi_enet4addr);
#endif
#ifdef CONFIG_HAS_ETH5
	eth_getenv_enetaddr("eth5addr", bd->bi_enet5addr);
#endif
#endif /* CONFIG_CMD_NET */

	WATCHDOG_RESET();

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

/** leave this here (after malloc(), environment and PCI are working) **/
	/* Initialize stdio devices */
	stdio_init();

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

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

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

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

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

	debug("U-Boot relocated to %08lx\n", dest_addr);

	/*
	 * Enable Interrupts
	 */
	interrupt_init();

#if defined(CONFIG_STATUS_LED) && defined(STATUS_LED_BOOT)
	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_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(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_PCMCIA) \
    && !defined(CONFIG_CMD_IDE)
	WATCHDOG_RESET();
	puts("PCMCIA:");
	pcmcia_init();
#endif

#if defined(CONFIG_CMD_IDE)
	WATCHDOG_RESET();
#ifdef	CONFIG_IDE_8xx_PCCARD
	puts("PCMCIA:");
#else
	puts("IDE:   ");
#endif
#if defined(CONFIG_START_IDE)
	if (board_start_ide())
		ide_init();
#else
	ide_init();
#endif
#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

#if defined(CONFIG_CMD_BEDBUG)
	WATCHDOG_RESET();
	bedbug_init();
#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;
		char 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(memsz, "%ldk", (ulong) (bd->bi_memsize / 1024) - pram);
		setenv("mem", memsz);
	}
#endif

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

	/* Initialization complete - start the monitor */

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

	/* NOTREACHED - no way out of command loop except booting */
}
示例#20
0
void board_init_r(gd_t *id, ulong dest_addr)
{
	char *s;
	bd_t *bd;
	ulong malloc_start;
#if !defined(CONFIG_SYS_NO_FLASH)
	ulong flash_size;
#endif

	gd = id;
	bd = gd->bd;

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

	monitor_flash_len = _end_ofs;
	/*
	 * Enable D$:
	 * I$, if needed, must be already enabled in start.S
	 */
	dcache_enable();

	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 */
	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
		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

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

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

#ifdef CONFIG_GENERIC_MMC
       puts("MMC:   ");
       mmc_initialize(bd);
#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

	/* 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

	 /* 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 */
	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", (bd->bi_memsize / 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 */
}
示例#21
0
文件: main.c 项目: bigbig6/tvheadend
int
main(int argc, char **argv)
{
  int i;
  sigset_t set;
#if ENABLE_MPEGTS
  uint32_t adapter_mask = 0;
#endif
  int  log_level   = LOG_INFO;
  int  log_options = TVHLOG_OPT_MILLIS | TVHLOG_OPT_STDERR | TVHLOG_OPT_SYSLOG;
  const char *log_debug = NULL, *log_trace = NULL;
  gid_t gid = -1;
  uid_t uid = -1;
  char buf[512];
  FILE *pidfile = NULL;
  extern int dvb_bouquets_parse;

  main_tid = pthread_self();

  /* Setup global mutexes */
  pthread_mutex_init(&fork_lock, NULL);
  pthread_mutex_init(&global_lock, NULL);
  pthread_mutex_init(&tasklet_lock, NULL);
  pthread_mutex_init(&atomic_lock, NULL);
  pthread_cond_init(&gtimer_cond, NULL);
  pthread_cond_init(&tasklet_cond, NULL);
  TAILQ_INIT(&tasklets);

  /* Defaults */
  tvheadend_webui_port      = 9981;
  tvheadend_webroot         = NULL;
  tvheadend_htsp_port       = 9982;
  tvheadend_htsp_port_extra = 0;
  time(&dispatch_clock);

  /* Command line options */
  int         opt_help         = 0,
              opt_version      = 0,
              opt_fork         = 0,
              opt_firstrun     = 0,
              opt_stderr       = 0,
              opt_syslog       = 0,
              opt_nosyslog     = 0,
              opt_uidebug      = 0,
              opt_abort        = 0,
              opt_noacl        = 0,
              opt_fileline     = 0,
              opt_threadid     = 0,
              opt_libav        = 0,
              opt_ipv6         = 0,
              opt_satip_rtsp   = 0,
#if ENABLE_TSFILE
              opt_tsfile_tuner = 0,
#endif
              opt_dump         = 0,
              opt_xspf         = 0,
              opt_dbus         = 0,
              opt_dbus_session = 0,
              opt_nobackup     = 0,
              opt_nobat        = 0;
  const char *opt_config       = NULL,
             *opt_user         = NULL,
             *opt_group        = NULL,
             *opt_logpath      = NULL,
             *opt_log_debug    = NULL,
             *opt_log_trace    = NULL,
             *opt_pidpath      = "/var/run/tvheadend.pid",
#if ENABLE_LINUXDVB
             *opt_dvb_adapters = NULL,
#endif
             *opt_bindaddr     = NULL,
             *opt_subscribe    = NULL,
             *opt_user_agent   = NULL;
  str_list_t  opt_satip_xml    = { .max = 10, .num = 0, .str = calloc(10, sizeof(char*)) };
  str_list_t  opt_tsfile       = { .max = 10, .num = 0, .str = calloc(10, sizeof(char*)) };
  cmdline_opt_t cmdline_opts[] = {
    {   0, NULL,        N_("Generic Options"),         OPT_BOOL, NULL         },
    { 'h', "help",      N_("Show this page"),          OPT_BOOL, &opt_help    },
    { 'v', "version",   N_("Show version information"),OPT_BOOL, &opt_version },

    {   0, NULL,        N_("Service Configuration"),   OPT_BOOL, NULL         },
    { 'c', "config",    N_("Alternate config path"),   OPT_STR,  &opt_config  },
    { 'B', "nobackup",  N_("Don't backup config tree at upgrade"), OPT_BOOL, &opt_nobackup },
    { 'f', "fork",      N_("Fork and run as daemon"),  OPT_BOOL, &opt_fork    },
    { 'u', "user",      N_("Run as user"),             OPT_STR,  &opt_user    },
    { 'g', "group",     N_("Run as group"),            OPT_STR,  &opt_group   },
    { 'p', "pid",       N_("Alternate pid path"),      OPT_STR,  &opt_pidpath },
    { 'C', "firstrun",  N_("If no user account exists then create one with\n"
	                   "no username and no password. Use with care as\n"
	                   "it will allow world-wide administrative access\n"
	                   "to your Tvheadend installation until you edit/create\n"
	                   "access-control from within the Tvheadend UI"),
      OPT_BOOL, &opt_firstrun },
#if ENABLE_DBUS_1
    { 'U', "dbus",      N_("Enable DBus"),
      OPT_BOOL, &opt_dbus },
    { 'e', "dbus_session", N_("DBus - use the session message bus instead system one"),
      OPT_BOOL, &opt_dbus_session },
#endif
#if ENABLE_LINUXDVB
    { 'a', "adapters",  N_("Only use specified DVB adapters (comma separated)"),
      OPT_STR, &opt_dvb_adapters },
#endif
#if ENABLE_SATIP_SERVER
    {   0, "satip_rtsp", N_("SAT>IP RTSP port number for server\n"
                            "(default: -1 = disable, 0 = webconfig, standard port is 554)"),
      OPT_INT, &opt_satip_rtsp },
#endif
#if ENABLE_SATIP_CLIENT
    {   0, "satip_xml", N_("URL with the SAT>IP server XML location"),
      OPT_STR_LIST, &opt_satip_xml },
#endif
    {   0, NULL,         N_("Server Connectivity"),    OPT_BOOL, NULL         },
    { '6', "ipv6",       N_("Listen on IPv6"),         OPT_BOOL, &opt_ipv6    },
    { 'b', "bindaddr",   N_("Specify bind address"),   OPT_STR,  &opt_bindaddr},
    {   0, "http_port",  N_("Specify alternative http port"),
      OPT_INT, &tvheadend_webui_port },
    {   0, "http_root",  N_("Specify alternative http webroot"),
      OPT_STR, &tvheadend_webroot },
    {   0, "htsp_port",  N_("Specify alternative htsp port"),
      OPT_INT, &tvheadend_htsp_port },
    {   0, "htsp_port2", N_("Specify extra htsp port"),
      OPT_INT, &tvheadend_htsp_port_extra },
    {   0, "useragent",  N_("Specify User-Agent header for the http client"),
      OPT_STR, &opt_user_agent },
    {   0, "xspf",       N_("Use XSPF playlist instead of M3U"),
      OPT_BOOL, &opt_xspf },

    {   0, NULL,        N_("Debug Options"),           OPT_BOOL, NULL         },
    { 'd', "stderr",    N_("Enable debug on stderr"),  OPT_BOOL, &opt_stderr  },
    { 's', "syslog",    N_("Enable debug to syslog"),  OPT_BOOL, &opt_syslog  },
    { 'S', "nosyslog",  N_("Disable syslog (all msgs)"), OPT_BOOL, &opt_nosyslog },
    { 'l', "logfile",   N_("Enable debug to file"),    OPT_STR,  &opt_logpath },
    {   0, "debug",     N_("Enable debug subsystems"),  OPT_STR,  &opt_log_debug },
#if ENABLE_TRACE
    {   0, "trace",     N_("Enable trace subsystems"), OPT_STR,  &opt_log_trace },
#endif
    {   0, "fileline",  N_("Add file and line numbers to debug"), OPT_BOOL, &opt_fileline },
    {   0, "threadid",  N_("Add the thread ID to debug"), OPT_BOOL, &opt_threadid },
#if ENABLE_LIBAV
    {   0, "libav",     N_("More verbose libav log"),  OPT_BOOL, &opt_libav },
#endif
    {   0, "uidebug",   N_("Enable webUI debug (non-minified JS)"), OPT_BOOL, &opt_uidebug },
    { 'A', "abort",     N_("Immediately abort"),       OPT_BOOL, &opt_abort   },
    { 'D', "dump",      N_("Enable coredumps for daemon"), OPT_BOOL, &opt_dump },
    {   0, "noacl",     N_("Disable all access control checks"),
      OPT_BOOL, &opt_noacl },
    {   0, "nobat",     N_("Disable DVB bouquets"),
      OPT_BOOL, &opt_nobat },
    { 'j', "join",      N_("Subscribe to a service permanently"),
      OPT_STR, &opt_subscribe },


#if ENABLE_TSFILE || ENABLE_TSDEBUG
    { 0, NULL, N_("Testing options"), OPT_BOOL, NULL },
    { 0, "tsfile_tuners", N_("Number of tsfile tuners"), OPT_INT, &opt_tsfile_tuner },
    { 0, "tsfile", N_("tsfile input (mux file)"), OPT_STR_LIST, &opt_tsfile },
#endif
#if ENABLE_TSDEBUG
    { 0, "tsdebug", N_("Output directory for tsdebug"), OPT_STR, &tvheadend_tsdebug },
#endif

  };

  /* Get current directory */
  tvheadend_cwd0 = dirname(tvh_strdupa(argv[0]));
  tvheadend_cwd = dirname(tvh_strdupa(tvheadend_cwd0));

  /* Set locale */
  setlocale(LC_ALL, "");
  setlocale(LC_NUMERIC, "C");

  /* make sure the timezone is set */
  tzset();

  /* Process command line */
  for (i = 1; i < argc; i++) {

    /* Find option */
    cmdline_opt_t *opt
      = cmdline_opt_find(cmdline_opts, ARRAY_SIZE(cmdline_opts), argv[i]);
    if (!opt)
      show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts),
                 _("invalid option specified [%s]"), argv[i]);

    /* Process */
    if (opt->type == OPT_BOOL)
      *((int*)opt->param) = 1;
    else if (++i == argc)
      show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts),
                 _("option %s requires a value"), opt->lopt);
    else if (opt->type == OPT_INT)
      *((int*)opt->param) = atoi(argv[i]);
    else if (opt->type == OPT_STR_LIST) {
      str_list_t *strl = opt->param;
      if (strl->num < strl->max)
        strl->str[strl->num++] = argv[i];
    }
    else
      *((char**)opt->param) = argv[i];

    /* Stop processing */
    if (opt_help)
      show_usage(argv[0], cmdline_opts, ARRAY_SIZE(cmdline_opts), NULL);
    if (opt_version)
      show_version(argv[0]);
  }

  /* Additional cmdline processing */
  if (opt_nobat)
    dvb_bouquets_parse = 0;
#if ENABLE_LINUXDVB
  if (!opt_dvb_adapters) {
    adapter_mask = ~0;
  } else {
    char *p, *e;
    char *r = NULL;
    char *dvb_adapters = strdup(opt_dvb_adapters);
    adapter_mask = 0x0;
    p = strtok_r(dvb_adapters, ",", &r);
    while (p) {
      int a = strtol(p, &e, 10);
      if (*e != 0 || a < 0 || a > 31) {
        fprintf(stderr, _("Invalid adapter number '%s'\n"), p);
        free(dvb_adapters);
        return 1;
      }
      adapter_mask |= (1 << a);
      p = strtok_r(NULL, ",", &r);
    }
    free(dvb_adapters);
    if (!adapter_mask) {
      fprintf(stderr, "%s", _("No adapters specified!\n"));
      return 1;
    }
  }
#endif
  if (tvheadend_webroot) {
    char *tmp;
    if (*tvheadend_webroot == '/')
      tmp = strdup(tvheadend_webroot);
    else {
      tmp = malloc(strlen(tvheadend_webroot)+2);
      *tmp = '/';
      strcpy(tmp+1, tvheadend_webroot);
    }
    if (tmp[strlen(tmp)-1] == '/')
      tmp[strlen(tmp)-1] = '\0';
    tvheadend_webroot = tmp;
  }
  tvheadend_webui_debug = opt_uidebug;

  /* Setup logging */
  if (isatty(2))
    log_options |= TVHLOG_OPT_DECORATE;
  if (opt_stderr || opt_syslog || opt_logpath) {
    if (!opt_log_trace && !opt_log_debug)
      log_debug      = "all";
    log_level      = LOG_DEBUG;
    if (opt_stderr)
      log_options   |= TVHLOG_OPT_DBG_STDERR;
    if (opt_syslog)
      log_options   |= TVHLOG_OPT_DBG_SYSLOG;
    if (opt_logpath)
      log_options   |= TVHLOG_OPT_DBG_FILE;
  }
  if (opt_nosyslog)
    log_options &= ~(TVHLOG_OPT_SYSLOG|TVHLOG_OPT_DBG_SYSLOG);
  if (opt_fileline)
    log_options |= TVHLOG_OPT_FILELINE;
  if (opt_threadid)
    log_options |= TVHLOG_OPT_THREAD;
  if (opt_libav)
    log_options |= TVHLOG_OPT_LIBAV;
  if (opt_log_trace) {
    log_level  = LOG_TRACE;
    log_trace  = opt_log_trace;
  }
  if (opt_log_debug)
    log_debug  = opt_log_debug;
    
  tvhlog_init(log_level, log_options, opt_logpath);
  tvhlog_set_debug(log_debug);
  tvhlog_set_trace(log_trace);
  tvhinfo("main", "Log started");
 
  signal(SIGPIPE, handle_sigpipe); // will be redundant later
  signal(SIGILL, handle_sigill);   // see handler..

  /* Set priviledges */
  if(opt_fork || opt_group || opt_user) {
    const char *homedir;
    struct group  *grp = getgrnam(opt_group ?: "video");
    struct passwd *pw  = opt_user ? getpwnam(opt_user) : NULL;

    if(grp != NULL) {
      gid = grp->gr_gid;
    } else {
      gid = 1;
    }

    if (pw != NULL) {
      if (getuid() != pw->pw_uid) {
        gid_t glist[16];
        int gnum;
        gnum = get_user_groups(pw, glist, ARRAY_SIZE(glist));
        if (gnum > 0 && setgroups(gnum, glist)) {
          char buf[256] = "";
          int i;
          for (i = 0; i < gnum; i++)
            snprintf(buf + strlen(buf), sizeof(buf) - 1 - strlen(buf),
                     ",%d", glist[i]);
          tvhlog(LOG_ALERT, "START",
                 "setgroups(%s) failed, do you have permission?", buf+1);
          return 1;
        }
      }
      uid     = pw->pw_uid;
      homedir = pw->pw_dir;
      setenv("HOME", homedir, 1);
    } else {
      uid = 1;
    }
  }

  uuid_init();
  config_boot(opt_config, gid, uid);
  tcp_server_preinit(opt_ipv6);
  http_server_init(opt_bindaddr);    // bind to ports only
  htsp_init(opt_bindaddr);	     // bind to ports only
  satip_server_init(opt_satip_rtsp); // bind to ports only

  if (opt_fork)
    pidfile = tvh_fopen(opt_pidpath, "w+");

  if (gid != -1 && (getgid() != gid) && setgid(gid)) {
    tvhlog(LOG_ALERT, "START",
           "setgid(%d) failed, do you have permission?", gid);
    return 1;
  }
  if (uid != -1 && (getuid() != uid) && setuid(uid)) {
    tvhlog(LOG_ALERT, "START",
           "setuid(%d) failed, do you have permission?", uid);
    return 1;
  }

  /* Daemonise */
  if(opt_fork) {
    if(daemon(0, 0)) {
      exit(2);
    }
    if(pidfile != NULL) {
      fprintf(pidfile, "%d\n", getpid());
      fclose(pidfile);
    }

    /* Make dumpable */
    if (opt_dump) {
#ifdef PLATFORM_LINUX
      if (chdir("/tmp"))
        tvhwarn("START", "failed to change cwd to /tmp");
      prctl(PR_SET_DUMPABLE, 1);
#else
      tvhwarn("START", "Coredumps not implemented on your platform");
#endif
    }

    umask(0);
  }

  tvheadend_running = 1;

  /* Start log thread (must be done post fork) */
  tvhlog_start();

  /* Alter logging */
  if (opt_fork)
    tvhlog_options &= ~TVHLOG_OPT_STDERR;
  if (!isatty(2))
    tvhlog_options &= ~TVHLOG_OPT_DECORATE;
  
  /* Initialise clock */
  pthread_mutex_lock(&global_lock);
  time(&dispatch_clock);

  /* Signal handling */
  sigfillset(&set);
  sigprocmask(SIG_BLOCK, &set, NULL);
  trap_init(argv[0]);

  /* SSL library init */
  OPENSSL_config(NULL);
  SSL_load_error_strings();
  SSL_library_init();

  /* Initialise configuration */
  notify_init();
  idnode_init();
  spawn_init();
  config_init(opt_nobackup == 0);

  /**
   * Initialize subsystems
   */

  epg_in_load = 1;

  tvhthread_create(&tasklet_tid, NULL, tasklet_thread, NULL);

  dbus_server_init(opt_dbus, opt_dbus_session);

  intlconv_init();
  
  api_init();

  fsmonitor_init();

  libav_init();

  tvhtime_init();

  profile_init();

  imagecache_init();

  http_client_init(opt_user_agent);
  esfilter_init();

  bouquet_init();

  service_init();

  dvb_init();

#if ENABLE_MPEGTS
  mpegts_init(adapter_mask, &opt_satip_xml, &opt_tsfile, opt_tsfile_tuner);
#endif

  channel_init();

  bouquet_service_resolve();

  subscription_init();

  dvr_config_init();

  access_init(opt_firstrun, opt_noacl);

#if ENABLE_TIMESHIFT
  timeshift_init();
#endif

  tcp_server_init();
  webui_init(opt_xspf);
#if ENABLE_UPNP
  upnp_server_init(opt_bindaddr);
#endif

  service_mapper_init();

  descrambler_init();

  epggrab_init();
  epg_init();

  dvr_init();

  dbus_server_start();

  http_server_register();
  satip_server_register();
  htsp_register();

  if(opt_subscribe != NULL)
    subscription_dummy_join(opt_subscribe, 1);

  avahi_init();
  bonjour_init();

  epg_updated(); // cleanup now all prev ref's should have been created
  epg_in_load = 0;

  pthread_mutex_unlock(&global_lock);

  /**
   * Wait for SIGTERM / SIGINT, but only in this thread
   */

  sigemptyset(&set);
  sigaddset(&set, SIGTERM);
  sigaddset(&set, SIGINT);

  signal(SIGTERM, doexit);
  signal(SIGINT, doexit);

  pthread_sigmask(SIG_UNBLOCK, &set, NULL);

  tvhlog(LOG_NOTICE, "START", "HTS Tvheadend version %s started, "
         "running as PID:%d UID:%d GID:%d, CWD:%s CNF:%s",
         tvheadend_version,
         getpid(), getuid(), getgid(), getcwd(buf, sizeof(buf)),
         hts_settings_get_root());

  if(opt_abort)
    abort();

  mainloop();

#if ENABLE_DBUS_1
  tvhftrace("main", dbus_server_done);
#endif
#if ENABLE_UPNP
  tvhftrace("main", upnp_server_done);
#endif
  tvhftrace("main", satip_server_done);
  tvhftrace("main", htsp_done);
  tvhftrace("main", http_server_done);
  tvhftrace("main", webui_done);
  tvhftrace("main", fsmonitor_done);
  tvhftrace("main", http_client_done);
  tvhftrace("main", tcp_server_done);

  // Note: the locking is obviously a bit redundant, but without
  //       we need to disable the gtimer_arm call in epg_save()
  pthread_mutex_lock(&global_lock);
  tvhftrace("main", epg_save);

#if ENABLE_TIMESHIFT
  tvhftrace("main", timeshift_term);
#endif
  pthread_mutex_unlock(&global_lock);

  tvhftrace("main", epggrab_done);
#if ENABLE_MPEGTS
  tvhftrace("main", mpegts_done);
#endif
  tvhftrace("main", descrambler_done);
  tvhftrace("main", service_mapper_done);
  tvhftrace("main", service_done);
  tvhftrace("main", channel_done);
  tvhftrace("main", bouquet_done);
  tvhftrace("main", dvr_done);
  tvhftrace("main", subscription_done);
  tvhftrace("main", access_done);
  tvhftrace("main", epg_done);
  tvhftrace("main", avahi_done);
  tvhftrace("main", bonjour_done);
  tvhftrace("main", imagecache_done);
  tvhftrace("main", lang_code_done);
  tvhftrace("main", api_done);

  tvhtrace("main", "tasklet enter");
  pthread_cond_signal(&tasklet_cond);
  pthread_join(tasklet_tid, NULL);
  tvhtrace("main", "tasklet thread end");
  tasklet_flush();
  tvhtrace("main", "tasklet leave");

  tvhftrace("main", hts_settings_done);
  tvhftrace("main", dvb_done);
  tvhftrace("main", lang_str_done);
  tvhftrace("main", esfilter_done);
  tvhftrace("main", profile_done);
  tvhftrace("main", intlconv_done);
  tvhftrace("main", urlparse_done);
  tvhftrace("main", idnode_done);
  tvhftrace("main", notify_done);
  tvhftrace("main", spawn_done);

  tvhlog(LOG_NOTICE, "STOP", "Exiting HTS Tvheadend");
  tvhlog_end();

  tvhftrace("main", config_done);

  if(opt_fork)
    unlink(opt_pidpath);
    
#if ENABLE_TSFILE
  free(opt_tsfile.str);
#endif
  free(opt_satip_xml.str);

  /* OpenSSL - welcome to the "cleanup" hell */
  ENGINE_cleanup();
  RAND_cleanup();
  CRYPTO_cleanup_all_ex_data();
  EVP_cleanup();
  CONF_modules_free();
#ifndef OPENSSL_NO_COMP
  COMP_zlib_cleanup();
#endif
  ERR_remove_state(0);
  ERR_free_strings();
#ifndef OPENSSL_NO_COMP
  sk_SSL_COMP_free(SSL_COMP_get_compression_methods());
#endif
  /* end of OpenSSL cleanup code */

#if ENABLE_DBUS_1
  extern void dbus_shutdown(void);
  if (opt_dbus) dbus_shutdown();
#endif
  return 0;
}

/**
 *
 */
void
tvh_str_set(char **strp, const char *src)
{
  free(*strp);
  *strp = src ? strdup(src) : NULL;
}


/**
 *
 */
int
tvh_str_update(char **strp, const char *src)
{
  if(src == NULL)
    return 0;
  free(*strp);
  *strp = strdup(src);
  return 1;
}


/**
 *
 */
void
scopedunlock(pthread_mutex_t **mtxp)
{
  pthread_mutex_unlock(*mtxp);
}
示例#22
0
文件: api_main.c 项目: neufbox/misc
static void __attribute__ ( ( constructor ) ) __init( void )
{
    api_init(  );
}
示例#23
0
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;

	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_NONCACHE_MEMORY
	mem_noncache_malloc_init(malloc_noncache_start, CONFIG_NONCACHE_MEMORY_SIZE);
#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;
#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 CONFIG_ALLWINNER
#ifdef DEBUG
    puts("ready to config storage\n");
#endif
	if((workmode == WORK_MODE_BOOT) || (workmode == WORK_MODE_CARD_PRODUCT))
	{
#if defined(CONFIG_SUNXI_DISPLAY)
	    drv_disp_init();
#endif
		board_display_device_open();
		board_display_layer_request();
	}

	ret = sunxi_flash_handle_init();
	if(!ret)
	{
		sunxi_partition_init();
	}
#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*/

#endif/*CONFIG_ALLWINNER*/

#ifdef 	CONFIG_ARCH_HOMELET
extern int check_boot_recovery_key();
extern int sprite_form_sysrecovery();
extern int sprite_led_init(void);
extern int sprite_led_exit(int status);
	if (!check_boot_recovery_key())
	{
		sprite_led_init();
		ret = sprite_form_sysrecovery();
		sprite_led_exit(ret);
	}
#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

	/* 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;
			FIL  script_fs;
			uchar  *buf = NULL;

			f_mount(0, &script_mount);
			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);
			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");
#ifdef CONFIG_ALLWINNER
#if (defined(CONFIG_SUN6I) || defined(CONFIG_A50) || defined(CONFIG_SUN7I))
		if(!ret)
		{
#ifndef CONFIG_ARCH_HOMELET
			printf("board_status_probe\n");
			board_status_probe(0);
#endif
			printf("sunxi_bmp_display\n");
			sunxi_bmp_display("bootlogo.bmp");
		}
#endif
		printf("WORK_MODE_BOOT\n");
#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 */
}
示例#24
0
文件: board.c 项目: BeanGu/U-boot
void board_init_r(gd_t *id, ulong dest_addr)
{
	ulong malloc_start;
#if !defined(CONFIG_SYS_NO_FLASH)
	ulong flash_size;
#endif

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

	monitor_flash_len = (ulong)&__rel_dyn_end - (ulong)_start;

	/* 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
	serial_initialize();

	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);

#ifdef CONFIG_ARCH_EARLY_INIT_R
	arch_early_init_r();
#endif
	power_init_board();

#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
		 */
		if (getenv_yesno("flashchecksum") == 1) {
			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_GENERIC_MMC
	puts("MMC:   ");
	mmc_initialize(gd->bd);
#endif

#ifdef CONFIG_CMD_SCSI
	puts("SCSI:  ");
	scsi_init();
#endif

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

	/* initialize environment */
	if (should_load_env())
		env_relocate();
	else
		set_default_env(NULL);

#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 */

#ifdef CONFIG_DISPLAY_BOARDINFO_LATE
# ifdef CONFIG_OF_CONTROL
	/* Put this here so it appears on the LCD, now it is ready */
	display_fdt_model(gd->fdt_blob);
# else
	checkboard();
# endif
#endif

#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();

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

#ifdef CONFIG_BOARD_LATE_INIT
	board_late_init();
#endif

#ifdef CONFIG_FASTBOOT
	fastboot_setup();
#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_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

#ifdef CONFIG_FASTBOOT
	check_fastboot();
#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 */
}
示例#25
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;/*u-boot.lds中定义*/

	/* 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
#ifndef CONFIG_CPU_EXYNOS5410
	serial_initialize();
#endif
#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);

#ifdef CONFIG_ARCH_EARLY_INIT_R
	arch_early_init_r();
#endif

#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_GENERIC_MMC
       puts("MMC:   ");
       mmc_initialize(gd->bd);
#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();//晚点执行的初始化在smdk5420.c
#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_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 */
}
示例#26
0
/**
 * Showtime main
 */
int
main(int argc, char **argv)
{
    struct timeval tv;
    const char *settingspath = NULL;
    const char *uiargs[16];
    const char *argv0 = argc > 0 ? argv[0] : "showtime";
    const char *forceview = NULL;
    int nuiargs = 0;
    int can_standby = 0;
    int can_poweroff = 0;
    int r;

    trace_level = TRACE_INFO;

    gettimeofday(&tv, NULL);
    srand(tv.tv_usec);

    arch_set_default_paths(argc, argv);

    /* We read options ourselfs since getopt() is broken on some (nintento wii)
       targets */

    argv++;
    argc--;

    while(argc > 0) {
        if(!strcmp(argv[0], "-h") || !strcmp(argv[0], "--help")) {
            printf("HTS Showtime %s\n"
                   "Copyright (C) 2007-2010 Andreas Öman\n"
                   "\n"
                   "Usage: %s [options] [<url>]\n"
                   "\n"
                   "  Options:\n"
                   "   -h, --help        - This help text.\n"
                   "   -d                - Enable debug output.\n"
                   "   --ffmpeglog       - Print ffmpeg log messages.\n"
                   "   --with-standby    - Enable system standby.\n"
                   "   --with-poweroff   - Enable system power-off.\n"
                   "   -s <path>         - Non-default Showtime settings path.\n"
                   "   --ui <ui>         - Use specified user interface.\n"
                   "   -L <ip:host>      - Send log messages to remote <ip:host>.\n"
                   "   --syslog          - Send log messages to syslog.\n"
#if ENABLE_STDIN
                   "   --stdin           - Listen on stdin for events.\n"
#endif
                   "   -v <view>         - Use specific view for <url>.\n"
                   "   --cache <path>    - Set path for cache [%s].\n"
#if ENABLE_SERDEV
                   "   --serdev          - Probe service ports for devices.\n"
#endif
                   "\n"
                   "  URL is any URL-type supported by Showtime, "
                   "e.g., \"file:///...\"\n"
                   "\n",
                   htsversion_full,
                   argv0,
                   showtime_cache_path);
            exit(0);
            argc--;
            argv++;

        } else if(!strcmp(argv[0], "-d")) {
            trace_level++;
            argc -= 1;
            argv += 1;
            continue;
        } else if(!strcmp(argv[0], "--ffmpeglog")) {
            ffmpeglog = 1;
            argc -= 1;
            argv += 1;
            continue;
        } else if(!strcmp(argv[0], "--syslog")) {
            trace_to_syslog = 1;
            argc -= 1;
            argv += 1;
            continue;
        } else if(!strcmp(argv[0], "--stdin")) {
            listen_on_stdin = 1;
            argc -= 1;
            argv += 1;
            continue;
#if ENABLE_SERDEV
        } else if(!strcmp(argv[0], "--serdev")) {
            enable_serdev = 1;
            argc -= 1;
            argv += 1;
            continue;
#endif
        } else if(!strcmp(argv[0], "--with-standby")) {
            can_standby = 1;
            argc -= 1;
            argv += 1;
            continue;
        } else if(!strcmp(argv[0], "--with-poweroff")) {
            can_poweroff = 1;
            argc -= 1;
            argv += 1;
            continue;
        } else if(!strcmp(argv[0], "-s") && argc > 1) {
            settingspath = argv[1];
            argc -= 2;
            argv += 2;
            continue;
        } else if(!strcmp(argv[0], "--ui") && argc > 1) {
            if(nuiargs < 16)
                uiargs[nuiargs++] = argv[1];
            argc -= 2;
            argv += 2;
            continue;
        } else if(!strcmp(argv[0], "-L") && argc > 1) {
            showtime_logtarget = argv[1];
            argc -= 2;
            argv += 2;
            continue;
        } else if (!strcmp(argv[0], "-v") && argc > 1) {
            forceview = argv[1];
            argc -= 2;
            argv += 2;
        } else if (!strcmp(argv[0], "--cache") && argc > 1) {
            mystrset(&showtime_cache_path, argv[1]);
            argc -= 2;
            argv += 2;
#ifdef __APPLE__
            /* ignore -psn argument, process serial number */
        } else if(!strncmp(argv[0], "-psn", 4)) {
            argc -= 1;
            argv += 1;
            continue;
#endif
        } else
            break;
    }


    unicode_init();

    /* Initialize property tree */
    prop_init();
    init_global_info();

    /* Initiailize logging */
    trace_init();

    /* Callout framework */
    callout_init();

    /* Notification framework */
    notifications_init();

    /* Architecture specific init */
    arch_init();

    htsmsg_store_init();

    /* Try to create cache path */
    if(showtime_cache_path != NULL &&
            (r = makedirs(showtime_cache_path)) != 0) {
        TRACE(TRACE_ERROR, "cache", "Unable to create cache path %s -- %s",
              showtime_cache_path, strerror(r));
        showtime_cache_path = NULL;
    }

    /* Initializte blob cache */
    blobcache_init();

    /* Try to create settings path */
    if(showtime_settings_path != NULL &&
            (r = makedirs(showtime_settings_path)) != 0) {
        TRACE(TRACE_ERROR, "settings", "Unable to create settings path %s -- %s",
              showtime_settings_path, strerror(r));
        showtime_settings_path = NULL;
    }

    /* Initialize keyring */
    keyring_init();

    /* Initialize settings */
    settings_init();

    /* Initialize libavcodec & libavformat */
    av_lockmgr_register(fflockmgr);
    av_log_set_callback(fflog);
    av_register_all();

    /* Freetype keymapper */
#if ENABLE_LIBFREETYPE
    freetype_init();
#endif

    /* Global keymapper */
    keymapper_init();

    /* Initialize media subsystem */
    media_init();

    /* Service handling */
    service_init();

    /* Initialize backend content handlers */
    backend_init();

    /* Initialize navigator */
    nav_init();

    /* Initialize audio subsystem */
    audio_init();

    /* Initialize bookmarks */
    bookmarks_init();

    /* Initialize plugin manager and load plugins */
    plugins_init();

    /* Internationalization */
    i18n_init();


    nav_open(NAV_HOME, NULL);

    /* Open initial page */
    if(argc > 0)
        nav_open(argv[0], forceview);

    /* Various interprocess communication stuff (D-Bus on Linux, etc) */
    ipc_init();

    /* Service discovery. Must be after ipc_init() (d-bus and threads, etc) */
    sd_init();

    /* Initialize various external APIs */
    api_init();

    /* HTTP server and UPNP */
#if ENABLE_HTTPSERVER
    http_server_init();
    upnp_init();
#endif


    /* */
    runcontrol_init(can_standby, can_poweroff);

    TRACE(TRACE_DEBUG, "core", "Starting UI");

    /* Initialize user interfaces */
    ui_start(nuiargs, uiargs, argv0);

    finalize();
}
示例#27
0
文件: main.c 项目: Agilack/eCow-logic
int main(void)
{
  dhcp dhcp_session;
  int  dhcp_state;
  http_server http;
  http_socket httpsock[4];
  http_content httpcontent[4];
  char oled_msg[17];
  char *pnt;
  int   step;

  api_init();
  uart_puts(" * eCowLogic firmware \r\n");

  hw_systick( hw_getfreq() / 1000 );

  dhcp_session.socket = 2;
  dhcp_session.buffer = (u8 *)buffer_dhcp;
  dhcp_init(&dhcp_session);
  
  oled_pos(1, 0);
  oled_puts("Reseau (DHCP)   ");
  step = 0;
  while(1)
  {
    dhcp_state = dhcp_run(&dhcp_session);
    if (dhcp_state == DHCP_IP_LEASED)
      break;
    step++;
    oled_pos(1, 13);
    if (step == 1) oled_puts(".  ");
    if (step == 2) oled_puts(".. ");
    if (step == 3) oled_puts("...");
    if (step == 4)
    {
      step = 0;
      dhcp_session.tick_1s++;
      uart_putc('.');
      oled_puts("   ");
    }
    delay(250);
  }
  pnt = oled_msg;
  pnt += b2ds(pnt, dhcp_session.dhcp_my_ip[0]); *pnt++ = '.';
  pnt += b2ds(pnt, dhcp_session.dhcp_my_ip[1]); *pnt++ = '.';
  pnt += b2ds(pnt, dhcp_session.dhcp_my_ip[2]); *pnt++ = '.';
  pnt += b2ds(pnt, dhcp_session.dhcp_my_ip[3]);
  for ( ; pnt < (oled_msg + 16); pnt++)
    *pnt = ' ';
  oled_msg[16] = 0;
  uart_puts("DHCP: LEASED ! ");
  uart_puts(oled_msg); uart_puts("\r\n");
  oled_pos(1, 0);
  oled_puts(oled_msg);
  
  spi_init();
  pld_init();

  //net_init();
  
  /* Init HTTP content */
  strcpy(httpcontent[0].name, "/pld");
  httpcontent[0].wildcard = 0;
  httpcontent[0].cgi = cgi_ng_pld;
  httpcontent[0].next = &httpcontent[1];
  /* Init HTTP content */
  strcpy(httpcontent[1].name, "/spi");
  httpcontent[1].wildcard = 0;
  httpcontent[1].cgi = cgi_spi;
  httpcontent[1].next = &httpcontent[2];
  /* Init HTTP content */
  strcpy(httpcontent[2].name, "/infos");
  httpcontent[2].wildcard = 0;
  httpcontent[2].cgi = cgi_info;
  httpcontent[2].next = &httpcontent[3];
  /* Init HTTP content */
  strcpy(httpcontent[3].name, "/");
  httpcontent[3].wildcard = 1;
  httpcontent[3].cgi = cgi_ng_page;
  httpcontent[3].next = 0;
  /* Init HTTP socket */
  httpsock[0].id = 4;
  httpsock[0].state = 0;
  httpsock[0].server = &http;
  httpsock[0].next = &httpsock[1];
  /* Init HTTP socket */
  httpsock[1].id = 5;
  httpsock[1].state = 0;
  httpsock[1].server = &http;
  httpsock[1].next = &httpsock[2];
  /* Init HTTP socket */
  httpsock[2].id = 6;
  httpsock[2].state = 0;
  httpsock[2].server = &http;
  httpsock[2].next = &httpsock[3];
  /* Init HTTP socket */
  httpsock[3].id = 7;
  httpsock[3].state = 0;
  httpsock[3].server = &http;
  httpsock[3].next = 0;
  /* Init the new HTTP layer */
  http.port   = 80;
  http.err404 = 0;
  http.err403 = 0;
  http.keepalive = 10;
  http.socks  = &httpsock[0];
  http.contents = &httpcontent[0];
  http_init(&http);
  
  while(1)
  {
    http_run(&http);
  }
}
示例#28
0
int main(int argc, char **argv) {
	int exit_code = EXIT_FAILURE;
	int i;
	bool help = false;
	bool version = false;
	bool check_config = false;
	bool daemon = false;
	const char *debug_filter = NULL;
	int pid_fd = -1;

	for (i = 1; i < argc; ++i) {
		if (strcmp(argv[i], "--help") == 0) {
			help = true;
		} else if (strcmp(argv[i], "--version") == 0) {
			version = true;
		} else if (strcmp(argv[i], "--check-config") == 0) {
			check_config = true;
		} else if (strcmp(argv[i], "--daemon") == 0) {
			daemon = true;
		} else if (strcmp(argv[i], "--debug") == 0) {
			if (i + 1 < argc && strncmp(argv[i + 1], "--", 2) != 0) {
				debug_filter = argv[++i];
			} else {
				debug_filter = "";
			}
		} else {
			fprintf(stderr, "Unknown option '%s'\n\n", argv[i]);
			print_usage();

			return EXIT_FAILURE;
		}
	}

	if (help) {
		print_usage();

		return EXIT_SUCCESS;
	}

	if (version) {
		printf("%s\n", VERSION_STRING);

		return EXIT_SUCCESS;
	}

	read_image_version();

	_x11_enabled = access("/etc/tf_x11_enabled", F_OK) == 0;

	if (prepare_paths() < 0) {
		return EXIT_FAILURE;
	}

	if (check_config) {
		return config_check(_config_filename) < 0 ? EXIT_FAILURE : EXIT_SUCCESS;
	}

	config_init(_config_filename);

	if (config_has_error()) {
		fprintf(stderr, "Error(s) occurred while reading config file '%s'",
		        _config_filename);

		goto error_config;
	}

	log_init();

	if (daemon) {
		pid_fd = daemon_start(_log_filename, _pid_filename, 1);
	} else {
		pid_fd = pid_file_acquire(_pid_filename, getpid());

		if (pid_fd == PID_FILE_ALREADY_ACQUIRED) {
			fprintf(stderr, "Already running according to '%s'\n", _pid_filename);
		}
	}

	if (pid_fd < 0) {
		goto error_pid_file;
	}

	if (daemon && _x11_enabled) {
		log_info("RED Brick API Daemon %s started (daemonized, X11 enabled) on %s image",
		         VERSION_STRING, _image_version);
	} else if (daemon) {
		log_info("RED Brick API Daemon %s started (daemonized) on %s image",
		         VERSION_STRING, _image_version);
	} else if (_x11_enabled) {
		log_info("RED Brick API Daemon %s started (X11 enabled) on %s image",
		         VERSION_STRING, _image_version);
	} else {
		log_info("RED Brick API Daemon %s started on %s image",
		         VERSION_STRING, _image_version);
	}

	if (debug_filter != NULL) {
		log_enable_debug_override(debug_filter);
	}

	if (config_has_warning()) {
		log_warn("Warning(s) in config file '%s', run with --check-config option for details",
		         _config_filename);
	}

	if (event_init() < 0) {
		goto error_event;
	}

	if (signal_init(handle_sighup, NULL) < 0) {
		goto error_signal;
	}

	if (process_monitor_init() < 0) {
		goto error_process_monitor;
	}

	if (cron_init() < 0) {
		goto error_cron;
	}

	if (inventory_init() < 0) {
		goto error_inventory;
	}

	if (api_init() < 0) {
		goto error_api;
	}

	if (network_init(_brickd_socket_filename, _cron_socket_filename) < 0) {
		goto error_network;
	}

	if (inventory_load_programs() < 0) {
		goto error_load_programs;
	}

	if (event_run(network_cleanup_brickd_and_socats) < 0) {
		goto error_run;
	}

	exit_code = EXIT_SUCCESS;

error_run:
	inventory_unload_programs();

error_load_programs:
	network_exit();

error_network:
	api_exit();

error_api:
	inventory_exit();

error_inventory:
	cron_exit();

error_cron:
	process_monitor_exit();

error_process_monitor:
	signal_exit();

error_signal:
	event_exit();

error_event:
	log_info("RED Brick API Daemon %s stopped", VERSION_STRING);

error_pid_file:
	if (pid_fd >= 0) {
		pid_file_release(_pid_filename, pid_fd);
	}

	log_exit();

error_config:
	config_exit();

	return exit_code;
}
示例#29
0
文件: main.c 项目: elambert/honeycomb
/* 
 * The main method of the Cluster Membership Monitor 
 */
int
main( int argc,
      char *argv[] )
{
    int c;
    cmm_nodeid_t node_id = CMM_INVALID_NODE_ID;
    char *filename = NULL;
    cmm_error_t err;
    cm_trace_level_t trace_level = CM_TRACE_LEVEL_NOTICE;
    fifo_t *lobby_to_sender, *stack_to_sender;
    int pipe_stack[2];
    struct sigaction action;

    /* Read and verify the input arguments */

    while ( (c=getopt(argc, argv, "n:f:d")) != EOF ) {
        switch (c) {
        case 'n' :
            node_id = atoi( argv[optind-1] );
            break;
            
        case 'f' :
            filename = strdup(optarg);
            if (!filename) {
                cm_trace(CM_TRACE_LEVEL_ERROR, 
                         "strdup failed" );
                exit(1);
            }
            break;
            
        case 'd' :
            trace_level = CM_TRACE_LEVEL_DEBUG;
            break;
        }
    }

    if ( node_id == CMM_INVALID_NODE_ID ) {
        usage( argv[0],
               "The node id paramater has to be specified" );
    }

    if ( filename == NULL ) {
        usage( argv[0],
               "The configuration file parameter has to be specified" );
    }

    daemonize();
    
    cm_openlog("CMM", trace_level);

    /* Block the SIGPIPE signals */
    
    action.sa_handler = SIG_IGN;
    if (sigaction(SIGPIPE, &action, NULL)) {
        cm_trace(CM_TRACE_LEVEL_ERROR,
                 "sigaction failed");
        cm_closelog();
        return(1);
    }

    cm_trace(CM_TRACE_LEVEL_NOTICE,
             "The local node id is %d",
             node_id );

    cm_trace(CM_TRACE_LEVEL_DEBUG,
             "The configuration file is %s",
             filename );


    err = cnt_init( filename, node_id );
    if (err != CMM_OK) {
        cm_trace(CM_TRACE_LEVEL_ERROR, 
                 "cnt_init failed [%d]",
                 err );
        return(1);
    }

    cnt_print();

    if ( pipe(pipe_stack) ) {
        cm_trace(CM_TRACE_LEVEL_ERROR, 
                 "pipe failed" );
        return(1);
    }
    
    cm_trace(CM_TRACE_LEVEL_DEBUG,
             "stack pipe has been created (%d %d)",
             pipe_stack[0], pipe_stack[1] );
    
    stack_to_sender = fifo_init(NULL);
    if (!stack_to_sender) {
        cm_trace(CM_TRACE_LEVEL_ERROR, 
                 "fifo_init failed" );
        return(1);
    }

    lobby_to_sender = fifo_init(stack_to_sender);
    if (!lobby_to_sender) {
        cm_trace(CM_TRACE_LEVEL_ERROR, 
                 "fifo_init failed" );
        return(1);
    }

    /* start the lobby server thread to listen to incoming messages from 
     * the predecessor node 
     */

    err = lobby_start( RING_PORT,
                       pipe_stack[1],
                       lobby_to_sender );
    if (err != CMM_OK) {
        cm_trace(CM_TRACE_LEVEL_ERROR, 
                 "lobby_start failed [%d]",
                 err );
        return(1);
    }

    /* start the sender server thread to establish connection with the 
     * successor node and send messages to it from the lobby_to_sender and 
     * the stack_to_sender fifos
     */
    err = sender_start( lobby_to_sender,
                        stack_to_sender );
    if (err != CMM_OK) {
        cm_trace(CM_TRACE_LEVEL_ERROR, 
                 "sender_start failed [%d]",
                 err );
        return(1);
    }

    /* Start the api server */

    err = api_init();
    if (err != CMM_OK) {
        cm_trace(CM_TRACE_LEVEL_ERROR, 
                 "api_init failed [%d]",
                 err );
        return(1);
    }
/*     err = heartbeat_start(); */
/*     if (err != CMM_OK) { */
/*         cm_trace(CM_TRACE_LEVEL_ERROR,  */
/*                  "heartbeat init failed [%d]", err); */
/*         return (1); */
/*     } */
    stack_start( pipe_stack[0], stack_to_sender );

    cm_trace(CM_TRACE_LEVEL_ERROR, 
             "The stack exited !");
    
    cm_closelog();

    return(0);
}