3 #include <sys/socket.h>
4 #include <netinet/in.h>
19 #include <semaphore.h>
20 #include <sys/ioctl.h>
24 #include <fwp_proto.h>
27 #define MAX_STREAMS 10
28 #define MIN_GRANULARITY 100
30 unsigned opt_packet_size = 800;
31 int opt_send_buf_size = -1;
32 unsigned opt_period_usec = 10*MSEC_TO_USEC;
34 unsigned opt_jitter = 0;
35 char *opt_output = "delay_stats";
36 unsigned opt_count_sec = 0;
37 unsigned opt_def_bandwidth = 200;
38 unsigned opt_def_period_msec = 0;
39 int opt_granularity_usec = MIN_GRANULARITY;
40 bool opt_wait_for_queue_is_full; /* Don't gather any statistics until any queue is full */
42 bool some_queue_is_full = false;
43 struct timespec reset_timestamp;
45 /* Locked when some queue is full to prevent multiple resets of
47 pthread_mutex_t queue_full_mutex = PTHREAD_MUTEX_INITIALIZER;
49 int ac_sockfd[AC_NUM];
53 unsigned received, last_received;
60 /* maximal traffic delay in ms - 10 s*/
61 #define MAX_DELAY_US 10000000
64 unsigned csc; /* Client-server-client delay divided by 2 */
65 unsigned cs; /* Client-server delay */
66 unsigned sc; /* Server-client delay */
69 struct delay_stat delay_stats[AC_NUM][MAX_DELAY_US/MIN_GRANULARITY];
70 pthread_mutex_t delay_stats_mutex = PTHREAD_MUTEX_INITIALIZER;
72 /*struct ac_stats[AC_NUM] {
73 unsigned long int min_trans_time;
74 unsigned long int sum_trans_time;
75 struct timespec recv_timestamp;
76 struct timespec send_timestamp;
80 /* Input parameters */
82 int bandwidth_bps; /* bits per second */
83 int jitter; /* percent */
84 /* Mulualy exclusive input parameters */
86 long period_usec; /* all time units are in microseconds */
90 struct sockaddr_in rem_addr;
96 pthread_mutex_t mutex;
97 unsigned long long sent, really_sent, received;
100 static struct cmsg_ipi {
102 struct in_pktinfo ipi;
103 } cmsg = { {sizeof(struct cmsg_ipi), SOL_IP, IP_PKTINFO},
108 struct send_endpoint sepoint[] = {
109 { .ac = AC_VO, .period_usec=200*MSEC_TO_USEC, .bandwidth_bps = 34*Kbit },
110 { .ac = AC_VI, .period_usec=25*MSEC_TO_USEC, .bandwidth_bps = 480*Kbit },
111 { .ac = AC_BE, .period_usec=40*MSEC_TO_USEC, .bandwidth_bps = 300*Kbit },
112 { .ac = AC_BK, .period_usec=40*MSEC_TO_USEC, .bandwidth_bps = 300*Kbit },
113 // { .ac = AC_VI, .period_usec=17*MSEC_TO_USEC, .bandwidth_bps = 675*Kbit },
117 struct stream streams[MAX_STREAMS];
119 unsigned int nr_streams = 0;
121 sem_t sem_thread_finished;
123 bool exit_flag = false;
126 #define negotiate_contract_for_stream(s) negotiate_contract_for_stream_fwp(s)
127 #define create_stream_endpoint(s) create_stream_endpoint_fwp(s)
128 #define send_packet(s, b) send_packet_fwp(s, b)
130 #define negotiate_contract_for_stream(s) 0
131 #define create_stream_endpoint(s) create_stream_endpoint_native(s)
132 #define send_packet(s, b) send_packet_native(s, b)
140 /* Interrupt all receivers */
141 for (i=0; i < AC_NUM; i++) {
142 pthread_kill(receivers[i].thread, SIGUSR1);
146 void stream_to_text(char *stream_desc, size_t n, struct stream *stream, long long useconds)
152 snprintf(real, sizeof(real), "; real: %s sent %lld (%lld/s), received %lld (%lld/s)",
153 bandwidth_to_text(buf[0], (long long)stream->really_sent*stream->packet_size*8*SEC_TO_USEC/useconds),
154 stream->sent, stream->sent*SEC_TO_USEC/useconds,
155 stream->received, stream->received*SEC_TO_USEC/useconds);
160 snprintf(stream_desc, n, "%d: %s %s (%d bytes per %s +-%s, %d packets/s)%s",
161 stream-streams, ac_to_text[stream->ac], bandwidth_to_text(buf[0], stream->bandwidth_bps),
162 stream->packet_size, usec_to_text(buf[1], stream->period_usec),
163 usec_to_text(buf[2], stream->jitter*stream->period_usec/100),
164 (int)(SEC_TO_USEC/stream->period_usec), real);
167 void save_results(int argc, char *argv[], int useconds)
170 const int mini = 3000/opt_granularity_usec;
172 unsigned send_count[AC_NUM];
174 fprintf(stderr, "Writing data to %s... ", logfname);
177 fprintf(logfd, "# Invoked as: ");
178 for (i=0; i<argc; i++) fprintf(logfd, "%s ", argv[i]);
179 fprintf(logfd, "\n");
181 if (useconds/SEC_TO_USEC != opt_count_sec) {
183 usec_to_text(buf, useconds);
184 fprintf(logfd, "# Data gathered for %s.\n", buf);
187 for (i = 0; i < nr_streams; i++) {
188 char stream_desc[200];
189 stream_to_text(stream_desc, sizeof(stream_desc), &streams[i], useconds);
190 fprintf(logfd, "# Stream %s\n", stream_desc);
193 /* Find maximal delay */
195 for (maxi = MAX_DELAY_US/opt_granularity_usec - 1; maxi >= 0; maxi--) {
196 for (ac = 0; ac < AC_NUM; ac++) {
197 if ((delay_stats[ac][maxi].csc != 0) ||
198 (delay_stats[ac][maxi].cs != 0) ||
199 (delay_stats[ac][maxi].sc != 0))
202 if (!allzeros) break;
205 if (maxi < mini) maxi = mini;
207 /* Calculate total number of sent packets per AC */
208 memset(send_count, 0, sizeof(send_count));
209 for (i = 0; i < nr_streams; i++) {
211 send_count[ac] += streams[i].sent;
216 for ( i = 0 ; i < maxi; i++) {
217 fprintf(logfd,"\n%f", i*opt_granularity_usec/1000.0);
218 for (ac = 0; ac < AC_NUM; ac++) {
220 val = (double)delay_stats[ac][i]*100.0 / sum[ac];
221 else val = -1; /* Don't display this ac */
222 fprintf(logfd," %lf", val);
226 fprintf(logfd,"\n\n");
229 fprintf(logfd,"## Format: msec csc%% cs%% sc%%\n");
232 for (ac = 0; ac < AC_NUM; ac++) {
233 struct delay_stat integral = {0,0,0}, last = {-1,-1,-1};
235 fprintf(logfd,"%f %f %f %f\n", 0.0, 0.0, 0.0, 0.0);
237 if (send_count[ac] != 0) {
239 while ((delay_stats[ac][i].csc == 0) &&
240 (delay_stats[ac][i].cs == 0) &&
241 (delay_stats[ac][i].sc == 0)) i++;
243 for (i++; i < maxi+1; i++) {
244 if (memcmp(&last, &integral, sizeof(last))) {
245 fprintf(logfd,"%f %f %f %f\n", i*opt_granularity_usec/1000.0,
246 (double)integral.csc*100.0 / send_count[ac],
247 (double)integral.cs *100.0 / send_count[ac],
248 (double)integral.sc *100.0 / send_count[ac]
253 integral.csc += delay_stats[ac][i-1].csc;
254 integral.sc += delay_stats[ac][i-1].sc;
255 integral.cs += delay_stats[ac][i-1].cs;
259 fprintf(logfd,"\n\n");
262 fprintf(stderr, "finished.\n");
268 int create_ac_socket(unsigned int ac)
271 unsigned int yes=1, tos;
274 if ((sockfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
276 perror("Unable to open socket");
279 if (fcntl(sockfd, F_SETFL, O_NONBLOCK) != 0) {
280 perror("set non-blocking socket");
283 if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
284 perror("Unable to set socket");
288 if (opt_send_buf_size >= 0) {
289 if (setsockopt(sockfd,SOL_SOCKET,SO_SNDBUF,&opt_send_buf_size,sizeof(opt_send_buf_size)) == -1) {
290 perror("Unable to set socket buffer size");
296 //tos = ((AC_NUM - ac) *2 - 1)*32;
298 if (setsockopt(sockfd, SOL_IP, IP_TOS, &tos, sizeof(tos))) {
299 perror("Unable to set TOS");
311 void reset_statistics()
314 for (i = 0; i < nr_streams; i++) {
315 pthread_mutex_lock(&streams[i].mutex);
317 streams[i].really_sent = 0;
318 streams[i].received = 0;
319 pthread_mutex_unlock(&streams[i].mutex);
321 pthread_mutex_lock(&delay_stats_mutex);
322 clock_gettime(CLOCK_REALTIME, &reset_timestamp);
323 memset(delay_stats, 0, sizeof(delay_stats));
324 pthread_mutex_unlock(&delay_stats_mutex);
327 void* receiver(void* queue)
330 struct sockaddr_in rem_addr;
332 unsigned int ac, rem_addr_length;
333 long long int trans_time_usec, client_to_server_usec, server_to_client_usec;
334 long long int min_trans_time;
335 struct timespec send_timestamp, server_timestamp, recv_timestamp;
344 rem_addr_length = sizeof(rem_addr);
347 FD_SET(ac_sockfd[ac], &fdset);
348 ret = select(ac_sockfd[ac]+1, &fdset, NULL, NULL, NULL);
350 if (errno == EINTR) continue;
351 perror("receiver select");
354 mlen = recvfrom(ac_sockfd[ac], &msg, sizeof(msg), 0,
355 (struct sockaddr*)&rem_addr, &rem_addr_length);
357 perror("Chyba pri prijimani pozadavku");
360 clock_gettime(CLOCK_REALTIME,&recv_timestamp);
361 send_timestamp = msg.send_timestamp;
362 server_timestamp = msg.sendback_timestamp;
364 /* Check whether this message was sent after reset_statistics() */
366 if ((ret = timespec_sub_usec(&send_timestamp, &reset_timestamp)) < 0) {
367 continue; /* If so, don't count it */
370 trans_time_usec = timespec_sub_usec(&recv_timestamp ,&send_timestamp) / 2;
371 client_to_server_usec = timespec_sub_usec(&server_timestamp, &send_timestamp);
372 server_to_client_usec = timespec_sub_usec(&recv_timestamp, &server_timestamp);
374 pthread_mutex_lock(&delay_stats_mutex);
375 if (trans_time_usec < MAX_DELAY_US && trans_time_usec >= 0) {
376 delay_stats[ac][trans_time_usec/opt_granularity_usec].csc++;
378 if (client_to_server_usec < MAX_DELAY_US && client_to_server_usec >= 0) {
379 delay_stats[ac][client_to_server_usec/opt_granularity_usec].cs++;
381 if (server_to_client_usec < MAX_DELAY_US && server_to_client_usec >= 0) {
382 delay_stats[ac][server_to_client_usec/opt_granularity_usec].sc++;
384 pthread_mutex_unlock(&delay_stats_mutex);
386 receivers[ac].received++;
388 pthread_mutex_lock(&streams[msg.stream].mutex);
389 streams[msg.stream].received++;
390 pthread_mutex_unlock(&streams[msg.stream].mutex);
392 /*if (trans_time_nsec < min_trans_time)
393 min_trans_time = trans_time_nsec;*/
394 /*printf("seqn= %lu tos= %d start= %lu(s).%lu(ns)"\
395 "stop= %lu(s).%lu(ns)\n trans_time = %lums\n",\
396 msg.seqn, msg.tos, send_timestamp.tv_sec,\
397 send_timestamp.tv_nsec,recv_timestamp.tv_sec,\
398 recv_timestamp.tv_nsec, trans_time_msec); */
401 sem_post(&sem_thread_finished);
408 * @return -1 in case of error, 1 in case of sucessfull send and 0
409 * when all buffers are full.
413 send_packet_native(struct stream* stream, union msg_buff* buff)
419 iov.iov_len = stream->packet_size;
420 msg.msg_name = (void*)&stream->rem_addr;
421 msg.msg_namelen = sizeof(stream->rem_addr);
425 msg.msg_control = &cmsg;
426 msg.msg_controllen = cmsg_len;
430 while (sendmsg(ac_sockfd[stream->ac], &msg, 0) < 0) {
431 if (errno == EINTR) continue;
432 if (errno == EAGAIN) {
433 if (opt_wait_for_queue_is_full &&
434 !some_queue_is_full &&
435 /* We use mutex as atomic test and set */
436 (pthread_mutex_trylock(&queue_full_mutex) != EBUSY)) {
437 some_queue_is_full = true;
443 perror("Error while sending");
452 send_packet_fwp(struct stream* stream, union msg_buff* buff)
455 /* while (sendto(ac_sockfd[stream->ac], buff, stream->packet_size, 0, */
456 /* (struct sockaddr*)&stream->rem_addr, sizeof(stream->rem_addr)) < 0) { */
457 /* if (errno == EINTR) continue; */
458 /* if (errno == EAGAIN) { */
459 /* if (opt_wait_for_queue_is_full && */
460 /* !some_queue_is_full && */
461 /* /\* We use mutex as atomic test and set *\/ */
462 /* (pthread_mutex_trylock(&queue_full_mutex) != EBUSY)) { */
463 /* some_queue_is_full = true; */
464 /* reset_statistics(); */
469 /* perror("Error while sending"); */
479 wait_for_next_send(struct stream* stream, struct timespec *last_send_time)
481 struct timespec time_to_wait, current_time, period, interval;
482 unsigned period_usec = stream->period_usec;
484 /* |~~~+~~~| jitter interval (width = 2*stream->jitter percentage from period)*/
485 /* |-------------| nominal period*/
486 if (stream->jitter) {
487 period.tv_nsec = USEC_TO_NSEC*(period_usec*(100-stream->jitter)/100
488 + rand() % (2*period_usec*stream->jitter/100));
490 period.tv_nsec = USEC_TO_NSEC*(period_usec);
494 timespec_add(&time_to_wait, last_send_time, &period);
495 clock_gettime(CLOCK_REALTIME,¤t_time);
496 timespec_sub(&interval,&time_to_wait,¤t_time);
497 nanosleep(&interval,NULL);
501 void* sender(void* arg)
504 unsigned long int seqn;
505 struct stream* stream = (struct stream*) arg;
506 char stream_desc[100];
509 stream_to_text(stream_desc, sizeof(stream_desc), stream, 0);
510 printf("%s\n", stream_desc);
512 if (stream->bandwidth_bps == 0)
518 set_rt_prio(90-stream->ac);
522 /* buff.msg.seqn = seqn++; */
523 /* buff.msg.tos = ac_to_tos[stream->ac]; */
524 buff.msg.stream = stream-streams;
526 clock_gettime(CLOCK_REALTIME,&buff.msg.send_timestamp);
528 ret = send_packet(stream, &buff);
533 pthread_mutex_lock(&stream->mutex);
536 stream->really_sent++;
537 pthread_mutex_unlock(&stream->mutex);
540 printf("%d", stream->ac);
544 wait_for_next_send(stream, &buff.msg.send_timestamp);
547 sem_post(&sem_thread_finished);
552 static int negotiate_contract_for_stream_fwp(struct stream *stream)
554 struct fwp_contract contract;
558 contract.budget = stream->packet_size;
559 contract.period_usec = stream->period_usec;
560 ret = fwp_contract_negotiate(&contract, &vres_id);
562 if (contract.status == FWP_CNT_NEGOTIATED) {
563 stream->vres_id = vres_id;
565 stream->vres_id = -1;
573 static void create_stream_endpoint_fwp(struct stream *stream)
575 /* TODO: How to create an enpoint? */
578 static void create_stream_endpoint_native(struct stream *stream)
582 memset(&stream->rem_addr,0, sizeof(stream->rem_addr));
584 stream->rem_addr.sin_family = AF_INET;
585 ph = gethostbyname(server_addr);
587 stream->rem_addr.sin_addr = *((struct in_addr *)ph->h_addr);
589 perror("Unknown server");
592 stream->rem_addr.sin_port = htons(BASE_PORT + stream->ac);
597 calc_stream_params(struct stream *stream)
600 unsigned period_usec;
604 /* If some parameters are not set explicitely, use default values. */
605 if (stream->bandwidth_bps < 0) stream->bandwidth_bps = opt_def_bandwidth * Kbit;
606 if (stream->packet_size < 0) stream->packet_size = opt_packet_size;
607 if (stream->period_usec < 0) stream->period_usec = opt_def_period_msec * MSEC_TO_USEC;
609 bandwidth = stream->bandwidth_bps;
611 /* Avoid arithmetic exception. Server thread will exit if
612 stream->bandwidth_bps == 0. */
613 if (bandwidth == 0) bandwidth = 1;
615 if (stream->packet_size) {
616 packet_size = stream->packet_size;
617 period_usec = SEC_TO_USEC*packet_size*8/bandwidth;
618 if (period_usec == 0) period_usec = 1;
619 } else if (stream->period_usec) {
620 period_usec = stream->period_usec;
621 packet_size = (long long)bandwidth/8 * period_usec/SEC_TO_USEC;
624 stream_to_text(buf, sizeof(buf), stream, 0);
625 fprintf(stderr, "Neither packet size nor period was specified for a stream %s\n", buf);
629 if (packet_size < sizeof(struct msg_t)) {
630 fprintf(stderr, "Packet size too small (min %d)\n", sizeof(struct msg_t));
634 stream->packet_size = packet_size;
635 stream->period_usec = period_usec;
636 stream->jitter = opt_jitter;
638 ret = negotiate_contract_for_stream(stream);
640 create_stream_endpoint(stream);
643 stream_to_text(buf, sizeof(buf), stream, 0);
644 fprintf(stderr, "Contract hasn't been accepted: %s\n", buf);
645 stream->bandwidth_bps = 0;
650 * Parse -b parameter.
652 * @param params String to parse
654 * @return NULL in case of success, pointer to a problematic character
657 char* parse_bandwidths(char *params)
659 struct stream *sp = &streams[nr_streams];
661 while (*params && nr_streams < MAX_STREAMS) {
662 char *ac_ids[AC_NUM] = { [AC_VO]="VO", [AC_VI]="VI", [AC_BE]="BE", [AC_BK]="BK" };
666 if (strlen(params) < 2)
668 for (i=0; i<AC_NUM; i++) {
669 if (strncmp(params, ac_ids[i], 2) == 0) {
671 params+=strlen(ac_ids[i]);
679 if (*params == ':') {
682 bw = strtol(params, &next_char, 10);
683 if (next_char == params)
689 sp->bandwidth_bps = bw*Kbit;
692 long packet_size = 0;
693 if (*params == '@') {
695 period = strtol(params, &next_char, 10);
701 if (*params == '/') {
703 packet_size = strtol(params, &next_char, 10);
704 if (packet_size == 0)
712 sp->period_usec = period*MSEC_TO_USEC;
713 sp->packet_size = packet_size;
717 if (*params != '\0' && *params != ',')
727 int main(int argc, char *argv[])
729 int ac, i, rc, seconds;
735 while ((opt = getopt(argc, argv, "B:b:c:g:I:j:o:qQ:s:T:")) != -1) {
738 opt_def_bandwidth = atoi(optarg);
742 error = parse_bandwidths(optarg);
745 fprintf(stderr, "Bandwidth parse error - string to short\n");
747 fprintf(stderr, "Bandwidth parse error at '%s'\n", error);
753 opt_count_sec = atoi(optarg);
756 opt_granularity_usec = atoi(optarg);
757 if (opt_granularity_usec < MIN_GRANULARITY) {
758 fprintf(stderr, "Granulatiry too small (min %d)!\n", MIN_GRANULARITY);
763 opt_interface = optarg;
766 opt_jitter = atoi(optarg);
772 opt_send_buf_size = atoi(optarg);
775 opt_wait_for_queue_is_full = true;
778 opt_packet_size = atoi(optarg);
781 opt_def_period_msec = atoi(optarg);
784 fprintf(stderr, "Usage: %s [ options ] server_addr\n\n", argv[0]);
785 fprintf(stderr, "Options:\n");
786 fprintf(stderr, " -B default bandwidth for -b option [kbit]\n");
787 fprintf(stderr, " -b bandwidth of streams (VO|VI|BE|BK)[:<kbit>][@<msec> or /<bytes>][,...]\n");
788 fprintf(stderr, " -c count (number of seconds to run)\n");
789 fprintf(stderr, " -g histogram granularity [usec]\n");
790 fprintf(stderr, " -I <interface> send packets from this interface");
791 fprintf(stderr, " -j send jitter (0-100) [%%]\n");
792 fprintf(stderr, " -o output filename (.dat will be appended)\n");
793 fprintf(stderr, " -q gather statistics only after some queue becomes full\n");
794 fprintf(stderr, " -Q <bytes> set size for socket send buffers\n");
795 fprintf(stderr, " -s size of data payload in packets [bytes] (default: %d)\n", opt_packet_size);
796 fprintf(stderr, " -T default period for -b option [msec]\n");
800 if (opt_packet_size && opt_def_period_msec) {
801 fprintf(stderr, "Error: Nonzero -T and -s can't be used together!.\n");
806 server_addr = argv[optind];
808 fprintf(stderr, "Expected server address argument\n");
813 parse_bandwidths("BE");
815 pthread_attr_init(&attr);
817 snprintf(logfname, sizeof(logfname), "%s.dat", opt_output);
819 if ((logfd = fopen(logfname,"w+")) == NULL) {
820 fprintf(stderr,"Can not open %s\n", logfname);
823 if (signal(SIGTERM, stopper) == SIG_ERR) {
824 perror("Error in signal registration");
828 if (signal(SIGINT, stopper) == SIG_ERR) {
829 perror("Signal handler registration error");
834 sa.sa_handler = empty_handler;
835 sa.sa_flags = 0; /* don't restart syscalls */
837 if (sigaction(SIGUSR1, &sa, NULL) < 0) {
838 perror("sigaction error");
842 sem_init(&sem_thread_finished, 0, 0);
846 /* create four receivers each per AC */
847 for (ac = AC_NUM - 1; ac >= 0; ac--) {
848 ac_sockfd[ac] = create_ac_socket(ac);
849 if (ac_sockfd[ac] < 0) {
852 rc = pthread_create(&receivers[ac].thread, &attr, receiver, (void*) ac);
854 fprintf(stderr, "Error while creating receiver %d\n",rc);
862 memset(&ifr, 0, sizeof(ifr));
863 strncpy(ifr.ifr_name, opt_interface, IFNAMSIZ-1);
864 if (ioctl(ac_sockfd[AC_VO], SIOCGIFINDEX, &ifr) < 0) {
865 fprintf(stderr, "unknown iface %s\n", opt_interface);
868 cmsg.ipi.ipi_ifindex = ifr.ifr_ifindex;
869 cmsg_len = sizeof(cmsg);
871 /* create sendpoints */
872 for (i = 0; i < nr_streams; i++) {
873 struct stream *s = &streams[i];
874 pthread_mutex_init(&s->mutex, NULL);
875 calc_stream_params(s);
876 rc = pthread_create(&thread, &attr, sender, (void*) s);
878 fprintf(stderr, "Error while creating sender %d\n",rc);
887 fprintf(stderr, "\r%3ds", seconds);
888 for (ac = 0; ac < AC_NUM; ac++) {
889 int delta = receivers[ac].received - receivers[ac].last_received;
890 receivers[ac].last_received = receivers[ac].received;
891 fprintf(stderr, " %s %5d %4d/s", ac_to_text[ac], receivers[ac].received, delta);
894 if (seconds == opt_count_sec)
898 fprintf(stderr, "\nWaiting for threads to finish\n");
899 /* Wait for all threads to finish */
900 for (i=0; i < nr_streams + AC_NUM; i++) {
901 sem_wait(&sem_thread_finished);
903 struct timespec end_timestamp, measure_length;
904 clock_gettime(CLOCK_REALTIME,&end_timestamp);
905 timespec_sub(&measure_length, &end_timestamp, &reset_timestamp);
907 save_results(argc, argv, timespec2usec(&measure_length));