示例#1
0
void _cdecl main (SHORT argc, char *argv[])
{
//  bool ok = FALSE;
//  char test[5];       // test for trap 05 errors
ULONG ulTimes;          // need for Trap Ctrl-Break Signal

#ifdef TESTING
  if(!dout) {
    DosBeep(500,300);
  }
  if(!memout) {
    DosBeep(1000,300);
  }
#endif

#ifdef ERR_HAND
rc = set_int24();
  if(rc != 0) {
     err_exit("Error initializing error handler", 3);
  }

MYEXCEPTIONREGISTRATIONRECORD myExceptionRegRecord;
myExceptionRegRecord.prev_structure = NULL;
myExceptionRegRecord.ExceptionHandler = MyExceptionHandler;
DosSetExceptionHandler((PEXCEPTIONREGISTRATIONRECORD) &myExceptionRegRecord);
DosSetSignalExceptionFocus(SIG_SETFOCUS, &ulTimes);

if(setjmp(myExceptionRegRecord.env))
   goto OnException;
#endif

  DBG_INI(dout<<"file "<<__FILE__<<" line "<<__LINE__<<" settings.numlock_on = "<<settings.numlock_on<<endl);

filesys_init();
get_current_directory(cwd);               // init cur dir
Mem::vmem_setup();
strcpy(exe_dir, *argv);    // assume loaded via X:\subdir\KED.EXE

DBG_FILE(dout << "EXE_DIR =  " << exe_dir <<endl);
DBG_MEM(memout<< " main after except setup "<< checkmem2 << endl);

assure_windows_ready();

if(!thread_init()) {
   err_exit("Error creating initial threads", 5);
}
process_env_string ("EDITOR");  /* do parameters from environment string */
strcpy (progname,*argv);
argc--;                         /* don't count program name */
argv++;
while (argc--) {                /* process each parameter */
   process_arg (*argv);
   argv++;
   }
if (!*settings.help_path) {     /* help is usually in same dir as program */
    delta_filename (settings.help_path, progname, "*.HLP");
   }

//#ifdef TESTING
//if(!debug_on) {
//   dout.close();
//   memout.close();
//}
//#endif


  assure_1_view();
  DBG_INI(dout<<"edit.cpp line "<<__LINE__<<" shell_command.s = °"<<settings.shell_command.s<<"°"<<endl);
  DBG_INI(dout<<"file "<<__FILE__<<" line "<<__LINE__<<" settings.numlock_on = "<<settings.numlock_on<<endl);
//  ok = load_keys();        //  Version 2.08 
//  if(!ok)
//    err_exit("Failed to load Keyboard driver", 10);

  edit_loop();
//  test[5000] = 'A';                    // test trap array bounds

  goto Ked_Exit;

OnException:
#ifdef ERR_HAND
DosUnsetExceptionHandler((PEXCEPTIONREGISTRATIONRECORD) &myExceptionRegRecord);
//  Screen.term_mess = "application trapped";
  err_exit(" application trapped", 20);
#endif

Ked_Exit:
#ifdef ERR_HAND
if(ORG_NUMLOCK) {
   DBG_NUML(dout<<" exit - setting NUMLOCK    on"<<endl);
   numlock_set(TRUE);
}
else {
   DBG_NUML(dout<<" exit - setting NUMLOCK    off"<<endl);
   numlock_set(FALSE);   
}
DosUnsetExceptionHandler((PEXCEPTIONREGISTRATIONRECORD) &myExceptionRegRecord);
#endif

DBG_MEM(memout<< " main after except setup "<< checkmem2 << endl);
DBG_BUGS(dout<<'\n'<<"    Normal Closedown in LOGFILE "<<endl);
}
示例#2
0
int
main(int argc, char *argv[])
{
	int i, bins;
	int n_thr=N_THREADS;
	int i_max=I_MAX;
	unsigned long size=SIZE;
	struct thread_st *st;

#if USE_MALLOC && USE_STARTER==2
	ptmalloc_init();
	printf("ptmalloc_init\n");
#endif

	if(argc > 1) n_total_max = atoi(argv[1]);
	if(n_total_max < 1) n_thr = 1;
	if(argc > 2) n_thr = atoi(argv[2]);
	if(n_thr < 1) n_thr = 1;
	if(n_thr > 100) n_thr = 100;
	if(argc > 3) i_max = atoi(argv[3]);

	if(argc > 4) size = atol(argv[4]);
	if(size < 2) size = 2;

	bins = MEMORY/(size*n_thr);
	if(argc > 5) bins = atoi(argv[5]);
	if(bins < 4) bins = 4;

	/*protect_stack(n_thr);*/

	thread_init();
	printf("total=%d threads=%d i_max=%d size=%ld bins=%d\n",
		   n_total_max, n_thr, i_max, size, bins);

	st = (struct thread_st *)malloc(n_thr*sizeof(*st));
	if(!st) exit(-1);

#if !defined NO_THREADS && (defined __sun__ || defined sun)
	/* I know of no other way to achieve proper concurrency with Solaris. */
	thr_setconcurrency(n_thr);
#endif

	/* Start all n_thr threads. */
	for(i=0; i<n_thr; i++) {
		st[i].u.bins = bins;
		st[i].u.max = i_max;
		st[i].u.size = size;
		st[i].u.seed = ((long)i_max*size + i) ^ bins;
		st[i].sp = 0;
		st[i].func = malloc_test;
		if(thread_create(&st[i])) {
			printf("Creating thread #%d failed.\n", i);
			n_thr = i;
			break;
		}
		printf("Created thread %lx.\n", (long)st[i].id);
	}

	/* Start an extra thread so we don't run out of stacks. */
	if(0) {
		struct thread_st lst;
		lst.u.bins = 10; lst.u.max = 20; lst.u.size = 8000; lst.u.seed = 8999;
		lst.sp = 0;
		lst.func = malloc_test;
		if(thread_create(&lst)) {
			printf("Creating thread #%d failed.\n", i);
		} else {
			wait_for_thread(&lst, 1, NULL);
		}
	}

	for(n_running=n_total=n_thr; n_running>0;) {
		wait_for_thread(st, n_thr, my_end_thread);
	}
	for(i=0; i<n_thr; i++) {
		free(st[i].sp);
	}
	free(st);
#if USE_MALLOC
	malloc_stats();
#endif
	printf("Done.\n");
	return 0;
}
示例#3
0
void plugin_init(G_GNUC_UNUSED GeanyData *gdata)
{
	GeanyKeyGroup *scope_key_group;
	char *gladefile = g_build_filename(PLUGINDATADIR, "scope.glade", NULL);
	GError *gerror = NULL;
	GtkWidget *menubar1 = find_widget(geany->main_widgets->window, "menubar1");
	guint item;
	const MenuKey *menu_key = debug_menu_keys;
	ToolItem *tool_item = toolbar_items;
	const ScopeCallback *scb;

	main_locale_init(LOCALEDIR, GETTEXT_PACKAGE);
	scope_key_group = plugin_set_key_group(geany_plugin, "scope", COUNT_KB, NULL);
	builder = gtk_builder_new();
	gtk_builder_set_translation_domain(builder, GETTEXT_PACKAGE);
	scp_tree_store_register_dynamic();

	if (!gtk_builder_add_from_file(builder, gladefile, &gerror))
	{
		msgwin_status_add(_("Scope: %s."), gerror->message);
		g_warning(_("Scope: %s."), gerror->message);
		g_error_free(gerror);
		g_object_unref(builder);
		builder = NULL;
	}

	g_free(gladefile);
	if (!builder)
		return;

	/* interface */
#ifndef G_OS_UNIX
	gtk_widget_hide(get_widget("terminal_show"));
#endif
	debug_item = get_widget("debug_item");
	if (menubar1)
		gtk_menu_shell_insert(GTK_MENU_SHELL(menubar1), debug_item, DEBUG_MENU_ITEM_POS);
	else
		gtk_container_add(GTK_CONTAINER(geany->main_widgets->tools_menu), debug_item);

	menu_connect("debug_menu", &debug_menu_info, NULL);
	ui_add_document_sensitive(get_widget("scope_reset_markers"));
	ui_add_document_sensitive(get_widget("scope_cleanup_files"));

	for (item = 0; item < EVALUATE_KB; item++, menu_key++)
	{
		keybindings_set_item(scope_key_group, item, on_scope_key, 0, 0, menu_key->name,
			_(menu_key->label), debug_menu_items[item].widget);
	}

	geany_statusbar = GTK_STATUSBAR(gtk_widget_get_parent(geany->main_widgets->progressbar));
	debug_statusbar = get_widget("debug_statusbar");
	debug_state_label = GTK_LABEL(get_widget("debug_state_label"));
	gtk_box_pack_end(GTK_BOX(geany_statusbar), debug_statusbar, FALSE, FALSE, 0);

	debug_panel = get_widget("debug_panel");
	gtk_notebook_append_page(GTK_NOTEBOOK(geany->main_widgets->message_window_notebook),
		debug_panel, get_widget("debug_label"));

	/* startup */
	gtk216_init();
	program_init();
	prefs_init();
	conterm_init();
	inspect_init();
	register_init();
	parse_init();
	debug_init();
	views_init();
	thread_init();
	break_init();
	watch_init();
	stack_init();
	local_init();
	memory_init();
	menu_init();
	menu_set_popup_keybindings(scope_key_group, item);

	for (item = 0; tool_item->index != -1; item++, tool_item++)
	{
		GtkMenuItem *menu_item = GTK_MENU_ITEM(debug_menu_items[tool_item->index].widget);
		GtkToolItem *button = gtk_tool_button_new(NULL, gtk_menu_item_get_label(menu_item));

		gtk_tool_button_set_use_underline(GTK_TOOL_BUTTON(button),
			gtk_menu_item_get_use_underline(menu_item));
		g_signal_connect(button, "clicked", G_CALLBACK(on_toolbar_button_clicked),
			GINT_TO_POINTER(tool_item->index));
		g_signal_connect(button, "toolbar-reconfigured",
			G_CALLBACK(on_toolbar_reconfigured), tool_item);
		tool_item->widget = GTK_WIDGET(button);
		plugin_add_toolbar_item(geany_plugin, button);
	}

	toolbar_update_state(DS_INACTIVE);
	views_update_state(DS_INACTIVE);
	configure_toolbar();

	g_signal_connect(debug_panel, "switch-page", G_CALLBACK(on_view_changed), NULL);
	for (scb = scope_callbacks; scb->name; scb++)
		plugin_signal_connect(geany_plugin, NULL, scb->name, FALSE, scb->callback, NULL);
}
示例#4
0
MemberThread::MemberThread()
{
  // inner thread, called within the class creation
  thread_init();
}
示例#5
0
static int
pbkdf2(uint8_t *passphrase, size_t passphraselen, uint8_t *salt,
    size_t saltlen, uint64_t iterations, uint8_t *output,
    size_t outputlen)
{
	int ret;
	uint64_t iter;
	uint32_t blockptr, i;
	uint16_t hmac_key_len;
	uint8_t *hmac_key;
	uint8_t block[SHA1_DIGEST_LEN * 2];
	uint8_t *hmacresult = block + SHA1_DIGEST_LEN;
	crypto_mechanism_t mech;
	crypto_key_t key;
	crypto_data_t in_data, out_data;
	crypto_ctx_template_t tmpl = NULL;

	/* initialize output */
	memset(output, 0, outputlen);

	/* initialize icp for use */
	thread_init();
	icp_init();

	/* HMAC key size is max(sizeof(uint32_t) + salt len, sha 256 len) */
	if (saltlen > SHA1_DIGEST_LEN) {
		hmac_key_len = saltlen + sizeof (uint32_t);
	} else {
		hmac_key_len = SHA1_DIGEST_LEN;
	}

	hmac_key = calloc(hmac_key_len, 1);
	if (!hmac_key) {
		ret = ENOMEM;
		goto error;
	}

	/* initialize sha 256 hmac mechanism */
	mech.cm_type = crypto_mech2id(SUN_CKM_SHA1_HMAC);
	mech.cm_param = NULL;
	mech.cm_param_len = 0;

	/* initialize passphrase as a crypto key */
	key.ck_format = CRYPTO_KEY_RAW;
	key.ck_length = CRYPTO_BYTES2BITS(passphraselen);
	key.ck_data = passphrase;

	/*
	 * initialize crypto data for the input data. length will change
	 * after the first iteration, so we will initialize it in the loop.
	 */
	in_data.cd_format = CRYPTO_DATA_RAW;
	in_data.cd_offset = 0;
	in_data.cd_raw.iov_base = (char *)hmac_key;

	/* initialize crypto data for the output data */
	out_data.cd_format = CRYPTO_DATA_RAW;
	out_data.cd_offset = 0;
	out_data.cd_length = SHA1_DIGEST_LEN;
	out_data.cd_raw.iov_base = (char *)hmacresult;
	out_data.cd_raw.iov_len = out_data.cd_length;

	/* initialize the context template */
	ret = crypto_create_ctx_template(&mech, &key, &tmpl, KM_SLEEP);
	if (ret != CRYPTO_SUCCESS) {
		ret = EIO;
		goto error;
	}

	/* main loop */
	for (blockptr = 0; blockptr < outputlen; blockptr += SHA1_DIGEST_LEN) {

		/*
		 * for the first iteration, the HMAC key is the user-provided
		 * salt concatenated with the block index (1-indexed)
		 */
		i = htobe32(1 + (blockptr / SHA1_DIGEST_LEN));
		memmove(hmac_key, salt, saltlen);
		memmove(hmac_key + saltlen, (uint8_t *)(&i), sizeof (uint32_t));

		/* block initializes to zeroes (no XOR) */
		memset(block, 0, SHA1_DIGEST_LEN);

		for (iter = 0; iter < iterations; iter++) {
			if (iter > 0) {
				in_data.cd_length = SHA1_DIGEST_LEN;
				in_data.cd_raw.iov_len = in_data.cd_length;
			} else {
				in_data.cd_length = saltlen + sizeof (uint32_t);
				in_data.cd_raw.iov_len = in_data.cd_length;
			}

			ret = crypto_mac(&mech, &in_data, &key, tmpl,
			    &out_data, NULL);
			if (ret != CRYPTO_SUCCESS) {
				ret = EIO;
				goto error;
			}

			/* HMAC key now becomes the output of this iteration */
			memmove(hmac_key, hmacresult, SHA1_DIGEST_LEN);

			/* XOR this iteration's result with the current block */
			for (i = 0; i < SHA1_DIGEST_LEN; i++) {
				block[i] ^= hmacresult[i];
			}
		}

		/*
		 * compute length of this block, make sure we don't write
		 * beyond the end of the output, truncating if necessary
		 */
		if (blockptr + SHA1_DIGEST_LEN > outputlen) {
			memmove(output + blockptr, block, outputlen - blockptr);
		} else {
			memmove(output + blockptr, block, SHA1_DIGEST_LEN);
		}
	}

	crypto_destroy_ctx_template(tmpl);
	free(hmac_key);
	icp_fini();
	thread_fini();

	return (0);

error:
	crypto_destroy_ctx_template(tmpl);
	if (hmac_key != NULL)
		free(hmac_key);
	icp_fini();
	thread_fini();

	return (ret);
}
示例#6
0
int master_threads2::thread_begin(void* arg)
{
	thread_init(arg);
	return 0;
}
示例#7
0
/* -------------------------------------------------------------------
 * main()
 *      Entry point into Iperf
 *
 * sets up signal handlers
 * initialize global locks and conditions
 * parses settings from environment and command line
 * starts up server or client thread
 * waits for all threads to complete
 * ------------------------------------------------------------------- */
#ifdef __cplusplus
extern "C"
#endif /* __cplusplus */
int IPERF_MAIN( int argc, char **argv ) {
#ifdef NO_EXIT
    should_exit = 0;
#endif /* NO_EXIT */
#ifdef IPERF_DEBUG
    debug_init();
#endif /* IPERF_DEBUG */

#ifndef NO_INTERRUPTS
#ifdef WIN32
    setsigalrmfunc(call_sigalrm);
#endif /* WIN32 */

    // Set SIGTERM and SIGINT to call our user interrupt function
    my_signal( SIGTERM, Sig_Interupt );
    my_signal( SIGINT,  Sig_Interupt );
    my_signal( SIGALRM,  Sig_Interupt );

#ifndef WIN32
    // Ignore broken pipes
    signal(SIGPIPE,SIG_IGN);
#else
    // Start winsock
    WORD wVersionRequested;
    WSADATA wsaData;

    // Using MAKEWORD macro, Winsock version request 2.2
    wVersionRequested = MAKEWORD(2, 2);

    int rc = WSAStartup( wVersionRequested, &wsaData );
    WARN_errno( rc == SOCKET_ERROR, ( "WSAStartup failed.\n" ) );
	if (rc != 0) {
	    fprintf(stderr, "The Winsock DLL was not found!\n");
		return 1;
	}

    /*
     * Confirm that the WinSock DLL supports 2.2. Note that if the DLL supports
	 * versions greater than 2.2 in addition to 2.2, it will still return 2.2 in
	 * wVersion since that is the version we requested.
     */
    if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2 ) {
        /* Tell the user that we could not find a usable WinSock DLL. */
        fprintf(stderr, "The DLL does not support the Winsock version %u.%u!\n", LOBYTE(wsaData.wVersion),HIBYTE(wsaData.wVersion));
        WSACleanup();
        return 1;
    }

    // Tell windows we want to handle our own signals
    SetConsoleCtrlHandler( sig_dispatcher, true );
#endif /* WIN32 */
#endif /* NO_INTERRUPTS */

    // Initialize global mutexes and conditions
    IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Initializing report condition.\n" ) );
    Condition_Initialize ( &ReportCond );
    IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Initializing report done condition.\n" ) );
    Condition_Initialize ( &ReportDoneCond );
    IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Initializing group condition mutex.\n" ) );
    Mutex_Initialize( &groupCond );
    IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Initializing clients mutex.\n" ) );
    Mutex_Initialize( &clients_mutex );

    // Initialize the thread subsystem
    IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE, ( "Initializing the thread subsystem.\n" ) );
    thread_init( );

    // Initialize the interrupt handling thread to 0
    sThread = thread_zeroid();

#ifndef NO_EXIT
    // perform any cleanup when quitting Iperf
    atexit( cleanup );
#endif /* NO_EXIT */

    // Allocate the "global" settings
    thread_Settings *ext_gSettings = (thread_Settings*) malloc( sizeof( thread_Settings ) );
    FAIL( ext_gSettings == NULL, ( "Unable to allocate memory for thread_Settings ext_gSettings.\n" ), NULL );
    IPERF_DEBUGF( MEMALLOC_DEBUG, IPERF_MEMALLOC_MSG( ext_gSettings, sizeof( thread_Settings ) ) );

    // Initialize settings to defaults
    Settings_Initialize( ext_gSettings );
#ifndef NO_ENVIRONMENT
    // read settings from environment variables
    Settings_ParseEnvironment( ext_gSettings );
#endif /* NO_ENVIORNMENT */
    // read settings from command-line parameters
    Settings_ParseCommandLine( argc, argv, ext_gSettings );

#ifdef NO_EXIT
    if (should_exit) {
        IPERF_DEBUGF( MEMFREE_DEBUG | IPERF_DBG_TRACE, IPERF_MEMFREE_MSG( ext_gSettings ) );
        FREE_PTR( ext_gSettings );

        IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Destroying report condition.\n" ) );
        Condition_Destroy( &ReportCond );
        IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Destroying report done condition.\n" ) );
        Condition_Destroy( &ReportDoneCond );
        IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Destroying group condition mutex.\n" ) );
        Mutex_Destroy( &groupCond );
        IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Destroying clients mutex.\n" ) );
        Mutex_Destroy( &clients_mutex );

        return 0;
    }
#endif /* NO_EXIT */

    // Check for either having specified client or server
    if ( ext_gSettings->mThreadMode == kMode_Client 
         || ext_gSettings->mThreadMode == kMode_Listener ) {
#ifdef WIN32
#ifndef NO_DAEMON
        // Start the server as a daemon
        // Daemon mode for non-windows in handled
        // in the listener_spawn function
        if ( isDaemon( ext_gSettings ) ) {
            CmdInstallService(argc, argv);
            return 0;
        }
#endif /* NO_DAEMON */

#ifndef NO_SERVICE
        // Remove the Windows service if requested
        if ( isRemoveService( ext_gSettings ) ) {
            // remove the service
            if ( CmdRemoveService() ) {
                fprintf(stderr, "IPerf Service is removed.\n");
                return 0;
            }
        }
#endif /* NO_SERVICE */
#endif /* WIN32 */
        // initialize client(s)
        if ( ext_gSettings->mThreadMode == kMode_Client ) {
            IPERF_DEBUGF( CLIENT_DEBUG | LISTENER_DEBUG | IPERF_DBG_TRACE, ( "Initializing client(s)...\n" ) );
            client_init( ext_gSettings );
        }

#ifdef HAVE_THREAD
        // start up the reporter and client(s) or listener
        thread_Settings *into = NULL;
        // Create the settings structure for the reporter thread
        IPERF_DEBUGF( CLIENT_DEBUG | LISTENER_DEBUG | REPORTER_DEBUG | IPERF_DBG_TRACE, ( "Creating the settings structure for the reporter thread.\n" ) );
        Settings_Copy( ext_gSettings, &into );
        into->mThreadMode = kMode_Reporter;

        // Have the reporter launch the client or listener
        IPERF_DEBUGF( CLIENT_DEBUG | LISTENER_DEBUG | IPERF_DBG_TRACE, ( "Setting the reporter to launch the client or listener before launching itself.\n" ) );
        into->runNow = ext_gSettings;
        
        // Start all the threads that are ready to go
        IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE, ( "Starting all the threads...\n" ) );
        thread_start( into );
#else
        // No need to make a reporter thread because we don't have threads
        IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE, ( "Starting iperf in a single thread...\n" ) );
        thread_start( ext_gSettings );
#endif /* HAVE_THREAD */
    } else {
        // neither server nor client mode was specified
        // print usage and exit

#ifdef WIN32
        // In Win32 we also attempt to start a previously defined service
        // Starting in 2.0 to restart a previously defined service
        // you must call iperf with "iperf -D" or using the environment variable
        SERVICE_TABLE_ENTRY dispatchTable[] =
        {
            { TEXT((char *) SZSERVICENAME), (LPSERVICE_MAIN_FUNCTION)service_main},
            { NULL, NULL}
        };

#ifndef NO_DAEMON
        // Only attempt to start the service if "-D" was specified
        if ( !isDaemon(ext_gSettings) ||
             // starting the service by SCM, there is no arguments will be passed in.
             // the arguments will pass into Service_Main entry.
             !StartServiceCtrlDispatcher(dispatchTable) )
            // If the service failed to start then print usage
#endif /* NO_DAEMON */
#endif /* WIN32 */
        fprintf( stderr, usage_short, argv[0], argv[0] );

        return 0;
    }

    // wait for other (client, server) threads to complete
//    IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE, ( "Waiting for other (client, server) threads to complete...\n" ) );
//    thread_joinall();
    
#ifdef NO_EXIT
	/* We can't run the atexit function */
#ifdef WIN32
    // Shutdown Winsock
    WSACleanup();
#endif /* WIN32 */
    // clean up the list of clients
    Iperf_destroy ( &clients );

    // shutdown the thread subsystem
    IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE, ( "Deinitializing the thread subsystem.\n" ) );

    IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Destroying report condition.\n" ) );
    Condition_Destroy( &ReportCond );
    IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Destroying report done condition.\n" ) );
    Condition_Destroy( &ReportDoneCond );
    IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Destroying group condition mutex.\n" ) );
    Mutex_Destroy( &groupCond );
    IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Destroying clients mutex.\n" ) );
    Mutex_Destroy( &clients_mutex );

#ifdef IPERF_DEBUG
    debug_init();
#endif /* IPERF_DEBUG */
#endif /* NO_EXIT */
	
    // all done!
    IPERF_DEBUGF( IPERF_DBG_TRACE | IPERF_DBG_STATE, ( "Done!\n" ) );
    return 0;
} // end main
示例#8
0
int main (void)
{
    L4_Word_t total;

    printf("\n\nHasenpfeffer operating system\n");
    printf("Copyright (C) 2005,2006. Senko Rasic <*****@*****.**>\n\n");


    printf("Initializing root task...\n");
    L4_KernelInterfacePage_t *kip = (L4_KernelInterfacePage_t *) L4_GetKernelInterface();
    void *bi = (void *) L4_BootInfo(kip);
    
    // we need to preload these I/O pages
    // ATA
    L4_Sigma0_GetPage(L4_nilthread, L4_Fpage(0x0000, 4096));

    // KIP
    L4_Sigma0_GetPage(L4_nilthread, L4_Fpage(L4_BootInfo(kip), 4096));
    L4_BootRec_t *br = NULL;

    if (L4_BootInfo_Valid((void *) bi)) {
        int n = L4_BootInfo_Entries(bi);
        br = L4_BootInfo_FirstEntry(bi);
        while (--n) {
            /* touch roottask data from here, because sigma0 only gives pages to initial *thread* */
            if (L4_BootRec_Type(br) == L4_BootInfo_SimpleExec) {
                L4_Word_t mi;
                for (mi = 0; mi < L4_Module_Size(br); mi += 4096) {
                    L4_Sigma0_GetPage(L4_nilthread, L4_Fpage(L4_Module_Start(br) + mi, 4096));
                }
            }
            br = L4_BootRec_Next(br);
        }
    } else {
        printf("panic: invalid bootinfo data\n");
        return 0;
    }

    memory_init();
    total = memory_get_free();

    printf("Creating root memory manager...\n");
    mman_tid = create_local_thread("root memory manager", kip, 1, memman, 4096);
    thread_init(mman_tid);

    printf("Initializing root task manager...\n");
    HpfCapability full, newthread, newtask;
    task_manager_init(&full, &newtask, &newthread);

    dir_paths[0] = "/process/TaskManager";
    dir_caps[0] = full;
    n_paths = 1;

    printf("Loading initial programs...\n");
    int n = L4_BootInfo_Entries(bi);
    br = L4_BootInfo_FirstEntry(bi);
    int first_program = 1;
    while (--n) {
        if (L4_BootRec_Type(br) == L4_BootInfo_Module) {
            L4_ThreadId_t tid = launch(br);
            if (first_program) {
                first_program = 0;

                // this is the root directory server
                if (hermes_capability(tid, &(dir_caps[1]))) {
                    // dir_paths[1] = "/process/DirectoryService";
                    dir_paths[1] = ""; // <- catch-all
                    n_paths = 2;
                }
            }
        }
        br = L4_BootRec_Next(br);
    }

    printf("Init done, running...\n\n");
    task_manager_main();

    return 0;
}
示例#9
0
	if ((global_mem->g_verbose) && (barrier_errs != 0))
		printf("\nThread %" PRIu32 " (id=%d core=%d) had %" PRIu32
		       " barrier_errs in %" PRIu32 " iterations\n", thread_num,
		       per_thread_mem->thread_id,
		       per_thread_mem->thread_core, barrier_errs, iterations);

	return barrier_errs;
}

static void *no_barrier_functional_test(void *arg UNUSED)
{
	per_thread_mem_t *per_thread_mem;
	uint32_t barrier_errs;

	per_thread_mem = thread_init();
	barrier_errs = barrier_test(per_thread_mem, 1);

	/*
	* Note that the following CU_ASSERT MAY appear incorrect, but for the
	* no_barrier test it should see barrier_errs or else there is something
	* wrong with the test methodology or the ODP thread implementation.
	* So this test PASSES only if it sees barrier_errs or a single
	* worker was used.
	*/
	CU_ASSERT(barrier_errs != 0 || global_mem->g_num_threads == 1);
	thread_finalize(per_thread_mem);

	return NULL;
}
示例#10
0
文件: entry.c 项目: bmarcot/kemerald
void		_main(void)
{
  uint32_t i;

  /**
   *
   *	Basic setup
   */

  /* enable the A20 line */
 
  /* disable the PIC (8259A chip) */
  pic_enable(false);

  /* disable the local APIC */
  //apic_enable(false);
  //apic_local_enable(false)

  /**
   *
   *	Protection
   */

  /* init and enable segmentation */
  //gdt_init();

  seg_init();
  //  INFINITE_LOOP();

  /* init and enable paging */
  //mmu_init();
  console_clear();
  mmu_init();

  /* init the system-call facilities */
  sc_init();

  /**
   *
   *	Interrupts
   */
  // INFINITE_LOOP();
  /* init and enable interrupts */
  idt_init();

  //INFINITE_LOOP();

  /* bind stage2 isrs */
  //isr_init();
  int_init();
  ex_init();

  //INFINITE_LOOP();

  /* configure the Local-APIC timer */
  //apic_local_timer_init(0x2ffffff);
  //apic_local_timer_init(0xffffff);

  /* configure the PIT timer */
  pit_init();

  printf("Local-APIC init...\n");
  /* Init the Local-APIC. */
  apic_local_init();
  apic_local_set_task_priority(0);
  printf("Local-APIC timer config...\n");
  apic_local_timer_config(0x2ffffff);
  printf("IO-APIC init...\n");
  apic_io_init();
  /* enable the local APIC */
  //apic_enable(true);
  apic_local_enable(true);

  printf("OK\n");

  /* configure the I/O APIC in charge of the PIT, keyboard, ... */
  //apic_io_init();
  /* STI(); */
/*   INFINITE_LOOP(); */

  /* clear the screen */
  console_clear();
  console_init();

  /* init the basic I/O services */
  stdio_init();
  //tty_init();
  //tty_activate(0);

 /*  sysenter(); */
  /*   vmx_supported(1); */
  test_malloc();

  /* init the serial number facility */
  serial_init();
  /*   printf("UID %d\n", serial_generate()); */
  /*   printf("UID %d\n", serial_generate()); */
  /*   printf("UID %d\n", serial_generate()); */

  /* init the task manager */
  thread_init();

  /* init the scheduler manager */
  sched_init();

  /* dump the memory */
  mem_dump();

  /* test the mmu. */
  //mmu_test();
  /* while (1) */
/*     ; */

  //video_init();

/*   msr = rdmsr(MSR_IA32_APIC_BASE); */
/*   printf("msr hi: %x\n", (uint32_t)(msr >> 32)); */
/*   printf("msr lo: %x\n", (uint32_t) msr); */
/*   msr = rdmsr(MSR_IA32_CR_PAT); */
/*   printf("msr hi: %x\n", (uint32_t)(msr >> 32)); */
/*   printf("msr lo: %x\n", (uint32_t) msr); */
/*   msr = rdmsr(MSR_IA32_PERF_GLOBAL_STATUS); */
/*   printf("msr hi: %x\n", (uint32_t)(msr >> 32)); */
/*   printf("msr lo: %x\n", (uint32_t) msr); */
/*   msr = rdmsr(MSR_IA32_PLATFORM_ID); */
/*   printf("msr hi: %x\n", (uint32_t)(msr >> 32)); */
/*   printf("msr lo: %x\n", (uint32_t) msr); */
/*   printf("Macrotest\n"); */
/*   MACROTEST(&msr); */
/*   printf("msr hi: %x\n", (uint32_t)(msr >> 32)); */
 /*  printf("apic-io ver: %x\n", apic_io_get_version()); */
/*   printf("apic-io id: %x\n", apic_io_get_id()); */

/*   printf("New GDT:\n"); */
/*   seg_init(); */
/*   printf("Old GDT:\n"); */
/*   for (i = 0; i < SEG_DESC_N; i++) */
/*     { */
/*       printf("%x - %x\n", gdt[i].high, gdt[i].low); */
/*     } */
  //INFINITE_LOOP();

  i = 1 << 5 | 1 << 9;
  printf("bsf(i) = %d\n", bsf(i));
  printf("bsr(i) = %d\n", bsr(i));
  i = 0;
  printf("bsr(i) = %d\n", bsr(i));

  printf("MSR_IA32_SYSENTER_CS high = %x\n", (uint32_t)(rdmsr(MSR_IA32_SYSENTER_CS) >> 32));
  printf("MSR_IA32_SYSENTER_CS low = %x\n", (uint32_t) rdmsr(MSR_IA32_SYSENTER_CS));

  printf("IA32_CR_PAT high = %x\n", (uint32_t)(rdmsr(MSR_IA32_CR_PAT) >> 32));
  printf("IA32_CR_PAT low = %x\n", (uint32_t) rdmsr(MSR_IA32_CR_PAT));

  /* jump to background task - code after this function is never reached */
  sched_launch();


  /*   test_multiline(); */
  /*   test_println(); */
  /*   test_interrupts(); */
  /*   test_itoa(); */
  /*   test_msr(); */
  //test_apic();
  //test_ide_dma();

  //printf("+ Bus 0\n", BG_BLACK | FG_RED | FG_INTENSITY);
  //pci_list(0, 2, 64);
  /*   printf("Bus 1\n", BG_BLACK | FG_RED | FG_INTENSITY); */
  /*   pci_list(1); */
  //test_ide_dma();
  //test_apic();

  //fprintf(0, "Protos v%d.%d - id:%x\n", 0, 12, 0xbe01);
  //fprintf(0, "\tid reg:\t%r\n", 0xbe01);
  //fprintf(0, "Ok!\n");
  // printf("Helo %% %d-%x-%r\n", 45, 0xabc78, 0xabc78);
  //printf("Helo %r\n", 0xbe01);

  //r = fprintf(stdout, "Almost %x years :)\n", 26);
  //fprintf(stdout, "size:%d\n", strlen("hello!"));

  //printf("fprintf result = %d\n", r);
  //printf(&((&stdio_filedes[0])->buffer[0]));

  //__asm__ ("rdtsc");


  // Halt the system
  while (1)
    HLT();
}
示例#11
0
文件: i686.c 项目: via/akaris-ng
void
i686_kmain(unsigned long magic, multiboot_info_t *info) {

  bootvideo_cls();

  parse_cmdline(info->cmdline);

  if (use_serial)
    i686_tty_init(0, 9600);

  i686_kernel.debug = i686_debug;

  if (magic != MULTIBOOT_BOOTLOADER_MAGIC) {
    i686_debug("Not booted from multiboot loader!\n");
    while (1);
  }
 
  i686_debug("mods_addr: %x\nmod_start: %x\n", info->mods_addr,
      0);

  i686_kernel.mutex = &i686_mutex;
  i686_kernel.bsp = (struct cpu *)i686_cpu_alloc();
  i686_kernel.bsp->kvirt = i686_virtmem_init(&i686_kernel);
  i686_kernel.phys = i686_physmem_alloc(&i686_kernel, info);

  kmem_init(i686_kernel.bsp->allocator);
  i686_kernel.bsp->v.init(i686_kernel.bsp);

  i686_debug("Location GDT entry: %x\n", ((struct i686_cpu *)i686_kernel.bsp)->gdt);

  virtaddr_t a;
  physaddr_t p;
  virtmem_error_t e1 = virtmem_kernel_alloc(i686_kernel.bsp->kvirt, &a, 1);
  assert(e1 == VIRTMEM_SUCCESS);
  physmem_error_t e2 = physmem_page_alloc(i686_kernel.bsp->localmem, 0, &p);
  assert(e2 == PHYSMEM_SUCCESS);
  virtmem_kernel_map_virt_to_phys(i686_kernel.bsp->kvirt, p, a);
  i686_debug("Allocated address: %x(->%x)\n", a, p);

  char *s = (char *)a;

  strcpy(s, "This shows the validity of this memory");
  i686_debug("%x contains: %s\n", a, s);

  struct kmem_cache *s1 = kmem_alloc(i686_kernel.bsp->allocator);
  kmem_cache_init(i686_kernel.bsp->allocator,
      s1, i686_kernel.bsp, "test", 128, NULL, NULL);

  char *t1 = kmem_cache_alloc(s1);
  i686_debug("cache at %x provided us with %x\n", s1, t1);
  strcpy(t1, "This shows the validity of the slab allocation");
  i686_debug("%x contains: %s\n", t1, t1);

  i686_address_space_init();
  struct address_space *as;
  struct memory_region *mr;
  address_space_alloc(&as);
  memory_region_alloc(&mr);

  e1 = virtmem_kernel_alloc(i686_kernel.bsp->kvirt, &a, 1);
  virtmem_kernel_map_virt_to_phys(i686_kernel.bsp->kvirt, (physaddr_t)as->pd, a);
  
  address_space_init_region(as, mr, (virtaddr_t)0x1000000, 0x2000);
  memory_region_set_flags(mr, 1, 1);
  memory_region_map(as, mr, NULL);

  const char *teststr = "This is a test string to be copied to userspace.";
  char testcpybuf[128];
  char opcodes[] = {0xeb, 0xfe};
  virtmem_copy_kernel_to_user(i686_kernel.bsp->kvirt, as->pd, (void *)0x1000ffc, 
      (const void *)teststr, strlen(teststr) + 1);
  virtmem_copy_user_to_kernel(i686_kernel.bsp->kvirt, (void *)&testcpybuf, 
      as->pd, (const void *)0x1000ffc, strlen(teststr) + 1);
  i686_debug("testcpybuf contains '%s'\n", testcpybuf);
  virtmem_copy_kernel_to_user(i686_kernel.bsp->kvirt, as->pd, (void *)0x1000000, 
      (const void *)opcodes, 2);


  struct thread *thr1;
  scheduler_thread_alloc(cpu()->sched, &thr1);
  thread_init(thr1, as);
  thr1->state = THREAD_RUNNABLE;
  scheduler_thread_add(cpu()->sched, thr1);
  scheduler_reschedule(cpu()->sched);
  virtmem_user_setup_kernelspace(i686_kernel.bsp->kvirt, as->pd);
  virtmem_set_context(i686_kernel.bsp->kvirt, as->pd);
  scheduler_resume(cpu()->sched);
  while (1);
}
示例#12
0
/* Initialise thread pool */
struct thpool_*
thpool_init(int num_threads)
{
	threads_on_hold   = 0;
	threads_keepalive = 1;

	if (num_threads < 0){
		num_threads = 0;
	}

	/* Make new thread pool */
	thpool_* thpool_p;
	thpool_p = (struct thpool_*)malloc(sizeof(struct thpool_));
	if (thpool_p == NULL) {
		fprintf(stderr, "thpool_init(): Could not allocate memory for thread pool\n");
		return NULL;
	}
	thpool_p->num_threads_alive   = 0;
	thpool_p->num_threads_working = 0;

	/* Initialise the job queue */
	if (jobqueue_init(thpool_p) == -1) {
		fprintf(stderr, "thpool_init(): Could not allocate memory for job queue\n");
		free(thpool_p);
		return NULL;
	}

	/* Make threads in pool */
	thpool_p->threads = (struct thread**)malloc(num_threads * sizeof(struct thread *));
	if (thpool_p->threads == NULL){
		fprintf(stderr, "thpool_init(): Could not allocate memory for threads\n");
		jobqueue_destroy(thpool_p);
		free(thpool_p->jobqueue_p);
		free(thpool_p);
		return NULL;
	}

    /* Make tag list */
    taglist *tlist;
    tlist = (taglist *) malloc(sizeof(taglist));
    if (tlist == NULL) {
        fprintf(stderr, "thpool_init(): Could not allocate memory for job queue\n");
		jobqueue_destroy(thpool_p);
		free(thpool_p->jobqueue_p);
        free(thpool_p->threads);
		free(thpool_p);
        return NULL;
    }
    tlist->num = TAGLIST_SIZE;
    tlist->tags = (tag *) calloc(tlist->num, sizeof(tag));
    if (tlist->tags == NULL) {
        fprintf(stderr, "thpool_init(): Could not allocate memory for tag list\n");
		jobqueue_destroy(thpool_p);
		free(thpool_p->jobqueue_p);
        free(thpool_p->threads);
		free(thpool_p);
        free(tlist);
        return NULL;
    }
    pthread_mutex_init(&tlist->lock, NULL);
    thpool_p->tlist = tlist;

	pthread_mutex_init(&(thpool_p->thcount_lock), NULL);
	pthread_cond_init(&thpool_p->threads_all_idle, NULL);
	
	/* Thread init */
	for (int n = 0; n < num_threads; n++) {
		thread_init(thpool_p, &thpool_p->threads[n], n);
		if (THPOOL_DEBUG)
			printf("THPOOL_DEBUG: Created thread %d in pool \n", n);
	}
	
	/* Wait for threads to initialize */
	while (thpool_p->num_threads_alive != num_threads) {}

	return thpool_p;
}
示例#13
0
error_t thread_create(struct task_s *task, pthread_attr_t *attr, struct thread_s **new_thread)
{
	kmem_req_t req;
	struct cluster_s *cluster;
	struct cpu_s *cpu;
	register struct thread_s *thread;
	struct page_s *page;

	//FIXME
	//cluster = cluster_cid2ptr(attr->cid);
	cluster = current_cluster;
	//cpu     = cpu_gid2ptr(attr->cpu_gid);
	cpu     = cpu_lid2ptr(attr->cpu_lid);

	// New Thread Ressources Allocation
	req.type  = KMEM_PAGE;
	req.size  = ARCH_THREAD_PAGE_ORDER;
	req.flags = AF_KERNEL | AF_ZERO | AF_REMOTE;
	req.ptr   = cluster;

#if CONFIG_THREAD_LOCAL_ALLOC
	req.ptr   = current_cluster;
#endif

	page      = kmem_alloc(&req);

	if(page == NULL) return EAGAIN;

	thread = (struct thread_s*) ppm_page2addr(page);

	thread_init(thread);

	// Initialize new thread
	thread_set_current_cpu(thread,cpu);

	sched_setpolicy(thread, attr->sched_policy);
	thread->task = task;
	thread->type = PTHREAD;

	if(attr->flags & PT_ATTR_DETACH)
		thread_clear_joinable(thread);
	else
		thread_set_joinable(thread);

	signal_init(thread);
	attr->tid = (uint_t)thread;
	attr->pid = task->pid;
	memcpy(&thread->info.attr, attr, sizeof(*attr));
	thread->info.page = page;
	thread->info.ppm_last_cid = attr->cid;

	wait_queue_init(&thread->info.wait_queue, "Join/Exit Sync");
	cpu_context_init(&thread->pws, thread); 

	// Set referenced thread pointer to new thread address
	*new_thread = thread;

        thread_dmsg(1, "%s: thread %x of task %u created on cluster %u by cpu %u\n",    \
                        __FUNCTION__, thread->info.attr.tid, thread->info.attr.pid,     \
                        thread->info.attr.cid, thread->info.attr.cpu_lid);

	return 0;
}
示例#14
0
int
nk_thread_create (nk_thread_fun_t fun, 
                  void * input,
                  void ** output,
                  uint8_t is_detached,
                  nk_stack_size_t stack_size,
                  nk_thread_id_t * tid,
                  int cpu)
{
    nk_thread_t * t = NULL;
    void * stack    = NULL;

    if (cpu == CPU_ANY) {
        cpu = my_cpu_id();
    }

#ifndef NAUT_CONFIG_THREAD_OPTIMIZE
    ASSERT(cpu < per_cpu_get(system)->num_cpus);

    if (cpu >= per_cpu_get(system)->num_cpus) {
        ERROR_PRINT("thread create received invalid CPU id (%u)\n", cpu);
        return -EINVAL;
    }
#endif

    t = malloc(sizeof(nk_thread_t));

#ifndef NAUT_CONFIG_THREAD_OPTIMIZE
    ASSERT(t);
    if (!t) {
        ERROR_PRINT("Could not allocate thread struct\n");
        return -EINVAL;
    }
    memset(t, 0, sizeof(nk_thread_t));
#endif


#ifndef NAUT_CONFIG_THREAD_OPTIMIZE
    if (stack_size) {
        stack         = (void*)malloc(stack_size);
        t->stack_size = stack_size;
    } else {
        stack         = (void*)malloc(PAGE_SIZE);
        t->stack_size =  PAGE_SIZE;
    }
#else
    stack         = malloc(PAGE_SIZE_4KB);
    t->stack_size = PAGE_SIZE_4KB;
#endif

    ASSERT(stack);

    if (thread_init(t, stack, is_detached, cpu, get_cur_thread()) < 0) {
        ERROR_PRINT("Could not initialize thread\n");
        goto out_err1;
    }

    t->status = NK_THR_INIT;
    
    t->fun = fun;
    t->input = input;
    t->output = output;
    
    enqueue_thread_on_tlist(t);

    if (tid) {
        *tid = (nk_thread_id_t)t;
    }

    SCHED_DEBUG("Thread create creating new thread with t=%p, tid=%lu\n", t, t->tid);

    return 0;

out_err1:
    free(stack);
    free(t);
    return -1;
}
示例#15
0
int main(int argc, char **argv)
{
    /* open log */
    if (0 != LOG_OPEN("./center", LOG_LEVEL_DEBUG, -1)) {
        fprintf(stderr, "open center log failed!\n");
        return 1;
    }

    if (0 != check_cmd()) {
        return 1;
    }

    /* protobuf verify version */
    GOOGLE_PROTOBUF_VERIFY_VERSION;

    struct event_base *main_base = event_base_new();
    if (NULL == main_base) {
        mfatal("main_base = event_base_new() failed!");
        return 1;
    }

    conn_init();

    /* thread */
    pthread_t worker[WORKER_NUM];
    thread_init(main_base, WORKER_NUM, worker);

    /* signal */
    struct event *signal_event;
    signal_event = evsignal_new(main_base, SIGINT, signal_cb, (void *)main_base);
    if (NULL == signal_event || 0 != event_add(signal_event, NULL)) {
        mfatal("create/add a signal event failed!");
        return 1;
    }

    /* listener for gate */
    struct sockaddr_in sa;
    bzero(&sa, sizeof(sa));
    sa.sin_family = AF_INET;
    sa.sin_addr.s_addr = htonl(INADDR_ANY);
    sa.sin_port = htons(44000);

    listener *lg = listener_new(main_base, (struct sockaddr *)&sa, sizeof(sa), gate_cb);
    if (NULL == lg) {
        mfatal("create client listener failed!");
        return 1;
    }

    /* connector to center */
    struct sockaddr_in csa;
    bzero(&csa, sizeof(csa));
    csa.sin_family = AF_INET;
    csa.sin_addr.s_addr = inet_addr("127.0.0.1");
    csa.sin_port = htons(43001);

    connector *ce = connector_new((struct sockaddr *)&csa, sizeof(csa), center_cb);
    if (NULL == ce) {
        mfatal("create center connector failed!");
        return 1;
    }

    event_base_dispatch(main_base);

    for (int i = 0; i < WORKER_NUM; i++)
        pthread_join(worker[i], NULL);

    connector_free(ce);
    listener_free(lg);
    event_free(signal_event);
    event_base_free(main_base);

    /* shutdown protobuf */
    google::protobuf::ShutdownProtobufLibrary();

    /* close log */
    LOG_CLOSE();

    return 0;
}
示例#16
0
void CCurlWrapper::PerformSimplePOST(const char *pUrl, const char *pFields)
{
	thread_detach(thread_init(CCurlWrapper::PerformPOST_ex, new CHTTPPOSTTask(pUrl, pFields)));
}
示例#17
0
文件: Main.c 项目: beartan/liteOS
int main(){


 TOSH_SET_PIN_DIRECTIONS();
   initScheduling();  
   thread_init();

  currentuse = 0; 
 
  printString("Start!\n");

  sei();



   mystrncpy(networkid, "sn03\0", 5);
   nodeid = 3;   
   mystrncpy(filenameid, "nodeA\0", 6); 
  


  


   TimerM_StdControl_init();

  



   AMStandard_Control_init();
   AMStandard_Control_start();
   
   SocketInit();
 




   currentMsg = 0;
   packetReadingNumber = 0;
   readingNumber = 0;
      
      
   nextindex = 0;
   
   
  
  CURRENT_NODE_ID = 17;

 
//add end
 //line 39
//Timer_start(2,REPEAT ,15000*MILLISECOND);

//TimerM_Timer_start(15, TIMER_REPEAT, 5000*MILLISECOND);

 //line 40
//Timer_start(1,REPEAT,1*MINUTE);


  initRadioHandle();

 
  CC2420ControlM_CC2420Control_TuneChannel(15);
  
  CC2420ControlM_CC2420Control_TunePower( 31) ; 


  __nesc_enable_interrupt();

  while (1) {
      runNextTask();
    }

	return 0;
}
示例#18
0
/*
 *	Running in virtual memory, on the interrupt stack.
 *	Does not return.  Dispatches initial thread.
 *
 *	Assumes that master_cpu is set.
 */
void setup_main()
{
	thread_t		startup_thread;

	panic_init();
	printf_init();

	sched_init();
	vm_mem_bootstrap();
	ipc_bootstrap();
	vm_mem_init();
	ipc_init();

	/*
	 * As soon as the virtual memory system is up, we record
	 * that this CPU is using the kernel pmap.
	 */
	PMAP_ACTIVATE_KERNEL(master_cpu);

	init_timers();
	init_timeout();

#if	XPR_DEBUG
	xprbootstrap();
#endif	XPR_DEBUG

	timestamp_init();

	mapable_time_init();

	machine_init();

	machine_info.max_cpus = NCPUS;
	machine_info.memory_size = phys_last_addr - phys_first_addr; /* XXX mem_size */
	machine_info.avail_cpus = 0;
	machine_info.major_version = KERNEL_MAJOR_VERSION;
	machine_info.minor_version = KERNEL_MINOR_VERSION;

	/*
	 *	Initialize the IPC, task, and thread subsystems.
	 */
	task_init();
	thread_init();
	swapper_init();
#if	MACH_HOST
	pset_sys_init();
#endif	MACH_HOST

	/*
	 *	Kick off the time-out driven routines by calling
	 *	them the first time.
	 */
	recompute_priorities();
	compute_mach_factor();
	
	/*
	 *	Create a kernel thread to start the other kernel
	 *	threads.  Thread_resume (from kernel_thread) calls
	 *	thread_setrun, which may look at current thread;
	 *	we must avoid this, since there is no current thread.
	 */

	/*
	 * Create the thread, and point it at the routine.
	 */
	(void) thread_create(kernel_task, &startup_thread);
	thread_start(startup_thread, start_kernel_threads);

	/*
	 * Give it a kernel stack.
	 */
	thread_doswapin(startup_thread);

	/*
	 * Pretend it is already running, and resume it.
	 * Since it looks as if it is running, thread_resume
	 * will not try to put it on the run queues.
	 *
	 * We can do all of this without locking, because nothing
	 * else is running yet.
	 */
	startup_thread->state |= TH_RUN;
	(void) thread_resume(startup_thread);

	/*
	 * Start the thread.
	 */
	cpu_launch_first_thread(startup_thread);
	/*NOTREACHED*/
}
示例#19
0
bool master_threads2::run_alone(const char* addrs, const char* path /* = NULL */,
	unsigned int count /* = 1 */, int threads_count /* = 1 */)
{
	// 每个进程只能有一个实例在运行
	acl_assert(has_called == false);
	has_called = true;
	daemon_mode_ = false;
	acl_assert(addrs && *addrs);

	__count_limit = count;

#ifdef WIN32
	acl_init();
#endif

	std::vector<ACL_VSTREAM*> sstreams;
	ACL_EVENT* eventp = acl_event_new_select_thr(1, 0);
	set_event(eventp);  // 设置基类的事件句柄

	ACL_ARGV*  tokens = acl_argv_split(addrs, ";,| \t");
	ACL_ITER   iter;

	acl_foreach(iter, tokens)
	{
		const char* addr = (const char*) iter.data;
		ACL_VSTREAM* sstream = acl_vstream_listen(addr, 128);
		if (sstream == NULL)
		{
			logger_error("listen %s error(%s)",
				addr, acl_last_serror());
			acl_argv_free(tokens);
			close_sstreams(eventp, sstreams);
			acl_event_free(eventp);
			return false;
		}
		acl_event_enable_listen(eventp, sstream, 0,
			listen_callback, sstream);
		sstreams.push_back(sstream);
	}

	acl_argv_free(tokens);

	// 初始化配置参数
	conf_.load(path);

	service_pre_jail(NULL);
	service_init(NULL);

	if (threads_count > 1)
	{
		__thread_pool = acl_thread_pool_create(threads_count, 120);
		acl_pthread_pool_atinit(__thread_pool, thread_begin, NULL);
		acl_pthread_pool_atfree(__thread_pool, thread_finish, NULL);
	}
	else
		thread_init(NULL);

	while (!__stop)
		acl_event_loop(eventp);

	if (__thread_pool)
		acl_pthread_pool_destroy(__thread_pool);
	else
		thread_exit(NULL);

	service_exit(NULL);

	// 必须在调用 acl_event_free 前调用 close_sstreams,因为在关闭
	// 网络流对象时依然有对 ACL_EVENT 引擎的使用
	close_sstreams(eventp, sstreams);
	acl_event_free(eventp);
	eventp = NULL;

	return true;
}
int thread_management_node_init(
    int8_t interface_id,
    channel_list_s *channel_list,
    device_configuration_s *device_configuration,
    link_configuration_s *static_configuration)
{
#ifdef HAVE_THREAD
    protocol_interface_info_entry_t *cur;
    nwk_scan_params_t *scan_params;

    if (!device_configuration) {
        return -1;
    }

    cur = protocol_stack_interface_info_get_by_id(interface_id);

    if (!cur) {
        tr_warn("Invalid interface id");
        return -1;
    }

    if (!cur->thread_info) {
        tr_warn("Not Thread specific interface");
        return -1;
    }

    if ((cur->lowpan_info & INTERFACE_NWK_ACTIVE) !=  0) {
        return -1;
    }

    if (cur->bootsrap_mode == ARM_NWK_BOOTSRAP_MODE_6LoWPAN_BORDER_ROUTER || cur->border_router_setup) {
        return -1;
    }

    if (thread_init(cur) < 0) {
        thread_nd_service_delete(cur->id);
        tr_warn("Thread Boostarp Init Fail");
        return -1;
    }
    if (thread_management_server_init(cur->id) != 0) {
        tr_warn("Thread management server init fail");
        return -1;
    }

    if (thread_diagnostic_init(cur->id) != 0) {
        tr_warn("Thread diagnostic init fail");
        return -1;
    }
    //Store setup to application Joiner Application
    if (thread_joiner_application_init(cur->id, device_configuration, static_configuration) != 0) {
        tr_error("mandatory device configuration missing");
        return -2;
    }

    // Joiner application copies and massages the device configuration - switch to massaged version
    device_configuration = thread_joiner_application_get_device_config(cur->id);
    if (!device_configuration) {
        return -1;
    }
    cur->if_lowpan_security_params->nwk_security_mode = NET_SEC_MODE_NO_LINK_SECURITY;
    cur->mac_parameters->mac_configured_sec_level = 0;

    // If no-one has already set a secret key, use the EUI-64 - Thread
    // wants RFC 7217 IIDs. Also ensure they're on for the Thread interface.
    // (Note that this will likely enable opaque IIDs on Ethernet too).
    if (!addr_opaque_iid_key_is_set()) {
        // Could we include some private key here?
        arm_nwk_ipv6_opaque_iid_key(device_configuration->eui64, 8);
        arm_nwk_ipv6_opaque_iid_enable(cur->id, true);
    }
    // Copy the channel list
    memset(&cur->mac_parameters->mac_channel_list, 0, sizeof(channel_list_s));
    if (channel_list) {
        // Application has given limited set of channels
        cur->mac_parameters->mac_channel_list = *channel_list;
    } else {
        cur->mac_parameters->mac_channel_list.channel_page = CHANNEL_PAGE_0;
        cur->mac_parameters->mac_channel_list.channel_mask[0] = 0x07FFF800;
    }

    scan_params = &cur->mac_parameters->nwk_scan_params;
    memset(&scan_params->stack_chan_list, 0, sizeof(channel_list_s));
    if (channel_list) {
        // Application has given limited set of channels
        scan_params->stack_chan_list = *channel_list;
    } else {
        scan_params->stack_chan_list.channel_page = CHANNEL_PAGE_0;
        scan_params->stack_chan_list.channel_mask[0] = 0x07FFF800;
    }
    scan_params->scan_duration = 5;

    cur->thread_info->masterSecretMaterial.valid_Info = false;
    thread_key_guard_timer_calculate(cur, static_configuration, true);

    cur->thread_info->maxChildCount = THREAD_MAX_CHILD_COUNT;
    cur->thread_info->rfc6775 = false;
    cur->thread_info->host_link_timeout = THREAD_END_DEVICE_DEFAULT_TIMEOUT;
    /* Thread will manage the address query timing, and report negatives. Set this high so as not to interfere. */
    cur->ipv6_neighbour_cache.retrans_timer = 10000;

    // Set default partition weighting
    cur->thread_info->partition_weighting = THREAD_DEFAULT_WEIGHTING;

    /* IP forwarding is off by default */
    cur->ip_forwarding = false;

    lowpan_adaptation_indirect_queue_params_set(cur,
                                                THREAD_INDIRECT_BIG_PACKET_THRESHOLD,
                                                THREAD_INDIRECT_BIG_PACKETS_TOTAL,
                                                THREAD_INDIRECT_SMALL_PACKETS_PER_CHILD);

    if (cur->bootsrap_mode == ARM_NWK_BOOTSRAP_MODE_6LoWPAN_SLEEPY_HOST) {
        cur->thread_info->requestFullNetworkData = false;
    } else {
        cur->thread_info->requestFullNetworkData = true;
    }

    cur->lowpan_info &= ~INTERFACE_NWK_BOOTSRAP_PANA_AUTHENTICATION;
    cur->configure_flags |= INTERFACE_SECURITY_DEFINED;
    cur->comm_status_ind_cb = thread_comm_status_indication_cb;
    return 0;
#else
    (void) interface_id;
    (void) channel_list;
    (void) device_configuration;
    (void) static_configuration;
    return -1;
#endif
}
示例#21
0
void
kernel_bootstrap(void)
{
	kern_return_t	result;
	thread_t	thread;
	char		namep[16];

	printf("%s\n", version); /* log kernel version */

	if (PE_parse_boot_argn("-l", namep, sizeof (namep))) /* leaks logging */
		turn_on_log_leaks = 1;

	PE_parse_boot_argn("trace", &new_nkdbufs, sizeof (new_nkdbufs));
	PE_parse_boot_argn("trace_wake", &wake_nkdbufs, sizeof (wake_nkdbufs));
	PE_parse_boot_argn("trace_panic", &write_trace_on_panic, sizeof(write_trace_on_panic));
	PE_parse_boot_argn("trace_typefilter", &trace_typefilter, sizeof(trace_typefilter));

	scale_setup();

	kernel_bootstrap_log("vm_mem_bootstrap");
	vm_mem_bootstrap();

	kernel_bootstrap_log("cs_init");
	cs_init();

	kernel_bootstrap_log("vm_mem_init");
	vm_mem_init();

	machine_info.memory_size = (uint32_t)mem_size;
	machine_info.max_mem = max_mem;
	machine_info.major_version = version_major;
	machine_info.minor_version = version_minor;


#if CONFIG_TELEMETRY
	kernel_bootstrap_log("telemetry_init");
	telemetry_init();
#endif

#if CONFIG_CSR
	kernel_bootstrap_log("csr_init");
	csr_init();
#endif

	kernel_bootstrap_log("stackshot_lock_init");	
	stackshot_lock_init();

	kernel_bootstrap_log("sched_init");
	sched_init();

	kernel_bootstrap_log("waitq_bootstrap");
	waitq_bootstrap();

	kernel_bootstrap_log("ipc_bootstrap");
	ipc_bootstrap();

#if CONFIG_MACF
	kernel_bootstrap_log("mac_policy_init");
	mac_policy_init();
#endif

	kernel_bootstrap_log("ipc_init");
	ipc_init();

	/*
	 * As soon as the virtual memory system is up, we record
	 * that this CPU is using the kernel pmap.
	 */
	kernel_bootstrap_log("PMAP_ACTIVATE_KERNEL");
	PMAP_ACTIVATE_KERNEL(master_cpu);

	kernel_bootstrap_log("mapping_free_prime");
	mapping_free_prime();						/* Load up with temporary mapping blocks */

	kernel_bootstrap_log("machine_init");
	machine_init();

	kernel_bootstrap_log("clock_init");
	clock_init();

	ledger_init();

	/*
	 *	Initialize the IPC, task, and thread subsystems.
	 */
#if CONFIG_COALITIONS
	kernel_bootstrap_log("coalitions_init");
	coalitions_init();
#endif

	kernel_bootstrap_log("task_init");
	task_init();

	kernel_bootstrap_log("thread_init");
	thread_init();

#if CONFIG_ATM
	/* Initialize the Activity Trace Resource Manager. */
	kernel_bootstrap_log("atm_init");
	atm_init();
#endif

#if CONFIG_BANK
	/* Initialize the BANK Manager. */
	kernel_bootstrap_log("bank_init");
	bank_init();
#endif
	
	/* initialize the corpse config based on boot-args */
	corpses_init();

	/*
	 *	Create a kernel thread to execute the kernel bootstrap.
	 */
	kernel_bootstrap_log("kernel_thread_create");
	result = kernel_thread_create((thread_continue_t)kernel_bootstrap_thread, NULL, MAXPRI_KERNEL, &thread);

	if (result != KERN_SUCCESS) panic("kernel_bootstrap: result = %08X\n", result);

	thread->state = TH_RUN;
	thread->last_made_runnable_time = mach_absolute_time();
	thread_deallocate(thread);

	kernel_bootstrap_log("load_context - done");
	load_context(thread);
	/*NOTREACHED*/
}
示例#22
0
/* -------------------------------------------------------------------
 * main()
 *      Entry point into Iperf
 *
 * sets up signal handlers
 * initialize global locks and conditions
 * parses settings from environment and command line
 * starts up server or client thread
 * waits for all threads to complete
 * ------------------------------------------------------------------- */
int main( int argc, char **argv ) {

    // Set SIGTERM and SIGINT to call our user interrupt function
    my_signal( SIGTERM, Sig_Interupt );
    my_signal( SIGINT,  Sig_Interupt );
    my_signal( SIGALRM,  Sig_Interupt );

#ifndef WIN32
    // Ignore broken pipes
    signal(SIGPIPE,SIG_IGN);
#else
    // Start winsock
    WSADATA wsaData;
    int rc = WSAStartup( 0x202, &wsaData );
    WARN_errno( rc == SOCKET_ERROR, "WSAStartup" );
	if (rc == SOCKET_ERROR)
		return 0;

    // Tell windows we want to handle our own signals
    SetConsoleCtrlHandler( sig_dispatcher, true );
#endif

    // Initialize global mutexes and conditions
    Condition_Initialize ( &ReportCond );
    Mutex_Initialize( &groupCond );
    Mutex_Initialize( &clients_mutex );

    // Initialize the thread subsystem
    thread_init( );

    // Initialize the interrupt handling thread to 0
    sThread = thread_zeroid();

    // perform any cleanup when quitting Iperf
    atexit( cleanup );

    // Allocate the "global" settings
    thread_Settings* ext_gSettings = new thread_Settings;

    // Initialize settings to defaults
    Settings_Initialize( ext_gSettings );
    // read settings from environment variables
    Settings_ParseEnvironment( ext_gSettings );
    // read settings from command-line parameters
    Settings_ParseCommandLine( argc, argv, ext_gSettings );

    // Check for either having specified client or server
    if ( ext_gSettings->mThreadMode == kMode_Client 
         || ext_gSettings->mThreadMode == kMode_Listener ) {
#ifdef WIN32
        // Start the server as a daemon
        // Daemon mode for non-windows in handled
        // in the listener_spawn function
        if ( isDaemon( ext_gSettings ) ) {
            CmdInstallService(argc, argv);
            return 0;
        }

        // Remove the Windows service if requested
        if ( isRemoveService( ext_gSettings ) ) {
            // remove the service
            if ( CmdRemoveService() ) {
                fprintf(stderr, "IPerf Service is removed.\n");

                return 0;
            }
        }
#endif
        // initialize client(s)
        if ( ext_gSettings->mThreadMode == kMode_Client ) {
            client_init( ext_gSettings );
        }

#ifdef HAVE_THREAD
        // start up the reporter and client(s) or listener
        {
            thread_Settings *into = NULL;
            // Create the settings structure for the reporter thread
            Settings_Copy( ext_gSettings, &into );
            into->mThreadMode = kMode_Reporter;

            // Have the reporter launch the client or listener
            into->runNow = ext_gSettings;
            
            // Start all the threads that are ready to go
            thread_start( into );
        }
#else
        // No need to make a reporter thread because we don't have threads
        thread_start( ext_gSettings );
#endif
    } else {
        // neither server nor client mode was specified
        // print usage and exit

#ifdef WIN32
        // In Win32 we also attempt to start a previously defined service
        // Starting in 2.0 to restart a previously defined service
        // you must call iperf with "iperf -D" or using the environment variable
        SERVICE_TABLE_ENTRY dispatchTable[] =
        {
            { TEXT(SZSERVICENAME), (LPSERVICE_MAIN_FUNCTION)service_main},
            { NULL, NULL}
        };

        // Only attempt to start the service if "-D" was specified
        if ( !isDaemon(ext_gSettings) ||
             // starting the service by SCM, there is no arguments will be passed in.
             // the arguments will pass into Service_Main entry.
             !StartServiceCtrlDispatcher(dispatchTable) )
            // If the service failed to start then print usage
#endif
        fprintf( stderr, usage_short, argv[0], argv[0] );

        return 0;
    }

    // wait for other (client, server) threads to complete
    thread_joinall();
    
    // all done!
    return 0;
} // end main
示例#23
0
extern "C" int
_start(kernel_args *bootKernelArgs, int currentCPU)
{
	if (bootKernelArgs->kernel_args_size != sizeof(kernel_args)
		|| bootKernelArgs->version != CURRENT_KERNEL_ARGS_VERSION) {
		// This is something we cannot handle right now - release kernels
		// should always be able to handle the kernel_args of earlier
		// released kernels.
		debug_early_boot_message("Version mismatch between boot loader and "
			"kernel!\n");
		return -1;
	}

	smp_set_num_cpus(bootKernelArgs->num_cpus);

	// wait for all the cpus to get here
	smp_cpu_rendezvous(&sCpuRendezvous, currentCPU);

	// the passed in kernel args are in a non-allocated range of memory
	if (currentCPU == 0)
		memcpy(&sKernelArgs, bootKernelArgs, sizeof(kernel_args));

	smp_cpu_rendezvous(&sCpuRendezvous2, currentCPU);

	// do any pre-booting cpu config
	cpu_preboot_init_percpu(&sKernelArgs, currentCPU);
	thread_preboot_init_percpu(&sKernelArgs, currentCPU);

	// if we're not a boot cpu, spin here until someone wakes us up
	if (smp_trap_non_boot_cpus(currentCPU, &sCpuRendezvous3)) {
		// init platform
		arch_platform_init(&sKernelArgs);

		// setup debug output
		debug_init(&sKernelArgs);
		set_dprintf_enabled(true);
		dprintf("Welcome to kernel debugger output!\n");
		dprintf("Haiku revision: %s\n", get_haiku_revision());

		// init modules
		TRACE("init CPU\n");
		cpu_init(&sKernelArgs);
		cpu_init_percpu(&sKernelArgs, currentCPU);
		TRACE("init interrupts\n");
		int_init(&sKernelArgs);

		TRACE("init VM\n");
		vm_init(&sKernelArgs);
			// Before vm_init_post_sem() is called, we have to make sure that
			// the boot loader allocated region is not used anymore
		boot_item_init();
		debug_init_post_vm(&sKernelArgs);
		low_resource_manager_init();

		// now we can use the heap and create areas
		arch_platform_init_post_vm(&sKernelArgs);
		lock_debug_init();
		TRACE("init driver_settings\n");
		driver_settings_init(&sKernelArgs);
		debug_init_post_settings(&sKernelArgs);
		TRACE("init notification services\n");
		notifications_init();
		TRACE("init teams\n");
		team_init(&sKernelArgs);
		TRACE("init ELF loader\n");
		elf_init(&sKernelArgs);
		TRACE("init modules\n");
		module_init(&sKernelArgs);
		TRACE("init semaphores\n");
		haiku_sem_init(&sKernelArgs);
		TRACE("init interrupts post vm\n");
		int_init_post_vm(&sKernelArgs);
		cpu_init_post_vm(&sKernelArgs);
		commpage_init();
		TRACE("init system info\n");
		system_info_init(&sKernelArgs);

		TRACE("init SMP\n");
		smp_init(&sKernelArgs);
		TRACE("init timer\n");
		timer_init(&sKernelArgs);
		TRACE("init real time clock\n");
		rtc_init(&sKernelArgs);
		timer_init_post_rtc();

		TRACE("init condition variables\n");
		condition_variable_init();

		// now we can create and use semaphores
		TRACE("init VM semaphores\n");
		vm_init_post_sem(&sKernelArgs);
		TRACE("init generic syscall\n");
		generic_syscall_init();
		smp_init_post_generic_syscalls();
		TRACE("init scheduler\n");
		scheduler_init();
		TRACE("init threads\n");
		thread_init(&sKernelArgs);
		TRACE("init kernel daemons\n");
		kernel_daemon_init();
		arch_platform_init_post_thread(&sKernelArgs);

		TRACE("init I/O interrupts\n");
		int_init_io(&sKernelArgs);
		TRACE("init VM threads\n");
		vm_init_post_thread(&sKernelArgs);
		low_resource_manager_init_post_thread();
		TRACE("init DPC\n");
		dpc_init();
		TRACE("init VFS\n");
		vfs_init(&sKernelArgs);
#if ENABLE_SWAP_SUPPORT
		TRACE("init swap support\n");
		swap_init();
#endif
		TRACE("init POSIX semaphores\n");
		realtime_sem_init();
		xsi_sem_init();
		xsi_msg_init();

		// Start a thread to finish initializing the rest of the system. Note,
		// it won't be scheduled before calling scheduler_start() (on any CPU).
		TRACE("spawning main2 thread\n");
		thread_id thread = spawn_kernel_thread(&main2, "main2",
			B_NORMAL_PRIORITY, NULL);
		resume_thread(thread);

		// We're ready to start the scheduler and enable interrupts on all CPUs.
		scheduler_enable_scheduling();

		// bring up the AP cpus in a lock step fashion
		TRACE("waking up AP cpus\n");
		sCpuRendezvous = sCpuRendezvous2 = 0;
		smp_wake_up_non_boot_cpus();
		smp_cpu_rendezvous(&sCpuRendezvous, 0); // wait until they're booted

		// exit the kernel startup phase (mutexes, etc work from now on out)
		TRACE("exiting kernel startup\n");
		gKernelStartup = false;

		smp_cpu_rendezvous(&sCpuRendezvous2, 0);
			// release the AP cpus to go enter the scheduler

		TRACE("starting scheduler on cpu 0 and enabling interrupts\n");
		scheduler_start();
		enable_interrupts();
	} else {
		// lets make sure we're in sync with the main cpu
		// the boot processor has probably been sending us
		// tlb sync messages all along the way, but we've
		// been ignoring them
		arch_cpu_global_TLB_invalidate();

		// this is run for each non boot processor after they've been set loose
		cpu_init_percpu(&sKernelArgs, currentCPU);
		smp_per_cpu_init(&sKernelArgs, currentCPU);

		// wait for all other AP cpus to get to this point
		smp_cpu_rendezvous(&sCpuRendezvous, currentCPU);
		smp_cpu_rendezvous(&sCpuRendezvous2, currentCPU);

		// welcome to the machine
		scheduler_start();
		enable_interrupts();
	}

#ifdef TRACE_BOOT
	// We disable interrupts for this dprintf(), since otherwise dprintf()
	// would acquires a mutex, which is something we must not do in an idle
	// thread, or otherwise the scheduler would be seriously unhappy.
	disable_interrupts();
	TRACE("main: done... begin idle loop on cpu %d\n", currentCPU);
	enable_interrupts();
#endif

	for (;;)
		arch_cpu_idle();

	return 0;
}
示例#24
0
/*
 *	Running in virtual memory, on the interrupt stack.
 *	Does not return.  Dispatches initial thread.
 *
 *	Assumes that master_cpu is set.
 */
void
setup_main(void)
{
	thread_t		startup_thread;

	printf_init();
	panic_init();

	sched_init();
	vm_mem_bootstrap();
	ipc_bootstrap();
	vm_mem_init();
	ipc_init();

	/*
	 * As soon as the virtual memory system is up, we record
	 * that this CPU is using the kernel pmap.
	 */
	PMAP_ACTIVATE_KERNEL(master_cpu);

	init_timers();
	timeout_init();

#if	CDLI > 0
	ns_init();	/* Initialize CDLI */
#endif	/* CDLI > 0 */

	dev_lookup_init();
	timeout_init();
	machine_init();

	machine_info.max_cpus = NCPUS;
	machine_info.memory_size = mem_size;
	machine_info.avail_cpus = 0;
	machine_info.major_version = KERNEL_MAJOR_VERSION;
	machine_info.minor_version = KERNEL_MINOR_VERSION;

#if	XPR_DEBUG
	xprbootstrap();
#endif	/* XPR_DEBUG */

	/*
	 *	Initialize the IPC, task, and thread subsystems.
	 */
	clock_init();
	utime_init();
        ledger_init();
#if	THREAD_SWAPPER
	thread_swapper_init();
#endif	/* THREAD_SWAPPER */
#if	TASK_SWAPPER
	task_swapper_init();
#endif	/* TASK_SWAPPER */
	task_init();
	act_init();
	thread_init();
	subsystem_init();
#if	TASK_SWAPPER
	task_swappable(&realhost, kernel_task, FALSE);
#endif	/* TASK_SWAPPER */
#if	MACH_HOST
	pset_sys_init();
#endif	/* MACH_HOST */

	/*
	 *	Kick off the time-out driven routines by calling
	 *	them the first time.
	 */
	recompute_priorities();
	compute_mach_factor();

	/*
	 *	Initialize the Event Trace Analysis Package.
	 * 	Dynamic Phase: 2 of 2
	 */
	etap_init_phase2();
	
	/*
	 *	Create a kernel thread to start the other kernel
	 *	threads.  Thread_resume (from kernel_thread) calls
	 *	thread_setrun, which may look at current thread;
	 *	we must avoid this, since there is no current thread.
	 */

	/*
	 * Create the thread, and point it at the routine.
	 */
	(void) thread_create_at(kernel_task, &startup_thread,
							start_kernel_threads);
#if	NCPUS > 1 && PARAGON860
	thread_bind(startup_thread, cpu_to_processor(master_cpu));
#endif
	/*
	 * Pretend it is already running, and resume it.
	 * Since it looks as if it is running, thread_resume
	 * will not try to put it on the run queues.
	 *
	 * We can do all of this without locking, because nothing
	 * else is running yet.
	 */
	startup_thread->state |= TH_RUN;
	(void) thread_resume(startup_thread->top_act);

	/*
	 * Start the thread.
	 */
	cpu_launch_first_thread(startup_thread);
	/*NOTREACHED*/
	panic("cpu_launch_first_thread returns!");
}
示例#25
0
文件: startup.c 项目: TalAloni/xnu
void
kernel_bootstrap(void)
{
	kern_return_t	result;
	thread_t	thread;
	char		namep[16];

	printf("%s\n", version); /* log kernel version */

#define kernel_bootstrap_kprintf(x...) /* kprintf("kernel_bootstrap: " x) */

	if (PE_parse_boot_argn("-l", namep, sizeof (namep))) /* leaks logging */
		turn_on_log_leaks = 1;

	PE_parse_boot_argn("trace", &new_nkdbufs, sizeof (new_nkdbufs));

	PE_parse_boot_argn("trace_wake", &wake_nkdbufs, sizeof (wake_nkdbufs));

	/* i386_vm_init already checks for this ; do it aagin anyway */
        if (PE_parse_boot_argn("serverperfmode", &serverperfmode, sizeof (serverperfmode))) {
                serverperfmode = 1;
        }
	scale_setup();

	kernel_bootstrap_kprintf("calling vm_mem_bootstrap\n");
	vm_mem_bootstrap();

	kernel_bootstrap_kprintf("calling cs_init\n");
	cs_init();

	kernel_bootstrap_kprintf("calling vm_mem_init\n");
	vm_mem_init();

	machine_info.memory_size = (uint32_t)mem_size;
	machine_info.max_mem = max_mem;
	machine_info.major_version = version_major;
	machine_info.minor_version = version_minor;

#if CONFIG_TELEMETRY
	kernel_bootstrap_kprintf("calling telemetry_init\n");
	telemetry_init();
#endif

	kernel_bootstrap_kprintf("calling stackshot_lock_init\n");	
	stackshot_lock_init();

	kernel_bootstrap_kprintf("calling sched_init\n");
	sched_init();

	kernel_bootstrap_kprintf("calling wait_queue_bootstrap\n");
	wait_queue_bootstrap();

	kernel_bootstrap_kprintf("calling ipc_bootstrap\n");
	ipc_bootstrap();

#if CONFIG_MACF
	mac_policy_init();
#endif
	kernel_bootstrap_kprintf("calling ipc_init\n");
	ipc_init();

	/*
	 * As soon as the virtual memory system is up, we record
	 * that this CPU is using the kernel pmap.
	 */
	kernel_bootstrap_kprintf("calling PMAP_ACTIVATE_KERNEL\n");
	PMAP_ACTIVATE_KERNEL(master_cpu);

	kernel_bootstrap_kprintf("calling mapping_free_prime\n");
	mapping_free_prime();						/* Load up with temporary mapping blocks */

	kernel_bootstrap_kprintf("calling machine_init\n");
	machine_init();

	kernel_bootstrap_kprintf("calling clock_init\n");
	clock_init();

	ledger_init();

	/*
	 *	Initialize the IPC, task, and thread subsystems.
	 */
	kernel_bootstrap_kprintf("calling task_init\n");
	task_init();

	kernel_bootstrap_kprintf("calling thread_init\n");
	thread_init();
	
	/*
	 *	Create a kernel thread to execute the kernel bootstrap.
	 */
	kernel_bootstrap_kprintf("calling kernel_thread_create\n");
	result = kernel_thread_create((thread_continue_t)kernel_bootstrap_thread, NULL, MAXPRI_KERNEL, &thread);

	if (result != KERN_SUCCESS) panic("kernel_bootstrap: result = %08X\n", result);

	thread->state = TH_RUN;
	thread_deallocate(thread);

	kernel_bootstrap_kprintf("calling load_context - done\n");
	load_context(thread);
	/*NOTREACHED*/
}
示例#26
0
文件: main.c 项目: AubrCool/ble-1
int main()
{
	int i;

#ifdef FPGA 
	pll_init();
#else
	bt16_pll_init();
#endif
    delay(500000);

    uart_init((96000000/ 460800));  // pa8
    puts(pubDate);
    puts("...fpga bt16 setup ok.......\n");

#ifdef FPGA 
	spi_int();  
#endif
    puts("-----1\n");
	system_init();

    puts("-----2\n");
	timer0_start();

    puts("-----3\n");
	RF_init();

    //----------debug
    HWI_Install(1, exception_isr, 3) ; //timer0_isr
    

	ENABLE_INT();

    puts("-----4\n");
	thread_init(os_create_thread, os_delete_thread);

    puts("-----5\n");
	sys_timer_init();

    puts("-----6\n");
    ble_main();
    btstack_main();

	/* device_manager_init(); */

	/*INTALL_HWI(BT_BLE_INT, le_hw_isr, 0);
	INTALL_HWI(18, le_test_uart_isr, 0);*/

	lbuf_init(malloc_buf, sizeof(malloc_buf)*4);

	/* btstack_v21_main(); */

    puts("------------4.0 start run loop-----------\n");
    while(1)
    {
		int c;
       //asm("idle");
	   /*delay(100000);*/
		for (i=0; i<PRIORITY_NUM; i++)
		{
			if (thread_fun[i]){
				thread_fun[i](i);
			}

		}
        c = getchar();
        switch(c)
        {
            case 'A':
                puts("user cmd : ADV\n");
                ble_set_adv();
                break;
            case 'S':
                puts("user cmd : SCAN\n");
                ble_set_scan();
                break;
            default:
                break;
        }

		/*run_loop_execute();*/
	   /*printf("k");*/
    }

    return 0;
}
示例#27
0
int bacstack_session_init(bacstack_session_t *session)
{
  int ret = 1;
  memset(session, 0, sizeof(*session));

  /* this setting sets the range that is used
   * as the network numbers of directly attached netork.
   * For example, if this value is set to 1000, then
   * the network out of port 0 will be assigned
   * network number 1000. The network out of port
   * 100 would be assigned network number 1100. This
   * number must be chosen to not conflict with
   * existing network numbers on the BACnet network */
  session->local_networks_origin = 65535 - 255;


  if(!rwlock_init(&session->routetable_lock)) {
    ret = 0;
    goto done;
  }
  
  if(!bacstack_routetable_init(&session->routetable, 2048)) {
    ret = 0;
    goto done;
  }

  if(!pool_init(&session->message_pool, BACSTACK_SESSION_MESSAGE_POOL_CAPACITY)) {
    ret = 0;
    goto done;
  }

  for(int i = 0; i < BACSTACK_SESSION_MESSAGE_POOL_CAPACITY; i++) {
    bacstack_message_t *message = malloc(sizeof(bacstack_message_t));
    if(message == NULL || !bacstack_message_init(message)) {
      ret = 0;
      goto done;
    }

    if(!pool_release(&session->message_pool, message)) {
      ret = 0;
      goto done;
    }
  }

  if(!pool_init(&session->proc_pool, BACSTACK_SESSION_MESSAGE_POOL_CAPACITY)) {
    ret = 0;
    goto done;
  }

  if(!bacdl_server_init(&session->dl_server, 54321)) {
    ret = 0;
    goto done;
  }

  if(!thread_init(&session->msg_proc_thread, bacstack_session_msg_proc_thread_handler, session)) {
    ret = 0;
    goto done;
  }

  if(!thread_init(&session->dl_accept_thread, bacstack_session_dl_accept_thread_handler, session)) {
    ret = 0;
    goto done;
  }

  if(!thread_init(&session->dl_receive_thread, bacstack_session_dl_receive_thread_handler, session)) {
    ret = 0;
    goto done;
  }

done:
  if(!ret){
    rwlock_destroy(&session->routetable_lock);
    bacstack_routetable_destroy(&session->routetable);
    pool_destroy(&session->message_pool);
    pool_destroy(&session->proc_pool);
    bacdl_server_destroy(&session->dl_server);
    thread_destroy(&session->msg_proc_thread);
    thread_destroy(&session->dl_accept_thread);
    thread_destroy(&session->dl_receive_thread);
  }
  return ret;
}
示例#28
0
void
freevms_main(void)
{
    char                        *command_line;

#   define                      ROOT_DEVICE_LENGTH 80
    char                        root_device[ROOT_DEVICE_LENGTH];
#   define                      CONSOLE_DEVICE_LENGTH 80
    char                        console_device[CONSOLE_DEVICE_LENGTH];

    L4_BootRec_t                *boot_record;

    L4_KernelInterfacePage_t    *kip;

    L4_ProcDesc_t               *main_proc_desc;

    L4_ThreadId_t               root_tid;
    L4_ThreadId_t               s0_tid;

    L4_Word_t                   api_flags;
    L4_Word_t                   boot_info;
    L4_Word_t                   i;
    L4_Word_t                   kernel_id;
    L4_Word_t                   kernel_interface;
    L4_Word_t                   num_boot_info_entries;
    L4_Word_t                   num_processors;
    L4_Word_t                   page_bits;
    L4_Word_t                   pagesize;

    struct vms$meminfo          mem_info;

    vms$pd_initialized = 0;

    notice("\n");
    notice(">>> FreeVMS %s (R)\n", FREEVMS_VERSION);
    notice("\n");

    kip = (L4_KernelInterfacePage_t *) L4_KernelInterface(&kernel_interface,
            &api_flags, &kernel_id);

    notice(SYSBOOT_I_SYSBOOT "leaving kernel privileges\n");
    notice(SYSBOOT_I_SYSBOOT "launching FreeVMS kernel with executive "
            "privileges\n");
    root_tid = L4_Myself();
    s0_tid = L4_GlobalId(kip->ThreadInfo.X.UserBase, 1);

    notice(SYSBOOT_I_SYSBOOT "booting main processor\n");

    for(page_bits = 0; !((1 << page_bits) & L4_PageSizeMask(kip)); page_bits++);
    pagesize = (((vms$pointer) 1) << page_bits);
    notice(SYSBOOT_I_SYSBOOT "computing page size: %d bytes\n",
            (int) pagesize);

    num_processors = L4_NumProcessors((void *) kip);

    switch(num_processors - 1)
    {
        case 0:
            break;

        case 1:
            notice(SYSBOOT_I_SYSBOOT "booting %d secondary processor\n",
                    (int) (num_processors - 1));
            break;

        default:
            notice(SYSBOOT_I_SYSBOOT "booting %d secondary processors\n",
                    (int) (num_processors - 1));
            break;
    }

    for(i = 0; i < num_processors; i++)
    {
        main_proc_desc = L4_ProcDesc((void *) kip, i);
        notice(SYSBOOT_I_SYSBOOT "CPU%d EXTFREQ=%d MHz, INTFREQ=%d MHz\n",
                (int) i, (int) (main_proc_desc->X.ExternalFreq / 1000),
                (int) (main_proc_desc->X.InternalFreq / 1000));
    }

    L4_Sigma0_GetPage(L4_nilthread, L4_Fpage(L4_BootInfo(kip), pagesize));

    boot_info = L4_BootInfo((void *) kip);
    num_boot_info_entries = L4_BootInfo_Entries((void *) boot_info);
    boot_record = L4_BootInfo_FirstEntry((void *) boot_info);

    for(i = 2; i < num_boot_info_entries; i++)
    {
        PANIC(L4_BootRec_Type(boot_record) != L4_BootInfo_SimpleExec);
        command_line = L4_SimpleExec_Cmdline(boot_record);

        if ((strstr(command_line, "vmskernel.sys") != NULL) && (i == 3))
        {
            break;
        }

        boot_record = L4_BootRec_Next(boot_record);
    }

    PANIC(L4_BootRec_Type(boot_record) != L4_BootInfo_SimpleExec);
    command_line = L4_SimpleExec_Cmdline(boot_record);
    notice(SYSBOOT_I_SYSBOOT "parsing command line: %s\n", command_line);
    sys$parsing(command_line, (char *) "root", root_device,
            ROOT_DEVICE_LENGTH);
    notice(SYSBOOT_I_SYSBOOT "selecting root device: %s\n", root_device);
    sys$parsing(command_line, (char *) "console", console_device,
            CONSOLE_DEVICE_LENGTH);
    notice(SYSBOOT_I_SYSBOOT "selecting console device: %s\n", console_device);

    dbg$virtual_memory = (strstr(command_line, " dbg$virtual_memory") != NULL)
            ? 1 : 0;
    dbg$sys_pagefault = (strstr(command_line, " dbg$sys_pagefault") != NULL)
            ? 1 : 0;
    dbg$vms_pagefault = (strstr(command_line, " dbg$vms_pagefault") != NULL)
            ? 1 : 0;

    // Starting virtual memory subsystem
    sys$mem_init(kip, &mem_info, pagesize);
    sys$bootstrap(&mem_info, pagesize);
    sys$objtable_init();
    sys$utcb_init(kip);
    sys$pd_init(&mem_info);
    sys$thread_init(kip);
    sys$populate_init_objects(&mem_info, pagesize);

    dev$init();
    names$init();

    sys$pager(kip, &mem_info, pagesize, root_device);
    sys$init(kip, &mem_info, pagesize, root_device);
    sys$loop();

    notice(">>> System halted\n");
    return;
}
示例#29
0
文件: libzfs_import.c 项目: JMoVS/zfs
/*
 * Given a list of directories to search, find all pools stored on disk.  This
 * includes partial pools which are not available to import.  If no args are
 * given (argc is 0), then the default directory (/dev/dsk) is searched.
 * poolname or guid (but not both) are provided by the caller when trying
 * to import a specific pool.
 */
static nvlist_t *
zpool_find_import_impl(libzfs_handle_t *hdl, importargs_t *iarg)
{
	int i, dirs = iarg->paths;
	struct dirent *dp;
	char path[MAXPATHLEN];
	char *end, **dir = iarg->path;
	size_t pathleft;
	nvlist_t *ret = NULL;
	pool_list_t pools = { 0 };
	pool_entry_t *pe, *penext;
	vdev_entry_t *ve, *venext;
	config_entry_t *ce, *cenext;
	name_entry_t *ne, *nenext;
	avl_tree_t slice_cache;
	rdsk_node_t *slice;
	void *cookie;

	verify(iarg->poolname == NULL || iarg->guid == 0);

	if (dirs == 0) {
#ifdef HAVE_LIBBLKID
		/* Use libblkid to scan all device for their type */
		if (zpool_find_import_blkid(hdl, &pools) == 0)
			goto skip_scanning;

		(void) zfs_error_fmt(hdl, EZFS_BADCACHE,
		    dgettext(TEXT_DOMAIN, "blkid failure falling back "
		    "to manual probing"));
#endif /* HAVE_LIBBLKID */

		dir = zpool_default_import_path;
		dirs = DEFAULT_IMPORT_PATH_SIZE;
	}

	/*
	 * Go through and read the label configuration information from every
	 * possible device, organizing the information according to pool GUID
	 * and toplevel GUID.
	 */
	for (i = 0; i < dirs; i++) {
		taskq_t *t;
		char *rdsk;
		int dfd;
		boolean_t config_failed = B_FALSE;
		DIR *dirp;

		/* use realpath to normalize the path */
		if (realpath(dir[i], path) == 0) {

			/* it is safe to skip missing search paths */
			if (errno == ENOENT)
				continue;

			zfs_error_aux(hdl, strerror(errno));
			(void) zfs_error_fmt(hdl, EZFS_BADPATH,
			    dgettext(TEXT_DOMAIN, "cannot open '%s'"), dir[i]);
			goto error;
		}
		end = &path[strlen(path)];
		*end++ = '/';
		*end = 0;
		pathleft = &path[sizeof (path)] - end;

		/*
		 * Using raw devices instead of block devices when we're
		 * reading the labels skips a bunch of slow operations during
		 * close(2) processing, so we replace /dev/dsk with /dev/rdsk.
		 */
		if (strcmp(path, "/dev/dsk/") == 0)
			rdsk = "/dev/rdsk/";
		else
			rdsk = path;

		if ((dfd = open(rdsk, O_RDONLY)) < 0 ||
		    (dirp = fdopendir(dfd)) == NULL) {
			if (dfd >= 0)
				(void) close(dfd);
			zfs_error_aux(hdl, strerror(errno));
			(void) zfs_error_fmt(hdl, EZFS_BADPATH,
			    dgettext(TEXT_DOMAIN, "cannot open '%s'"),
			    rdsk);
			goto error;
		}

		avl_create(&slice_cache, slice_cache_compare,
		    sizeof (rdsk_node_t), offsetof(rdsk_node_t, rn_node));

		/*
		 * This is not MT-safe, but we have no MT consumers of libzfs
		 */
		while ((dp = readdir(dirp)) != NULL) {
			const char *name = dp->d_name;
			if (name[0] == '.' &&
			    (name[1] == 0 || (name[1] == '.' && name[2] == 0)))
				continue;

			slice = zfs_alloc(hdl, sizeof (rdsk_node_t));
			slice->rn_name = zfs_strdup(hdl, name);
			slice->rn_avl = &slice_cache;
			slice->rn_dfd = dfd;
			slice->rn_hdl = hdl;
			slice->rn_nozpool = B_FALSE;
			avl_add(&slice_cache, slice);
		}
		/*
		 * create a thread pool to do all of this in parallel;
		 * rn_nozpool is not protected, so this is racy in that
		 * multiple tasks could decide that the same slice can
		 * not hold a zpool, which is benign.  Also choose
		 * double the number of processors; we hold a lot of
		 * locks in the kernel, so going beyond this doesn't
		 * buy us much.
		 */
		thread_init();
		t = taskq_create("z_import", 2 * max_ncpus, defclsyspri,
		    2 * max_ncpus, INT_MAX, TASKQ_PREPOPULATE);
		for (slice = avl_first(&slice_cache); slice;
		    (slice = avl_walk(&slice_cache, slice,
		    AVL_AFTER)))
			(void) taskq_dispatch(t, zpool_open_func, slice,
			    TQ_SLEEP);
		taskq_wait(t);
		taskq_destroy(t);
		thread_fini();

		cookie = NULL;
		while ((slice = avl_destroy_nodes(&slice_cache,
		    &cookie)) != NULL) {
			if (slice->rn_config != NULL && !config_failed) {
				nvlist_t *config = slice->rn_config;
				boolean_t matched = B_TRUE;

				if (iarg->poolname != NULL) {
					char *pname;

					matched = nvlist_lookup_string(config,
					    ZPOOL_CONFIG_POOL_NAME,
					    &pname) == 0 &&
					    strcmp(iarg->poolname, pname) == 0;
				} else if (iarg->guid != 0) {
					uint64_t this_guid;

					matched = nvlist_lookup_uint64(config,
					    ZPOOL_CONFIG_POOL_GUID,
					    &this_guid) == 0 &&
					    iarg->guid == this_guid;
				}
				if (!matched) {
					nvlist_free(config);
				} else {
					/*
					 * use the non-raw path for the config
					 */
					(void) strlcpy(end, slice->rn_name,
					    pathleft);
					if (add_config(hdl, &pools, path, i+1,
					    slice->rn_num_labels, config) != 0)
						config_failed = B_TRUE;
				}
			}
			free(slice->rn_name);
			free(slice);
		}
		avl_destroy(&slice_cache);

		(void) closedir(dirp);

		if (config_failed)
			goto error;
	}

#ifdef HAVE_LIBBLKID
skip_scanning:
#endif
	ret = get_configs(hdl, &pools, iarg->can_be_active);

error:
	for (pe = pools.pools; pe != NULL; pe = penext) {
		penext = pe->pe_next;
		for (ve = pe->pe_vdevs; ve != NULL; ve = venext) {
			venext = ve->ve_next;
			for (ce = ve->ve_configs; ce != NULL; ce = cenext) {
				cenext = ce->ce_next;
				if (ce->ce_config)
					nvlist_free(ce->ce_config);
				free(ce);
			}
			free(ve);
		}
		free(pe);
	}

	for (ne = pools.names; ne != NULL; ne = nenext) {
		nenext = ne->ne_next;
		free(ne->ne_name);
		free(ne);
	}

	return (ret);
}
示例#30
0
int main()
{
	int ret;
	//环境的初始化
	inittest();
	u8 id1,id2;
	ret = thread_init();                //初始化模块环境
	if(ret){
		printf("thread init error!\n");
		goto error;
	}

	id1 = 2;
	ret = thread_create(id1, (void *)thread_test1, NULL, THREAD_MODE_NORMAL, 0);             //建立普通线程
	if(ret){
		printf("thread1 create error!\n");
		goto error;
	}
	id2 = 3;
	u8 test_num = 10;
	u8 prio = 5;
	ret = thread_create(id2, (void *)thread_test2, &test_num, THREAD_MODE_REALTIME, prio);   //建立实时线程
	if(ret){
		printf("thread1 create error!\n");
		goto error;
	}
	sleep(5);
	/*********测试用例1**************/
	ret = thread_cancel(id1);              //普通线程取消
	assert(ret==0,"test1:thread cancel fail!");

	/*********测试用例2**************/
	ret = thread_cancel(id2);              //实时线程取消
	assert(ret==0,"test2:thread cancel fail!");

	/*********测试用例3**************/
	id1 = 1;
	ret = thread_create(id1, (void *)thread_test1, NULL, THREAD_MODE_NORMAL, 0);             //建立普通线程
	if(ret){
		printf("thread1 create error!\n");
		goto error;
	}
	ret = thread_cancel(id1);              //普通线程取消
	assert(ret==0,"test3:thread cancel fail!");

	/*********测试用例4**************/
	id1 = 31;
	ret = thread_create(id1, (void *)thread_test1, NULL, THREAD_MODE_NORMAL, 0);             //建立普通线程
	if(ret){
		printf("thread1 create error!\n");
		goto error;
	}
	ret = thread_cancel(id1);              //普通线程取消
	assert(ret==0,"test4:thread cancel fail!");

	/*********测试用例5**************/
	id1 = 32;
	ret = thread_cancel(id1);              //普通线程取消
	assert(ret==-ERR_INVAL,"test5:thread cancel fail!");

	/*********测试用例6**************/
	id1 = 6;
	ret = thread_cancel(id1);              //普通线程取消
	assert(ret==-ERR_NODEV,"test6:thread cancel fail!");

	sleep(5);
	finaltest();

error:
	exit(0);
}