]> rtime.felk.cvut.cz Git - frescor/fwp.git/blob - wme_test/wclient.c
Added checks for fail in FWP initialization
[frescor/fwp.git] / wme_test / wclient.c
1 #include <errno.h>
2 #include <sys/types.h>
3 #include <sys/socket.h>
4 #include <netinet/in.h>
5 #include <arpa/inet.h>
6 #include <netdb.h>
7 #include <signal.h>
8 #include <sys/wait.h>
9 #include <stdio.h>
10 #include <unistd.h>
11 #include <fcntl.h>
12 #include <time.h>
13 #include <string.h>
14 #include <pthread.h>
15 #include <string.h>
16 #include <stdlib.h>
17 #include <stdbool.h>
18 #include "common.h"
19 #include <semaphore.h>
20 #include <sys/ioctl.h>
21 #include <net/if.h>
22
23 #ifdef WITH_FWP
24 #include <fwp_confdefs.h>
25 #include <fwp.h>
26 #include <fwp_vres.h>
27 #endif
28
29 #define MAX_STREAMS  10 
30 #define MIN_GRANULARITY 100
31
32 unsigned opt_packet_size = 800;
33 int opt_send_buf_size = -1;
34 unsigned opt_period_usec = 10*MSEC_TO_USEC;
35 char    *opt_interface;
36 unsigned opt_jitter = 0;
37 char    *opt_output = "delay_stats";
38 unsigned opt_count_sec = 0;
39 unsigned opt_def_bandwidth = 200;
40 unsigned opt_def_period_msec = 0;
41 int opt_granularity_usec = MIN_GRANULARITY;
42 bool opt_wait_for_queue_is_full; /* Don't gather any statistics until any queue is full */
43 char *opt_comment = NULL;
44
45 bool some_queue_is_full = false;
46 struct timespec reset_timestamp;
47
48 /* Locked when some queue is full to prevent multiple resets of
49    statstics. */
50 pthread_mutex_t queue_full_mutex = PTHREAD_MUTEX_INITIALIZER;
51
52 int ac_sockfd[AC_NUM];
53
54 struct receiver {
55         pthread_t thread;
56         unsigned received, last_received;
57 } receivers[AC_NUM];
58
59 FILE* logfd;
60 char* server_addr; 
61 char logfname[100];
62
63 /* maximal traffic delay in ms - 10 s*/
64 #define MAX_DELAY_US 10000000
65
66 struct delay_stat {
67         unsigned csc;           /* Client-server-client delay divided by 2 */
68         unsigned cs;            /* Client-server delay */
69         unsigned sc;            /* Server-client delay */
70 };
71
72 struct delay_stat delay_stats[AC_NUM][MAX_DELAY_US/MIN_GRANULARITY];
73 pthread_mutex_t delay_stats_mutex = PTHREAD_MUTEX_INITIALIZER;
74
75 /*struct ac_stats[AC_NUM] {
76    unsigned long int min_trans_time;
77    unsigned long int sum_trans_time;
78    struct timespec   recv_timestamp;
79    struct timespec   send_timestamp; 
80 };*/
81
82 struct stream {
83         /* Input parameters */
84         enum ac ac;             /*  */
85         int bandwidth_bps;      /* bits per second */
86         int jitter;             /* percent */
87         /* Mulualy exclusive input parameters */
88         int packet_size;
89         long period_usec;       /* all time units are in microseconds */
90
91         /* Internal fields */
92 #ifndef WITH_FWP
93         struct sockaddr_in rem_addr;
94 #else
95         fwp_endpoint_d_t endpoint;
96         fwp_vres_d_t vres;
97 #endif
98
99         /* Statistics */
100         pthread_mutex_t mutex;
101         unsigned long long sent, really_sent, received;
102 };
103
104 static struct cmsg_ipi {
105         struct cmsghdr cm;
106         struct in_pktinfo ipi;
107 } cmsg = { {sizeof(struct cmsg_ipi), SOL_IP, IP_PKTINFO},
108            {0, }};
109 int cmsg_len = 0;
110
111 /*
112 struct send_endpoint sepoint[] = {
113         { .ac = AC_VO, .period_usec=200*MSEC_TO_USEC, .bandwidth_bps = 34*Kbit },
114         { .ac = AC_VI, .period_usec=25*MSEC_TO_USEC, .bandwidth_bps =  480*Kbit },
115         { .ac = AC_BE, .period_usec=40*MSEC_TO_USEC, .bandwidth_bps =  300*Kbit },
116         { .ac = AC_BK, .period_usec=40*MSEC_TO_USEC, .bandwidth_bps =  300*Kbit },
117 //      { .ac = AC_VI, .period_usec=17*MSEC_TO_USEC, .bandwidth_bps =  675*Kbit },
118 };
119 */
120
121 struct stream streams[MAX_STREAMS];
122
123 unsigned int nr_streams = 0;
124
125 sem_t sem_thread_finished;
126
127 bool exit_flag = false;
128
129 #ifdef WITH_FWP
130 #define negotiate_contract_for_stream(s) negotiate_contract_for_stream_fwp(s)
131 #define create_stream_endpoint(s) create_stream_endpoint_fwp(s)
132 #define send_packet(s, b) send_packet_fwp(s, b)
133 #else
134 #define negotiate_contract_for_stream(s) 0
135 #define create_stream_endpoint(s) create_stream_endpoint_native(s)
136 #define send_packet(s, b) send_packet_native(s, b)
137 #endif
138
139 void stopper()
140 {
141         int i;
142         exit_flag = true;
143
144         /* Interrupt all receivers */
145         for (i=0; i < AC_NUM; i++) {
146                 pthread_kill(receivers[i].thread, SIGUSR1);
147         }
148 }
149
150 void stream_to_text(char *stream_desc, size_t n, struct stream *stream, long long useconds)
151 {
152         char buf[3][12];
153         char real[100];
154
155         if (useconds) {
156                 snprintf(real, sizeof(real), "; real: %s sent %lld (%lld/s), received %lld (%lld/s)",
157                          bandwidth_to_text(buf[0], (long long)stream->really_sent*stream->packet_size*8*SEC_TO_USEC/useconds),
158                          stream->sent, stream->sent*SEC_TO_USEC/useconds,
159                          stream->received, stream->received*SEC_TO_USEC/useconds);
160         } else {
161                 real[0]=0;
162         }
163         
164         snprintf(stream_desc, n, "%d: %s %s (%d bytes per %s +-%s, %d packets/s)%s",
165                  stream-streams, ac_to_text[stream->ac], bandwidth_to_text(buf[0], stream->bandwidth_bps),
166                  stream->packet_size, usec_to_text(buf[1], stream->period_usec),
167                  usec_to_text(buf[2], stream->jitter*stream->period_usec/100),
168                  (int)(SEC_TO_USEC/stream->period_usec), real);
169 }
170
171 void save_results(int argc, char *argv[], int useconds)
172 {
173         int ac, i, maxi;
174         const int mini = 3000/opt_granularity_usec;
175         bool allzeros;
176         unsigned send_count[AC_NUM];
177
178         fprintf(stderr, "Writing data to %s... ", logfname);
179         fflush(stderr);
180
181         fprintf(logfd, "# Invoked as: ");
182         for (i=0; i<argc; i++) fprintf(logfd, "%s ", argv[i]);
183         if (opt_comment) {
184                 fprintf(logfd, "(%s)", opt_comment);
185         }
186         fprintf(logfd, "\n");
187
188         if (useconds/SEC_TO_USEC != opt_count_sec) {
189                 char buf[20];
190                 usec_to_text(buf, useconds);
191                 fprintf(logfd, "# Data gathered for %s.\n", buf);
192         }
193                 
194         for (i = 0; i < nr_streams; i++) {
195                 char stream_desc[200];
196                 stream_to_text(stream_desc, sizeof(stream_desc), &streams[i], useconds);
197                 fprintf(logfd, "# Stream %s\n", stream_desc);
198         }
199
200         /* Find maximal delay */
201         allzeros = true;
202         for (maxi = MAX_DELAY_US/opt_granularity_usec - 1; maxi >= 0; maxi--) {
203                 for (ac = 0; ac < AC_NUM; ac++) {
204                         if ((delay_stats[ac][maxi].csc != 0) ||
205                             (delay_stats[ac][maxi].cs != 0) ||
206                             (delay_stats[ac][maxi].sc != 0))
207                                 allzeros = false;
208                 }
209                 if (!allzeros) break;
210         }
211         maxi++;
212         if (maxi < mini) maxi = mini;
213
214         /* Calculate total number of sent packets per AC */
215         memset(send_count, 0, sizeof(send_count));
216         for (i = 0; i < nr_streams; i++) {
217                 ac = streams[i].ac;
218                 send_count[ac] += streams[i].sent;
219         }
220
221 #if 0
222         /* Write pdf */
223         for ( i = 0 ; i < maxi; i++) {
224                 fprintf(logfd,"\n%f", i*opt_granularity_usec/1000.0);
225                 for (ac = 0; ac < AC_NUM; ac++) { 
226                         if (sum[ac])
227                                 val = (double)delay_stats[ac][i]*100.0 / sum[ac];
228                         else val = -1; /* Don't display this ac */
229                         fprintf(logfd," %lf", val);
230                 }
231         }
232         
233         fprintf(logfd,"\n\n");
234 #endif
235         
236         fprintf(logfd,"## Format: msec csc%% cs%% sc%%\n");
237
238         /* Write PDF */
239         for (ac = 0; ac < AC_NUM; ac++) {
240                 struct delay_stat integral = {0,0,0}, last = {-1,-1,-1};
241
242                 fprintf(logfd,"%f %f %f %f\n", 0.0, 0.0, 0.0, 0.0);
243
244                 if (send_count[ac] != 0) {
245                         i=0;
246                         while ((delay_stats[ac][i].csc == 0) &&
247                                (delay_stats[ac][i].cs == 0) &&
248                                (delay_stats[ac][i].sc == 0)) i++;
249                 
250                         for (i++; i < maxi+1; i++) {
251                                 if (memcmp(&last, &integral, sizeof(last))) {
252                                         char buf[3][20];
253                                         snprintf(buf[0], sizeof(buf[0]), "%f", (double)integral.csc*100.0 / send_count[ac]);
254                                         snprintf(buf[1], sizeof(buf[1]), "%f", (double)integral.cs *100.0 / send_count[ac]);
255                                         snprintf(buf[2], sizeof(buf[2]), "%f", (double)integral.sc *100.0 / send_count[ac]);
256                                                  
257                                         fprintf(logfd,"%f %s %s %s\n", i*opt_granularity_usec/1000.0,
258                                                 integral.csc != last.csc ? buf[0] : "-",
259                                                 integral.cs  != last.cs  ? buf[1] : "-",
260                                                 integral.sc  != last.sc  ? buf[2] : "-"
261                                                 );
262                                         last = integral;
263                                 }
264                                 if (i>0) {
265                                         integral.csc += delay_stats[ac][i-1].csc;
266                                         integral.sc  += delay_stats[ac][i-1].sc;
267                                         integral.cs  += delay_stats[ac][i-1].cs;
268                                 }
269                         }
270                 }
271                 fprintf(logfd,"\n\n");
272         }
273         
274         fprintf(stderr, "finished.\n");
275         fclose(logfd);
276
277         exit(0);
278 }
279
280 int create_ac_socket(unsigned int ac) 
281 {
282         int sockfd;
283         unsigned int yes=1, tos;
284
285
286         if ((sockfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)
287         {
288                 perror("Unable to open socket");
289                 return -1;
290         }
291         if (fcntl(sockfd, F_SETFL, O_NONBLOCK) != 0) {
292                 perror("set non-blocking socket");
293                 return -1;
294         }
295         if (setsockopt(sockfd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
296                 perror("Unable to set socket");
297                 return -1;
298         }
299
300         if (opt_send_buf_size >= 0) {
301                 if (setsockopt(sockfd,SOL_SOCKET,SO_SNDBUF,&opt_send_buf_size,sizeof(opt_send_buf_size)) == -1) {
302                         perror("Unable to set socket buffer size");
303                         return -1;
304                 }
305         }
306
307         
308         //tos = ((AC_NUM - ac) *2 - 1)*32;
309         tos = ac_to_tos[ac];
310         if (setsockopt(sockfd, SOL_IP, IP_TOS, &tos, sizeof(tos))) {
311                 perror("Unable to set TOS");
312                 close(sockfd);
313                 return -1;
314         }
315
316         return sockfd;
317 }
318
319 void empty_handler()
320 {
321 }
322
323 void reset_statistics()
324 {
325         int i;
326         for (i = 0; i < nr_streams; i++) {
327                 pthread_mutex_lock(&streams[i].mutex);
328                 streams[i].sent = 0;
329                 streams[i].really_sent = 0;
330                 streams[i].received = 0;
331                 pthread_mutex_unlock(&streams[i].mutex);
332         }
333         pthread_mutex_lock(&delay_stats_mutex);
334         clock_gettime(CLOCK_REALTIME, &reset_timestamp);
335         memset(delay_stats, 0, sizeof(delay_stats));
336         pthread_mutex_unlock(&delay_stats_mutex);
337 }
338
339 void* receiver(void* queue)
340 {
341         struct msg_t    msg;
342         struct  sockaddr_in rem_addr;
343         int     mlen, ret;
344         unsigned int ac, rem_addr_length; 
345         long long int trans_time_usec, client_to_server_usec, server_to_client_usec;
346         long long int min_trans_time;
347         struct timespec send_timestamp, server_timestamp, recv_timestamp;
348         fd_set fdset;
349         
350         min_trans_time = ~0;
351         
352         block_signals();
353         set_rt_prio(99);
354
355         ac = (int)queue;
356         rem_addr_length = sizeof(rem_addr);
357         FD_ZERO(&fdset);
358         while (!exit_flag) {
359                 FD_SET(ac_sockfd[ac], &fdset);
360                 ret = select(ac_sockfd[ac]+1, &fdset, NULL, NULL, NULL);
361                 if (ret < 0) {
362                         if (errno == EINTR) continue;
363                         perror("receiver select");
364                         goto out;
365                 }
366                 mlen = recvfrom(ac_sockfd[ac], &msg, sizeof(msg), 0,
367                                 (struct sockaddr*)&rem_addr, &rem_addr_length);
368                 if (mlen < 0) {
369                         perror("Chyba pri prijimani pozadavku");
370                         goto out;
371                 }       
372                 clock_gettime(CLOCK_REALTIME,&recv_timestamp);
373                 send_timestamp = msg.send_timestamp;
374                 server_timestamp = msg.sendback_timestamp;
375
376                 /* Check whether this message was sent after reset_statistics() */
377
378                 if ((ret = timespec_sub_usec(&send_timestamp, &reset_timestamp)) < 0) {
379                         continue; /* If so, don't count it */
380                 }
381
382                 trans_time_usec = timespec_sub_usec(&recv_timestamp ,&send_timestamp) / 2;
383                 client_to_server_usec = timespec_sub_usec(&server_timestamp, &send_timestamp);
384                 server_to_client_usec = timespec_sub_usec(&recv_timestamp, &server_timestamp);
385
386                 pthread_mutex_lock(&delay_stats_mutex);
387                 if (trans_time_usec < MAX_DELAY_US && trans_time_usec >= 0) {
388                         delay_stats[ac][trans_time_usec/opt_granularity_usec].csc++;
389                 }
390                 if (client_to_server_usec < MAX_DELAY_US && client_to_server_usec >= 0) {
391                         delay_stats[ac][client_to_server_usec/opt_granularity_usec].cs++;
392                 }
393                 if (server_to_client_usec < MAX_DELAY_US && server_to_client_usec >= 0) {
394                         delay_stats[ac][server_to_client_usec/opt_granularity_usec].sc++;
395                 }
396                 pthread_mutex_unlock(&delay_stats_mutex);
397                 
398                 receivers[ac].received++;
399                 
400                 pthread_mutex_lock(&streams[msg.stream].mutex);
401                 streams[msg.stream].received++;
402                 pthread_mutex_unlock(&streams[msg.stream].mutex);
403         
404                 /*if (trans_time_nsec < min_trans_time) 
405                         min_trans_time = trans_time_nsec;*/
406                 /*printf("seqn= %lu tos= %d start= %lu(s).%lu(ns)"\
407                          "stop= %lu(s).%lu(ns)\n trans_time = %lums\n",\
408                          msg.seqn, msg.tos, send_timestamp.tv_sec,\
409                          send_timestamp.tv_nsec,recv_timestamp.tv_sec,\
410                          recv_timestamp.tv_nsec, trans_time_msec); */
411         }
412 out:
413         sem_post(&sem_thread_finished);
414         return NULL;
415 }
416
417 /** 
418  * Send a packet.
419  * 
420  * @return -1 in case of error, 1 in case of sucessfull send and 0
421  *         when all buffers are full.
422  */
423 #ifndef WITH_FWP
424 static inline int 
425 send_packet_native(struct stream* stream, union msg_buff* buff)
426 {
427         struct iovec  iov;
428         struct msghdr msg;
429
430         iov.iov_base = buff;
431         iov.iov_len = stream->packet_size;
432         msg.msg_name = (void*)&stream->rem_addr;
433         msg.msg_namelen = sizeof(stream->rem_addr);
434         msg.msg_iov = &iov;
435         msg.msg_iovlen = 1;
436         msg.msg_flags = 0;
437         msg.msg_control = &cmsg;
438         msg.msg_controllen = cmsg_len;
439
440         int ret = 1;
441         
442         while (sendmsg(ac_sockfd[stream->ac], &msg, 0) < 0) {
443                 if (errno == EINTR) continue;
444                 if (errno == EAGAIN) {
445                         if (opt_wait_for_queue_is_full && 
446                             !some_queue_is_full && 
447                             /* We use mutex as atomic test and set */
448                             (pthread_mutex_trylock(&queue_full_mutex) != EBUSY)) {
449                                 some_queue_is_full = true;
450                                 reset_statistics();
451                         }
452                         ret = 0;
453                         break;
454                 } else {
455                         perror("Error while sending");
456                         ret = -1;
457                         break;
458                 }
459         }
460         return ret;
461 }
462 #else
463 static inline int 
464 send_packet_fwp(struct stream* stream, union msg_buff* buff)
465 {
466         int ret;
467
468         ret = fwp_send(stream->endpoint, buff, stream->packet_size, 0);
469         
470         return ret;
471 }
472 #endif
473
474 static inline void
475 wait_for_next_send(struct stream* stream, struct timespec *last_send_time)
476 {
477         struct timespec time_to_wait, current_time, period, interval;
478         unsigned period_usec = stream->period_usec;
479
480         /*           |~~~+~~~| jitter interval (width = 2*stream->jitter percentage from period)*/
481         /* |-------------|     nominal period*/
482         if (stream->jitter) {
483                 period.tv_nsec = USEC_TO_NSEC*(period_usec*(100-stream->jitter)/100
484                                                + rand() % (2*period_usec*stream->jitter/100));
485         } else {
486                 period.tv_nsec = USEC_TO_NSEC*(period_usec);
487         }
488         period.tv_sec = 0;
489         
490         timespec_add(&time_to_wait, last_send_time, &period);
491         clock_gettime(CLOCK_REALTIME,&current_time);
492         timespec_sub(&interval,&time_to_wait,&current_time);
493         nanosleep(&interval,NULL);
494 }
495
496
497 void* sender(void* arg)
498 {
499         union msg_buff buff;
500         unsigned long int seqn;
501         struct stream* stream = (struct stream*) arg;
502         char stream_desc[100];
503         int ret;
504
505         stream_to_text(stream_desc, sizeof(stream_desc), stream, 0);
506         printf("%s\n", stream_desc);
507
508         if (stream->bandwidth_bps == 0)
509                 goto out;
510
511         seqn = 0;
512         
513         block_signals();
514         set_rt_prio(90-stream->ac);
515
516         while (!exit_flag) {
517
518 /*              buff.msg.seqn = seqn++; */
519 /*              buff.msg.tos = ac_to_tos[stream->ac]; */
520                 buff.msg.stream = stream-streams;
521                 
522                 clock_gettime(CLOCK_REALTIME,&buff.msg.send_timestamp);
523
524                 ret = send_packet(stream, &buff);
525                 if (ret < 0) {
526                         goto out;
527                 }
528
529                 pthread_mutex_lock(&stream->mutex);
530                 stream->sent++;
531                 if (ret > 0)
532                         stream->really_sent++;
533                 pthread_mutex_unlock(&stream->mutex);
534
535 #ifdef DEBUG
536                 printf("%d", stream->ac);
537                 fflush(stdout);
538 #endif
539
540                 wait_for_next_send(stream, &buff.msg.send_timestamp);
541         }
542 out:
543         sem_post(&sem_thread_finished);
544         return NULL;
545 }
546
547 #ifdef WITH_FWP
548 static int negotiate_contract_for_stream_fwp(struct stream *stream)
549 {
550         fwp_contract_t contract;
551         fwp_contract_d_t contract_d;
552         fwp_vres_d_t vres2;
553         int ret;
554
555         /* Contract for client->server stream */
556         contract.budget = stream->packet_size;
557         contract.period_usec = stream->period_usec;
558
559         contract_d = fwp_contract_create(&contract);
560         ret = fwp_contract_negotiate(contract_d, &stream->vres);
561
562         /* Contract for server->client stream */
563         contract.budget = stream->packet_size;
564         contract.period_usec = stream->period_usec;
565
566         contract_d = fwp_contract_create(&contract);
567         ret = fwp_contract_negotiate(contract_d, &vres2);
568
569         /* We don't use the vres at server, since the server doesn't
570          * know the parameters. Instread, server uses plain
571          * sockets. */
572         
573         return ret;
574 }
575 #endif
576
577 #ifdef WITH_FWP
578 static void create_stream_endpoint_fwp(struct stream *stream)
579 {
580 /*      fwp_endpoint_attr_t  attr; */
581         int ret;
582         struct hostent* ph;
583
584 /*      fwp_endpoint_attr_init(&attr); */
585 /*      fwp_endpoint_attr_setreliability(&attr, FWP_EPOINT_BESTEFFORT); */
586
587         ph = gethostbyname(server_addr);
588         if (ph && ph->h_addr_list[0]) {
589                 struct in_addr *a = (struct in_addr *)(ph->h_addr_list[0]);
590                 ret = fwp_send_endpoint_create(a->s_addr, BASE_PORT + fwp_vres_get_ac(stream->vres),
591                                                NULL, &stream->endpoint);
592                 /* stream->rem_addr.sin_port = htons(BASE_PORT + stream->ac); */
593                 if (ret < 0) {
594                         perror("fwp_send_endpoint_create");
595                         exit(1);
596                 }
597                 ret = fwp_send_endpoint_bind(stream->endpoint, stream->vres);
598                 if (ret != 0) {
599                         perror("fwp_send_endpoint_bind");
600                         exit(1);
601                 }
602
603                 
604         }
605         else {
606                 char str[100];
607                 snprintf(str, sizeof(str), "gethostbyname(%s)", server_addr);
608                 perror(str);
609                 exit(1);
610         }
611
612 }
613 #else
614 static void create_stream_endpoint_native(struct stream *stream)
615 {
616         struct hostent* ph;
617
618         memset(&stream->rem_addr,0, sizeof(stream->rem_addr));
619
620         stream->rem_addr.sin_family = AF_INET;
621         ph = gethostbyname(server_addr);
622         if (ph)
623                 stream->rem_addr.sin_addr = *((struct in_addr *)ph->h_addr);
624         else {
625                 char str[100];
626                 snprintf(str, sizeof(str), "gethostbyname(%s)", server_addr);
627                 perror(str);
628                 exit(1);
629         }
630         stream->rem_addr.sin_port = htons(BASE_PORT + stream->ac);
631 }
632 #endif
633
634 static inline void
635 calc_stream_params(struct stream *stream)
636 {
637         int packet_size;
638         unsigned period_usec;
639         int bandwidth;
640         int ret;
641
642         /* If some parameters are not set explicitely, use default values. */
643         if (stream->bandwidth_bps < 0) stream->bandwidth_bps = opt_def_bandwidth * Kbit;
644         if (stream->packet_size < 0) stream->packet_size = opt_packet_size;
645         if (stream->period_usec < 0) stream->period_usec = opt_def_period_msec * MSEC_TO_USEC;
646
647         bandwidth = stream->bandwidth_bps;
648
649         /* Avoid arithmetic exception. Server thread will exit if
650            stream->bandwidth_bps == 0. */
651         if (bandwidth == 0) bandwidth = 1;
652
653         if (stream->packet_size) {
654                 packet_size = stream->packet_size;
655                 period_usec = SEC_TO_USEC*packet_size*8/bandwidth;
656                 if (period_usec == 0) period_usec = 1;
657         } else if (stream->period_usec) {
658                 period_usec = stream->period_usec;
659                 packet_size = (long long)bandwidth/8 * period_usec/SEC_TO_USEC;
660         } else {
661                 char buf[200];
662                 stream_to_text(buf, sizeof(buf), stream, 0);
663                 fprintf(stderr, "Neither packet size nor period was specified for a stream %s\n", buf);
664                 exit(1);
665         }
666
667         if (packet_size < sizeof(struct msg_t)) {
668                 fprintf(stderr, "Packet size too small (min %d)\n", sizeof(struct msg_t));
669                 exit(1);
670         }
671
672         stream->packet_size = packet_size;
673         stream->period_usec = period_usec;
674         stream->jitter = opt_jitter;
675
676         ret = negotiate_contract_for_stream(stream);
677         if (ret == 0) {
678                 create_stream_endpoint(stream);
679         } else {
680                 char buf[200];
681                 stream_to_text(buf, sizeof(buf), stream, 0);
682                 fprintf(stderr, "Contract hasn't been accepted: %s\n", buf);
683                 stream->bandwidth_bps = 0;
684         }
685 }
686
687 /** 
688  * Parse -b parameter.
689  * 
690  * @param params String to parse
691  * 
692  * @return NULL in case of success, pointer to a problematic character
693  *         on error.
694  */
695 char* parse_bandwidths(char *params)
696 {
697         struct stream *sp = &streams[nr_streams];
698
699         while (*params && nr_streams < MAX_STREAMS) {
700                 char *ac_ids[AC_NUM] = { [AC_VO]="VO", [AC_VI]="VI", [AC_BE]="BE", [AC_BK]="BK" };
701                 int i;
702                 char *next_char;
703
704                 if (strlen(params) < 2)
705                         return params;
706                 for (i=0; i<AC_NUM; i++) {
707                         if (strncmp(params, ac_ids[i], 2) == 0) {
708                                 sp->ac = i;
709                                 params+=strlen(ac_ids[i]);
710                                 break;
711                         }
712                 }
713                 if (i==AC_NUM)
714                         return params;
715
716                 long bw;
717                 if (*params == ':') {
718                         params++;
719
720                         bw = strtol(params, &next_char, 10);
721                         if (next_char == params)
722                                 return params;
723                         params = next_char;
724                 } else
725                         bw = -1;
726                 
727                 sp->bandwidth_bps = bw*Kbit;
728
729                 long period = 0;
730                 long packet_size = 0;
731                 if (*params == '@') {
732                         params++;
733                         period = strtol(params, &next_char, 10);
734                         if (period == 0)
735                                 return params;
736                         params = next_char;
737                 }
738                 else {
739                         if (*params == '/') {
740                                 params++;
741                                 packet_size = strtol(params, &next_char, 10);
742                                 if (packet_size == 0)
743                                         return params;
744                                 params = next_char;
745                         } else {
746                                 packet_size = -1; 
747                                 period = -1;
748                         }
749                 }
750                 sp->period_usec = period*MSEC_TO_USEC;
751                 sp->packet_size = packet_size;
752
753                 
754
755                 if (*params != '\0' && *params != ',')
756                         return params;
757                 nr_streams++;
758                 sp++;
759                 if (*params == ',')
760                         params++;
761         }
762         return NULL;
763 }
764
765 int main(int argc, char *argv[])
766 {
767         int ac, i, rc, seconds;
768         pthread_attr_t attr;
769         pthread_t thread;
770         char opt;
771
772
773         while ((opt = getopt(argc, argv, "B:b:C:c:g:I:j:o:qQ:s:T:")) != -1) {
774                 switch (opt) {
775                         case 'B':
776                                 opt_def_bandwidth = atoi(optarg);
777                                 break;
778                         case 'b': {
779                                 char *error;
780                                 error = parse_bandwidths(optarg);
781                                 if (error != NULL) {
782                                         if (*error == '\0')
783                                                 fprintf(stderr, "Bandwidth parse error - string to short\n");
784                                         else
785                                                 fprintf(stderr, "Bandwidth parse error at '%s'\n", error);
786                                         exit(1);
787                                 }
788                                 break;
789                         }
790                         case 'C':
791                                 opt_comment = optarg;
792                                 break;
793                         case 'c':
794                                 opt_count_sec = atoi(optarg);
795                                 break;
796                         case 'g':
797                                 opt_granularity_usec = atoi(optarg);
798                                 if (opt_granularity_usec < MIN_GRANULARITY) {
799                                         fprintf(stderr, "Granulatiry too small (min %d)!\n", MIN_GRANULARITY);
800                                         exit(1);
801                                 }
802                                 break;
803                         case 'I':
804                                 opt_interface = optarg;
805                                 break;
806                         case 'j':
807                                 #ifdef WITH_FWP
808                                 fprintf(stderr, "-j is not allowd when compiled with FWP\n");
809                                 exit(1);
810                                 #else
811                                 opt_jitter = atoi(optarg);
812                                 #endif
813                                 break;
814                         case 'o':
815                                 opt_output = optarg;
816                                 break;
817                         case 'Q':
818                                 opt_send_buf_size = atoi(optarg);
819                                 break;
820                         case 'q':
821                                 opt_wait_for_queue_is_full = true;
822                                 break;
823                         case 's':
824                                 opt_packet_size = atoi(optarg);
825                                 break;
826                         case 'T':
827                                 opt_def_period_msec = atoi(optarg);
828                                 break;
829                         default:
830                                 fprintf(stderr, "Usage: %s [ options ] server_addr\n\n", argv[0]);
831                                 fprintf(stderr, "Options:\n");
832                                 fprintf(stderr, "    -B  default bandwidth for -b option [kbit]\n");
833                                 fprintf(stderr, "    -b  bandwidth of streams (VO|VI|BE|BK)[:<kbit>][@<msec> or /<bytes>][,...]\n");
834                                 fprintf(stderr, "    -C  comment (added to header)\n");
835                                 fprintf(stderr, "    -c  count (number of seconds to run)\n");
836                                 fprintf(stderr, "    -g  histogram granularity [usec]\n");
837                                 fprintf(stderr, "    -I  <interface> send packets from this interface");
838                                 fprintf(stderr, "    -j  send jitter (0-100) [%%]\n");
839                                 fprintf(stderr, "    -o  output filename (.dat will be appended)\n");
840                                 fprintf(stderr, "    -q  gather statistics only after some queue becomes full\n");
841                                 fprintf(stderr, "    -Q  <bytes> set size for socket send buffers\n");
842                                 fprintf(stderr, "    -s  size of data payload in packets [bytes] (default: %d)\n", opt_packet_size);
843                                 fprintf(stderr, "    -T  default period for -b option [msec]\n");
844                                 exit(1);
845                 }
846         }
847         if (opt_packet_size && opt_def_period_msec) {
848                 fprintf(stderr, "Error: Nonzero -T and -s can't be used together!.\n");
849                 exit(1);
850         }
851
852         if (optind < argc) {
853                 server_addr = argv[optind];
854         } else {
855                 fprintf(stderr, "Expected server address argument\n");
856                 exit(1);
857         }
858
859         if (nr_streams == 0)
860                 parse_bandwidths("BE");
861                 
862         pthread_attr_init(&attr);
863
864         snprintf(logfname, sizeof(logfname), "%s.dat", opt_output);
865
866         if ((logfd = fopen(logfname,"w+")) == NULL) {
867                 fprintf(stderr,"Can not open %s\n", logfname);
868                 exit(1);
869         }
870         if (signal(SIGTERM, stopper) == SIG_ERR) {
871                 perror("Error in signal registration");
872                 exit(1);
873         }
874                 
875         if (signal(SIGINT, stopper) == SIG_ERR) {
876                 perror("Signal handler registration error");
877                 exit(1);
878         }
879
880         struct sigaction sa;
881         sa.sa_handler = empty_handler;
882         sa.sa_flags = 0;        /* don't restart syscalls */
883
884         if (sigaction(SIGUSR1, &sa, NULL) < 0) {
885                 perror("sigaction error");
886                 exit(1);
887         }
888
889         sem_init(&sem_thread_finished, 0, 0);
890
891         reset_statistics();
892
893 #ifdef WITH_FWP
894         rc = fwp_init();
895         if (rc != 0) {
896                 fprintf(stderr, "FWP initialization failed\n");
897                 exit(1);
898         }
899 #endif
900
901         /* create four receivers each per AC */
902         for (ac = AC_NUM - 1; ac >= 0; ac--) {
903                 ac_sockfd[ac] = create_ac_socket(ac);
904                 if (ac_sockfd[ac] < 0) {
905                         return 1;
906                 }
907                 rc = pthread_create(&receivers[ac].thread, &attr, receiver, (void*) ac);
908                 if (rc) {
909                         fprintf(stderr, "Error while creating receiver %d\n",rc);
910                         return 1;
911                 }
912         }               
913                         
914         if (opt_interface) {
915                 struct ifreq ifr;
916
917                 memset(&ifr, 0, sizeof(ifr));
918                 strncpy(ifr.ifr_name, opt_interface, IFNAMSIZ-1);
919                 if (ioctl(ac_sockfd[AC_VO], SIOCGIFINDEX, &ifr) < 0) {
920                         fprintf(stderr, "unknown iface %s\n", opt_interface);
921                         exit(1);
922                 }
923                 cmsg.ipi.ipi_ifindex = ifr.ifr_ifindex;
924                 cmsg_len = sizeof(cmsg);
925         }
926         /* create sendpoints */
927         for (i = 0; i < nr_streams; i++) {
928                 struct stream *s = &streams[i];
929                 pthread_mutex_init(&s->mutex, NULL);
930                 calc_stream_params(s);
931                 rc = pthread_create(&thread, &attr, sender, (void*) s);
932                 if (rc) {
933                         fprintf(stderr, "Error while creating sender %d\n",rc);
934                         return 1;
935                 }
936         }
937         
938         seconds = 0;
939         while (!exit_flag) {
940                 sleep(1);
941                 seconds++;
942                 fprintf(stderr, "\r%3ds", seconds);
943                 for (ac = 0; ac < AC_NUM; ac++) {
944                         int delta = receivers[ac].received - receivers[ac].last_received;
945                         receivers[ac].last_received = receivers[ac].received;
946                         fprintf(stderr, " %s %5d %4d/s", ac_to_text[ac], receivers[ac].received, delta);
947                 }
948                 fflush(stderr);
949                 if (seconds == opt_count_sec)
950                         stopper();
951         }
952
953         fprintf(stderr, "\nWaiting for threads to finish\n");
954         /* Wait for all threads to finish */
955         for (i=0; i < nr_streams + AC_NUM; i++) {
956                 sem_wait(&sem_thread_finished);
957         }
958         struct timespec end_timestamp, measure_length;
959         clock_gettime(CLOCK_REALTIME,&end_timestamp);
960         timespec_sub(&measure_length, &end_timestamp, &reset_timestamp);
961
962         save_results(argc, argv, timespec2usec(&measure_length));
963
964         return 0;
965 }