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