Beispiel #1
0
/**
 * Set the process priority from LOWEST to HIGHEST, check if returns correct
 */
void test_proc_p1_4() {
    int i = 0;
    int ret;
    int proc = 3;

    while (1) {
        //printf("Process 4\r\n");
        ret = get_process_priority(g_test_procs[proc].pid);
        if (ret != LOW) {
            test_results[g_test_procs[proc].pid] = 0;
        }
        ret = set_process_priority(g_test_procs[proc].pid, HIGH);
        if (ret != 0) {
            test_results[g_test_procs[proc].pid] = 0;
        }
        ret = get_process_priority(g_test_procs[proc].pid);
        if (ret != HIGH) {
            test_results[g_test_procs[proc].pid] = 0;
        }

        ret = set_process_priority(g_test_procs[proc].pid, LOW);
        if (ret != 0) {
            test_results[g_test_procs[proc].pid] = 0;
        }
        if (i == 0) {
            if (test_results[proc] == 1) {
                printf("G005_test: test 4 OK\r\n");
            } else {
                printf("G005_test: test 4 FAIL\r\n");
            }
        }
        i = 1;
        ret = release_processor();
    }
}
Beispiel #2
0
void prepare_system(const struct config *config)
{
	if (config->verbose)
		printf("set cpu affinity to cpu #%u\n", config->cpu);

	set_cpu_affinity(config->cpu);

	switch (config->prio) {
	case SCHED_HIGH:
		if (config->verbose)
			printf("high priority condition requested\n");

		set_process_priority(PRIORITY_HIGH);
		break;
	case SCHED_LOW:
		if (config->verbose)
			printf("low priority condition requested\n");

		set_process_priority(PRIORITY_LOW);
		break;
	default:
		if (config->verbose)
			printf("default priority condition requested\n");

		set_process_priority(PRIORITY_DEFAULT);
	}
}
Beispiel #3
0
/**
 * Prints results of our tests
 */
void test_proc_p1_6() {
    int i;
    static int ranOnce = 0;
    static int passed = 0;
    while (1) {
        if (ranOnce == 0) {
            for (i = 0; i < 5; i++) {
                if (test_results[i] == 1) {
                    passed++;
                }
                while (test_ran[i] == 0) {
                    release_processor();
                }
            }
            printf("G005_test: ");
            printf("%d", passed);
            printf("/5 OK\r\n");
            printf("G005_test: ");
            printf("%d", (5 - passed));
            printf("/5 FAIL\r\n");
            printf("G005_test: END\r\n");
            ranOnce = 1;
            set_process_priority(PID_P6, LOW);
            set_process_priority(PID_TIMER_TEST_PROC, MEDIUM);
        }
        release_processor();
    }
}
Beispiel #4
0
void proc3(void) {
		while (prev_pid == 6) {
				mem[index++] = request_memory_block();
		} // proc 3 should be blocked and go to 6

    // TC 3c: memory block released, proc_6 is still blocked
    if (prev_pid != 2) {
    	prev_success = 0;
    }

    // END of TC 3c

		// 1: LOW
		// 2: MEDIUM
		// 3: HIGH
		// 4, 5: LOWEST
		// 6: HIGH, blocked
    // TC 3d: Block everything and preempt to null process after starvation
    prev_pid = 3;
    set_process_priority(2, LOW);
    set_process_priority(1, MEDIUM);
    // 1: MEDIUM
		// 2: LOW
		// 3: HIGH, will be blocked
		// 4, 5: LOWEST
		// 6: HIGH, blocked
    mem[index++] = request_memory_block(); // blocks proc_3, goes to proc_1
}
Beispiel #5
0
void test_proc_p2_5(void) {
    int i = 1;
    int counter = 0;
    int result_pid = 4;

    while (1) {
        if (i % 2 == 0) {
            if (++counter == 10) {
                set_process_priority(PID_P4, HIGH);
                break;
            } else {
                release_processor();
            }
        }
        i++;
    }
    test_ran[result_pid] = 1;
    if (test_ran[PID_P4 - 1] == 0) {
        printf("G005_test: test 5 FAIL\r\n");
        test_results[result_pid] = 0;
    } else {
        printf("G005_test: test 5 OK\r\n");
    }
    set_process_priority(PID_P5, LOW);
    while (1) {
        release_processor();
    }
}
Beispiel #6
0
//Test 5 sender (receiving process blocks) and
//Test 6 sender (higher priority recipient preempts upon recieving message)
void proc5(void) {
    int pid = 5;
    int destination = 6;
    msgbuf *msg;
    
    //create message
    msg = request_memory_block();
    msg->mtype = DEFAULT;
    msg->mtext[0] = MSG_TEXT_1;
    
    //set priority to medium so that proc6 will run until it blocks
    set_process_priority(pid, MEDIUM);
    //mark test 5 passed if it is already failed by proc6 not blocking
    if (test_status[4] != TEST_FAILURE){//This lower priority process should run before proc6 finishes receiving a message, because this process has not sent it yet.
        test_status[4] = TEST_SUCCESS;//TEST 5: receive blocks. 
    }
    
    //send message
    send_message(destination, msg);
    //should now be preempted by proc6, which is higher priority and now has a message to receive.
    
    
    //mark test 6 failed if it is not yet passed(should have been preempted on send by proc6
    if (test_status[5] != TEST_SUCCESS){//If proc5 is preempted, proc6 will mark this test passed before this line...
        test_status[5] = TEST_FAILURE;//... so if this line runs, preemption did not work as expected.
    }

    //Done testing
    set_process_priority(pid, LOWEST);
    while (1) {
        release_processor();
    }
}
Beispiel #7
0
/**
 * @brief: a process that prints five numbers
 *         and then releases a memory block
 */
void proc2(void)
{
	int i = 0;
	int ret_val = 20;
	void *p_mem_blk;
	
	p_mem_blk = request_memory_block();
	set_process_priority(PID_P2, MEDIUM);
	while ( 1) {
		if ( i != 0 && i%5 == 0 ) {
			uart0_put_string("\n\r");
			ret_val = release_memory_block(p_mem_blk);
#ifdef DEBUG_0
			printf("proc2: ret_val=%d\n", ret_val);
#endif /* DEBUG_0 */
			if ( ret_val == -1 ) {
				break;
			}
		}
		uart0_put_char('0' + i%10);
		i++;
	}
	uart0_put_string("proc2: end of testing\n\r");
	set_process_priority(PID_P2, LOWEST);
	while ( 1 ) {
		release_processor();
	}
}
Beispiel #8
0
/**
 * @brief: Sets priority for process and returns get value
 */
void priority_test(void)
{	
	int ret_val = 50;
	int i = 0;
	//set_process_priority(5,1);
	
	while(1) {	
		for (i = 1;i < 3;i++) {
			set_process_priority(3,i);
			print_debug("PRIORITY SET!\r\n");
		}
		
		print_debug("Process 3 completed!\r\n");
		
		set_process_priority(3,3);
		ret_val = release_processor();
		//printf("Timer result: %d \r\n",g_timer_count);
		if (ret_val == -1) {
			print_debug("G021_test: test 3 FAIL\r\n");
			test_results[2] = 0;
		} else {
			print_debug("G021_test: test 3 OK\r\n");
		}
	}
}
Beispiel #9
0
void process_priority_proc(void) {
    msg_buf* message;
    message = (msg_buf*)request_memory_block();
    message->mtype = KCD_REG;
    copy_string("%C", message->mtext);
    send_message(PID_KCD, message);

    while (1){
        int neg_1 = -1;
        int mtext_len;
        msg_buf* message = (msg_buf*) receive_message(&neg_1);
        if (message == NULL) {
            continue;
        }

        mtext_len = str_len(message->mtext);

        if (message->mtext[1] == 'C' && (mtext_len == 8 || mtext_len == 7)) {
            int p_id;
            int p_priority;

            if (mtext_len == 7) {
                // %C X Y
                p_id = message->mtext[3] - '0';
                p_priority = message->mtext[5] - '0';
            } else {
                // %C XX Y
                p_id = (message->mtext[3] - '0') * 10;
                p_id = message->mtext[4] - '0';
                p_priority = message->mtext[6] - '0';
            }

            if (set_process_priority(p_id, p_priority) == RTX_ERR) {
                msg_buf* err_msg = (msg_buf*)request_memory_block();
							  Node* msg_node = (Node*)request_memory_block();
                err_msg->mtype = CRT_DISPLAY;
                copy_string("Invalid Command for set process priority\n\r", err_msg->mtext);

                //sends error to CRT
                msg_node->sender_id = PID_SET_PRIO;
                msg_node->receiving_id = PID_CRT;
                msg_node->data = err_msg;
                send_message_node(msg_node);
            }

        } else {
            msg_buf* err_msg = (msg_buf*)request_memory_block();
					  Node* msg_node = (Node*)request_memory_block();
            err_msg->mtype = CRT_DISPLAY;
            copy_string("Invalid Format for set process priority\n\r", err_msg->mtext);

            //sends error to CRT
            msg_node->sender_id = PID_SET_PRIO;
            msg_node->receiving_id = PID_CRT;
            msg_node->data = err_msg;
            send_message_node(msg_node);
        }
        release_memory_block(message);
    }
}
Beispiel #10
0
void set_priority_proc(void) {
	
	/*sends message to kcd to register the command types*/
	ENVELOPE *msg = (ENVELOPE *)request_memory_block();
	msg->message_type = MSG_COMMAND_REGISTRATION;
	msg->sender_pid = SET_PRIORITY_PID;
	msg->destination_pid = KCD_PID;
	set_message(msg, "%C" + '\0', 4*sizeof(char));
	send_message(KCD_PID, msg);
	while(1){
		int priority, pid;
		ENVELOPE * rec_msg = (ENVELOPE*) receive_message(NULL);
		char * char_message = (char *) rec_msg->message;
		if ((char_message[3] >= '1')&&(char_message[3] <= '6')&&(char_message[4] == ' ')&&(char_message[5] >= '0')&&(char_message[5] <= '3') && (char_message[6] == '\0')){
			pid = char_message[3] - '0';
			priority = char_message[5] - '0';
			//printf("message %s", char_message);
			//printf("pid %d priority %d", pid, priority);
			set_process_priority(pid, priority);	
		}
		else {				
			ENVELOPE * error_msg = (ENVELOPE*) request_memory_block();
			error_msg->sender_pid = SET_PRIORITY_PID;
			error_msg->destination_pid = CRT_PID;
			error_msg->message_type = MSG_CRT_DISPLAY;

			error_msg->message = error_msg + HEADER_OFFSET;
			sprintf(error_msg->message, "You have entered an invalid input\n\r"); 

			send_message(CRT_PID, error_msg);
		}
		release_memory_block(rec_msg);
	}
	
}
Beispiel #11
0
//Test 1 reciever (message can be accurately sent/recieved)
void proc2(void) {
    int pid = 2;
    int sender = 1;
    msgbuf *msg;
    
    msg = receive_message(&sender);
    
    //check message contents
    if (msg->mtype == DEFAULT && msg->mtext[0] == MSG_TEXT_1){
        test_status[0] = TEST_SUCCESS;//TEST 1: Message contents same as when sent
    } else {
        test_status[0] = TEST_FAILURE;//message contents incorrect
    }
    
    release_memory_block(msg);
    
    //Done testing
    set_process_priority(pid, LOWEST);

#ifdef _DEBUG_HOTKEYS
    // Force this process to be BLOCKED_ON_RECEIVE
    receive_message(NULL);
#endif // _DEBUG_HOTKEYS

    while (1) {
        release_processor();
    }
}
Beispiel #12
0
/**
 * @brief: a process that prints 4x5 numbers
 */
void test_proc_p1_a_2(void) {
    int i = 0;
    int ret_val = 20;
    int counter = 0;

    while ( 1) {
        if ( i != 0 && i % 5 == 0 ) {
            uart1_put_string("\n\r");
            counter++;
            if ( counter == 4 ) {
                ret_val = set_process_priority(PID_P1, HIGH);
                break;
            } else {
                ret_val = release_processor();
            }
#ifdef DEBUG_0
            printf("proc2: ret_val=%d\n", ret_val);
#endif /* DEBUG_0 */
        }
        uart1_put_char('0' + i % 10);
        i++;
    }
    uart1_put_string("proc2 end of testing\n\r");
    while ( 1 ) {
        release_processor();
    }
}
void priority_switch_command_handler()
{
    // register the command
    MessageEnvelope * kcd_msg = (MessageEnvelope *)request_memory_block();
    kcd_msg->type = TYPE_REGISTER_CMD;
    kcd_msg->msg[0] = '%';
    kcd_msg->msg[1] = 'C';
    send_message(KCD_PID, kcd_msg);

    // loop waiting for messages from the KCD
    while (1) {
        MessageEnvelope * cmd = receive_message(NULL);

        if (cmd->msg[0] != '%' || cmd->msg[1] != 'C' || cmd->msg[2] != ' ') {
            str_copy((BYTE *)"Command was invalid\n\r", (BYTE *)cmd->msg);
            send_message(CRT_PID, cmd);
            continue;
        }

        UINT32 i;

        // find the space in the argument and put a null there so ascii_to_int
        // can parse the two numbers independently
        for (i = 3; cmd->msg[i] != NULL; i ++) {
            if (cmd->msg[i] == ' ') {
                cmd->msg[i] = NULL;
                break;
            }
        }

        SINT32 pid = ascii_to_int(&cmd->msg[3]);
        SINT32 priority = ascii_to_int(&cmd->msg[i + 1]);

        if (pid == -1) {
            str_copy((BYTE *)"PID was invalid\n\r", (BYTE *)cmd->msg);
            send_message(CRT_PID, cmd);
            continue;
        }

        if (priority == -1) {
            str_copy((BYTE *)"Priority was invalid\n\r", (BYTE *)cmd->msg);
            send_message(CRT_PID, cmd);
            continue;
        }

        //rtx_dbug_outs_int("PID: ", pid);
        //rtx_dbug_outs_int("Priority: ", priority);

        int success = set_process_priority(pid, priority);

        if (success != 0) {
            str_copy((BYTE *)"Cannot change that process to that priority\n\r", (BYTE *)cmd->msg);
            send_message(CRT_PID, cmd);
            continue;
        }

        str_copy((BYTE *)"Priority change successful\n\r", (BYTE *)cmd->msg);
        send_message(CRT_PID, cmd);
    }
}
Beispiel #14
0
void proc4(void) {
	// TESTING PRIORITY LEVEL SETTER - CORRECT USAGE
	while (1) {
		int result;
		result = 1;

		set_process_priority(4,2);
		if (get_process_priority(4) != 2)
			result = 0;
		set_process_priority(4,3);

		results[4] = result;

		release_processor();
	}
}
Beispiel #15
0
/* Delayed Send Test */
void test_proc_p2_1(void) {
    int result_pid = 0;
    msg_buf_t* msg_envelope = NULL;
    char* msg = "Hello";

    msg_envelope = (msg_buf_t*)request_memory_block();

    strncpy(msg_envelope->msg_data, msg, 5);
    delayed_send(PID_P1, msg_envelope, CLOCK_INTERVAL);
    msg_envelope = (msg_buf_t*)receive_message(NULL);

    if (strcmp(msg_envelope->msg_data, msg) == 5) {
        printf("G005_test: test 1 OK\r\n");
    } else {
        printf("G005_test: test 1 FAIL\r\n");
        test_results[result_pid] = 0;
    }

    release_memory_block(msg_envelope);
    test_ran[result_pid] = 1;
    set_process_priority(g_test_procs[result_pid].pid, 3);

    while (1) {
        release_processor();
    }
}
Beispiel #16
0
/* Sends message to user process 2 */
void test_proc_p2_3(void) {
    int result_pid = 2;
    msg_buf_t* msg_envelope = 0;
    char* sent_msg = "OS";
    char* received_msg = "SE350";

    msg_envelope = (msg_buf_t*)request_memory_block();

    strncpy(msg_envelope->msg_data, sent_msg, 2);
    send_message(PID_P2, msg_envelope);

    msg_envelope = (msg_buf_t*)receive_message(NULL);

    if (strcmp(msg_envelope->msg_data, received_msg) == 5) {
        printf("G005_test: test 3 OK\r\n");
    } else {
        printf("G005_test: test 3 FAIL\r\n");
        test_results[result_pid] = 0;
    }

    release_memory_block(msg_envelope);
    test_ran[result_pid] = 1;
    set_process_priority(g_test_procs[result_pid].pid, 3);

    while (1) {
        release_processor();
    }
}
Beispiel #17
0
/* third party dummy test process 1 */ 
void test1() {
    int i;
    printf_u_0("rtx_test: test1\r\n", 1);

    set_process_priority(1, 1);
    printf_u_1("Getting priority for PID 1: %i\n\r", get_process_priority(1));
    set_process_priority(2, 1);
    printf_u_1("Getting priority for PID 2: %i\n\r", get_process_priority(2));
    
    set_process_priority(1, 3);
    printf_u_1("Getting priority for PID 1: %i\n\r", get_process_priority(1));
    set_process_priority(2, 3);
    printf_u_1("Getting priority for PID 2: %i\n\r", get_process_priority(2));

    i = 0;
    while (1) {
        g_test_fixture.release_processor();
    }
}
int main(int argc, const char *argv[])
{
    /*设置进程优先级*/
    set_process_priority();

    /*设置进程资源*/
    set_process_ulimit_resource();

    while( 1 )
        sleep(1);
    return 0;
}
Beispiel #19
0
void proc5(void) {
	// TESTING PRIORITY LEVEL SETTER - SETTING PRIORITY OF ANOTHER PROCESS - FAILS
	while (1) {
		int result;
		result = 1;

		set_process_priority(4,2);
		if (get_process_priority(4) == 2)
			result = 0;

		results[5] = result;

		release_processor();
	}
}
Beispiel #20
0
//Test 4 (normal message is recieved before a delayed message)
void proc4(void) {
    int pid = 4;
    msgbuf *delayed_msg;
    msgbuf *normal_msg;
    msgbuf *received_msg;
    
    //create delayed message
    delayed_msg = request_memory_block();
    delayed_msg->mtype = DEFAULT;
    delayed_msg->mtext[0] = MSG_TEXT_1;
    
    //create normal message
    normal_msg = request_memory_block();
    normal_msg->mtype = DEFAULT;
    normal_msg->mtext[0] = MSG_TEXT_2;//different text from the delayed message
    
    //send delayed message
    delayed_send(pid, delayed_msg, DELAY);
    //send normal message
    send_message(pid, normal_msg);
    
    //recieve message
    received_msg = receive_message(&pid);
    
    //if normal message, mark test passed
    if (received_msg->mtext[0] == MSG_TEXT_2){//should get the non delayed message before the delayed message even though it was sent later.
        test_status[3] = TEST_SUCCESS;//TEST 4: normal message is recieved before delayed message
    } else {
        test_status[3] = TEST_FAILURE;
    }
    //release message memory
    release_memory_block(received_msg);
    //recieve massage
    received_msg = receive_message(&pid);//reusing variable now that the test is finished.
    //release message memory
    release_memory_block(received_msg);

    //Done testing
    set_process_priority(pid, LOWEST);
    while (1) {
        release_processor();
    }
}
Beispiel #21
0
//TC 2: Blocked on receive & preemption
void proc2(void) {
	MSG_BUF* envelope = 0;
	char* msg1 = "SE 350";
	char* msg2 = "LAB";

	envelope = (MSG_BUF*)request_memory_block();

	strcpy(envelope->mtext, msg1);
	send_message(1, envelope);

	//TC 3: IPC
	envelope = (MSG_BUF*)request_memory_block();

	strcpy(envelope->mtext, msg2);
	send_message(3, envelope);

	envelope = (MSG_BUF*)receive_message(NULL);

	if (strcmp(envelope->mtext, msg2) == 0) {
		prev_success = 1;
	} else {
		prev_success = 0;
	}

	release_memory_block(envelope);

	if (prev_success) {
		uart1_put_string("G003_test: test ");
		uart1_put_char(3 + 48);
		uart1_put_string(" OK\n\r");
		pass = pass + 1;
	} else {
		uart1_put_string("G003_test: test ");
		uart1_put_char(3 + 48);
		uart1_put_string(" FAIL\n\r");
	}

	set_process_priority(4, HIGH);
	
	while (1) {
		release_processor(); 
	}	
}
Beispiel #22
0
//Test 2 (delayed send does not block), and
//Test 3 (delayed recieve occurs after correct amount of time)
void proc3(void) {
    int pid = 3;
    msgbuf *msg;
    int start_time;
    int end_time;
    
    //create message
    msg = request_memory_block();
    msg->mtype = DEFAULT;
    msg->mtext[0] = MSG_TEXT_1;
    
    //check time
    start_time = get_time();
    
    //send with delay
    delayed_send(pid, msg, DELAY);
    
    test_status[1] = TEST_SUCCESS;//TEST 2: Send does not block 
    //(if it did, we wouldn't reach this line because this process is sending the message to itself)
    
    receive_message(&pid);//don't need to store, because we have the original. Just checking the timing.
    
    //check time
    end_time = get_time();
    //mark test 3 passed if it is late enough, otherwise make it failed
    if (end_time >= start_time + DELAY){
        test_status[2] = TEST_SUCCESS;//TEST 3: delayed message recieved after the appropriate delay
    } else {
        test_status[2] = TEST_FAILURE;//message recieved too soon
    }
    
    //release message memory
    release_memory_block(msg);

    //Done testing
    set_process_priority(pid, LOWEST);

    while (1) {
        release_processor();
    }
}
Beispiel #23
0
//Test 5 sender (receiving process blocks) and
//Test 6 sender (higher priority recipient preempts upon recieving message)
void proc6(void) {
    int pid = 6;
    int sender = 5;

    //recieve message
    receive_message(&sender);
    //mark test 5 failed if not passed by proc5 while this process was blocked.
    if (test_status[4] != TEST_SUCCESS){//If this line runs before proc5 sends a message...
        test_status[4] = TEST_FAILURE;//receive did not block.
    }
    
    //mark test 6 passed if it is not failed
    if (test_status[5] != TEST_FAILURE){//if proc5 stops running after sending a message until after this process has run
        test_status[5] = TEST_SUCCESS;//TEST 6: higher priority recipient preempts upon recieving message
    }
    
    //Done testing
    set_process_priority(pid, LOWEST);
    while (1) {
        release_processor();
    }
}
Beispiel #24
0
int
ntpdmain(
	int argc,
	char *argv[]
	)
{
	l_fp		now;
	struct recvbuf *rbuf;
	const char *	logfilename;
# ifdef HAVE_UMASK
	mode_t		uv;
# endif
# if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
	uid_t		uid;
# endif
# if defined(HAVE_WORKING_FORK)
	long		wait_sync = 0;
	int		pipe_fds[2];
	int		rc;
	int		exit_code;
#  ifdef _AIX
	struct sigaction sa;
#  endif
#  if !defined(HAVE_SETSID) && !defined (HAVE_SETPGID) && defined(TIOCNOTTY)
	int		fid;
#  endif
# endif	/* HAVE_WORKING_FORK*/
# ifdef SCO5_CLOCK
	int		fd;
	int		zero;
# endif

# ifdef NEED_PTHREAD_WARMUP
	my_pthread_warmup();
# endif
	
# ifdef HAVE_UMASK
	uv = umask(0);
	if (uv)
		umask(uv);
	else
		umask(022);
# endif
	saved_argc = argc;
	saved_argv = argv;
	progname = argv[0];
	initializing = TRUE;		/* mark that we are initializing */
	parse_cmdline_opts(&argc, &argv);
# ifdef DEBUG
	debug = OPT_VALUE_SET_DEBUG_LEVEL;
#  ifdef HAVE_SETLINEBUF
	setlinebuf(stdout);
#  endif
# endif

	if (HAVE_OPT(NOFORK) || HAVE_OPT(QUIT)
# ifdef DEBUG
	    || debug
# endif
	    || HAVE_OPT(SAVECONFIGQUIT))
		nofork = TRUE;

	init_logging(progname, NLOG_SYNCMASK, TRUE);
	/* honor -l/--logfile option to log to a file */
	if (HAVE_OPT(LOGFILE)) {
		logfilename = OPT_ARG(LOGFILE);
		syslogit = FALSE;
		change_logfile(logfilename, FALSE);
	} else {
		logfilename = NULL;
		if (nofork)
			msyslog_term = TRUE;
		if (HAVE_OPT(SAVECONFIGQUIT))
			syslogit = FALSE;
	}
	msyslog(LOG_NOTICE, "%s: Starting", Version);

	{
		int i;
		char buf[1024];	/* Secret knowledge of msyslog buf length */
		char *cp = buf;

		/* Note that every arg has an initial space character */
		snprintf(cp, sizeof(buf), "Command line:");
		cp += strlen(cp);

		for (i = 0; i < saved_argc ; ++i) {
			snprintf(cp, sizeof(buf) - (cp - buf),
				" %s", saved_argv[i]);
			cp += strlen(cp);
		}
		msyslog(LOG_INFO, "%s", buf);
	}

	/*
	 * Install trap handlers to log errors and assertion failures.
	 * Default handlers print to stderr which doesn't work if detached.
	 */
	isc_assertion_setcallback(assertion_failed);
	isc_error_setfatal(library_fatal_error);
	isc_error_setunexpected(library_unexpected_error);

	/* MPE lacks the concept of root */
# if defined(HAVE_GETUID) && !defined(MPE)
	uid = getuid();
	if (uid && !HAVE_OPT( SAVECONFIGQUIT )) {
		msyslog_term = TRUE;
		msyslog(LOG_ERR,
			"must be run as root, not uid %ld", (long)uid);
		exit(1);
	}
# endif

/*
 * Enable the Multi-Media Timer for Windows?
 */
# ifdef SYS_WINNT
	if (HAVE_OPT( MODIFYMMTIMER ))
		set_mm_timer(MM_TIMER_HIRES);
# endif

#ifdef HAVE_DNSREGISTRATION
/*
 * Enable mDNS registrations?
 */
	if (HAVE_OPT( MDNS )) {
		mdnsreg = TRUE;
	}
#endif  /* HAVE_DNSREGISTRATION */

	if (HAVE_OPT( NOVIRTUALIPS ))
		listen_to_virtual_ips = 0;

	/*
	 * --interface, listen on specified interfaces
	 */
	if (HAVE_OPT( INTERFACE )) {
		int		ifacect = STACKCT_OPT( INTERFACE );
		const char**	ifaces  = STACKLST_OPT( INTERFACE );
		sockaddr_u	addr;

		while (ifacect-- > 0) {
			add_nic_rule(
				is_ip_address(*ifaces, AF_UNSPEC, &addr)
					? MATCH_IFADDR
					: MATCH_IFNAME,
				*ifaces, -1, ACTION_LISTEN);
			ifaces++;
		}
	}

	if (HAVE_OPT( NICE ))
		priority_done = 0;

# ifdef HAVE_SCHED_SETSCHEDULER
	if (HAVE_OPT( PRIORITY )) {
		config_priority = OPT_VALUE_PRIORITY;
		config_priority_override = 1;
		priority_done = 0;
	}
# endif

# ifdef HAVE_WORKING_FORK
	/* make sure the FDs are initialised */
	pipe_fds[0] = -1;
	pipe_fds[1] = -1;
	do {					/* 'loop' once */
		if (!HAVE_OPT( WAIT_SYNC ))
			break;
		wait_sync = OPT_VALUE_WAIT_SYNC;
		if (wait_sync <= 0) {
			wait_sync = 0;
			break;
		}
		/* -w requires a fork() even with debug > 0 */
		nofork = FALSE;
		if (pipe(pipe_fds)) {
			exit_code = (errno) ? errno : -1;
			msyslog(LOG_ERR,
				"Pipe creation failed for --wait-sync: %m");
			exit(exit_code);
		}
		waitsync_fd_to_close = pipe_fds[1];
	} while (0);				/* 'loop' once */
# endif	/* HAVE_WORKING_FORK */

	init_lib();
# ifdef SYS_WINNT
	/*
	 * Start interpolation thread, must occur before first
	 * get_systime()
	 */
	init_winnt_time();
# endif
	/*
	 * Initialize random generator and public key pair
	 */
	get_systime(&now);

	ntp_srandom((int)(now.l_i * now.l_uf));

	/*
	 * Detach us from the terminal.  May need an #ifndef GIZMO.
	 */
	if (!nofork) {

# ifdef HAVE_WORKING_FORK
		rc = fork();
		if (-1 == rc) {
			exit_code = (errno) ? errno : -1;
			msyslog(LOG_ERR, "fork: %m");
			exit(exit_code);
		}
		if (rc > 0) {	
			/* parent */
			exit_code = wait_child_sync_if(pipe_fds[0],
						       wait_sync);
			exit(exit_code);
		}
		
		/*
		 * child/daemon 
		 * close all open files excepting waitsync_fd_to_close.
		 * msyslog() unreliable until after init_logging().
		 */
		closelog();
		if (syslog_file != NULL) {
			fclose(syslog_file);
			syslog_file = NULL;
			syslogit = TRUE;
		}
		close_all_except(waitsync_fd_to_close);
		INSIST(0 == open("/dev/null", 0) && 1 == dup2(0, 1) \
			&& 2 == dup2(0, 2));

		init_logging(progname, 0, TRUE);
		/* we lost our logfile (if any) daemonizing */
		setup_logfile(logfilename);

#  ifdef SYS_DOMAINOS
		{
			uid_$t puid;
			status_$t st;

			proc2_$who_am_i(&puid);
			proc2_$make_server(&puid, &st);
		}
#  endif	/* SYS_DOMAINOS */
#  ifdef HAVE_SETSID
		if (setsid() == (pid_t)-1)
			msyslog(LOG_ERR, "setsid(): %m");
#  elif defined(HAVE_SETPGID)
		if (setpgid(0, 0) == -1)
			msyslog(LOG_ERR, "setpgid(): %m");
#  else		/* !HAVE_SETSID && !HAVE_SETPGID follows */
#   ifdef TIOCNOTTY
		fid = open("/dev/tty", 2);
		if (fid >= 0) {
			ioctl(fid, (u_long)TIOCNOTTY, NULL);
			close(fid);
		}
#   endif	/* TIOCNOTTY */
		ntp_setpgrp(0, getpid());
#  endif	/* !HAVE_SETSID && !HAVE_SETPGID */
#  ifdef _AIX
		/* Don't get killed by low-on-memory signal. */
		sa.sa_handler = catch_danger;
		sigemptyset(&sa.sa_mask);
		sa.sa_flags = SA_RESTART;
		sigaction(SIGDANGER, &sa, NULL);
#  endif	/* _AIX */
# endif		/* HAVE_WORKING_FORK */
	}

# ifdef SCO5_CLOCK
	/*
	 * SCO OpenServer's system clock offers much more precise timekeeping
	 * on the base CPU than the other CPUs (for multiprocessor systems),
	 * so we must lock to the base CPU.
	 */
	fd = open("/dev/at1", O_RDONLY);		
	if (fd >= 0) {
		zero = 0;
		if (ioctl(fd, ACPU_LOCK, &zero) < 0)
			msyslog(LOG_ERR, "cannot lock to base CPU: %m");
		close(fd);
	}
# endif

	/* Setup stack size in preparation for locking pages in memory. */
# if defined(HAVE_MLOCKALL)
#  ifdef HAVE_SETRLIMIT
	ntp_rlimit(RLIMIT_STACK, DFLT_RLIMIT_STACK * 4096, 4096, "4k");
#   ifdef RLIMIT_MEMLOCK
	/*
	 * The default RLIMIT_MEMLOCK is very low on Linux systems.
	 * Unless we increase this limit malloc calls are likely to
	 * fail if we drop root privilege.  To be useful the value
	 * has to be larger than the largest ntpd resident set size.
	 */
	ntp_rlimit(RLIMIT_MEMLOCK, DFLT_RLIMIT_MEMLOCK * 1024 * 1024, 1024 * 1024, "MB");
#   endif	/* RLIMIT_MEMLOCK */
#  endif	/* HAVE_SETRLIMIT */
# else	/* !HAVE_MLOCKALL follows */
#  ifdef HAVE_PLOCK
#   ifdef PROCLOCK
#    ifdef _AIX
	/*
	 * set the stack limit for AIX for plock().
	 * see get_aix_stack() for more info.
	 */
	if (ulimit(SET_STACKLIM, (get_aix_stack() - 8 * 4096)) < 0)
		msyslog(LOG_ERR,
			"Cannot adjust stack limit for plock: %m");
#    endif	/* _AIX */
#   endif	/* PROCLOCK */
#  endif	/* HAVE_PLOCK */
# endif	/* !HAVE_MLOCKALL */

	/*
	 * Set up signals we pay attention to locally.
	 */
# ifdef SIGDIE1
	signal_no_reset(SIGDIE1, finish);
	signal_no_reset(SIGDIE2, finish);
	signal_no_reset(SIGDIE3, finish);
	signal_no_reset(SIGDIE4, finish);
# endif
# ifdef SIGBUS
	signal_no_reset(SIGBUS, finish);
# endif

# if !defined(SYS_WINNT) && !defined(VMS)
#  ifdef DEBUG
	(void) signal_no_reset(MOREDEBUGSIG, moredebug);
	(void) signal_no_reset(LESSDEBUGSIG, lessdebug);
#  else
	(void) signal_no_reset(MOREDEBUGSIG, no_debug);
	(void) signal_no_reset(LESSDEBUGSIG, no_debug);
#  endif	/* DEBUG */
# endif	/* !SYS_WINNT && !VMS */

	/*
	 * Set up signals we should never pay attention to.
	 */
# ifdef SIGPIPE
	signal_no_reset(SIGPIPE, SIG_IGN);
# endif

	/*
	 * Call the init_ routines to initialize the data structures.
	 *
	 * Exactly what command-line options are we expecting here?
	 */
	INIT_SSL();
	init_auth();
	init_util();
	init_restrict();
	init_mon();
	init_timer();
	init_request();
	init_control();
	init_peer();
# ifdef REFCLOCK
	init_refclock();
# endif
	set_process_priority();
	init_proto();		/* Call at high priority */
	init_io();
	init_loopfilter();
	mon_start(MON_ON);	/* monitor on by default now	  */
				/* turn off in config if unwanted */

	/*
	 * Get the configuration.  This is done in a separate module
	 * since this will definitely be different for the gizmo board.
	 */
	getconfig(argc, argv);

	if (-1 == cur_memlock) {
# if defined(HAVE_MLOCKALL)
		/*
		 * lock the process into memory
		 */
		if (   !HAVE_OPT(SAVECONFIGQUIT)
#  ifdef RLIMIT_MEMLOCK
		    && -1 != DFLT_RLIMIT_MEMLOCK
#  endif
		    && 0 != mlockall(MCL_CURRENT|MCL_FUTURE))
			msyslog(LOG_ERR, "mlockall(): %m");
# else	/* !HAVE_MLOCKALL follows */
#  ifdef HAVE_PLOCK
#   ifdef PROCLOCK
		/*
		 * lock the process into memory
		 */
		if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(PROCLOCK))
			msyslog(LOG_ERR, "plock(PROCLOCK): %m");
#   else	/* !PROCLOCK follows  */
#    ifdef TXTLOCK
		/*
		 * Lock text into ram
		 */
		if (!HAVE_OPT(SAVECONFIGQUIT) && 0 != plock(TXTLOCK))
			msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
#    else	/* !TXTLOCK follows */
		msyslog(LOG_ERR, "plock() - don't know what to lock!");
#    endif	/* !TXTLOCK */
#   endif	/* !PROCLOCK */
#  endif	/* HAVE_PLOCK */
# endif	/* !HAVE_MLOCKALL */
	}

	loop_config(LOOP_DRIFTINIT, 0);
	report_event(EVNT_SYSRESTART, NULL, NULL);
	initializing = FALSE;

# ifdef HAVE_DROPROOT
	if (droproot) {
		/* Drop super-user privileges and chroot now if the OS supports this */

#  ifdef HAVE_LINUX_CAPABILITIES
		/* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
		if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
			msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
			exit(-1);
		}
#  elif HAVE_SOLARIS_PRIVS
		/* Nothing to do here */
#  else
		/* we need a user to switch to */
		if (user == NULL) {
			msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
			exit(-1);
		}
#  endif	/* HAVE_LINUX_CAPABILITIES || HAVE_SOLARIS_PRIVS */

		if (user != NULL) {
			if (isdigit((unsigned char)*user)) {
				sw_uid = (uid_t)strtoul(user, &endp, 0);
				if (*endp != '\0')
					goto getuser;

				if ((pw = getpwuid(sw_uid)) != NULL) {
					free(user);
					user = estrdup(pw->pw_name);
					sw_gid = pw->pw_gid;
				} else {
					errno = 0;
					msyslog(LOG_ERR, "Cannot find user ID %s", user);
					exit (-1);
				}

			} else {
getuser:
				errno = 0;
				if ((pw = getpwnam(user)) != NULL) {
					sw_uid = pw->pw_uid;
					sw_gid = pw->pw_gid;
				} else {
					if (errno)
						msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
					else
						msyslog(LOG_ERR, "Cannot find user `%s'", user);
					exit (-1);
				}
			}
		}
		if (group != NULL) {
			if (isdigit((unsigned char)*group)) {
				sw_gid = (gid_t)strtoul(group, &endp, 0);
				if (*endp != '\0')
					goto getgroup;
			} else {
getgroup:
				if ((gr = getgrnam(group)) != NULL) {
					sw_gid = gr->gr_gid;
				} else {
					errno = 0;
					msyslog(LOG_ERR, "Cannot find group `%s'", group);
					exit (-1);
				}
			}
		}

		if (chrootdir ) {
			/* make sure cwd is inside the jail: */
			if (chdir(chrootdir)) {
				msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
				exit (-1);
			}
			if (chroot(chrootdir)) {
				msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
				exit (-1);
			}
			if (chdir("/")) {
				msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
				exit (-1);
			}
		}
#  ifdef HAVE_SOLARIS_PRIVS
		if ((lowprivs = priv_str_to_set(LOWPRIVS, ",", NULL)) == NULL) {
			msyslog(LOG_ERR, "priv_str_to_set() failed:%m");
			exit(-1);
		}
		if ((highprivs = priv_allocset()) == NULL) {
			msyslog(LOG_ERR, "priv_allocset() failed:%m");
			exit(-1);
		}
		(void) getppriv(PRIV_PERMITTED, highprivs);
		(void) priv_intersect(highprivs, lowprivs);
		if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
			msyslog(LOG_ERR, "setppriv() failed:%m");
			exit(-1);
		}
#  endif /* HAVE_SOLARIS_PRIVS */
		if (user && initgroups(user, sw_gid)) {
			msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
			exit (-1);
		}
		if (group && setgid(sw_gid)) {
			msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
			exit (-1);
		}
		if (group && setegid(sw_gid)) {
			msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
			exit (-1);
		}
		if (group) {
			if (0 != setgroups(1, &sw_gid)) {
				msyslog(LOG_ERR, "setgroups(1, %d) failed: %m", sw_gid);
				exit (-1);
			}
		}
		else if (pw)
			if (0 != initgroups(pw->pw_name, pw->pw_gid)) {
				msyslog(LOG_ERR, "initgroups(<%s>, %d) filed: %m", pw->pw_name, pw->pw_gid);
				exit (-1);
			}
		if (user && setuid(sw_uid)) {
			msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
			exit (-1);
		}
		if (user && seteuid(sw_uid)) {
			msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
			exit (-1);
		}

#  if !defined(HAVE_LINUX_CAPABILITIES) && !defined(HAVE_SOLARIS_PRIVS)
		/*
		 * for now assume that the privilege to bind to privileged ports
		 * is associated with running with uid 0 - should be refined on
		 * ports that allow binding to NTP_PORT with uid != 0
		 */
		disable_dynamic_updates |= (sw_uid != 0);  /* also notifies routing message listener */
#  endif /* !HAVE_LINUX_CAPABILITIES && !HAVE_SOLARIS_PRIVS */

		if (disable_dynamic_updates && interface_interval) {
			interface_interval = 0;
			msyslog(LOG_INFO, "running as non-root disables dynamic interface tracking");
		}

#  ifdef HAVE_LINUX_CAPABILITIES
		{
			/*
			 *  We may be running under non-root uid now, but we still hold full root privileges!
			 *  We drop all of them, except for the crucial one or two: cap_sys_time and
			 *  cap_net_bind_service if doing dynamic interface tracking.
			 */
			cap_t caps;
			char *captext;
			
			captext = (0 != interface_interval)
				      ? "cap_sys_time,cap_net_bind_service=pe"
				      : "cap_sys_time=pe";
			caps = cap_from_text(captext);
			if (!caps) {
				msyslog(LOG_ERR,
					"cap_from_text(%s) failed: %m",
					captext);
				exit(-1);
			}
			if (-1 == cap_set_proc(caps)) {
				msyslog(LOG_ERR,
					"cap_set_proc() failed to drop root privs: %m");
				exit(-1);
			}
			cap_free(caps);
		}
#  endif	/* HAVE_LINUX_CAPABILITIES */
#  ifdef HAVE_SOLARIS_PRIVS
		if (priv_delset(lowprivs, "proc_setid") == -1) {
			msyslog(LOG_ERR, "priv_delset() failed:%m");
			exit(-1);
		}
		if (setppriv(PRIV_SET, PRIV_PERMITTED, lowprivs) == -1) {
			msyslog(LOG_ERR, "setppriv() failed:%m");
			exit(-1);
		}
		priv_freeset(lowprivs);
		priv_freeset(highprivs);
#  endif /* HAVE_SOLARIS_PRIVS */
		root_dropped = TRUE;
		fork_deferred_worker();
	}	/* if (droproot) */
# endif	/* HAVE_DROPROOT */

/* libssecomp sandboxing */
#if defined (LIBSECCOMP) && (KERN_SECCOMP)
	scmp_filter_ctx ctx;

	if ((ctx = seccomp_init(SCMP_ACT_KILL)) < 0)
		msyslog(LOG_ERR, "%s: seccomp_init(SCMP_ACT_KILL) failed: %m", __func__);
	else {
		msyslog(LOG_DEBUG, "%s: seccomp_init(SCMP_ACT_KILL) succeeded", __func__);
	}

#ifdef __x86_64__
int scmp_sc[] = {
	SCMP_SYS(adjtimex),
	SCMP_SYS(bind),
	SCMP_SYS(brk),
	SCMP_SYS(chdir),
	SCMP_SYS(clock_gettime),
	SCMP_SYS(clock_settime),
	SCMP_SYS(close),
	SCMP_SYS(connect),
	SCMP_SYS(exit_group),
	SCMP_SYS(fstat),
	SCMP_SYS(fsync),
	SCMP_SYS(futex),
	SCMP_SYS(getitimer),
	SCMP_SYS(getsockname),
	SCMP_SYS(ioctl),
	SCMP_SYS(lseek),
	SCMP_SYS(madvise),
	SCMP_SYS(mmap),
	SCMP_SYS(munmap),
	SCMP_SYS(open),
	SCMP_SYS(poll),
	SCMP_SYS(read),
	SCMP_SYS(recvmsg),
	SCMP_SYS(rename),
	SCMP_SYS(rt_sigaction),
	SCMP_SYS(rt_sigprocmask),
	SCMP_SYS(rt_sigreturn),
	SCMP_SYS(select),
	SCMP_SYS(sendto),
	SCMP_SYS(setitimer),
	SCMP_SYS(setsid),
	SCMP_SYS(socket),
	SCMP_SYS(stat),
	SCMP_SYS(time),
	SCMP_SYS(write),
};
#endif
#ifdef __i386__
int scmp_sc[] = {
	SCMP_SYS(_newselect),
	SCMP_SYS(adjtimex),
	SCMP_SYS(brk),
	SCMP_SYS(chdir),
	SCMP_SYS(clock_gettime),
	SCMP_SYS(clock_settime),
	SCMP_SYS(close),
	SCMP_SYS(exit_group),
	SCMP_SYS(fsync),
	SCMP_SYS(futex),
	SCMP_SYS(getitimer),
	SCMP_SYS(madvise),
	SCMP_SYS(mmap),
	SCMP_SYS(mmap2),
	SCMP_SYS(munmap),
	SCMP_SYS(open),
	SCMP_SYS(poll),
	SCMP_SYS(read),
	SCMP_SYS(rename),
	SCMP_SYS(rt_sigaction),
	SCMP_SYS(rt_sigprocmask),
	SCMP_SYS(select),
	SCMP_SYS(setitimer),
	SCMP_SYS(setsid),
	SCMP_SYS(sigprocmask),
	SCMP_SYS(sigreturn),
	SCMP_SYS(socketcall),
	SCMP_SYS(stat64),
	SCMP_SYS(time),
	SCMP_SYS(write),
};
#endif
	{
		int i;

		for (i = 0; i < COUNTOF(scmp_sc); i++) {
			if (seccomp_rule_add(ctx,
			    SCMP_ACT_ALLOW, scmp_sc[i], 0) < 0) {
				msyslog(LOG_ERR,
				    "%s: seccomp_rule_add() failed: %m",
				    __func__);
			}
		}
	}

	if (seccomp_load(ctx) < 0)
		msyslog(LOG_ERR, "%s: seccomp_load() failed: %m",
		    __func__);	
	else {
		msyslog(LOG_DEBUG, "%s: seccomp_load() succeeded", __func__);
	}
#endif /* LIBSECCOMP and KERN_SECCOMP */

# ifdef HAVE_IO_COMPLETION_PORT

	for (;;) {
		GetReceivedBuffers();
# else /* normal I/O */

	BLOCK_IO_AND_ALARM();
	was_alarmed = FALSE;

	for (;;) {
		if (alarm_flag) {	/* alarmed? */
			was_alarmed = TRUE;
			alarm_flag = FALSE;
		}

		if (!was_alarmed && !has_full_recv_buffer()) {
			/*
			 * Nothing to do.  Wait for something.
			 */
			io_handler();
		}

		if (alarm_flag) {	/* alarmed? */
			was_alarmed = TRUE;
			alarm_flag = FALSE;
		}

		if (was_alarmed) {
			UNBLOCK_IO_AND_ALARM();
			/*
			 * Out here, signals are unblocked.  Call timer routine
			 * to process expiry.
			 */
			timer();
			was_alarmed = FALSE;
			BLOCK_IO_AND_ALARM();
		}

# endif		/* !HAVE_IO_COMPLETION_PORT */

# ifdef DEBUG_TIMING
		{
			l_fp pts;
			l_fp tsa, tsb;
			int bufcount = 0;

			get_systime(&pts);
			tsa = pts;
# endif
			rbuf = get_full_recv_buffer();
			while (rbuf != NULL) {
				if (alarm_flag) {
					was_alarmed = TRUE;
					alarm_flag = FALSE;
				}
				UNBLOCK_IO_AND_ALARM();

				if (was_alarmed) {
					/* avoid timer starvation during lengthy I/O handling */
					timer();
					was_alarmed = FALSE;
				}

				/*
				 * Call the data procedure to handle each received
				 * packet.
				 */
				if (rbuf->receiver != NULL) {
# ifdef DEBUG_TIMING
					l_fp dts = pts;

					L_SUB(&dts, &rbuf->recv_time);
					DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
					collect_timing(rbuf, "buffer processing delay", 1, &dts);
					bufcount++;
# endif
					(*rbuf->receiver)(rbuf);
				} else {
					msyslog(LOG_ERR, "fatal: receive buffer callback NULL");
					abort();
				}

				BLOCK_IO_AND_ALARM();
				freerecvbuf(rbuf);
				rbuf = get_full_recv_buffer();
			}
# ifdef DEBUG_TIMING
			get_systime(&tsb);
			L_SUB(&tsb, &tsa);
			if (bufcount) {
				collect_timing(NULL, "processing", bufcount, &tsb);
				DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
			}
		}
# endif

		/*
		 * Go around again
		 */

# ifdef HAVE_DNSREGISTRATION
		if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
			mdnsreg = current_time;
			msyslog(LOG_INFO, "Attempting to register mDNS");
			if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL, 
			    htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
				if (!--mdnstries) {
					msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
				} else {	
					msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
				}
			} else {
				msyslog(LOG_INFO, "mDNS service registered.");
				mdnsreg = FALSE;
			}
		}
# endif /* HAVE_DNSREGISTRATION */

	}
	UNBLOCK_IO_AND_ALARM();
	return 1;
}
#endif	/* !SIM */


#if !defined(SIM) && defined(SIGDIE1)
/*
 * finish - exit gracefully
 */
static RETSIGTYPE
finish(
	int sig
	)
{
	const char *sig_desc;

	sig_desc = NULL;
#ifdef HAVE_STRSIGNAL
	sig_desc = strsignal(sig);
#endif
	if (sig_desc == NULL)
		sig_desc = "";
	msyslog(LOG_NOTICE, "%s exiting on signal %d (%s)", progname,
		sig, sig_desc);
	/* See Bug 2513 and Bug 2522 re the unlink of PIDFILE */
# ifdef HAVE_DNSREGISTRATION
	if (mdns != NULL)
		DNSServiceRefDeallocate(mdns);
# endif
	peer_cleanup();
	exit(0);
}
#endif	/* !SIM && SIGDIE1 */


#ifndef SIM
/*
 * wait_child_sync_if - implements parent side of -w/--wait-sync
 */
# ifdef HAVE_WORKING_FORK
static int
wait_child_sync_if(
	int	pipe_read_fd,
	long	wait_sync
	)
{
	int	rc;
	int	exit_code;
	time_t	wait_end_time;
	time_t	cur_time;
	time_t	wait_rem;
	fd_set	readset;
	struct timeval wtimeout;

	if (0 == wait_sync) 
		return 0;

	/* waitsync_fd_to_close used solely by child */
	close(waitsync_fd_to_close);
	wait_end_time = time(NULL) + wait_sync;
	do {
		cur_time = time(NULL);
		wait_rem = (wait_end_time > cur_time)
				? (wait_end_time - cur_time)
				: 0;
		wtimeout.tv_sec = wait_rem;
		wtimeout.tv_usec = 0;
		FD_ZERO(&readset);
		FD_SET(pipe_read_fd, &readset);
		rc = select(pipe_read_fd + 1, &readset, NULL, NULL,
			    &wtimeout);
		if (-1 == rc) {
			if (EINTR == errno)
				continue;
			exit_code = (errno) ? errno : -1;
			msyslog(LOG_ERR,
				"--wait-sync select failed: %m");
			return exit_code;
		}
		if (0 == rc) {
			/*
			 * select() indicated a timeout, but in case
			 * its timeouts are affected by a step of the
			 * system clock, select() again with a zero 
			 * timeout to confirm.
			 */
			FD_ZERO(&readset);
			FD_SET(pipe_read_fd, &readset);
			wtimeout.tv_sec = 0;
			wtimeout.tv_usec = 0;
			rc = select(pipe_read_fd + 1, &readset, NULL,
				    NULL, &wtimeout);
			if (0 == rc)	/* select() timeout */
				break;
			else		/* readable */
				return 0;
		} else			/* readable */
			return 0;
	} while (wait_rem > 0);

	fprintf(stderr, "%s: -w/--wait-sync %ld timed out.\n",
		progname, wait_sync);
	return ETIMEDOUT;
}
Beispiel #25
0
void proc1(void) {
	// Start of TC 1
	//TC 1: allocation and deallocation
	void* test_blk1 = NULL;
	void* test_blk2 = NULL;
	int status1 = 1;
	int status2 = 1;

	uart1_put_string("\n\r");
	uart1_put_string("G003_test: START\n\r");
	uart1_put_string("G003_test: total ");
	uart1_put_char(total + 48);
	uart1_put_string(" tests\n\r");
	
	test_blk1 = request_memory_block();
	test_blk2 = request_memory_block();

	if (test_blk1 == test_blk2 || test_blk1 == NULL || test_blk2 == NULL) {
		prev_success = 0;
	}

	status1 = release_memory_block(test_blk1); 
	status2 = release_memory_block(test_blk2);

	if (status1 != 0 || status2 != 0) {
		prev_success = 0;
	}

	// End of TC 1
	if (prev_success) {
		uart1_put_string("G003_test: test ");
		uart1_put_char(1 + 48);
		uart1_put_string(" OK\n\r");
		pass = pass + 1;
	} else {
		uart1_put_string("G003_test: test ");
		uart1_put_char(1 + 48);
		uart1_put_string(" FAIL\n\r");
	}

	prev_success = 1;
	
	// Start of TC 2
	// TC 2a: change itself to be lower than the max
	prev_pid = 1;
	set_process_priority(1, LOW);
	// set_process_priority(1, HIGH);
	
	if (prev_pid != 6) {
		prev_success = 0;
	}
	// At here, priority of the procs:
	// 1: LOW
	// 2, 3, 4, 5: LOWEST
	// 6: LOW

	// TC 2d: change a proc s.t. B=A to B>A, A is current
	prev_pid = 1;
	set_process_priority(6, HIGH); // should go to 6

	// TC 2e: change a proc s.t. B<A to B=A, A is current, then B should be run
	if (prev_pid != 6) {
		prev_success = 0;
	}
	// At here, priority of the procs:
	// 1: HIGH
	// 2, 3, 4, 5: LOWEST
	// 6: HIGH

	// TC 2f: change a proc s.t. B=A to B<A, A is current, then still A
	prev_pid = 1;
	set_process_priority(6, LOW);

	// TC 2f: change a proc s.t. B=A to B<A, A is current, then still A
	if (prev_pid != 1) {
		prev_success = 0;
	}
	// At here, priority of the procs:
	// 1: HIGH
	// 2, 3, 4, 5: LOWEST
	// 6: LOW

	// TC 2g: change a proc s.t. B<A to B>A, A is current, then jump to B
	// First, change itself to be MEDIUM
	set_process_priority(1, MEDIUM);

	if (prev_pid != 1) {
		prev_success = 0;
	}
	
	prev_pid = 1;
	// Then, change 6 to HIGH
	set_process_priority(6, HIGH);
	
	// If TC 2 ever reaches here, TC 2 fails
	if (prev_pid == 1) {
		uart1_put_string("G003_test: test ");
		uart1_put_char(2 + 48);
		uart1_put_string(" FAIL\n\r");	
	}

	
    // TC 3d: Block everything and preempt to null process after starvation
	if (prev_pid != 3) {
		prev_success = 0;
	}
	// 1: MEDIUM
	// 2: LOW
	// 3: HIGH, blocked
	// 4, 5: LOWEST
	// 6: HIGH, blocked
	prev_pid = 1;
	mem[index++] = request_memory_block(); 
}
Beispiel #26
0
/*
 * Main program.  Initialize us, disconnect us from the tty if necessary,
 * and loop waiting for I/O and/or timer expiries.
 */
int
ntpdmain(
	int argc,
	char *argv[]
	)
{
	l_fp now;
	struct recvbuf *rbuf;
#ifdef _AIX			/* HMS: ifdef SIGDANGER? */
	struct sigaction sa;
#endif

	progname = argv[0];
	initializing = 1;		/* mark that we are initializing */
	process_commandline_opts(&argc, &argv);
	init_logging(progname, 1);	/* Open the log file */

	char *error = NULL;
	if (sandbox_init("ntpd", SANDBOX_NAMED, &error) == -1) {
		msyslog(LOG_ERR, "sandbox_init(ntpd, SANDBOX_NAMED) failed: %s", error);
		sandbox_free_error(error);
	}
#ifdef HAVE_UMASK
	{
		mode_t uv;

		uv = umask(0);
		if(uv)
			(void) umask(uv);
		else
			(void) umask(022);
	}
#endif

#if defined(HAVE_GETUID) && !defined(MPE) /* MPE lacks the concept of root */
	{
		uid_t uid;

		uid = getuid();
		if (uid && !HAVE_OPT( SAVECONFIGQUIT )) {
			msyslog(LOG_ERR, "ntpd: must be run as root, not uid %ld", (long)uid);
			printf("must be run as root, not uid %ld\n", (long)uid);
			exit(1);
		}
	}
#endif

	/* getstartup(argc, argv); / * startup configuration, may set debug */

#ifdef DEBUG
	debug = DESC(DEBUG_LEVEL).optOccCt;
	DPRINTF(1, ("%s\n", Version));
#endif

	/* honor -l/--logfile option to log to a file */
	setup_logfile();

/*
 * Enable the Multi-Media Timer for Windows?
 */
#ifdef SYS_WINNT
	if (HAVE_OPT( MODIFYMMTIMER ))
		set_mm_timer(MM_TIMER_HIRES);
#endif

	if (HAVE_OPT( NOFORK ) || HAVE_OPT( QUIT )
#ifdef DEBUG
	    || debug
#endif
	    || HAVE_OPT( SAVECONFIGQUIT ))
		nofork = 1;

	if (HAVE_OPT( NOVIRTUALIPS ))
		listen_to_virtual_ips = 0;

	/*
	 * --interface, listen on specified interfaces
	 */
	if (HAVE_OPT( INTERFACE )) {
		int	ifacect = STACKCT_OPT( INTERFACE );
		const char**	ifaces  = STACKLST_OPT( INTERFACE );
		isc_netaddr_t	netaddr;

		while (ifacect-- > 0) {
			add_nic_rule(
				is_ip_address(*ifaces, &netaddr)
					? MATCH_IFADDR
					: MATCH_IFNAME,
				*ifaces, -1, ACTION_LISTEN);
			ifaces++;
		}
	}

	if (HAVE_OPT( NICE ))
		priority_done = 0;

#if defined(HAVE_SCHED_SETSCHEDULER)
	if (HAVE_OPT( PRIORITY )) {
		config_priority = OPT_VALUE_PRIORITY;
		config_priority_override = 1;
		priority_done = 0;
	}
#endif

#ifdef SYS_WINNT
	/*
	 * Start interpolation thread, must occur before first
	 * get_systime()
	 */
	init_winnt_time();
#endif
	/*
	 * Initialize random generator and public key pair
	 */
	get_systime(&now);

	ntp_srandom((int)(now.l_i * now.l_uf));

#if !defined(VMS)
# ifndef NODETACH
	/*
	 * Detach us from the terminal.  May need an #ifndef GIZMO.
	 */
	if (!nofork) {

		/*
		 * Install trap handlers to log errors and assertion
		 * failures.  Default handlers print to stderr which 
		 * doesn't work if detached.
		 */
		isc_assertion_setcallback(assertion_failed);
		isc_error_setfatal(library_fatal_error);
		isc_error_setunexpected(library_unexpected_error);

#  ifndef SYS_WINNT
#   ifdef HAVE_DAEMON
		daemon(0, 0);
#   else /* not HAVE_DAEMON */
		if (fork())	/* HMS: What about a -1? */
			exit(0);

		{
#if !defined(F_CLOSEM)
			u_long s;
			int max_fd;
#endif /* !FCLOSEM */
			if (syslog_file != NULL) {
				fclose(syslog_file);
				syslog_file = NULL;
			}
#if defined(F_CLOSEM)
			/*
			 * From 'Writing Reliable AIX Daemons,' SG24-4946-00,
			 * by Eric Agar (saves us from doing 32767 system
			 * calls)
			 */
			if (fcntl(0, F_CLOSEM, 0) == -1)
			    msyslog(LOG_ERR, "ntpd: failed to close open files(): %m");
#else  /* not F_CLOSEM */

# if defined(HAVE_SYSCONF) && defined(_SC_OPEN_MAX)
			max_fd = sysconf(_SC_OPEN_MAX);
# else /* HAVE_SYSCONF && _SC_OPEN_MAX */
			max_fd = getdtablesize();
# endif /* HAVE_SYSCONF && _SC_OPEN_MAX */
			for (s = 0; s < max_fd; s++)
				(void) close((int)s);
#endif /* not F_CLOSEM */
			(void) open("/", 0);
			(void) dup2(0, 1);
			(void) dup2(0, 2);

			init_logging(progname, 0);
			/* we lost our logfile (if any) daemonizing */
			setup_logfile();

#ifdef SYS_DOMAINOS
			{
				uid_$t puid;
				status_$t st;

				proc2_$who_am_i(&puid);
				proc2_$make_server(&puid, &st);
			}
#endif /* SYS_DOMAINOS */
#if defined(HAVE_SETPGID) || defined(HAVE_SETSID)
# ifdef HAVE_SETSID
			if (setsid() == (pid_t)-1)
				msyslog(LOG_ERR, "ntpd: setsid(): %m");
# else
			if (setpgid(0, 0) == -1)
				msyslog(LOG_ERR, "ntpd: setpgid(): %m");
# endif
#else /* HAVE_SETPGID || HAVE_SETSID */
			{
# if defined(TIOCNOTTY)
				int fid;

				fid = open("/dev/tty", 2);
				if (fid >= 0)
				{
					(void) ioctl(fid, (u_long) TIOCNOTTY, (char *) 0);
					(void) close(fid);
				}
# endif /* defined(TIOCNOTTY) */
# ifdef HAVE_SETPGRP_0
				(void) setpgrp();
# else /* HAVE_SETPGRP_0 */
				(void) setpgrp(0, getpid());
# endif /* HAVE_SETPGRP_0 */
			}
#endif /* HAVE_SETPGID || HAVE_SETSID */
#ifdef _AIX
			/* Don't get killed by low-on-memory signal. */
			sa.sa_handler = catch_danger;
			sigemptyset(&sa.sa_mask);
			sa.sa_flags = SA_RESTART;

			(void) sigaction(SIGDANGER, &sa, NULL);
#endif /* _AIX */
		}
#   endif /* not HAVE_DAEMON */
#  endif /* SYS_WINNT */
	}
# endif /* NODETACH */
#endif /* VMS */

#ifdef SCO5_CLOCK
	/*
	 * SCO OpenServer's system clock offers much more precise timekeeping
	 * on the base CPU than the other CPUs (for multiprocessor systems),
	 * so we must lock to the base CPU.
	 */
	{
	    int fd = open("/dev/at1", O_RDONLY);
	    if (fd >= 0) {
		int zero = 0;
		if (ioctl(fd, ACPU_LOCK, &zero) < 0)
		    msyslog(LOG_ERR, "cannot lock to base CPU: %m");
		close( fd );
	    } /* else ...
	       *   If we can't open the device, this probably just isn't
	       *   a multiprocessor system, so we're A-OK.
	       */
	}
#endif

#if defined(HAVE_MLOCKALL) && defined(MCL_CURRENT) && defined(MCL_FUTURE)
# ifdef HAVE_SETRLIMIT
	/*
	 * Set the stack limit to something smaller, so that we don't lock a lot
	 * of unused stack memory.
	 */
	{
	    struct rlimit rl;

	    /* HMS: must make the rlim_cur amount configurable */
	    if (getrlimit(RLIMIT_STACK, &rl) != -1
		&& (rl.rlim_cur = 50 * 4096) < rl.rlim_max)
	    {
		    if (setrlimit(RLIMIT_STACK, &rl) == -1)
		    {
			    msyslog(LOG_ERR,
				"Cannot adjust stack limit for mlockall: %m");
		    }
	    }
#  ifdef RLIMIT_MEMLOCK
	    /*
	     * The default RLIMIT_MEMLOCK is very low on Linux systems.
	     * Unless we increase this limit malloc calls are likely to
	     * fail if we drop root privlege.  To be useful the value
	     * has to be larger than the largest ntpd resident set size.
	     */
	    rl.rlim_cur = rl.rlim_max = 32*1024*1024;
	    if (setrlimit(RLIMIT_MEMLOCK, &rl) == -1) {
		msyslog(LOG_ERR, "Cannot set RLIMIT_MEMLOCK: %m");
	    }
#  endif /* RLIMIT_MEMLOCK */
	}
# endif /* HAVE_SETRLIMIT */
	/*
	 * lock the process into memory
	 */
	if (mlockall(MCL_CURRENT|MCL_FUTURE) < 0)
		msyslog(LOG_ERR, "mlockall(): %m");
#else /* not (HAVE_MLOCKALL && MCL_CURRENT && MCL_FUTURE) */
# ifdef HAVE_PLOCK
#  ifdef PROCLOCK
#   ifdef _AIX
	/*
	 * set the stack limit for AIX for plock().
	 * see get_aix_stack() for more info.
	 */
	if (ulimit(SET_STACKLIM, (get_aix_stack() - 8*4096)) < 0)
	{
		msyslog(LOG_ERR,"Cannot adjust stack limit for plock on AIX: %m");
	}
#   endif /* _AIX */
	/*
	 * lock the process into memory
	 */
	if (plock(PROCLOCK) < 0)
		msyslog(LOG_ERR, "plock(PROCLOCK): %m");
#  else /* not PROCLOCK */
#   ifdef TXTLOCK
	/*
	 * Lock text into ram
	 */
	if (plock(TXTLOCK) < 0)
		msyslog(LOG_ERR, "plock(TXTLOCK) error: %m");
#   else /* not TXTLOCK */
	msyslog(LOG_ERR, "plock() - don't know what to lock!");
#   endif /* not TXTLOCK */
#  endif /* not PROCLOCK */
# endif /* HAVE_PLOCK */
#endif /* not (HAVE_MLOCKALL && MCL_CURRENT && MCL_FUTURE) */

	/*
	 * Set up signals we pay attention to locally.
	 */
#ifdef SIGDIE1
	(void) signal_no_reset(SIGDIE1, finish);
#endif	/* SIGDIE1 */
#ifdef SIGDIE2
	(void) signal_no_reset(SIGDIE2, finish);
#endif	/* SIGDIE2 */
#ifdef SIGDIE3
	(void) signal_no_reset(SIGDIE3, finish);
#endif	/* SIGDIE3 */
#ifdef SIGDIE4
	(void) signal_no_reset(SIGDIE4, finish);
#endif	/* SIGDIE4 */

#ifdef SIGBUS
	(void) signal_no_reset(SIGBUS, finish);
#endif /* SIGBUS */

#if !defined(SYS_WINNT) && !defined(VMS)
# ifdef DEBUG
	(void) signal_no_reset(MOREDEBUGSIG, moredebug);
	(void) signal_no_reset(LESSDEBUGSIG, lessdebug);
# else
	(void) signal_no_reset(MOREDEBUGSIG, no_debug);
	(void) signal_no_reset(LESSDEBUGSIG, no_debug);
# endif /* DEBUG */
#endif /* !SYS_WINNT && !VMS */

	/*
	 * Set up signals we should never pay attention to.
	 */
#if defined SIGPIPE
	(void) signal_no_reset(SIGPIPE, SIG_IGN);
#endif	/* SIGPIPE */

	/*
	 * Call the init_ routines to initialize the data structures.
	 *
	 * Exactly what command-line options are we expecting here?
	 */
	init_auth();
	init_util();
	init_restrict();
	init_mon();
	init_timer();
	init_lib();
	init_request();
	init_control();
	init_peer();
#ifdef REFCLOCK
	init_refclock();
#endif
	set_process_priority();
	init_proto();		/* Call at high priority */
	init_io();
	init_loopfilter();
	mon_start(MON_ON);	/* monitor on by default now	  */
				/* turn off in config if unwanted */

	/*
	 * Get the configuration.  This is done in a separate module
	 * since this will definitely be different for the gizmo board.
	 */
	getconfig(argc, argv);
	NLOG(NLOG_SYSINFO) /* 'if' clause for syslog */
	msyslog(LOG_NOTICE, "%s", Version);
	report_event(EVNT_SYSRESTART, NULL, NULL);
	loop_config(LOOP_DRIFTCOMP, old_drift);
	initializing = 0;

#ifdef HAVE_DROPROOT
	if( droproot ) {
		/* Drop super-user privileges and chroot now if the OS supports this */

#ifdef HAVE_LINUX_CAPABILITIES
		/* set flag: keep privileges accross setuid() call (we only really need cap_sys_time): */
		if (prctl( PR_SET_KEEPCAPS, 1L, 0L, 0L, 0L ) == -1) {
			msyslog( LOG_ERR, "prctl( PR_SET_KEEPCAPS, 1L ) failed: %m" );
			exit(-1);
		}
#else
		/* we need a user to switch to */
		if (user == NULL) {
			msyslog(LOG_ERR, "Need user name to drop root privileges (see -u flag!)" );
			exit(-1);
		}
#endif /* HAVE_LINUX_CAPABILITIES */

		if (user != NULL) {
			if (isdigit((unsigned char)*user)) {
				sw_uid = (uid_t)strtoul(user, &endp, 0);
				if (*endp != '\0')
					goto getuser;

				if ((pw = getpwuid(sw_uid)) != NULL) {
					user = strdup(pw->pw_name);
					if (NULL == user) {
						msyslog(LOG_ERR, "strdup() failed: %m");
						exit (-1);
					}
					sw_gid = pw->pw_gid;
				} else {
					errno = 0;
					msyslog(LOG_ERR, "Cannot find user ID %s", user);
					exit (-1);
				}

			} else {
getuser:
				errno = 0;
				if ((pw = getpwnam(user)) != NULL) {
					sw_uid = pw->pw_uid;
					sw_gid = pw->pw_gid;
				} else {
					if (errno)
					    msyslog(LOG_ERR, "getpwnam(%s) failed: %m", user);
					else
					    msyslog(LOG_ERR, "Cannot find user `%s'", user);
					exit (-1);
				}
			}
		}
		if (group != NULL) {
			if (isdigit((unsigned char)*group)) {
				sw_gid = (gid_t)strtoul(group, &endp, 0);
				if (*endp != '\0')
					goto getgroup;
			} else {
getgroup:
				if ((gr = getgrnam(group)) != NULL) {
					sw_gid = gr->gr_gid;
				} else {
					errno = 0;
					msyslog(LOG_ERR, "Cannot find group `%s'", group);
					exit (-1);
				}
			}
		}

		if (chrootdir ) {
			/* make sure cwd is inside the jail: */
			if (chdir(chrootdir)) {
				msyslog(LOG_ERR, "Cannot chdir() to `%s': %m", chrootdir);
				exit (-1);
			}
			if (chroot(chrootdir)) {
				msyslog(LOG_ERR, "Cannot chroot() to `%s': %m", chrootdir);
				exit (-1);
			}
			if (chdir("/")) {
				msyslog(LOG_ERR, "Cannot chdir() to`root after chroot(): %m");
				exit (-1);
			}
		}
		if (user && initgroups(user, sw_gid)) {
			msyslog(LOG_ERR, "Cannot initgroups() to user `%s': %m", user);
			exit (-1);
		}
		if (group && setgid(sw_gid)) {
			msyslog(LOG_ERR, "Cannot setgid() to group `%s': %m", group);
			exit (-1);
		}
		if (group && setegid(sw_gid)) {
			msyslog(LOG_ERR, "Cannot setegid() to group `%s': %m", group);
			exit (-1);
		}
		if (user && setuid(sw_uid)) {
			msyslog(LOG_ERR, "Cannot setuid() to user `%s': %m", user);
			exit (-1);
		}
		if (user && seteuid(sw_uid)) {
			msyslog(LOG_ERR, "Cannot seteuid() to user `%s': %m", user);
			exit (-1);
		}

#ifndef HAVE_LINUX_CAPABILITIES
		/*
		 * for now assume that the privilege to bind to privileged ports
		 * is associated with running with uid 0 - should be refined on
		 * ports that allow binding to NTP_PORT with uid != 0
		 */
		disable_dynamic_updates |= (sw_uid != 0);  /* also notifies routing message listener */
#endif

		if (disable_dynamic_updates && interface_interval) {
			interface_interval = 0;
			msyslog(LOG_INFO, "running in unprivileged mode disables dynamic interface tracking");
		}

#ifdef HAVE_LINUX_CAPABILITIES
		do {
			/*
			 *  We may be running under non-root uid now, but we still hold full root privileges!
			 *  We drop all of them, except for the crucial one or two: cap_sys_time and
			 *  cap_net_bind_service if doing dynamic interface tracking.
			 */
			cap_t caps;
			char *captext = (interface_interval)
				? "cap_sys_time,cap_net_bind_service=ipe"
				: "cap_sys_time=ipe";
			if( ! ( caps = cap_from_text( captext ) ) ) {
				msyslog( LOG_ERR, "cap_from_text() failed: %m" );
				exit(-1);
			}
			if( cap_set_proc( caps ) == -1 ) {
				msyslog( LOG_ERR, "cap_set_proc() failed to drop root privileges: %m" );
				exit(-1);
			}
			cap_free( caps );
		} while(0);
#endif /* HAVE_LINUX_CAPABILITIES */

	}    /* if( droproot ) */
#endif /* HAVE_DROPROOT */

	/*
	 * Use select() on all on all input fd's for unlimited
	 * time.  select() will terminate on SIGALARM or on the
	 * reception of input.	Using select() means we can't do
	 * robust signal handling and we get a potential race
	 * between checking for alarms and doing the select().
	 * Mostly harmless, I think.
	 */
	/* On VMS, I suspect that select() can't be interrupted
	 * by a "signal" either, so I take the easy way out and
	 * have select() time out after one second.
	 * System clock updates really aren't time-critical,
	 * and - lacking a hardware reference clock - I have
	 * yet to learn about anything else that is.
	 */
#if defined(HAVE_IO_COMPLETION_PORT)

	for (;;) {
		GetReceivedBuffers();
#else /* normal I/O */

	BLOCK_IO_AND_ALARM();
	was_alarmed = 0;
	for (;;)
	{
# if !defined(HAVE_SIGNALED_IO)
		extern fd_set activefds;
		extern int maxactivefd;

		fd_set rdfdes;
		int nfound;
# endif

		if (alarm_flag)		/* alarmed? */
		{
			was_alarmed = 1;
			alarm_flag = 0;
		}

		if (!was_alarmed && has_full_recv_buffer() == ISC_FALSE)
		{
			/*
			 * Nothing to do.  Wait for something.
			 */
# ifndef HAVE_SIGNALED_IO
			rdfdes = activefds;
#  if defined(VMS) || defined(SYS_VXWORKS)
			/* make select() wake up after one second */
			{
				struct timeval t1;

				t1.tv_sec = 1; t1.tv_usec = 0;
				nfound = select(maxactivefd+1, &rdfdes, (fd_set *)0,
						(fd_set *)0, &t1);
			}
#  else
			nfound = select(maxactivefd+1, &rdfdes, (fd_set *)0,
					(fd_set *)0, (struct timeval *)0);
#  endif /* VMS */
			if (nfound > 0)
			{
				l_fp ts;

				get_systime(&ts);

				(void)input_handler(&ts);
			}
			else if (nfound == -1 && errno != EINTR)
				msyslog(LOG_ERR, "select() error: %m");
#  ifdef DEBUG
			else if (debug > 5)
				msyslog(LOG_DEBUG, "select(): nfound=%d, error: %m", nfound);
#  endif /* DEBUG */
# else /* HAVE_SIGNALED_IO */

			wait_for_signal();
# endif /* HAVE_SIGNALED_IO */
			if (alarm_flag)		/* alarmed? */
			{
				was_alarmed = 1;
				alarm_flag = 0;
			}
		}

		if (was_alarmed)
		{
			UNBLOCK_IO_AND_ALARM();
			/*
			 * Out here, signals are unblocked.  Call timer routine
			 * to process expiry.
			 */
			timer();
			was_alarmed = 0;
			BLOCK_IO_AND_ALARM();
		}

#endif /* ! HAVE_IO_COMPLETION_PORT */

#ifdef DEBUG_TIMING
		{
			l_fp pts;
			l_fp tsa, tsb;
			int bufcount = 0;

			get_systime(&pts);
			tsa = pts;
#endif
			rbuf = get_full_recv_buffer();
			while (rbuf != NULL)
			{
				if (alarm_flag)
				{
					was_alarmed = 1;
					alarm_flag = 0;
				}
				UNBLOCK_IO_AND_ALARM();

				if (was_alarmed)
				{	/* avoid timer starvation during lengthy I/O handling */
					timer();
					was_alarmed = 0;
				}

				/*
				 * Call the data procedure to handle each received
				 * packet.
				 */
				if (rbuf->receiver != NULL)	/* This should always be true */
				{
#ifdef DEBUG_TIMING
					l_fp dts = pts;

					L_SUB(&dts, &rbuf->recv_time);
					DPRINTF(2, ("processing timestamp delta %s (with prec. fuzz)\n", lfptoa(&dts, 9)));
					collect_timing(rbuf, "buffer processing delay", 1, &dts);
					bufcount++;
#endif
					(rbuf->receiver)(rbuf);
				} else {
					msyslog(LOG_ERR, "receive buffer corruption - receiver found to be NULL - ABORTING");
					abort();
				}

				BLOCK_IO_AND_ALARM();
				freerecvbuf(rbuf);
				rbuf = get_full_recv_buffer();
			}
#ifdef DEBUG_TIMING
			get_systime(&tsb);
			L_SUB(&tsb, &tsa);
			if (bufcount) {
				collect_timing(NULL, "processing", bufcount, &tsb);
				DPRINTF(2, ("processing time for %d buffers %s\n", bufcount, lfptoa(&tsb, 9)));
			}
		}
#endif

		/*
		 * Go around again
		 */

#ifdef HAVE_DNSREGISTRATION
		if (mdnsreg && (current_time - mdnsreg ) > 60 && mdnstries && sys_leap != LEAP_NOTINSYNC) {
			mdnsreg = current_time;
			msyslog(LOG_INFO, "Attemping to register mDNS");
			if ( DNSServiceRegister (&mdns, 0, 0, NULL, "_ntp._udp", NULL, NULL, 
			    htons(NTP_PORT), 0, NULL, NULL, NULL) != kDNSServiceErr_NoError ) {
				if (!--mdnstries) {
					msyslog(LOG_ERR, "Unable to register mDNS, giving up.");
				} else {	
					msyslog(LOG_INFO, "Unable to register mDNS, will try later.");
				}
			} else {
				msyslog(LOG_INFO, "mDNS service registered.");
				mdnsreg = 0;
			}
		}
#endif /* HAVE_DNSREGISTRATION */

	}
	UNBLOCK_IO_AND_ALARM();
	return 1;
}


#ifdef SIGDIE2
/*
 * finish - exit gracefully
 */
static RETSIGTYPE
finish(
	int sig
	)
{
	msyslog(LOG_NOTICE, "ntpd exiting on signal %d", sig);
#ifdef HAVE_DNSREGISTRATION
	if (mdns != NULL)
		DNSServiceRefDeallocate(mdns);
#endif
	switch (sig) {
# ifdef SIGBUS
	case SIGBUS:
		printf("\nfinish(SIGBUS)\n");
		exit(0);
# endif
	case 0:			/* Should never happen... */
		return;

	default:
		exit(0);
	}
}
Beispiel #27
0
void proc6(void) {
	// TC 2a: change itself to be lower than the max: PASS if prev pid is 1
	if (prev_pid != 1) {
		prev_success = 0;
		// At here, priority of the procs:
		// 1: LOW
		// 2, 3, 4, 5: LOWEST
		// 6: MEDIUM
	}

	//TC 2b: set itself to a higher one with currently being the higeest -> still itself
	prev_pid = 6;
	set_process_priority(6, HIGH);

	//TC 2b: set itself to a higher one with currently being the higeest -> still itself: PASS if prev_pid is 6
	if (prev_pid != 6) {
		prev_success = 0;
		// At here, priority of the procs:
		// 1: LOW
		// 2, 3, 4, 5: LOWEST
		// 6: HIGH
	}

	//TC 2c: set itself to be the same as the currently highest other than itself -> switch to that highest
	prev_pid = 6;
	set_process_priority(6, LOW);

	// TC 2d: change a proc s.t. B=A to B>A, A is current
	if (prev_pid != 1) {
		prev_success = 0;
		// At here, priority of the procs:
		// 1: LOW
		// 2, 3, 4, 5: LOWEST
		// 6: HIGH
	}

	// TC 2e: change a proc s.t. B<A to B=A, A is current, then B should be run
	prev_pid = 6;
	set_process_priority(1, HIGH);

	// TC 2g: change a proc s.t. B<A to B>A, A is current, then jump to B
	if (prev_pid != 1) {
		prev_success = 0;
		// At here, priority of the procs:
		// 1: MEDIUM
		// 2, 3, 4, 5: LOWEST
		// 6: HIGH
	}

	// TC 2h: change itself to be the same priority of itself: no change
	prev_pid = 6;
	set_process_priority(6, HIGH);
	
	// Finish TC 2
	if (prev_pid == 6 && prev_success) {
		uart1_put_string("G003_test: test ");
		uart1_put_char(2 + 48);
		uart1_put_string(" OK\n\r");
		pass = pass + 1;
	} else {
		uart1_put_string("G003_test: test ");
		uart1_put_char(2 + 48);
		uart1_put_string(" FAIL\n\r");
	}
	
	// END of TC 2

	prev_success = 1;

	// Start of TC 3

	// TC 3a: null process operations
	// 1: MEDIUM
	// 2, 3, 4, 5: LOWEST
	// 6: HIGH
	if (set_process_priority(0, LOW) != RTX_ERR) {
		prev_success = 0;
	}

	set_process_priority(1, LOW);
	set_process_priority(2, MEDIUM);

	// TC 3b: allocate all memory blocks, free one, return
	// 1: LOW
	// 2: MEDIUM
	// 3, 4, 5: LOWEST
	// 6: HIGH, will be blocked

	while (prev_pid == 6) {
		mem[index++] = request_memory_block();
  } // proc 6 should be preempted and go to 2

    // TC 3b: proc_6 is return from blocked queue to ready queue and is the highest priority process
    if (prev_pid != 2) {
    	prev_success = 0;
    }

    prev_pid = 6;
    // TC 3c: with 2 procs at highest priority, block both procs, then release memory in another proc to return to proc_6
    set_process_priority(3, HIGH); // jumps to proc_3
    // 1: LOW
	// 2: MEDIUM
	// 3: HIGH, blocked
	// 4, 5: LOWEST
	// 6: HIGH, will be blocked
		prev_pid = 6;
    mem[index++] = request_memory_block(); // blocks proc_6, goes to proc_2
}
Beispiel #28
0
void kcd_process()
{
    int sender_id;
    int prog_process_id;
    int i;
    char prog_char;
    KCD_TABLE_ENTRY *cur_entry;
    KCD_TABLE_ENTRY *new_kcd_table_entry;
    MSG_BUF *received_msg;
    int msg_type;
		int p_process_id = 0;
		int p_new_priority = 0;
		char *num_char;
    char *cur_msg;
    linked_list_init(&proc_reg_buf);
    linked_list_init(&kcd_reg_table);
    while (1)
    {
        received_msg = (MSG_BUF*)receive_message(&sender_id);            // block on receive message
        msg_type = received_msg->mtype;
        cur_msg = received_msg->mtext;

        if (msg_type == MSG_DEFAULT)
        {                        // input char from keyboard
            if (*cur_msg == '%')
            {
                prog_char = *(cur_msg+1);
                prog_process_id = -1;
							p_process_id = 0;
							p_new_priority = 0;
								if(prog_char == 'C'){
									
									// start parsing process id
									num_char = cur_msg + 3;	// skip through '%' 'C' and ' ' characters
									while(*num_char != ' '){
										p_process_id = (p_process_id * 10) + (*num_char - '0');
										num_char++;
									}
									num_char++;		// this skips the empty space
									
									// start parsing new_priority
									while(*num_char != '\0'){
										p_new_priority = (p_new_priority) * 10 + (*num_char - '0');
										num_char++;
									}
									
									// make function call to set the priority
									set_process_priority(p_process_id, p_new_priority);
									
								} else {

									for (i = 0; i < kcd_reg_table.size; i++)
									{
                    cur_entry = list_entry(linked_list_get(&kcd_reg_table, i), KCD_TABLE_ENTRY, m_lnode);
                    if (cur_entry->program_char == prog_char)
                    {
                        prog_process_id = cur_entry->process_id;
                        break;
                    }
									}

									if (prog_process_id != -1)
									{
                    // found the corresponding process in kcd_reg_table
                    // TODO: send message to corresponding process
                    // current implementation is to send the rest of the messages to the process, ends with '\n' character
                    MSG_BUF *new_message = (MSG_BUF *) request_memory_block();
                    new_message->mtype = MSG_DEFAULT;
										strcpy(new_message->mtext,cur_msg);
                    //new_message->mtext[0] = *cur_msg;        // maybe change to original received_message mtext
                    send_message(prog_process_id, new_message);
									} else
									{
                    // throw error, process not found
									}
								}
								
            } else
            {
                // throw error
            }
        } else if (msg_type == MSG_KCD_REG)
        {
            prog_char = received_msg->mtext[1];
						
						if(prog_char == 'C'){
							// ignore such key register as the C is a speical character reserved for setting priority of process
							break;
						}
					
            //TODO: check if such command already exist
						for (i = 0; i < kcd_reg_table.size; i++){
							cur_entry = list_entry(linked_list_get(&kcd_reg_table, i), KCD_TABLE_ENTRY, m_lnode);
							if ( cur_entry->program_char == prog_char){
								prog_process_id = cur_entry->process_id;
								return;
              }
            }
            // create a new kcd_reg entry
						new_kcd_table_entry = (KCD_TABLE_ENTRY*)request_memory_block();
            new_kcd_table_entry->process_id = sender_id;
            new_kcd_table_entry->program_char = prog_char;
            linked_list_push_back(&kcd_reg_table, &(new_kcd_table_entry->m_lnode));
            //release_memory_block(received_msg);
        }
    }
}
Beispiel #29
0
/* Daemon init sequence */
static void
start_check(void)
{
	/* Initialize sub-system */
	if (ipvs_start() != IPVS_SUCCESS) {
		stop_check(KEEPALIVED_EXIT_FATAL);
		return;
	}

	init_checkers_queue();
#ifdef _WITH_VRRP_
	init_interface_queue();
	kernel_netlink_init();
#endif

	/* Parse configuration file */
	global_data = alloc_global_data();
	check_data = alloc_check_data();
	if (!check_data)
		stop_check(KEEPALIVED_EXIT_FATAL);

	init_data(conf_file, check_init_keywords);

	init_global_data(global_data);

	/* Post initializations */
#ifdef _MEM_CHECK_
	log_message(LOG_INFO, "Configuration is using : %zu Bytes", mem_allocated);
#endif

	/* Remove any entries left over from previous invocation */
	if (!reload && global_data->lvs_flush)
		ipvs_flush_cmd();

#ifdef _WITH_SNMP_CHECKER_
	if (!reload && global_data->enable_snmp_checker)
		check_snmp_agent_init(global_data->snmp_socket);
#endif

	/* SSL load static data & initialize common ctx context */
	if (!init_ssl_ctx())
		stop_check(KEEPALIVED_EXIT_FATAL);

	/* fill 'vsg' members of the virtual_server_t structure.
	 * We must do that after parsing config, because
	 * vs and vsg declarations may appear in any order
	 */
	link_vsg_to_vs();

	/* Set the process priority and non swappable if configured */
	if (global_data->checker_process_priority)
		set_process_priority(global_data->checker_process_priority);

	if (global_data->checker_no_swap)
		set_process_dont_swap(4096);	/* guess a stack size to reserve */

	/* Processing differential configuration parsing */
	if (reload)
		clear_diff_services();

	/* Initialize IPVS topology */
	if (!init_services())
		stop_check(KEEPALIVED_EXIT_FATAL);

	/* Dump configuration */
	if (__test_bit(DUMP_CONF_BIT, &debug)) {
		dump_global_data(global_data);
		dump_check_data(check_data);
	}

#ifdef _WITH_VRRP_
	/* Initialize linkbeat */
	init_interface_linkbeat();
#endif

	/* Register checkers thread */
	register_checkers_thread();
}
Beispiel #30
0
/* Daemon init sequence */
static void
start_vrrp(void)
{
	/* Initialize sub-system */
	init_interface_queue();
	kernel_netlink_init();
	gratuitous_arp_init();
	ndisc_init();

	global_data = alloc_global_data();

#ifdef _HAVE_LIBIPTC_
	iptables_init();
#endif

	/* Parse configuration file */
	vrrp_data = alloc_vrrp_data();
	init_data(conf_file, vrrp_init_keywords);
	if (!vrrp_data) {
		stop_vrrp();
		return;
	}
	init_global_data(global_data);

	/* Set the process priority and non swappable if configured */
	if (global_data->vrrp_process_priority)
		set_process_priority(global_data->vrrp_process_priority);

	if (global_data->vrrp_no_swap)
		set_process_dont_swap(4096);	/* guess a stack size to reserve */

#ifdef _WITH_SNMP_
	if (!reload && (global_data->enable_snmp_keepalived || global_data->enable_snmp_rfcv2 || global_data->enable_snmp_rfcv3)) {
		vrrp_snmp_agent_init(global_data->snmp_socket);
#ifdef _WITH_SNMP_RFC_
		vrrp_start_time = timer_now();
#endif
	}
#endif

#ifdef _WITH_LVS_
	if (vrrp_ipvs_needed()) {
		/* Initialize ipvs related */
		if (ipvs_start() != IPVS_SUCCESS) {
			stop_vrrp();
			return;
		}

#ifdef _HAVE_IPVS_SYNCD_
		/* If we are managing the sync daemon, then stop any
		 * instances of it that may have been running if
		 * we terminated abnormally */
		ipvs_syncd_cmd(IPVS_STOPDAEMON, NULL, IPVS_MASTER, 0, true);
		ipvs_syncd_cmd(IPVS_STOPDAEMON, NULL, IPVS_BACKUP, 0, true);
#endif
	}
#endif

	if (reload) {
		clear_diff_saddresses();
#ifdef _HAVE_FIB_ROUTING_
		clear_diff_srules();
		clear_diff_sroutes();
#endif
		clear_diff_vrrp();
		clear_diff_script();
	}
	else {
		/* Clear leftover static entries */
		netlink_iplist(vrrp_data->static_addresses, IPADDRESS_DEL);
#ifdef _HAVE_FIB_ROUTING_
		netlink_rtlist(vrrp_data->static_routes, IPROUTE_DEL);
		netlink_error_ignore = ENOENT;
		netlink_rulelist(vrrp_data->static_rules, IPRULE_DEL, true);
		netlink_error_ignore = 0;
#endif
	}

	/* Complete VRRP initialization */
	if (!vrrp_complete_init()) {
		if (vrrp_ipvs_needed()) {
			stop_vrrp();
		}
		return;
	}

#ifdef _HAVE_LIBIPTC_
	iptables_startup();
#endif

	/* Post initializations */
#ifdef _DEBUG_
	log_message(LOG_INFO, "Configuration is using : %lu Bytes", mem_allocated);
#endif

	/* Set static entries */
	netlink_iplist(vrrp_data->static_addresses, IPADDRESS_ADD);
#ifdef _HAVE_FIB_ROUTING_
	netlink_rtlist(vrrp_data->static_routes, IPROUTE_ADD);
	netlink_rulelist(vrrp_data->static_rules, IPRULE_ADD, false);
#endif

	/* Dump configuration */
	if (__test_bit(DUMP_CONF_BIT, &debug)) {
		list ifl;

		dump_global_data(global_data);
		dump_vrrp_data(vrrp_data);
		ifl = get_if_list();
		if (!LIST_ISEMPTY(ifl))
			dump_list(ifl);
	}

	/* Initialize linkbeat */
	init_interface_linkbeat();

	/* Init & start the VRRP packet dispatcher */
	thread_add_event(master, vrrp_dispatcher_init, NULL,
			 VRRP_DISPATCHER);
}