]> rtime.felk.cvut.cz Git - frescor/fwp.git/blob - wme_test/wclient.c
wme_test: Added missing declaration when compiled without FWP
[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 struct timespec reset_timestamp;
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         for (i = 0; i < nr_streams; i++) {
352                 pthread_mutex_lock(&streams[i].mutex);
353                 streams[i].sent = 0;
354                 streams[i].really_sent = 0;
355                 streams[i].received = 0;
356                 pthread_mutex_unlock(&streams[i].mutex);
357         }
358         pthread_mutex_lock(&delay_stats_mutex);
359         clock_gettime(CLOCK_REALTIME, &reset_timestamp);
360         memset(delay_stats, 0, sizeof(delay_stats));
361         pthread_mutex_unlock(&delay_stats_mutex);
362 }
363
364 #ifndef WITH_FWP
365 int recv_packet_native(unsigned ac, struct msg_t *msg)
366 {
367         int     mlen, ret;
368         fd_set fdset;
369         struct  sockaddr_in rem_addr;
370         unsigned int rem_addr_length; 
371
372         FD_ZERO(&fdset);
373         FD_SET(ac_sockfd[ac], &fdset);
374         rem_addr_length = sizeof(rem_addr);
375         mlen = -1;
376         while (!exit_flag) {
377                 ret = select(ac_sockfd[ac]+1, &fdset, NULL, NULL, NULL);
378                 if (ret < 0) {
379                         if (errno == EINTR) continue;
380                         error(0, errno, "receiver select");
381                         return -1;
382                 }
383                 mlen = recvfrom(ac_sockfd[ac], msg, sizeof(*msg), 0,
384                                 (struct sockaddr*)&rem_addr, &rem_addr_length);
385                 break;
386         }
387         return mlen;
388 }
389 #else
390 int recv_packet_fwp(struct stream *stream, struct msg_t *msg)
391 {
392         int     mlen;
393         mlen = fwp_recv(stream->resp_endpoint, msg, sizeof(*msg), 0);
394         return mlen;
395 }
396 #endif
397
398 void* receiver(void* arg)
399 {
400         struct msg_t    msg;
401         long long int trans_time_usec, client_to_server_usec, server_to_client_usec;
402         long long int min_trans_time;
403         struct timespec send_timestamp, server_timestamp, recv_timestamp;
404         int     mlen, ret;
405         unsigned ac;
406         
407         min_trans_time = ~0;
408         
409         block_signals();
410         set_rt_prio(99);
411
412         while (!exit_flag) {
413 #ifdef WITH_FWP
414                 struct stream *stream = arg;
415                 ac = stream->ac;
416                 mlen = recv_packet_fwp(stream, &msg);
417 #else
418                 ac = (unsigned)arg;
419                 mlen = recv_packet_native(ac, &msg);
420 #endif
421                 if (mlen < 0) {
422                         error(0, errno, "receive_packet error");
423                         goto out;
424                 }       
425                 clock_gettime(CLOCK_REALTIME,&recv_timestamp);
426                 send_timestamp = msg.send_timestamp;
427                 server_timestamp = msg.sendback_timestamp;
428
429                 /* Check whether this message was sent after reset_statistics() */
430
431                 if ((ret = timespec_sub_usec(&send_timestamp, &reset_timestamp)) < 0) {
432                         continue; /* If so, don't count it */
433                 }
434
435                 trans_time_usec = timespec_sub_usec(&recv_timestamp ,&send_timestamp) / 2;
436                 client_to_server_usec = timespec_sub_usec(&server_timestamp, &send_timestamp);
437                 server_to_client_usec = timespec_sub_usec(&recv_timestamp, &server_timestamp);
438
439                 pthread_mutex_lock(&delay_stats_mutex);
440                 if (trans_time_usec < MAX_DELAY_US && trans_time_usec >= 0) {
441                         delay_stats[ac][trans_time_usec/opt_granularity_usec].csc++;
442                 }
443                 if (client_to_server_usec < MAX_DELAY_US && client_to_server_usec >= 0) {
444                         delay_stats[ac][client_to_server_usec/opt_granularity_usec].cs++;
445                 }
446                 if (server_to_client_usec < MAX_DELAY_US && server_to_client_usec >= 0) {
447                         delay_stats[ac][server_to_client_usec/opt_granularity_usec].sc++;
448                 }
449                 pthread_mutex_unlock(&delay_stats_mutex);
450
451 #ifdef WITH_FWP
452                 if (trans_time_usec > stream->wc_delay) {
453                         stream->wc_delay = trans_time_usec;
454                 }
455 #endif
456                 receivers[ac].received++;
457                 
458                 pthread_mutex_lock(&streams[msg.stream].mutex);
459                 streams[msg.stream].received++;
460                 pthread_mutex_unlock(&streams[msg.stream].mutex);
461         
462                 /*if (trans_time_nsec < min_trans_time) 
463                         min_trans_time = trans_time_nsec;*/
464                 /*printf("seqn= %lu tos= %d start= %lu(s).%lu(ns)"\
465                          "stop= %lu(s).%lu(ns)\n trans_time = %lums\n",\
466                          msg.seqn, msg.tos, send_timestamp.tv_sec,\
467                          send_timestamp.tv_nsec,recv_timestamp.tv_sec,\
468                          recv_timestamp.tv_nsec, trans_time_msec); */
469         }
470 out:
471         sem_post(&sem_thread_finished);
472         return NULL;
473 }
474
475 /** 
476  * Send a packet.
477  * 
478  * @return -1 in case of error, 1 in case of sucessfull send and 0
479  *         when all buffers are full.
480  */
481 #ifndef WITH_FWP
482 static inline int 
483 send_packet_native(struct stream* stream, union msg_buff* buff)
484 {
485         struct iovec  iov;
486         struct msghdr msg;
487
488         iov.iov_base = buff;
489         iov.iov_len = stream->packet_size;
490         msg.msg_name = (void*)&stream->rem_addr;
491         msg.msg_namelen = sizeof(stream->rem_addr);
492         msg.msg_iov = &iov;
493         msg.msg_iovlen = 1;
494         msg.msg_flags = 0;
495         msg.msg_control = &cmsg;
496         msg.msg_controllen = cmsg_len;
497
498         int ret = 1;
499         
500         while (sendmsg(ac_sockfd[stream->ac], &msg, 0) < 0) {
501                 if (errno == EINTR) continue;
502                 if (errno == EAGAIN) {
503                         if (opt_wait_for_queue_is_full && 
504                             !some_queue_is_full && 
505                             /* We use mutex as atomic test and set */
506                             (pthread_mutex_trylock(&queue_full_mutex) != EBUSY)) {
507                                 some_queue_is_full = true;
508                                 reset_statistics();
509                         }
510                         ret = 0;
511                         break;
512                 } else {
513                         error(0, errno, "Error while sending");
514                         ret = -1;
515                         break;
516                 }
517         }
518         return ret;
519 }
520 #else
521 static inline int 
522 send_packet_fwp(struct stream* stream, union msg_buff* buff)
523 {
524         int ret;
525
526         buff->msg.resp_port = htons(stream->resp_port);
527         ret = fwp_send(stream->endpoint, buff, stream->packet_size, 0);
528         
529         return ret;
530 }
531 #endif
532
533 static inline void
534 wait_for_next_send(struct stream* stream, struct timespec *last_send_time)
535 {
536         struct timespec time_to_wait, current_time, period, interval;
537         unsigned period_usec = stream->period_usec;
538
539         /*           |~~~+~~~| jitter interval (width = 2*stream->jitter percentage from period)*/
540         /* |-------------|     nominal period*/
541         if (stream->jitter) {
542                 period.tv_nsec = USEC_TO_NSEC*(period_usec*(100-stream->jitter)/100
543                                                + rand() % (2*period_usec*stream->jitter/100));
544         } else {
545                 period.tv_nsec = USEC_TO_NSEC*(period_usec);
546         }
547         period.tv_sec = 0;
548         
549         timespec_add(&time_to_wait, last_send_time, &period);
550         clock_gettime(CLOCK_REALTIME,&current_time);
551         timespec_sub(&interval,&time_to_wait,&current_time);
552         nanosleep(&interval,NULL);
553 }
554
555
556 void* sender(void* arg)
557 {
558         union msg_buff buff;
559         unsigned long int seqn;
560         struct stream* stream = (struct stream*) arg;
561         int ret;
562
563 #ifndef WITH_FWP
564         char stream_desc[100];
565         stream_to_text(stream_desc, sizeof(stream_desc), stream, 0);
566         printf("%s\n", stream_desc);
567 #endif
568         if (stream->bandwidth_bps == 0)
569                 goto out;
570
571         seqn = 0;
572         
573         block_signals();
574         set_rt_prio(90-stream->ac);
575
576         while (!exit_flag) {
577
578 /*              buff.msg.seqn = seqn++; */
579 /*              buff.msg.tos = ac_to_tos[stream->ac]; */
580                 buff.msg.stream = stream-streams;
581                 
582                 clock_gettime(CLOCK_REALTIME,&buff.msg.send_timestamp);
583
584                 ret = send_packet(stream, &buff);
585                 if (ret < 0) {
586                         goto out;
587                 }
588
589                 pthread_mutex_lock(&stream->mutex);
590                 stream->sent++;
591                 if (ret > 0)
592                         stream->really_sent++;
593                 pthread_mutex_unlock(&stream->mutex);
594
595 #ifdef DEBUG
596                 printf("%d", stream->ac);
597                 fflush(stdout);
598 #endif
599
600                 wait_for_next_send(stream, &buff.msg.send_timestamp);
601         }
602 out:
603         sem_post(&sem_thread_finished);
604         return NULL;
605 }
606
607 #ifdef WITH_FWP
608 static int negotiate_contract_for_stream_fwp(struct stream *stream)
609 {
610         fwp_contract_t contract;
611         fwp_vres_d_t vres2;
612         int ret;
613
614         /* Contract for client->server stream */
615         memset(&contract, 0, sizeof(contract));
616         contract.budget = stream->packet_size;
617         contract.period_usec = stream->period_usec;
618         contract.deadline_usec = 3*stream->period_usec;
619         
620         stream->contract_send = fwp_contract_create(&contract);
621         ret = fwp_contract_negotiate(stream->contract_send, &stream->vres);
622         if (ret != 0) {
623                 stream->contract_send = NULL;
624 /*              fprintf(stderr, "Send contract was not accepted\n\n\n"); */
625                 return ret;
626         }
627
628         /* Contract for server->client stream */
629         memset(&contract, 0, sizeof(contract));
630         contract.budget = stream->packet_size;
631         contract.period_usec = stream->period_usec;
632         contract.deadline_usec = 3*stream->period_usec;
633
634         stream->contract_resp = fwp_contract_create(&contract);
635         ret = fwp_contract_negotiate(stream->contract_resp, &vres2);
636         if (ret != 0) {
637                 stream->contract_resp = NULL;
638 /*              fprintf(stderr, "Receive contract was not accepted\n\n\n"); */
639                 return ret;
640         }
641
642         /* We don't use the vres at server, since the server doesn't
643          * know the parameters. Instread, server uses plain
644          * sockets. */
645         
646         return ret;
647 }
648 #endif
649
650 #ifdef WITH_FWP
651 static void create_stream_endpoint_fwp(struct stream *stream)
652 {
653 /*      fwp_endpoint_attr_t  attr; */
654         int ret;
655         struct hostent* ph;
656
657         stream->ac = fwp_vres_get_ac(stream->vres);
658
659 /*      fwp_endpoint_attr_init(&attr); */
660 /*      fwp_endpoint_attr_setreliability(&attr, FWP_EPOINT_BESTEFFORT); */
661
662         ph = gethostbyname(server_addr);
663         if (ph && ph->h_addr_list[0]) {
664                 struct in_addr *a = (struct in_addr *)(ph->h_addr_list[0]);
665                 ret = fwp_send_endpoint_create(a->s_addr, BASE_PORT + stream->ac,
666                                                NULL, &stream->endpoint);
667                 /* stream->rem_addr.sin_port = htons(BASE_PORT + stream->ac); */
668                 if (ret < 0) error(1, errno, "fwp_send_endpoint_create");
669                 
670                 ret = fwp_send_endpoint_bind(stream->endpoint, stream->vres);
671                 if (ret != 0) error(1, errno, "fwp_send_endpoint_bind");
672                 
673                 ret = fwp_receive_endpoint_create(0, NULL, &stream->resp_endpoint);
674                 if (ret != 0) error(1, errno, "fwp_receive_endpoint_create");
675                 
676                 unsigned int port;
677                 fwp_endpoint_get_params(stream->resp_endpoint, NULL, &port, NULL);
678                 stream->resp_port = port;
679
680                 ret = pthread_create(&stream->receiver.thread, NULL, receiver, (void*)stream);
681                 if (ret) error(1, ret, "Error while creating receiver");
682                 
683                 stream->receiver.valid = true;
684         }
685         else {
686                 error(1, errno, "gethostbyname(%s)", server_addr);
687         }
688
689 }
690 #else
691 static void create_stream_endpoint_native(struct stream *stream)
692 {
693         struct hostent* ph;
694
695         memset(&stream->rem_addr,0, sizeof(stream->rem_addr));
696
697         stream->rem_addr.sin_family = AF_INET;
698         ph = gethostbyname(server_addr);
699         if (ph)
700                 stream->rem_addr.sin_addr = *((struct in_addr *)ph->h_addr);
701         else {
702                 error(1, errno, "gethostbyname(%s)", server_addr);
703         }
704         stream->rem_addr.sin_port = htons(BASE_PORT + stream->ac);
705 }
706 #endif
707
708 static inline void
709 calc_stream_params(struct stream *stream)
710 {
711         int packet_size;
712         unsigned period_usec;
713         int bandwidth;
714         int ret;
715
716         /* If some parameters are not set explicitely, use default values. */
717         if (stream->bandwidth_bps < 0) stream->bandwidth_bps = opt_def_bandwidth * Kbit;
718         if (stream->packet_size < 0) stream->packet_size = opt_packet_size;
719         if (stream->period_usec < 0) stream->period_usec = opt_def_period_msec * MSEC_TO_USEC;
720
721         bandwidth = stream->bandwidth_bps;
722
723         /* Avoid arithmetic exception. Server thread will exit if
724            stream->bandwidth_bps == 0. */
725         if (bandwidth == 0) bandwidth = 1;
726
727         if (stream->packet_size) {
728                 packet_size = stream->packet_size;
729                 period_usec = SEC_TO_USEC*packet_size*8/bandwidth;
730                 if (period_usec == 0) period_usec = 1;
731         } else if (stream->period_usec) {
732                 period_usec = stream->period_usec;
733                 packet_size = (long long)bandwidth/8 * period_usec/SEC_TO_USEC;
734         } else {
735                 char buf[200];
736                 stream_to_text(buf, sizeof(buf), stream, 0);
737                 error(1, 0, "Neither packet size nor period was specified for a stream %s", buf);
738         }
739
740         if (packet_size < sizeof(struct msg_t)) {
741                 error(1, 0, "Packet size too small (min %d)", sizeof(struct msg_t));
742         }
743
744         stream->packet_size = packet_size;
745         stream->period_usec = period_usec;
746         stream->jitter = opt_jitter;
747
748         ret = negotiate_contract_for_stream(stream);
749         if (ret == 0) {
750                 create_stream_endpoint(stream);
751         } else {
752                 char buf[200];
753                 stream_to_text(buf, sizeof(buf), stream, 0);
754                 fprintf(stderr, "Contract hasn't been accepted:\n%s\n", buf);
755                 stream->bandwidth_bps = 0;
756                 some_contract_not_accepted = true;
757         }
758 }
759
760 /** 
761  * Parse -b parameter.
762  * 
763  * @param params String to parse
764  * 
765  * @return NULL in case of success, pointer to a problematic character
766  *         on error.
767  */
768 char* parse_bandwidths(char *params)
769 {
770         struct stream *sp = &streams[nr_streams];
771
772         while (*params && nr_streams < MAX_STREAMS) {
773                 char *ac_ids[AC_NUM] = { [AC_VO]="VO", [AC_VI]="VI", [AC_BE]="BE", [AC_BK]="BK" };
774                 int i;
775                 char *next_char;
776
777                 if (strlen(params) < 2)
778                         return params;
779                 for (i=0; i<AC_NUM; i++) {
780                         if (strncmp(params, ac_ids[i], 2) == 0) {
781                                 sp->ac = i;
782                                 params+=strlen(ac_ids[i]);
783                                 break;
784                         }
785                 }
786                 if (i==AC_NUM)
787                         return params;
788
789                 long bw;
790                 if (*params == ':') {
791                         params++;
792
793                         bw = strtol(params, &next_char, 10);
794                         if (next_char == params)
795                                 return params;
796                         params = next_char;
797                 } else
798                         bw = -1;
799                 
800                 sp->bandwidth_bps = bw*Kbit;
801
802                 long period = 0;
803                 long packet_size = 0;
804                 if (*params == '@') {
805                         params++;
806                         period = strtol(params, &next_char, 10);
807                         if (period == 0)
808                                 return params;
809                         params = next_char;
810                 }
811                 else {
812                         if (*params == '/') {
813                                 params++;
814                                 packet_size = strtol(params, &next_char, 10);
815                                 if (packet_size == 0)
816                                         return params;
817                                 params = next_char;
818                         } else {
819                                 packet_size = -1; 
820                                 period = -1;
821                         }
822                 }
823                 sp->period_usec = period*MSEC_TO_USEC;
824                 sp->packet_size = packet_size;
825
826                 
827
828                 if (*params != '\0' && *params != ',')
829                         return params;
830                 nr_streams++;
831                 sp++;
832                 if (*params == ',')
833                         params++;
834         }
835         return NULL;
836 }
837
838 #ifdef WITH_FWP
839 void wait_for_all_threads_to_finish_fwp(void)
840 {
841         int i;
842         /* Wait for all threads to finish */
843         /* FIXME: */
844 /*      for (i=0; i < 2*nr_streams; i++) { */
845 /*              sem_wait(&sem_thread_finished); */
846 /*      } */
847 }
848 #else
849 void wait_for_all_threads_to_finish_native(void)
850 {
851         int i;
852         /* Wait for all threads to finish */
853         for (i=0; i < nr_streams + AC_NUM; i++) {
854                 sem_wait(&sem_thread_finished);
855         }
856 }
857 #endif
858
859 #ifdef WITH_FWP
860 void init_gui()
861 {
862         initscr();
863         cbreak();
864         noecho();
865 }
866
867 #define addfield(title, format, ...)                                    \
868         move(y, x);                                                     \
869         x+=strlen(title)+1;                                             \
870         if (i == 0) addstr(title);                                      \
871         else {                                                          \
872                 snprintf(str, sizeof(str), format, __VA_ARGS__);        \
873                 addstr(str);                                            \
874         }
875
876 void print_status(int seconds)
877 {
878         int i;
879         char str[200], s1[20];
880         int x = 0, y;
881         struct stream *s = NULL;
882         
883         for (i = 0; i <= nr_streams; i++) {
884                 if (i>0) s = &streams[i-1];
885                 y=i;
886                 x=0;
887                 addfield("Stream", "%d", i);
888                 addfield("Bandwidth", "%s", bandwidth_to_text(s1, s->bandwidth_bps));
889                 addfield("Packet size", "%d bytes", s->packet_size);
890                 addfield("Period   ", "%s", usec_to_text(s1, s->period_usec));
891                 addfield("AC   ", "%s", ac_to_text[s->ac]);
892                 addfield("Worst-case delay", "%s", usec_to_text(s1, s->wc_delay));
893                 addfield("Received responses", "%lld", s->received);
894         }
895         refresh();
896 }
897 #else
898 void init_gui() {}
899 void print_status(int seconds)
900 {
901         int ac;
902         fprintf(stderr, "\r%3ds", seconds);
903         for (ac = 0; ac < AC_NUM; ac++) {
904                 int delta = receivers[ac].received - receivers[ac].last_received;
905                 receivers[ac].last_received = receivers[ac].received;
906                 fprintf(stderr, " %s %5d %4d/s", ac_to_text[ac], receivers[ac].received, delta);
907         }
908         fflush(stderr);
909 }
910 #endif
911
912 int main(int argc, char *argv[])
913 {
914         int i, rc, frames, seconds;
915         pthread_attr_t attr;
916         pthread_t thread;
917         char opt;
918
919
920         while ((opt = getopt(argc, argv, "B:b:C:c:g:I:j:o:qQ:s:T:")) != -1) {
921                 switch (opt) {
922                         case 'B':
923                                 opt_def_bandwidth = atoi(optarg);
924                                 break;
925                         case 'b': {
926                                 char *errpos;
927                                 errpos = parse_bandwidths(optarg);
928                                 if (errpos != NULL) {
929                                         if (*errpos == '\0')
930                                                 error(1, 0, "Bandwidth parse error - string to short");
931                                         else
932                                                 error(1, 0, "Bandwidth parse error at '%s'", errpos);
933                                 }
934                                 break;
935                         }
936                         case 'C':
937                                 opt_comment = optarg;
938                                 break;
939                         case 'c':
940                                 opt_count_sec = atoi(optarg);
941                                 break;
942                         case 'g':
943                                 opt_granularity_usec = atoi(optarg);
944                                 if (opt_granularity_usec < MIN_GRANULARITY) {
945                                         error(1, 0, "Granulatiry too small (min %d)", MIN_GRANULARITY);
946                                 }
947                                 break;
948                         case 'I':
949                                 opt_interface = optarg;
950                                 break;
951                         case 'j':
952                                 #ifdef WITH_FWP
953                                 error(1, 0, "-j is not allowd when compiled with FWP");
954                                 #else
955                                 opt_jitter = atoi(optarg);
956                                 #endif
957                                 break;
958                         case 'o':
959                                 opt_output = optarg;
960                                 break;
961                         case 'Q':
962                                 opt_send_buf_size = atoi(optarg);
963                                 break;
964                         case 'q':
965                                 opt_wait_for_queue_is_full = true;
966                                 break;
967                         case 's':
968                                 opt_packet_size = atoi(optarg);
969                                 break;
970                         case 'T':
971                                 opt_def_period_msec = atoi(optarg);
972                                 break;
973                         default:
974                                 fprintf(stderr, "Usage: %s [ options ] server_addr\n\n", argv[0]);
975                                 fprintf(stderr, "Options:\n");
976                                 fprintf(stderr, "    -B  default bandwidth for -b option [kbit]\n");
977                                 fprintf(stderr, "    -b  bandwidth of streams (VO|VI|BE|BK)[:<kbit>][@<msec> or /<bytes>][,...]\n");
978                                 fprintf(stderr, "    -C  comment (added to header)\n");
979                                 fprintf(stderr, "    -c  count (number of seconds to run)\n");
980                                 fprintf(stderr, "    -g  histogram granularity [usec]\n");
981                                 fprintf(stderr, "    -I  <interface> send packets from this interface");
982                                 fprintf(stderr, "    -j  send jitter (0-100) [%%]\n");
983                                 fprintf(stderr, "    -o  output filename (.dat will be appended)\n");
984                                 fprintf(stderr, "    -q  gather statistics only after some queue becomes full\n");
985                                 fprintf(stderr, "    -Q  <bytes> set size for socket send buffers\n");
986                                 fprintf(stderr, "    -s  size of data payload in packets [bytes] (default: %d)\n", opt_packet_size);
987                                 fprintf(stderr, "    -T  default period for -b option [msec]\n");
988                                 exit(1);
989                 }
990         }
991         if (opt_packet_size && opt_def_period_msec) {
992                 error(1, 0, "Error: Nonzero -T and -s can't be used together!");
993         }
994
995         if (optind < argc) {
996                 server_addr = argv[optind];
997         } else {
998                 error(1, 0, "Expected server address argument");
999         }
1000
1001         if (nr_streams == 0)
1002                 parse_bandwidths("BE");
1003                 
1004         pthread_attr_init(&attr);
1005
1006         snprintf(logfname, sizeof(logfname), "%s.dat", opt_output);
1007
1008         if ((logfd = fopen(logfname,"w+")) == NULL) {
1009                 error(1, errno ,"Can not open %s", logfname);
1010         }
1011         if (signal(SIGTERM, stopper) == SIG_ERR) {
1012                 error(1, errno, "Error in signal registration");
1013         }
1014                 
1015         if (signal(SIGINT, stopper) == SIG_ERR) {
1016                 error(1, errno, "Signal handler registration error");
1017         }
1018
1019         struct sigaction sa;
1020         sa.sa_handler = empty_handler;
1021         sa.sa_flags = 0;        /* don't restart syscalls */
1022
1023         if (sigaction(SIGUSR1, &sa, NULL) < 0) {
1024                 error(1, errno, "sigaction error");
1025         }
1026
1027         sem_init(&sem_thread_finished, 0, 0);
1028
1029         reset_statistics();
1030
1031 #ifdef WITH_FWP
1032         rc = fwp_init();
1033         if (rc != 0) {
1034                 error(1, errno, "FWP initialization failed");
1035         }
1036 #else
1037         int ac;
1038         /* create four receivers each per AC */
1039         for (ac = AC_NUM - 1; ac >= 0; ac--) {
1040                 ac_sockfd[ac] = create_ac_socket(ac);
1041                 if (ac_sockfd[ac] < 0) {
1042                         return 1;
1043                 }
1044                 rc = pthread_create(&receivers[ac].thread, &attr, receiver, (void*) ac);
1045                 if (rc) {
1046                         error(1, rc, "Error while creating receiver");
1047                 }
1048                 receivers[ac].valid = true;
1049         }               
1050 #endif
1051
1052                         
1053         if (opt_interface) {
1054                 struct ifreq ifr;
1055
1056                 memset(&ifr, 0, sizeof(ifr));
1057                 strncpy(ifr.ifr_name, opt_interface, IFNAMSIZ-1);
1058                 if (ioctl(ac_sockfd[AC_VO], SIOCGIFINDEX, &ifr) < 0) {
1059                         error(1, 0, "unknown iface %s", opt_interface);
1060                 }
1061                 cmsg.ipi.ipi_ifindex = ifr.ifr_ifindex;
1062                 cmsg_len = sizeof(cmsg);
1063         }
1064         /* create sendpoints */
1065         for (i = 0; i < nr_streams; i++) {
1066                 struct stream *s = &streams[i];
1067                 pthread_mutex_init(&s->mutex, NULL);
1068                 calc_stream_params(s);
1069                 rc = pthread_create(&thread, &attr, sender, (void*) s);
1070                 if (rc) error(1, rc, "Error while creating sender");
1071         }
1072
1073         if (some_contract_not_accepted) {
1074                 stopper();
1075         } else {
1076                 //init_gui();
1077
1078                 seconds = 1;
1079                 frames=0;
1080                 while (!exit_flag) {
1081                         usleep(40000);
1082                         frames++;
1083                         if (frames>=25) {
1084                                 seconds++;
1085                                 frames = 0;
1086                         }
1087                         print_status(seconds);
1088                         if (seconds == opt_count_sec)
1089                                 stopper();
1090                 }
1091         }
1092
1093 #ifdef WITH_FWP
1094         //endwin();
1095         fwp_done();
1096 #else
1097         fprintf(stderr, "\nWaiting for threads to finish\n");
1098         wait_for_all_threads_to_finish();
1099
1100         struct timespec end_timestamp, measure_length;
1101         clock_gettime(CLOCK_REALTIME,&end_timestamp);
1102         timespec_sub(&measure_length, &end_timestamp, &reset_timestamp);
1103
1104         save_results(argc, argv, timespec2usec(&measure_length));
1105 #endif
1106
1107         return 0;
1108 }