3 #include <sys/socket.h>
4 #include <netinet/in.h>
19 #include <semaphore.h>
21 #define MAX_STREAMS 10
22 #define MIN_GRANULARITY 100
24 unsigned opt_packet_size = 800;
25 unsigned opt_period_usec = 10*MSEC_TO_USEC;
26 unsigned opt_jitter = 0;
27 char *opt_output = "delay_stats";
28 unsigned opt_count_sec = 0;
29 unsigned opt_def_bandwidth = 200;
30 unsigned opt_def_period_msec = 0;
31 int opt_granularity_usec = MIN_GRANULARITY;
32 bool opt_wait_for_queue_is_full; /* Don't gather any statistics until any queue is full */
34 bool some_queue_is_full = false;
35 struct timespec reset_timestamp;
37 /* Locked when some queue is full to prevent multiple resets of
39 pthread_mutex_t queue_full_mutex = PTHREAD_MUTEX_INITIALIZER;
41 int ac_sockfd[AC_NUM];
45 unsigned received, last_received;
52 /* maximal traffic delay in ms - 10 s*/
53 #define MAX_DELAY_US 10000000
55 unsigned delay_stats[AC_NUM][MAX_DELAY_US/MIN_GRANULARITY];
56 pthread_mutex_t delay_stats_mutex = PTHREAD_MUTEX_INITIALIZER;
58 /*struct ac_stats[AC_NUM] {
59 unsigned long int min_trans_time;
60 unsigned long int sum_trans_time;
61 struct timespec recv_timestamp;
62 struct timespec send_timestamp;
66 /* Input parameters */
68 int bandwidth_bps; /* bits per second */
69 int jitter; /* percent */
70 /* Mulualy exclusive input parameters */
72 long period_usec; /* all time units are in microseconds */
73 struct sockaddr_in rem_addr;
76 pthread_mutex_t mutex;
77 unsigned long long sent, really_sent, received;
81 struct send_endpoint sepoint[] = {
82 { .ac = AC_VO, .period_usec=200*MSEC_TO_USEC, .bandwidth_bps = 34*Kbit },
83 { .ac = AC_VI, .period_usec=25*MSEC_TO_USEC, .bandwidth_bps = 480*Kbit },
84 { .ac = AC_BE, .period_usec=40*MSEC_TO_USEC, .bandwidth_bps = 300*Kbit },
85 { .ac = AC_BK, .period_usec=40*MSEC_TO_USEC, .bandwidth_bps = 300*Kbit },
86 // { .ac = AC_VI, .period_usec=17*MSEC_TO_USEC, .bandwidth_bps = 675*Kbit },
90 struct stream streams[MAX_STREAMS];
92 unsigned int nr_streams = 0;
94 sem_t sem_thread_finished;
96 bool exit_flag = false;
103 /* Interrupt all receivers */
104 for (i=0; i < AC_NUM; i++) {
105 pthread_kill(receivers[i].thread, SIGUSR1);
109 void stream_to_text(char *stream_desc, size_t n, struct stream *stream, long long useconds)
115 snprintf(real, sizeof(real), "; real: %s sent %lld (%lld/s), received %lld (%lld/s)",
116 bandwidth_to_text(buf[0], (long long)stream->really_sent*stream->packet_size*8*SEC_TO_USEC/useconds),
117 stream->sent, stream->sent*SEC_TO_USEC/useconds,
118 stream->received, stream->received*SEC_TO_USEC/useconds);
123 snprintf(stream_desc, n, "%d: %s %s (%d bytes per %s +-%s, %d packets/s)%s",
124 stream-streams, ac_to_text[stream->ac], bandwidth_to_text(buf[0], stream->bandwidth_bps),
125 stream->packet_size, usec_to_text(buf[1], stream->period_usec),
126 usec_to_text(buf[2], stream->jitter*stream->period_usec/100),
127 (int)(SEC_TO_USEC/stream->period_usec), real);
130 void save_results(int argc, char *argv[], int useconds)
133 const int mini = 3000/opt_granularity_usec;
135 unsigned sum[AC_NUM];
138 fprintf(stderr, "Writing data to %s... ", logfname);
141 fprintf(logfd, "# Invoked as: ");
142 for (i=0; i<argc; i++) fprintf(logfd, "%s ", argv[i]);
143 fprintf(logfd, "\n");
145 if (useconds/SEC_TO_USEC != opt_count_sec) {
146 fprintf(logfd, "# Data gathered for %d seconds.\n", (int)(useconds/SEC_TO_USEC));
149 for (i = 0; i < nr_streams; i++) {
150 char stream_desc[120];
151 stream_to_text(stream_desc, sizeof(stream_desc), &streams[i], useconds);
152 fprintf(logfd, "# Stream %s\n", stream_desc);
155 /* Find maximal delay */
157 for (maxi = MAX_DELAY_US/opt_granularity_usec - 1; maxi >= 0; maxi--) {
158 for (ac = 0; ac < AC_NUM; ac++) {
159 if (delay_stats[ac][maxi] != 0) allzeros = false;
161 if (!allzeros) break;
164 if (maxi < mini) maxi = mini;
166 /* Calculate total number of sent packets per AC */
167 for (ac = 0; ac < AC_NUM; ac++) sum[ac] = 0;
168 for (i = 0; i < nr_streams; i++) {
170 sum[ac] += streams[i].sent;
175 for ( i = 0 ; i < maxi; i++) {
176 fprintf(logfd,"\n%f", i*opt_granularity_usec/1000.0);
177 for (ac = 0; ac < AC_NUM; ac++) {
179 val = (double)delay_stats[ac][i]*100.0 / sum[ac];
180 else val = -1; /* Don't display this ac */
181 fprintf(logfd," %lf", val);
185 fprintf(logfd,"\n\n");
189 for (ac = 0; ac < AC_NUM; ac++) {
190 unsigned long long integral = 0, last = -1;
192 fprintf(logfd,"%f %f\n", 0.0, 0.0);
196 while (delay_stats[ac][i] == 0) i++;
198 for (i++; i < maxi+1; i++) {
199 if (last != integral) {
200 val = (double)integral*100.0 / sum[ac];
201 fprintf(logfd,"%f %f\n", i*opt_granularity_usec/1000.0, val);
205 integral += delay_stats[ac][i-1];
208 fprintf(logfd,"\n\n");
211 fprintf(stderr, "finished.\n");
218 void timespec_add (struct timespec *sum, const struct timespec *left,
219 const struct timespec *right)
221 sum->tv_sec = left->tv_sec + right->tv_sec;
222 sum->tv_nsec = left->tv_nsec + right->tv_nsec;
224 if (sum->tv_nsec >= 1000000000){
226 sum->tv_nsec -= 1000000000;
231 void timespec_sub (struct timespec *diff, const struct timespec *left,
232 const struct timespec *right)
234 diff->tv_sec = left->tv_sec - right->tv_sec;
235 diff->tv_nsec = left->tv_nsec - right->tv_nsec;
237 if (diff->tv_nsec < 0){
239 diff->tv_nsec += 1000000000;
243 static inline long long timespec_sub_usec(const struct timespec *left,
244 const struct timespec *right)
246 struct timespec result;
247 timespec_sub(&result, left, right);
248 return result.tv_sec * SEC_TO_USEC +
249 result.tv_nsec / USEC_TO_NSEC;
252 static inline long long timespec2usec(const struct timespec *ts)
254 return ts->tv_sec * SEC_TO_USEC + ts->tv_nsec / USEC_TO_NSEC;
258 int create_ac_socket(unsigned int ac)
261 unsigned int yes=1, tos;
264 if ((sockfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
266 perror("Unable to open socket");
269 if (fcntl(sockfd, F_SETFL, O_NONBLOCK) != 0) {
270 perror("set non-blocking socket");
273 if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
274 perror("Unable to set socket");
279 //tos = ((AC_NUM - ac) *2 - 1)*32;
281 if (setsockopt(sockfd, SOL_IP, IP_TOS, &tos, sizeof(tos))) {
282 perror("Unable to set TOS");
294 void reset_statistics()
298 for (i = 0; i < nr_streams; i++) {
299 pthread_mutex_lock(&streams[i].mutex);
301 streams[i].really_sent = 0;
302 streams[i].received = 0;
303 pthread_mutex_unlock(&streams[i].mutex);
305 pthread_mutex_lock(&delay_stats_mutex);
306 clock_gettime(CLOCK_MONOTONIC, &reset_timestamp);
307 memset(delay_stats, 0, sizeof(delay_stats));
308 pthread_mutex_unlock(&delay_stats_mutex);
311 void* receiver(void* queue)
314 struct sockaddr_in rem_addr;
316 unsigned int ac, rem_addr_length;
317 long long int trans_time_usec, client_to_server_usec, server_to_client_usec;
318 long long int min_trans_time;
319 struct timespec send_timestamp, server_timestamp, recv_timestamp;
328 rem_addr_length = sizeof(rem_addr);
331 FD_SET(ac_sockfd[ac], &fdset);
332 ret = select(ac_sockfd[ac]+1, &fdset, NULL, NULL, NULL);
334 if (errno == EINTR) continue;
335 perror("receiver select");
338 mlen = recvfrom(ac_sockfd[ac], &msg, sizeof(msg), 0,
339 (struct sockaddr*)&rem_addr, &rem_addr_length);
341 perror("Chyba pri prijimani pozadavku");
344 clock_gettime(CLOCK_MONOTONIC,&recv_timestamp);
345 send_timestamp = msg.send_timestamp;
346 /* server_timestamp = msg.sendback_timestamp; */
348 /* Check whether this message was sent after reset_statistics() */
350 if (timespec_sub_usec(&send_timestamp, &reset_timestamp) < 0) {
351 continue; /* If so, don't count it */
354 trans_time_usec = timespec_sub_usec(&recv_timestamp ,&send_timestamp);
355 client_to_server_usec = timespec_sub_usec(&server_timestamp, &send_timestamp);
356 server_to_client_usec = timespec_sub_usec(&recv_timestamp, &server_timestamp);
358 trans_time_usec /= 2;
360 if (trans_time_usec < MAX_DELAY_US) {
361 pthread_mutex_lock(&delay_stats_mutex);
362 delay_stats[ac][trans_time_usec/opt_granularity_usec]++;
363 pthread_mutex_unlock(&delay_stats_mutex);
366 receivers[ac].received++;
367 pthread_mutex_lock(&streams[msg.stream].mutex);
368 streams[msg.stream].received++;
369 pthread_mutex_unlock(&streams[msg.stream].mutex);
371 /*if (trans_time_nsec < min_trans_time)
372 min_trans_time = trans_time_nsec;*/
373 /*printf("seqn= %lu tos= %d start= %lu(s).%lu(ns)"\
374 "stop= %lu(s).%lu(ns)\n trans_time = %lums\n",\
375 msg.seqn, msg.tos, send_timestamp.tv_sec,\
376 send_timestamp.tv_nsec,recv_timestamp.tv_sec,\
377 recv_timestamp.tv_nsec, trans_time_msec); */
380 sem_post(&sem_thread_finished);
387 * @return -1 in case of error, 1 in case of sucessfull send and 0
388 * when all buffers are full.
391 send_packet(struct stream* stream, union msg_buff* buff)
394 while (sendto(ac_sockfd[stream->ac], &buff, stream->packet_size, 0,
395 (struct sockaddr*)&stream->rem_addr, sizeof(stream->rem_addr)) < 0) {
396 if (errno == EINTR) continue;
397 if (errno == EAGAIN) {
398 if (opt_wait_for_queue_is_full &&
399 !some_queue_is_full &&
400 /* We use mutex as atomic test and set */
401 (pthread_mutex_trylock(&queue_full_mutex) != EBUSY)) {
402 some_queue_is_full = true;
408 perror("Error while sending");
417 wait_for_next_send(struct stream* stream, struct timespec *last_send_time)
419 struct timespec time_to_wait, current_time, period, interval;
420 unsigned period_usec = stream->period_usec;
422 /* |~~~+~~~| jitter interval (width = 2*stream->jitter percentage from period)*/
423 /* |-------------| nominal period*/
424 if (stream->jitter) {
425 period.tv_nsec = USEC_TO_NSEC*(period_usec*(100-stream->jitter)/100
426 + rand() % (2*period_usec*stream->jitter/100));
428 period.tv_nsec = USEC_TO_NSEC*(period_usec);
432 timespec_add(&time_to_wait, last_send_time, &period);
433 clock_gettime(CLOCK_MONOTONIC,¤t_time);
434 timespec_sub(&interval,&time_to_wait,¤t_time);
435 nanosleep(&interval,NULL);
439 void* sender(void* arg)
442 unsigned long int seqn;
443 struct stream* stream = (struct stream*) arg;
444 char stream_desc[100];
447 stream_to_text(stream_desc, sizeof(stream_desc), stream, 0);
448 printf("%s\n", stream_desc);
450 if (stream->bandwidth_bps == 0)
456 set_rt_prio(90-stream->ac);
460 /* buff.msg.seqn = seqn++; */
461 /* buff.msg.tos = ac_to_tos[stream->ac]; */
462 buff.msg.stream = stream-streams;
464 clock_gettime(CLOCK_MONOTONIC,&buff.msg.send_timestamp);
466 ret = send_packet(stream, &buff);
471 pthread_mutex_lock(&stream->mutex);
474 stream->really_sent++;
475 pthread_mutex_unlock(&stream->mutex);
478 printf("%d", stream->ac);
482 wait_for_next_send(stream, &buff.msg.send_timestamp);
485 sem_post(&sem_thread_finished);
490 calc_stream_params(struct stream *stream)
493 unsigned period_usec;
497 bandwidth = stream->bandwidth_bps;
499 if (stream->packet_size) {
500 packet_size = stream->packet_size;
501 period_usec = SEC_TO_USEC*packet_size*8/bandwidth;
502 if (period_usec == 0) period_usec = 1;
503 } else if (stream->period_usec) {
504 period_usec = stream->period_usec;
505 packet_size = (long long)bandwidth/8 * period_usec/SEC_TO_USEC;
508 stream_to_text(buf, sizeof(buf), stream, 0);
509 fprintf(stderr, "Neither packet size nor period was specified for a stream %s\n", buf);
513 if (packet_size < sizeof(struct msg_t)) {
514 fprintf(stderr, "Packet size too small (min %d)\n", sizeof(struct msg_t));
518 stream->packet_size = packet_size;
519 stream->period_usec = period_usec;
520 stream->jitter = opt_jitter;
522 memset(&stream->rem_addr,0, sizeof(stream->rem_addr));
524 stream->rem_addr.sin_family = AF_INET;
525 ph = gethostbyname(server_addr);
527 stream->rem_addr.sin_addr = *((struct in_addr *)ph->h_addr);
529 perror("Unknown server");
532 stream->rem_addr.sin_port = htons(BASE_PORT + stream->ac);
537 * Parse -b parameter.
539 * @param params String to parse
541 * @return NULL in case of success, pointer to a problematic character
544 char* parse_bandwidths(char *params)
546 struct stream *sp = &streams[nr_streams];
548 while (*params && nr_streams < MAX_STREAMS) {
549 char *ac_ids[AC_NUM] = { [AC_VO]="VO", [AC_VI]="VI", [AC_BE]="BE", [AC_BK]="BK" };
553 if (strlen(params) < 2)
555 for (i=0; i<AC_NUM; i++) {
556 if (strncmp(params, ac_ids[i], 2) == 0) {
558 params+=strlen(ac_ids[i]);
566 if (*params == ':') {
569 bw = strtol(params, &next_char, 10);
570 if (next_char == params)
574 bw = opt_def_bandwidth;
576 sp->bandwidth_bps = bw*Kbit;
579 long packet_size = 0;
580 if (*params == '@') {
582 period = strtol(params, &next_char, 10);
588 if (*params == '/') {
590 packet_size = strtol(params, &next_char, 10);
591 if (packet_size == 0)
595 packet_size = opt_packet_size;
596 period = opt_def_period_msec;
599 sp->period_usec = period*MSEC_TO_USEC;
600 sp->packet_size = packet_size;
604 if (*params != '\0' && *params != ',')
614 int main(int argc, char *argv[])
616 int ac, i, rc, seconds;
622 while ((opt = getopt(argc, argv, "B:b:c:g:j:o:qs:T:")) != -1) {
625 opt_def_bandwidth = atoi(optarg);
629 error = parse_bandwidths(optarg);
632 fprintf(stderr, "Bandwidth parse error - string to short\n");
634 fprintf(stderr, "Bandwidth parse error at '%s'\n", error);
640 opt_count_sec = atoi(optarg);
643 opt_granularity_usec = atoi(optarg);
644 if (opt_granularity_usec < MIN_GRANULARITY) {
645 fprintf(stderr, "Granulatiry too small (min %d)!\n", MIN_GRANULARITY);
650 opt_jitter = atoi(optarg);
656 opt_wait_for_queue_is_full = true;
659 opt_packet_size = atoi(optarg);
662 opt_def_period_msec = atoi(optarg);
665 fprintf(stderr, "Usage: %s [ options ] server_addr\n\n", argv[0]);
666 fprintf(stderr, "Options:\n");
667 fprintf(stderr, " -B default bandwidth for -b option [kbit]\n");
668 fprintf(stderr, " -b bandwidth of streams (VO|VI|BE|BK)[:<kbit>][@<msec> or /<bytes>][,...]\n");
669 fprintf(stderr, " -c count (number of seconds to run)\n");
670 fprintf(stderr, " -g histogram granularity [usec]\n");
671 fprintf(stderr, " -j send jitter (0-100) [%%]\n");
672 fprintf(stderr, " -o output filename (.dat will be appended)\n");
673 fprintf(stderr, " -q gather statistics only after some queue becomes full\n");
674 fprintf(stderr, " -s size of data payload in packets [bytes] (default: %d)\n", opt_packet_size);
675 fprintf(stderr, " -T default period for -b option [msec]\n");
679 if (opt_packet_size && opt_def_period_msec) {
680 fprintf(stderr, "Error: Nonzero -T and -s can't be used together!.\n");
685 server_addr = argv[optind];
687 fprintf(stderr, "Expected server address argument\n");
692 parse_bandwidths("BE");
694 pthread_attr_init(&attr);
696 snprintf(logfname, sizeof(logfname), "%s.dat", opt_output);
698 if ((logfd = fopen(logfname,"w+")) == NULL) {
699 fprintf(stderr,"Can not open %s\n", logfname);
702 if (signal(SIGTERM, stopper) == SIG_ERR) {
703 perror("Error in signal registration");
707 if (signal(SIGINT, stopper) == SIG_ERR) {
708 perror("Signal handler registration error");
713 sa.sa_handler = empty_handler;
714 sa.sa_flags = 0; /* don't restart syscalls */
716 if (sigaction(SIGUSR1, &sa, NULL) < 0) {
717 perror("sigaction error");
721 sem_init(&sem_thread_finished, 0, 0);
725 /* create four receivers each per AC */
726 for (ac = AC_NUM - 1; ac >= 0; ac--) {
727 ac_sockfd[ac] = create_ac_socket(ac);
728 rc = pthread_create(&receivers[ac].thread, &attr, receiver, (void*) ac);
730 fprintf(stderr, "Error while creating receiver %d\n",rc);
735 /* create sendpoints */
736 for (i = 0; i < nr_streams; i++) {
737 struct stream *s = &streams[i];
738 pthread_mutex_init(&s->mutex, NULL);
739 calc_stream_params(s);
740 rc = pthread_create(&thread, &attr, sender, (void*) s);
742 fprintf(stderr, "Error while creating sender %d\n",rc);
751 fprintf(stderr, "\r%3ds", seconds);
752 for (ac = 0; ac < AC_NUM; ac++) {
753 int delta = receivers[ac].received - receivers[ac].last_received;
754 receivers[ac].last_received = receivers[ac].received;
755 fprintf(stderr, " %s %5d %4d/s", ac_to_text[ac], receivers[ac].received, delta);
758 if (seconds == opt_count_sec)
762 fprintf(stderr, "\nWaiting for threads to finish\n");
763 /* Wait for all threads to finish */
764 for (i=0; i < nr_streams + AC_NUM; i++) {
765 sem_wait(&sem_thread_finished);
767 struct timespec end_timestamp, measure_length;
768 clock_gettime(CLOCK_MONOTONIC,&end_timestamp);
769 timespec_sub(&measure_length, &end_timestamp, &reset_timestamp);
771 save_results(argc, argv, timespec2usec(&measure_length));