예제 #1
0
int main(int argc, char** argv) {

  ros::init(argc, argv, "system_state");

  ros::NodeHandle handle;

  stats_pub = handle.advertise<igvc_msgs::system_stats>("system_stats", 10);

  double frequency = 10.0;

  if(handle.hasParam("frequency")) {
    handle.getParam("frequency", frequency);
  }

  ros::Rate rate(frequency);

  while(!ros::isShuttingDown()) {
    if(stats_pub.getNumSubscribers() > 0) {
      igvc_msgs::system_stats stats;
      stats.header.stamp = ros::Time::now();
      stats.memory = get_used_memory();
      stats.cpu = get_cpu_usage();
      stats_pub.publish(stats);
    }
    rate.sleep();
  }

  return 0;
}
예제 #2
0
파일: main.c 프로젝트: sriramster/essayer
int main() {
     int stat = 0;
     c = (struct cpu_usage*)(malloc(sizeof(struct cpu_usage)));
     c = get_cpu_usage();
     printf("\n cpu time = %d %d %d",c->cpu_t,c->idle_t,c->sys_t);
     return 0;
}
예제 #3
0
int
main(int argc, char **argv)
{
	struct event* ev;
	struct event* timeout;
	struct event_base* base;

	evutil_socket_t pair[2];
	struct timeval tv;
	struct cpu_usage_timer timer;

	double usage, secPassed, secUsed;

#ifdef _WIN32
	WORD wVersionRequested;
	WSADATA wsaData;
	int	err;

	wVersionRequested = MAKEWORD(2, 2);

	err = WSAStartup(wVersionRequested, &wsaData);
#endif
	if (evutil_socketpair(AF_UNIX, SOCK_STREAM, 0, pair) == -1)
		return (1);

	/* Initalize the event library */
	base = event_base_new();

	/* Initalize a timeout to terminate the test */
	timeout = evtimer_new(base,timeout_cb,&timeout);
	/* and watch for writability on one end of the pipe */
	ev = event_new(base,pair[1],EV_WRITE | EV_PERSIST, write_cb, &ev);

	tv.tv_sec  = 1;
	tv.tv_usec = 500*1000;

	evtimer_add(timeout, &tv);

	event_add(ev, NULL);

	start_cpu_usage_timer(&timer);

	event_base_dispatch(base);

	get_cpu_usage(&timer, &secPassed, &secUsed, &usage);

	/* attempt to calculate our cpu usage over the test should be
	   virtually nil */

	printf("usec used=%d, usec passed=%d, cpu usage=%.2f%%\n",
	    (int)(secUsed*1e6),
	    (int)(secPassed*1e6),
	    usage*100);

	if (usage > 50.0) /* way too high */
	  return 1;

	return 0;
}
예제 #4
0
int update_cpu(cpu_t *cpu)
{
        int ret1 = -1, ret2 = -1;
        ret1 = get_cpu_usage(cpu);
        ret2 = get_cpu_info(cpu);

        if (ret1 < 0 || ret2 < 0)
                return -1;

        return 0;
}
예제 #5
0
/*
* cpu_info_msg: output message
* msg_len: the size of output message.
* output message is included cpu's usage, real cpu frequecy and cpu governor's current cpu frequency.
*/
void show_cpu_usage_and_freq(char * cpu_info_msg, int msg_len)
{	
	unsigned long cpu_freq = 0;
	unsigned long cpu_curr_freq = 0;
	long cpu_usage = 0;

	long iowait_usage = 0;

	int cpu;

	int len = msg_len; 
	int str_len = 0;
	int tmp_len = 0;

	if(!cpu_info_msg || msg_len <= 0)
	{
		return;
	}
	
	for_each_present_cpu(cpu)
	{
		cpu_freq = acpuclk_get_rate(cpu); /*real cpu frequency*/
		cpu_curr_freq = (unsigned long) cpufreq_quick_get(cpu); /*cpu governor's current cpu frequency*/
		cpu_usage = get_cpu_usage(cpu, &iowait_usage); /*get cpu usage*/

//CORE-DL-ExportCpuInfo-00 +[
		if (cpu == 0) {
			cpu0_usage = cpu_usage;
			iowait0_usage = iowait_usage;
		} else if (cpu == 1) {
			cpu1_usage = cpu_usage;
			iowait1_usage = iowait_usage;
		}
//CORE-DL-ExportCpuInfo-00 +]

		tmp_len = snprintf((cpu_info_msg + str_len), len, "[C%d%s:%3ld%% IOW=%3ld%% F=%lu crF=%lu]", cpu, (cpu_is_offline(cpu) ? " off" : ""), cpu_usage, iowait_usage, cpu_freq, cpu_curr_freq);	
		
		str_len += tmp_len;
		len -= tmp_len;
		
		if(len <= 0 || str_len >= msg_len)
		{
			break;
		}
	}

	if(len > 0 && str_len < msg_len)
	{
		snprintf((cpu_info_msg + str_len), len, "C%d:", smp_processor_id()); /*this cpu is handling this timer interrupt*/
	}
	
}
예제 #6
0
파일: main.c 프로젝트: Asm1r/utils
int main(int argc, const char *argv[])
{
        (void)argc;
        (void)argv;

        Display *dpy;
        char msg[100];

        dpy = XOpenDisplay(NULL);

        struct net_bandwidth speed;
        struct tm tm;
        time_t t;

        do
        {
                speed = get_network_speed();
                t = time(NULL);
                tm = *localtime(&t);

                sprintf(msg, "freq: %" PRIi32 "MHz "
                             "temp: %" PRIi32 "C "
                             "cpu: %" PRIi32 "%% "
                             "ram: %" PRIi64 "MB "
                             "U: %" PRIu32 "kB D: %" PRIu32 "kB "
                             "V: %" PRIi64 "%% "
                             "%02d.%02d. %02d:%02d\n",
                        get_cpu_freq(), get_cpu_temp(), get_cpu_usage(),
                        get_ram_usage(), speed.up, speed.down,
                        get_alsa_volume(), tm.tm_mday, tm.tm_mon + 1,
                        tm.tm_hour, tm.tm_min);

		XStoreName(dpy, DefaultRootWindow(dpy), msg);
		XSync(dpy, False);

        } while(!sleep(DELAY));

        XCloseDisplay(dpy);

        printf("Something happened!");

        return 0;
}
예제 #7
0
void
cpu_usage_minotor()
{
	cpu_timer = (cpu_timer + 1) % 6;
	if (cpu_timer) return;
#if 0
	unsigned int usage = get_cpu_usage();
#else
	unsigned int usage = cpu_main(0, NULL, 0);
#endif
	if (usage > 99)
		high_cpu_usage_count++;
	else
		high_cpu_usage_count = 0;

	if (high_cpu_usage_count > 30)
	{
		dbG("reboot for high CPU load !!!\n");
		dbG("reboot for high CPU load !!!\n");
		dbG("reboot for high CPU load !!!\n");
		sys_exit();	
	}
}
int
main (int argc, char **argv, char **envp)
{
    global_prog_name = argv[0];
    if (argc == 1) {
        usage(global_prog_name);
        exit(1);
    }

    // Determine which version of OS X we are running on.
    int major_version_num;
    int minor_version_num;
    int subminor_version_num;
    get_macosx_version(&major_version_num, &minor_version_num,
                       &subminor_version_num);
    struct poll_state ps;
    ps.use_polling = 0;
    if (major_version_num >= 10) {
        // Mac OS X 10.5.* and earlier return a number that appears
        // correct from the ru_maxrss field of getrusage(), also
        // filled in by wait4().

        // Mac OS X 10.6.* always returns 0 for ru_maxrss, so we must
        // use a different method to measure it.
        ps.use_polling = 1;
    }

    char **child_argv = (char **) malloc((unsigned) argc * sizeof(char *));
    int i;
    for (i = 1; i < argc; i++) {
        child_argv[i-1] = argv[i];
    }
    child_argv[argc-1] = NULL;
    // char **p;
    // for (p = child_argv; *p != NULL; p++) {
    //     fprintf(stderr, " p[%d]='%s'", p-child_argv, *p);
    // }
    // fprintf(stderr, "\n");

    struct timeval start_time;
    struct timeval end_time;
    unsigned int num_cpus = get_num_cpus();
    cpu_usage *total_cpu_stats_start = malloc_cpu_stats(1);
    cpu_usage *per_cpu_stats_start = malloc_cpu_stats(num_cpus);
    cpu_usage *total_cpu_stats_end = malloc_cpu_stats(1);
    cpu_usage *per_cpu_stats_end = malloc_cpu_stats(num_cpus);

    get_cpu_usage(num_cpus, per_cpu_stats_start, total_cpu_stats_start);
    int ret = gettimeofday(&start_time, NULL);
    // tbd: check ret

    pid_t pid = fork();
    if (pid == -1) {
        fprintf(stderr, "Error return status -1 while attempting"
                " to call fork().  errno=%d\n", errno);
        perror(global_prog_name);
        exit(3);
    } else if (pid == 0) {

        // We are the child process

        // Set the uid to the original uid of the process that invoked
        // the timemem-darwin process, so that the command being
        // measured is run with that user's priviliges, not with root
        // privileges.
        int original_uid = getuid();
        int ret = setuid(original_uid);
        if (ret != 0) {
            fprintf(stderr, "Error return status %d while attempting"
                    " to set uid to %d.  errno=%d\n", ret, original_uid,
                    errno);
            perror(global_prog_name);
            exit(4);
        }

        ret = execvp(child_argv[0], child_argv);
        // Normally the call above will not return.
        fprintf(stderr, "Error return status %d while attempting"
                " to call execvp().  errno=%d\n", ret, errno);
        perror(global_prog_name);
        exit(2);

    }

    // We are the parent process.

    // We want to wait until the child process finishes, but we also
    // want to periodically poll the child process's resident set size
    // (memory usage).  On OS X 10.5.8 and earlier, simply using
    // wait4() for the child to finish would fill in the rusage struct
    // with the maximum resident set size, but this value is always
    // filled in with 0 in OS X 10.6, hence the use of polling.

    // We implement the polling by calling setitimer() so that we are
    // sent a SIGALRM signal every 100 msec.  This should cause
    // wait4() to return early.  We handle the signal, and then call
    // wait4() again.

    // Read the current maximum resident set size once before starting
    // the timer, because the most likely reason for it to fail is
    // that we are not running with root privileges.
    if (ps.use_polling) {
        if (init_polling_process_rss(pid, &ps) != 0) {
            run_as_superuser_msg(global_prog_name);
            exit(1);
        }
        poll_process_rss(&ps);
        
        // Set up the SIGALRM signal handler.
        global_sigalrm_handled = 0;
        enable_handling_sigalrm();
        
        // Set timer to send us a SIGALRM signal every 100 msec.
        int timer_period_msec = 100;
        enable_timer(timer_period_msec);
    }

    //int wait_opts = WNOHANG;
    int wait_opts = 0;
    int wait_status;
    int wait4_ret;
    struct rusage r;
    while (1) {
        wait4_ret = wait4(pid, &wait_status, wait_opts, &r);
        if (wait4_ret != -1) {
            break;
        }
        if ((errno == EINTR) && ps.use_polling) {
            // Most likely the SIGALRM timer signal was handled.  If
            // so, poll the child process's memory use once.  The
            // timer should automatically signal again periodically
            // without having to reset it.
            if (global_sigalrm_handled) {
                poll_process_rss(&ps);
                global_sigalrm_handled = 0;
                if (ps.task_info_errored) {
                    disable_timer();
                    ignore_sigalrm();
                }
            }
            // Go around and call wait4() again.
        } else {
            fprintf(stderr, "wait4() returned %d.  errno=%d\n",
                    wait4_ret, errno);
            perror(global_prog_name);
            exit(5);
        }
    }

    // We may not use end_time if there are errors we haven't checked
    // for yet from wait4(), but it is more accurate to call this as
    // soon after wait4() returns as we can.  It is out of the loop
    // above to avoid the overhead of calling it on every poll time.
    if (debug) {
        fprintf(stderr, "About to call gettimeofday()\n");
    }
    ret = gettimeofday(&end_time, NULL);
    // tbd: check ret
    get_cpu_usage(num_cpus, per_cpu_stats_end, total_cpu_stats_end);
    
    if (wait4_ret != pid) {
        fprintf(stderr, "wait4() returned pid=%d.  Expected pid"
                " %d of child process.  Try again.\n", wait4_ret, pid);
        fprintf(stderr, "wait4 r.ru_maxrss=%ld\n", r.ru_maxrss);
        exit(7);
    }
    ps.wait4_returned_normally = 1;
    if (debug) {
        fprintf(stderr, "wait4() returned pid=%d of child process."
                "  Done!\n", pid);
    }
    
    if (ps.use_polling) {
        // Disable the timer.  Ignore SIGALRM, too, just in case one
        // more happens.
        if (debug) {
            fprintf(stderr, "About to disable the timer\n");
        }
        disable_timer();
        if (debug) {
            fprintf(stderr, "About to ignore SIGALRM\n");
        }
        ignore_sigalrm();
    }

    // Elapsed time
    int elapsed_msec = timeval_diff_msec(&start_time, &end_time);
    fprintf(stderr, "real %9d.%03d\n", (elapsed_msec / 1000),
            (elapsed_msec % 1000));

    // User, sys times
    fprintf(stderr, "user %9ld.%03d\n", r.ru_utime.tv_sec,
            r.ru_utime.tv_usec / 1000);
    fprintf(stderr, "sys  %9ld.%03d\n", r.ru_stime.tv_sec,
            r.ru_stime.tv_usec / 1000);
    
    // Maximum resident set size
    
    if (! ps.use_polling) {
        // At least on the Intel Core 2 Duo Mac OS X 10.5.8 machine on
        // which I first tested this code, it seemed to give a value
        // of up to 2^31-4096 bytes correctly, but if it went a little
        // bit over that, the fprintf statement showed it as 0, not
        // 2^31 bytes.  For now, I'll do a special check for 0 and
        // print out what I believe to be the correct value.
        
        // One way to test this on that machine is as follows.  The
        // first command below prints 2^31-4096 bytes as the maximum
        // resident set size.  Without the "if" condition below, the
        // second command below prints 0 as the maximum resident set
        // size.
        
        // ./timemem-darwin ../../memuse/test-memuse 2096863
        // ./timemem-darwin ../../memuse/test-memuse 2096864
        
        // Reference:
        // http://lists.apple.com/archives/darwin-kernel/2009/Mar/msg00005.html

        if (r.ru_maxrss == 0L) {
            // Print 2^31 bytes exactly
            fprintf(stderr, "2147483648  maximum resident set size from getrusage\n");
        } else {
            fprintf(stderr, "%10lu  maximum resident set size from getrusage\n",
                    (unsigned long) r.ru_maxrss);
        }
    }
    if (ps.use_polling) {
        long delta = (long) ps.max_rss_bytes - (long) r.ru_maxrss;
        fprintf(stderr, "%10lu  maximum resident set size from polling (%.1f MB, delta %ld bytes = %.1f MB)\n",
                (unsigned long) ps.max_rss_bytes,
                (double) ps.max_rss_bytes / (1024.0 * 1024.0),
                delta,
                (double) delta / (1024.0 * 1024.0));
        double elapsed_time_sec = (double) elapsed_msec / 1000.0;
        fprintf(stderr,
                "number of times rss polled=%ld, avg of %.1f times per second\n", 
                ps.num_polls,
                (double) ps.num_polls / elapsed_time_sec);
        fprintf(stderr,
                "time between consecutive polls (msec): min=%.1f max=%.1f\n",
                (double) ps.consecutive_poll_separation_min_msec,
                (double) ps.consecutive_poll_separation_max_msec);
        int64 max_rss_first_seen_msec =
            timeval_diff_msec(&start_time,
                              &(ps.poll_time_when_maxrss_first_seen));
        fprintf(stderr, "Max RSS observed %.1f sec after start time\n",
                (double) max_rss_first_seen_msec / 1000.0);
        if (ps.task_info_errored) {
            int64 diff_msec = timeval_diff_msec(&end_time,
                                                &(ps.task_info_error_time));
            if (diff_msec <= 0 && diff_msec >= -100) {
                // Then the error most likely occurred because the
                // child process had already exited.  Ignore it.
            } else {
                fprintf(stderr, "A call to task_info() returned an error.  error_time - end_time = %.3f sec.  This may mean the maximum resident set size measurement above is too low.\n",
                        (double) diff_msec / 1000.0);
            }
        }
    }

    // Show separate busy percentage for each CPU core
    fprintf(stderr, "Per core CPU utilization (%d cores):", num_cpus);
    for (i = 0; i < num_cpus; i++) {
        uint64 total = (per_cpu_stats_end[i].total -
                        per_cpu_stats_start[i].total);
        int cpu_busy_percent = 0;
        if (total != 0) {
            uint64 idle = (per_cpu_stats_end[i].idle -
                           per_cpu_stats_start[i].idle);
            cpu_busy_percent =
                (int) round(100.0 * (1.0 - ((float) idle)/total));
        }
        fprintf(stderr, " %d%%", cpu_busy_percent);
    }
    fprintf(stderr, "\n");
    
    if (WIFEXITED(wait_status)) {
        // Exit with the same status that the child process did.
        exit(WEXITSTATUS(wait_status));
    } else if (WIFSIGNALED(wait_status)) {
        fprintf(stderr,
                "Command stopped due to signal %d without calling exit().\n",
                WTERMSIG(wait_status));
        exit(1);
    } else {
        fprintf(stderr,
                "Command is stopped due to signal %d, and can be restarted.\n",
                WSTOPSIG(wait_status));
        exit(2);
    }

    return 0;
}
예제 #9
0
int run_ntttcp_receiver(struct ntttcp_test_endpoint *tep)
{
	int err_code = NO_ERROR;
	struct ntttcp_test *test = tep->test;
	char *log = NULL;
	bool verbose_log = test->verbose;

	int threads_created = 0;
	struct ntttcp_stream_server *ss;
	int rc, t;
	uint64_t nbytes = 0, total_bytes = 0;
	struct timeval now;
	double actual_test_time = 0;
	struct cpu_usage *init_cpu_usage, *final_cpu_usage;
	struct tcp_retrans *init_tcp_retrans, *final_tcp_retrans;

	/* for calculate the resource usage */
	init_cpu_usage = (struct cpu_usage *) malloc(sizeof(struct cpu_usage));
	if (!init_cpu_usage) {
		PRINT_ERR("receiver: error when creating cpu_usage struct");
		return ERROR_MEMORY_ALLOC;
	}
	final_cpu_usage = (struct cpu_usage *) malloc(sizeof(struct cpu_usage));
	if (!final_cpu_usage) {
		free (init_cpu_usage);
		PRINT_ERR("receiver: error when creating cpu_usage struct");
		return ERROR_MEMORY_ALLOC;
	}

	/* for calculate the TCP re-transmit */
	init_tcp_retrans = (struct tcp_retrans *) malloc(sizeof(struct tcp_retrans));
	if (!init_tcp_retrans) {
		free (init_cpu_usage);
		free (final_cpu_usage);
		PRINT_ERR("sender: error when creating tcp_retrans struct");
		return ERROR_MEMORY_ALLOC;
	}
	final_tcp_retrans = (struct tcp_retrans *) malloc(sizeof(struct tcp_retrans));
	if (!final_tcp_retrans) {
		free (init_cpu_usage);
		free (final_cpu_usage);
		free (init_tcp_retrans);
		PRINT_ERR("sender: error when creating tcp_retrans struct");
		return ERROR_MEMORY_ALLOC;
	}

	/* create threads */
	for (t = 0; t < test->parallel; t++) {
		ss = tep->server_streams[t];
		ss->server_port = test->server_base_port + t;	

		if (test->protocol == TCP) {
			rc = pthread_create(&tep->threads[t],
						NULL,
						run_ntttcp_receiver_tcp_stream,
						(void*)ss);
		}
		else {
			rc = pthread_create(&tep->threads[t],
						NULL,
						run_ntttcp_receiver_udp_stream,
						(void*)ss);
		}

		if (rc) {
			PRINT_ERR("pthread_create() create thread failed");
			err_code = ERROR_PTHREAD_CREATE;
			continue;
		}
		threads_created++;
	}

	/* create synch thread */
	if (test->no_synch == false) {
		/* ss struct is not used in sync thread, because:
		 * we are only allowed to pass one param to the thread in pthread_create();
		 * but the information stored in ss, is not enough to be used for synch;
		 * so we pass *tep to the pthread_create().
		 * notes:
		 * 1) we will calculate the tcp port for synch stream in create_receiver_sync_socket().
		 *   the synch_port = base_port -1
		 * 2) we will assign the protocol for synch stream to TCP, always, in create_receiver_sync_socket()
		 */
		ss = tep->server_streams[test->parallel];
		ss->server_port = test->server_base_port - 1; //just for bookkeeping
		ss->protocol = TCP; //just for bookkeeping
		ss->is_sync_thread = 1;	

		rc = pthread_create(&tep->threads[t],
				NULL,
				create_receiver_sync_socket,
				(void*)tep);
		if (rc) {
				PRINT_ERR("pthread_create() create thread failed");
			err_code = ERROR_PTHREAD_CREATE;
		}
		else {
			threads_created++;
		}
	}

	asprintf(&log, "%d threads created", threads_created);
	PRINT_DBG_FREE(log);

	while ( 1 ) {
		/* for receiver, there are two ways to trigger test start:
		 * a) if synch enabled, then sync thread will trigger loght_on after sync completed;
		 *	see create_receiver_sync_socket()
		 * b) if no synch enabled, then any tcp server accept client connections, the ligh_on will be triggered;
		 *	see ntttcp_server_epoll(), or ntttcp_server_select()
		 */
		wait_light_on();

		/* reset server side perf counters at the begining, after light-is-on
		 * this is to handle the case when: receiver in sync mode, but sender connected as no_sync mode
		 * in this case, before loght_no, the threads have some data counted already
		 */
		for (t=0; t < threads_created; t++)
			__atomic_store_n( &(tep->server_streams[t]->total_bytes_transferred), 0, __ATOMIC_SEQ_CST );

		get_cpu_usage( init_cpu_usage );
		get_tcp_retrans( init_tcp_retrans );

		/* run the timer. it will trigger turn_off_light() after timer timeout */
		run_test_timer(tep->confirmed_duration);
		tep->state = TEST_RUNNING;
		gettimeofday(&now, NULL);
		tep->start_time = now;

		/* wait test done */
		wait_light_off();
		tep->state = TEST_FINISHED;
		gettimeofday(&now, NULL);
		tep->end_time = now;

		/* calculate the actual test run time */
		actual_test_time = get_time_diff(&tep->end_time, &tep->start_time);

		/* calculate resource usage */
		get_cpu_usage( final_cpu_usage );
		get_tcp_retrans( final_tcp_retrans );

		//sleep(1);  //looks like server needs more time to receive data ...

		/* calculate server side throughput */
		total_bytes = 0;
		print_thread_result(-1, 0, 0);
		for (t=0; t < threads_created; t++){
			/* exclude the sync thread */
			if (tep->server_streams[t]->is_sync_thread)
				continue;

			nbytes = (uint64_t)__atomic_load_n( &(tep->server_streams[t]->total_bytes_transferred), __ATOMIC_SEQ_CST );
			total_bytes += nbytes;
			print_thread_result(t, nbytes, actual_test_time);
		}

		print_total_result(tep->test, total_bytes, actual_test_time,
				   init_cpu_usage, final_cpu_usage,
				   init_tcp_retrans, final_tcp_retrans);
	}

	/* as receiver threads will keep listening on ports, so they will not exit */
	for (t=0; t < threads_created; t++) {
		pthread_join(tep->threads[t], NULL);
	}

	free (init_cpu_usage);
	free (final_cpu_usage);
	free (init_tcp_retrans);
	free (final_tcp_retrans);

	return err_code;
}
예제 #10
0
int run_ntttcp_sender(struct ntttcp_test_endpoint *tep)
{
	int err_code = NO_ERROR;
	struct ntttcp_test *test = tep->test;
	char *log = NULL;
	bool verbose_log = test->verbose;

	int threads_created = 0;
	struct ntttcp_stream_client *cs;
	int rc, t, n, reply_received;
	uint64_t nbytes = 0, total_bytes = 0;
	void *p_retval;
	struct timeval now;
	double actual_test_time = 0;
	struct cpu_usage *init_cpu_usage, *final_cpu_usage;
	struct tcp_retrans *init_tcp_retrans, *final_tcp_retrans;

	/* for calculate the resource usage */
	init_cpu_usage = (struct cpu_usage *) malloc(sizeof(struct cpu_usage));
	if (!init_cpu_usage) {
		PRINT_ERR("sender: error when creating cpu_usage struct");
		return ERROR_MEMORY_ALLOC;
	}
	final_cpu_usage = (struct cpu_usage *) malloc(sizeof(struct cpu_usage));
	if (!final_cpu_usage) {
		free (init_cpu_usage);
		PRINT_ERR("sender: error when creating cpu_usage struct");
		return ERROR_MEMORY_ALLOC;
	}

	/* for calculate the TCP re-transmit */
	init_tcp_retrans = (struct tcp_retrans *) malloc(sizeof(struct tcp_retrans));
	if (!init_tcp_retrans) {
		free (init_cpu_usage);
		free (final_cpu_usage);
		PRINT_ERR("sender: error when creating tcp_retrans struct");
		return ERROR_MEMORY_ALLOC;
	}
	final_tcp_retrans = (struct tcp_retrans *) malloc(sizeof(struct tcp_retrans));
	if (!final_tcp_retrans) {
		free (init_cpu_usage);
		free (final_cpu_usage);
		free (init_tcp_retrans);
		PRINT_ERR("sender: error when creating tcp_retrans struct");
		return ERROR_MEMORY_ALLOC;
	}

	if (test->no_synch == false ) {
		/* Negotiate with receiver on:
		* 1) receiver state: is receiver busy with another test?
		* 2) submit sender's test duration time to receiver to negotiate
		* 3) request receiver to start the test
		*/
		reply_received = create_sender_sync_socket( tep );
		if (reply_received == 0) {
			PRINT_ERR("sender: failed to create sync socket");
			return ERROR_GENERAL;
		}
		tep->synch_socket = reply_received;
		reply_received = query_receiver_busy_state(tep->synch_socket);
		if (reply_received == -1) {
			PRINT_ERR("sender: failed to query receiver state");
			return ERROR_GENERAL;
		}
		if (reply_received == 1) {
			PRINT_ERR("sender: receiver is busy with another test");
			return ERROR_GENERAL;
		}
		reply_received = negotiate_test_duration(tep->synch_socket, test->duration);
		if (reply_received == -1) {
			PRINT_ERR("sender: failed to negotiate test duration with receiver");
			return ERROR_GENERAL;
		}
		if (reply_received != test->duration) {
			asprintf(&log, "test duration negotiated is: %d seconds", reply_received);
			PRINT_INFO_FREE(log);
		}
		tep->confirmed_duration = reply_received;
		reply_received = request_to_start(tep->synch_socket);
		if (reply_received == -1) {
			PRINT_ERR("sender: failed to sync with receiver to start test");
			return ERROR_GENERAL;
		}
		if (reply_received == 0) {
			PRINT_ERR("sender: receiver refuse to start test right now");
			return ERROR_GENERAL;
		}

		/* if we go here, the pre-test sync has completed */
		PRINT_INFO("Network activity progressing...");
	}
	else {
		PRINT_INFO("Starting sender activity (no sync) ...");
	}

	/* create threads */
	for (t = 0; t < test->parallel; t++) {
		for (n = 0; n < test->conn_per_thread; n++ ) {
			cs = tep->client_streams[t * test->conn_per_thread + n];
			/* in client side, multiple connections will (one thread for one connection)
			 * connect to same port on server
			 */
			cs->server_port = test->server_base_port + t;

			/* If sender side is being asked to pin the client source port */
			if (test->client_base_port > 0)
				cs->client_port = test->client_base_port + n * test->parallel + t;
	
			if (test->protocol == TCP) {
				rc = pthread_create(&tep->threads[threads_created],
							NULL,
							run_ntttcp_sender_tcp_stream,
							(void*)cs);
			}
			else {
				rc = pthread_create(&tep->threads[threads_created],
							NULL,
							run_ntttcp_sender_udp_stream,
							(void*)cs);
			}

			if (rc) {
				PRINT_ERR("pthread_create() create thread failed");
				err_code = ERROR_PTHREAD_CREATE;
				continue;
			}
			else{
				threads_created++;
			}
		}
	}
	asprintf(&log, "%d threads created", threads_created);
	PRINT_DBG_FREE(log);

	turn_on_light();

	get_cpu_usage( init_cpu_usage );
	get_tcp_retrans( init_tcp_retrans );

	/* run the timer. it will trigger turn_off_light() after timer timeout */
	run_test_timer(tep->confirmed_duration );
	tep->state = TEST_RUNNING;
	gettimeofday(&now, NULL);
	tep->start_time = now;

	/* wait test done */
	wait_light_off();
	tep->state = TEST_FINISHED;
	gettimeofday(&now, NULL);
	tep->end_time = now;

	/* calculate the actual test run time */
	actual_test_time = get_time_diff(&tep->end_time, &tep->start_time);

	/* 
	 * if actual_test_time < tep->confirmed_duration;
	 * then this indicates that in the sender side, test is being interrupted.
	 * hence, tell receiver about this.
	 */
	if (actual_test_time < tep->confirmed_duration) {
		tell_receiver_test_exit(tep->synch_socket);
	}
	close(tep->synch_socket);

	/* calculate resource usage */
	get_cpu_usage( final_cpu_usage );
	get_tcp_retrans( final_tcp_retrans );

	/* calculate client side throughput, but exclude the last thread as it is synch thread */
	print_thread_result(-1, 0, 0);
	for (n = 0; n < threads_created; n++) {
		if (pthread_join(tep->threads[n], &p_retval) !=0 ) {
			PRINT_ERR("sender: error when pthread_join");
			continue;
		}
		nbytes = tep->client_streams[n]->total_bytes_transferred;
		total_bytes += nbytes;
		print_thread_result(n, nbytes, actual_test_time);
	}
	print_total_result(tep->test, total_bytes, actual_test_time,
			   init_cpu_usage, final_cpu_usage,
			   init_tcp_retrans, final_tcp_retrans);

	free (init_cpu_usage);
	free (final_cpu_usage);
	free (init_tcp_retrans);
	free (final_tcp_retrans);

	return err_code;
}
예제 #11
0
/* wathchdog is runned in NORMAL_PERIOD, 1 seconds
 * check in each NORMAL_PERIOD
 *	1. button
 *
 * check in each NORAML_PERIOD*10
 *
 *      1. ntptime 
 *      2. time-dependent service
 *      3. http-process
 *      4. usb hotplug status
 */
void watchdog(void)
{
	/* handle button */
	btn_check();

	/* if timer is set to less than 1 sec, then bypass the following */
	if (itv.it_value.tv_sec == 0) return;

	if (nvram_match("asus_mfg", "1"))
	{
		system("rmmod hw_nat");
		if (pids("ntp"))
			system("killall -SIGTERM ntp");
		if (pids("ntpclient"))
			system("killall ntpclient");
		if (pids("udhcpc"))
			system("killall -SIGTERM udhcpc");
#if (!defined(W7_LOGO) && !defined(WIFI_LOGO))
		if (pids("ots"))
			system("killall ots");
#endif
		stop_wanduck();
		stop_logger();
		stop_upnp();	// it may cause upnp cannot run
		stop_dhcpd();
		stop_dns();
#if (!defined(W7_LOGO) && !defined(WIFI_LOGO))
		stop_pspfix();
#endif
		stop_wsc();
		stop_wsc_2g();
		stop_lltd();
		stop_networkmap();
		stop_httpd();
		stop_lpd();
		stop_u2ec();
		kill_pidfile_s("/var/run/linkstatus_monitor.pid", SIGTERM);
		if (pids("detectWan"))
			system("killall detectWan");
#if (!defined(W7_LOGO) && !defined(WIFI_LOGO))
		stop_rstats();
		kill_pidfile_s("/var/run/detect_internet.pid", SIGTERM);
#endif
		if (pids("tcpcheck"))
			system("killall -SIGTERM tcpcheck");
#ifdef HTTPD_CHECK
		if (pids("httpdcheck"))
			system("killall -SIGTERM httpdcheck");
#endif
		if (pids("traceroute"))
			system("killall traceroute");
		if (pids("usbled"))
			system("killall -SIGTERM usbled");

		nvram_set("asus_mfg", "2");
	}

#if 0
	// reboot signal checking
	if (nvram_match("reboot", "1"))
	{
		printf("[watchdog] nvram match reboot\n");

		reboot_count++;
		if (reboot_count >= 2) 
		{
//			kill(1, SIGTERM);
			sys_exit();
		}

		return;
	}
#else
	if (nvram_match("reboot", "1")) return;
#endif

	if (stop_service_type_99) return;

	if (!nvram_match("asus_mfg", "0")) return;

	watchdog_period = (watchdog_period + 1) % 10;

	if (watchdog_period) return;

#ifdef BTN_SETUP
	if (btn_pressed_setup >= BTNSETUP_START) return;
#endif

#if (!defined(W7_LOGO) && !defined(WIFI_LOGO))
	if (count_to_stop_wps > 0)
	{
		count_to_stop_wps--;

		if (!count_to_stop_wps)
		{
//			if (nvram_match("wl_radio_x", "1"))
			stop_wsc();			// psp fix
//			if (nvram_match("rt_radio_x", "1"))
			stop_wsc_2g();			// psp fix
			nvram_set("wps_enable", "0");	// psp fix
		}
	}
#endif

	ddns_timer = (ddns_timer + 1) % 4320;

	if (nvram_match("asus_debug", "1"))
		mem_timer = (mem_timer + 1) % 60;

	if (!watchdog_count)
		watchdog_count++;
	else if (watchdog_count++ == 1)
	{
#if 0
		if (!strcmp(nvram_safe_get("rc_service"), "restart_upnp"))
			service_handle();
		else
#endif
		if (	nvram_match("router_disable", "0") &&
			nvram_match("upnp_enable", "1") &&
			nvram_match("upnp_started", "0")	)
		{
//			if (has_wan_ip())
			{
				dbg("[watchdog] starting upnp...\n");
				stop_upnp();
				start_upnp();
			}
		}
	}

	/* check for time-dependent services */
	svc_timecheck();

	/* http server check */
	httpd_processcheck();

	u2ec_processcheck();

	media_processcheck();
#if 0
	samba_processcheck();
#endif
	pppd_processcheck();

	if (nvram_match("wan_route_x", "IP_Routed"))
		nm_processcheck();

	cpu_usage_minotor();

	dm_block_chk();

	if (nvram_match("asus_debug", "1") && !mem_timer)
	{
		print_num_of_connections();
		dbg("Hardware NAT: %s\n", is_hwnat_loaded() ? "Enabled": "Disabled");
		dbg("Software QoS: %s\n", nvram_match("qos_enable", "1") ? "Enabled": "Disabled");
		dbg("pppd running: %s\n", pids("pppd") ? "Yes": "No");
#if 0
		dbg("CPU usage: %d%%\n", get_cpu_usage());
#else
		dbg("CPU usage: %d%%\n", cpu_main(0, NULL, 0));
#endif
		system("free");
		system("date");
		print_uptime();
	}

#ifdef CDMA
	/* CDMA_DOWN = 99, none
	 * CDMA_DOWN = 1, currently down
	 * CDMA_DOWN = 2, currently up
	 * CDMA_DOWN = 0, currently trying to connect
	 */
	if (nvram_match("cdma_down", "1"))
	{
		logmessage("CDMA client", "cdma is down(%d)!", cdma_down);

		cdma_down++;
		cdma_connec t = 0;

		if (cdma_down == 2)
		{
			printf("[watchdog] stop wan\n");
			stop_wan();
			start_wan();
		}
		else if (cdma_down >= 12) /* 2 minutes timeout for retry */
		{
			cdma_down = 0;
		}
	}
	else if (nvram_match("cdma_down", "0"))
	{
		logmessage("CDMA client", "cdma try connect(%d)!", cdma_connect);
		cdma_down = 0;
		cdma_connect++;

		if (cdma_connect > 12) /* 2 minitues timeout for connecting */
		{
			nvram_set("cdma_down", "1");
		}
	}
	else
	{
		cdma_down = 0;
		cdma_connect = 0;
	}
#endif

	if (nvram_match("wan_route_x", "IP_Routed"))
	{
		if (!is_phyconnected() || !has_wan_ip())
			return;

		/* sync time to ntp server if necessary */
		if (!nvram_match("wan_dns_t", "") && !nvram_match("wan_gateway_t", ""))
		{
			ntp_timesync();
		}

		if (	nvram_match("ddns_enable_x", "1") && 
			(!nvram_match("ddns_updated", "1") || !ddns_timer)
		)
		{
			logmessage("RT-N56U", "[start ddns] watchdog");
			start_ddns();
		}

		if (!ddns_timer)
		{
			stop_networkmap();
			start_networkmap();
		}
	}
	else
	{
		if (/*!nvram_match("lan_dns_t", "") && */!nvram_match("lan_gateway_t", ""))
			ntp_timesync();
	}
}
예제 #12
0
void Tasksettings::refresh_stats(){
    get_cpu_usage();
}
예제 #13
0
void count_cpu_time(void){
	if (unlikely(debug_cpu_usage_enable == 1 && (1000*(jiffies_64 - Last_checked_jiffies)/HZ >= CPU_USAGE_CHECK_INTERVAL_MS)))
	{
		struct task_struct * p = current;
		struct pt_regs *regs = get_irq_regs();

		/*Kernel-SC-add-cpuFreq-info-01+[*/
		unsigned long cpu_freq = acpuclk_get_rate(smp_processor_id());
		unsigned long cpu_curr_freq = (unsigned long) cpufreq_quick_get(smp_processor_id());
		/*Kernel-SC-add-cpuFreq-info-01+]*/

		if (likely(p != 0))
		{
			if (regs != 0)
			{
				if (regs->ARM_pc <= TASK_SIZE)  /* User space */
				{
					struct mm_struct *mm = p->mm;
					struct vm_area_struct *vma;
					struct file *map_file = NULL;

					/* Parse vma information */
					vma = find_vma(mm, regs->ARM_pc);

					if (vma != NULL)
					{
						map_file = vma->vm_file;
					
						if (map_file)  /* memory-mapped file */
						{
							printk(KERN_INFO "[CPU] %3ld%% LR=0x%08lx PC=0x%08lx [U][%4d][%s][%s+0x%lx] CPUFreq=%lu CurrFreq=%lu\r\n",
								get_cpu_usage(),
								regs->ARM_lr, 
								regs->ARM_pc, 
								(unsigned int) p->pid,
								p->comm,
								map_file->f_path.dentry->d_iname, 
								regs->ARM_pc - vma->vm_start,
								cpu_freq,
								cpu_curr_freq);/*Kernel-SC-add-cpuFreq-info-01**/
						}
						else 
						{
							const char *name = arch_vma_name(vma);
							if (!name) 
							{
								if (mm) 
								{
									if (vma->vm_start <= mm->start_brk &&
										vma->vm_end >= mm->brk) 
									{
										name = "heap";
									} 
									else if (vma->vm_start <= mm->start_stack &&
										vma->vm_end >= mm->start_stack) 
									{
										name = "stack";
									}
								}
								else 
								{
									name = "vdso";
								}
							}
							printk(KERN_INFO "[CPU] %3ld%% LR=0x%08lx PC=0x%08lx [U][%4d][%s][%s] CPUFreq=%lu CurrFreq=%lu\r\n",
								get_cpu_usage(),
								regs->ARM_lr, 
								regs->ARM_pc, 
								(unsigned int) p->pid,
								p->comm, 
								name,
								cpu_freq,
								cpu_curr_freq);/*Kernel-SC-add-cpuFreq-info-01**/
						}
					}
				}
				else /* Kernel space */
				{
					printk(KERN_INFO "[CPU] %3ld%% LR=0x%08lx PC=0x%08lx [K][%4d][%s] CPUFreq=%lu CurrFreq=%lu", 
						get_cpu_usage(),
						regs->ARM_lr, 
						regs->ARM_pc, 
						(unsigned int) p->pid,
						p->comm,
						cpu_freq,
						cpu_curr_freq);/*Kernel-SC-add-cpuFreq-info-01**/
					
					#ifdef CONFIG_KALLSYMS
					print_symbol("[%s]\r\n", regs->ARM_pc);
					#else
					printk("\r\n");
					#endif
				}
			}
			else  /* Can't get PC & RA address */
			{
				printk(KERN_INFO "[CPU] %3ld%% [%s] CPUFreq=%lu CurrFreq=%lu\r\n", get_cpu_usage(), p->comm, cpu_freq, cpu_curr_freq);/*Kernel-SC-add-cpuFreq-info-01**/
			}
		}
		else  /* Can't get process information */
		{
			printk(KERN_INFO "[CPU] %3ld%% ERROR: p=0x%08lx, regs=0x%08lx CPUFreq=%lu CurrFreq=%lu\r\n", get_cpu_usage(), (long)p, (long)regs, cpu_freq, cpu_curr_freq);/*Kernel-SC-add-cpuFreq-info-01**/
		}
	}
}
예제 #14
0
	UInt32 HawkProfiler::GetCpuUsage()
	{
		m_iCpuUsage = get_cpu_usage();
		return m_iCpuUsage;
	}