e5b0b98a89afef1b607eba662b46a14def1b85f5
[cascardo/linux.git] / Documentation / networking / timestamping / txtimestamp.c
1 /*
2  * Copyright 2014 Google Inc.
3  * Author: willemb@google.com (Willem de Bruijn)
4  *
5  * Test software tx timestamping, including
6  *
7  * - SCHED, SND and ACK timestamps
8  * - RAW, UDP and TCP
9  * - IPv4 and IPv6
10  * - various packet sizes (to test GSO and TSO)
11  *
12  * Consult the command line arguments for help on running
13  * the various testcases.
14  *
15  * This test requires a dummy TCP server.
16  * A simple `nc6 [-u] -l -p $DESTPORT` will do
17  *
18  *
19  * This program is free software; you can redistribute it and/or modify it
20  * under the terms and conditions of the GNU General Public License,
21  * version 2, as published by the Free Software Foundation.
22  *
23  * This program is distributed in the hope it will be useful, but WITHOUT
24  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
25  * FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for
26  * more details.
27  *
28  * You should have received a copy of the GNU General Public License along with
29  * this program; if not, write to the Free Software Foundation, Inc.,
30  * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
31  */
32
33 #include <arpa/inet.h>
34 #include <asm/types.h>
35 #include <error.h>
36 #include <errno.h>
37 #include <linux/errqueue.h>
38 #include <linux/if_ether.h>
39 #include <linux/net_tstamp.h>
40 #include <netdb.h>
41 #include <net/if.h>
42 #include <netinet/in.h>
43 #include <netinet/ip.h>
44 #include <netinet/udp.h>
45 #include <netinet/tcp.h>
46 #include <netpacket/packet.h>
47 #include <poll.h>
48 #include <stdarg.h>
49 #include <stdint.h>
50 #include <stdio.h>
51 #include <stdlib.h>
52 #include <string.h>
53 #include <sys/ioctl.h>
54 #include <sys/select.h>
55 #include <sys/socket.h>
56 #include <sys/time.h>
57 #include <sys/types.h>
58 #include <time.h>
59 #include <unistd.h>
60
61 /* command line parameters */
62 static int cfg_proto = SOCK_STREAM;
63 static int cfg_ipproto = IPPROTO_TCP;
64 static int cfg_num_pkts = 4;
65 static int do_ipv4 = 1;
66 static int do_ipv6 = 1;
67 static int cfg_payload_len = 10;
68 static uint16_t dest_port = 9000;
69
70 static struct sockaddr_in daddr;
71 static struct sockaddr_in6 daddr6;
72 static struct timespec ts_prev;
73
74 static void __print_timestamp(const char *name, struct timespec *cur,
75                               uint32_t key, int payload_len)
76 {
77         if (!(cur->tv_sec | cur->tv_nsec))
78                 return;
79
80         fprintf(stderr, "  %s: %lu s %lu us (seq=%u, len=%u)",
81                         name, cur->tv_sec, cur->tv_nsec / 1000,
82                         key, payload_len);
83
84         if ((ts_prev.tv_sec | ts_prev.tv_nsec)) {
85                 int64_t cur_ms, prev_ms;
86
87                 cur_ms = (long) cur->tv_sec * 1000 * 1000;
88                 cur_ms += cur->tv_nsec / 1000;
89
90                 prev_ms = (long) ts_prev.tv_sec * 1000 * 1000;
91                 prev_ms += ts_prev.tv_nsec / 1000;
92
93                 fprintf(stderr, "  (%+ld us)", cur_ms - prev_ms);
94         }
95
96         ts_prev = *cur;
97         fprintf(stderr, "\n");
98 }
99
100 static void print_timestamp_usr(void)
101 {
102         struct timespec ts;
103         struct timeval tv;      /* avoid dependency on -lrt */
104
105         gettimeofday(&tv, NULL);
106         ts.tv_sec = tv.tv_sec;
107         ts.tv_nsec = tv.tv_usec * 1000;
108
109         __print_timestamp("  USR", &ts, 0, 0);
110 }
111
112 static void print_timestamp(struct scm_timestamping *tss, int tstype,
113                             int tskey, int payload_len)
114 {
115         const char *tsname;
116
117         switch (tstype) {
118         case SCM_TSTAMP_SCHED:
119                 tsname = "  ENQ";
120                 break;
121         case SCM_TSTAMP_SND:
122                 tsname = "  SND";
123                 break;
124         case SCM_TSTAMP_ACK:
125                 tsname = "  ACK";
126                 break;
127         default:
128                 error(1, 0, "unknown timestamp type: %u",
129                 tstype);
130         }
131         __print_timestamp(tsname, &tss->ts[0], tskey, payload_len);
132 }
133
134 static void __poll(int fd)
135 {
136         struct pollfd pollfd;
137         int ret;
138
139         memset(&pollfd, 0, sizeof(pollfd));
140         pollfd.fd = fd;
141         ret = poll(&pollfd, 1, 100);
142         if (ret != 1)
143                 error(1, errno, "poll");
144 }
145
146 static void __recv_errmsg_cmsg(struct msghdr *msg, int payload_len)
147 {
148         struct sock_extended_err *serr = NULL;
149         struct scm_timestamping *tss = NULL;
150         struct cmsghdr *cm;
151
152         for (cm = CMSG_FIRSTHDR(msg);
153              cm && cm->cmsg_len;
154              cm = CMSG_NXTHDR(msg, cm)) {
155                 if (cm->cmsg_level == SOL_SOCKET &&
156                     cm->cmsg_type == SCM_TIMESTAMPING) {
157                         tss = (void *) CMSG_DATA(cm);
158                 } else if ((cm->cmsg_level == SOL_IP &&
159                      cm->cmsg_type == IP_RECVERR) ||
160                     (cm->cmsg_level == SOL_IPV6 &&
161                      cm->cmsg_type == IPV6_RECVERR)) {
162
163                         serr = (void *) CMSG_DATA(cm);
164                         if (serr->ee_errno != ENOMSG ||
165                             serr->ee_origin != SO_EE_ORIGIN_TIMESTAMPING) {
166                                 fprintf(stderr, "unknown ip error %d %d\n",
167                                                 serr->ee_errno,
168                                                 serr->ee_origin);
169                                 serr = NULL;
170                         }
171                 } else
172                         fprintf(stderr, "unknown cmsg %d,%d\n",
173                                         cm->cmsg_level, cm->cmsg_type);
174         }
175
176         if (serr && tss)
177                 print_timestamp(tss, serr->ee_info, serr->ee_data, payload_len);
178 }
179
180 static int recv_errmsg(int fd)
181 {
182         static char ctrl[1024 /* overprovision*/];
183         static struct msghdr msg;
184         struct iovec entry;
185         static char *data;
186         int ret = 0;
187
188         data = malloc(cfg_payload_len);
189         if (!data)
190                 error(1, 0, "malloc");
191
192         memset(&msg, 0, sizeof(msg));
193         memset(&entry, 0, sizeof(entry));
194         memset(ctrl, 0, sizeof(ctrl));
195         memset(data, 0, sizeof(data));
196
197         entry.iov_base = data;
198         entry.iov_len = cfg_payload_len;
199         msg.msg_iov = &entry;
200         msg.msg_iovlen = 1;
201         msg.msg_name = NULL;
202         msg.msg_namelen = 0;
203         msg.msg_control = ctrl;
204         msg.msg_controllen = sizeof(ctrl);
205
206         ret = recvmsg(fd, &msg, MSG_ERRQUEUE);
207         if (ret == -1 && errno != EAGAIN)
208                 error(1, errno, "recvmsg");
209
210         __recv_errmsg_cmsg(&msg, ret);
211
212         free(data);
213         return ret == -1;
214 }
215
216 static void do_test(int family, unsigned int opt)
217 {
218         char *buf;
219         int fd, i, val, total_len;
220
221         if (family == IPPROTO_IPV6 && cfg_proto != SOCK_STREAM) {
222                 /* due to lack of checksum generation code */
223                 fprintf(stderr, "test: skipping datagram over IPv6\n");
224                 return;
225         }
226
227         total_len = cfg_payload_len;
228         if (cfg_proto == SOCK_RAW) {
229                 total_len += sizeof(struct udphdr);
230                 if (cfg_ipproto == IPPROTO_RAW)
231                         total_len += sizeof(struct iphdr);
232         }
233
234         buf = malloc(total_len);
235         if (!buf)
236                 error(1, 0, "malloc");
237
238         fd = socket(family, cfg_proto, cfg_ipproto);
239         if (fd < 0)
240                 error(1, errno, "socket");
241
242         if (cfg_proto == SOCK_STREAM) {
243                 val = 1;
244                 if (setsockopt(fd, IPPROTO_TCP, TCP_NODELAY,
245                                (char*) &val, sizeof(val)))
246                         error(1, 0, "setsockopt no nagle");
247
248                 if (family == PF_INET) {
249                         if (connect(fd, (void *) &daddr, sizeof(daddr)))
250                                 error(1, errno, "connect ipv4");
251                 } else {
252                         if (connect(fd, (void *) &daddr6, sizeof(daddr6)))
253                                 error(1, errno, "connect ipv6");
254                 }
255         }
256
257         opt |= SOF_TIMESTAMPING_SOFTWARE |
258                SOF_TIMESTAMPING_OPT_ID;
259         if (setsockopt(fd, SOL_SOCKET, SO_TIMESTAMPING,
260                        (char *) &opt, sizeof(opt)))
261                 error(1, 0, "setsockopt timestamping");
262
263         for (i = 0; i < cfg_num_pkts; i++) {
264                 memset(&ts_prev, 0, sizeof(ts_prev));
265                 memset(buf, 'a' + i, total_len);
266                 buf[total_len - 2] = '\n';
267                 buf[total_len - 1] = '\0';
268
269                 if (cfg_proto == SOCK_RAW) {
270                         struct udphdr *udph;
271                         int off = 0;
272
273                         if (cfg_ipproto == IPPROTO_RAW) {
274                                 struct iphdr *iph = (void *) buf;
275
276                                 memset(iph, 0, sizeof(*iph));
277                                 iph->ihl      = 5;
278                                 iph->version  = 4;
279                                 iph->ttl      = 2;
280                                 iph->daddr    = daddr.sin_addr.s_addr;
281                                 iph->protocol = IPPROTO_UDP;
282                                 /* kernel writes saddr, csum, len */
283
284                                 off = sizeof(*iph);
285                         }
286
287                         udph = (void *) buf + off;
288                         udph->source = ntohs(9000);     /* random spoof */
289                         udph->dest   = ntohs(dest_port);
290                         udph->len    = ntohs(sizeof(*udph) + cfg_payload_len);
291                         udph->check  = 0;       /* not allowed for IPv6 */
292                 }
293
294                 print_timestamp_usr();
295                 if (cfg_proto != SOCK_STREAM) {
296                         if (family == PF_INET)
297                                 val = sendto(fd, buf, total_len, 0, (void *) &daddr, sizeof(daddr));
298                         else
299                                 val = sendto(fd, buf, total_len, 0, (void *) &daddr6, sizeof(daddr6));
300                 } else {
301                         val = send(fd, buf, cfg_payload_len, 0);
302                 }
303                 if (val != total_len)
304                         error(1, errno, "send");
305
306                 /* wait for all errors to be queued, else ACKs arrive OOO */
307                 usleep(50 * 1000);
308
309                 __poll(fd);
310
311                 while (!recv_errmsg(fd)) {}
312         }
313
314         if (close(fd))
315                 error(1, errno, "close");
316
317         free(buf);
318         usleep(400 * 1000);
319 }
320
321 static void __attribute__((noreturn)) usage(const char *filepath)
322 {
323         fprintf(stderr, "\nUsage: %s [options] hostname\n"
324                         "\nwhere options are:\n"
325                         "  -4:   only IPv4\n"
326                         "  -6:   only IPv6\n"
327                         "  -h:   show this message\n"
328                         "  -l N: send N bytes at a time\n"
329                         "  -r:   use raw\n"
330                         "  -R:   use raw (IP_HDRINCL)\n"
331                         "  -p N: connect to port N\n"
332                         "  -u:   use udp\n",
333                         filepath);
334         exit(1);
335 }
336
337 static void parse_opt(int argc, char **argv)
338 {
339         int proto_count = 0;
340         char c;
341
342         while ((c = getopt(argc, argv, "46hl:p:rRu")) != -1) {
343                 switch (c) {
344                 case '4':
345                         do_ipv6 = 0;
346                         break;
347                 case '6':
348                         do_ipv4 = 0;
349                         break;
350                 case 'r':
351                         proto_count++;
352                         cfg_proto = SOCK_RAW;
353                         cfg_ipproto = IPPROTO_UDP;
354                         break;
355                 case 'R':
356                         proto_count++;
357                         cfg_proto = SOCK_RAW;
358                         cfg_ipproto = IPPROTO_RAW;
359                         break;
360                 case 'u':
361                         proto_count++;
362                         cfg_proto = SOCK_DGRAM;
363                         cfg_ipproto = IPPROTO_UDP;
364                         break;
365                 case 'l':
366                         cfg_payload_len = strtoul(optarg, NULL, 10);
367                         break;
368                 case 'p':
369                         dest_port = strtoul(optarg, NULL, 10);
370                         break;
371                 case 'h':
372                 default:
373                         usage(argv[0]);
374                 }
375         }
376
377         if (!cfg_payload_len)
378                 error(1, 0, "payload may not be nonzero");
379         if (cfg_proto != SOCK_STREAM && cfg_payload_len > 1472)
380                 error(1, 0, "udp packet might exceed expected MTU");
381         if (!do_ipv4 && !do_ipv6)
382                 error(1, 0, "pass -4 or -6, not both");
383         if (proto_count > 1)
384                 error(1, 0, "pass -r, -R or -u, not multiple");
385
386         if (optind != argc - 1)
387                 error(1, 0, "missing required hostname argument");
388 }
389
390 static void resolve_hostname(const char *hostname)
391 {
392         struct addrinfo *addrs, *cur;
393         int have_ipv4 = 0, have_ipv6 = 0;
394
395         if (getaddrinfo(hostname, NULL, NULL, &addrs))
396                 error(1, errno, "getaddrinfo");
397
398         cur = addrs;
399         while (cur && !have_ipv4 && !have_ipv6) {
400                 if (!have_ipv4 && cur->ai_family == AF_INET) {
401                         memcpy(&daddr, cur->ai_addr, sizeof(daddr));
402                         daddr.sin_port = htons(dest_port);
403                         have_ipv4 = 1;
404                 }
405                 else if (!have_ipv6 && cur->ai_family == AF_INET6) {
406                         memcpy(&daddr6, cur->ai_addr, sizeof(daddr6));
407                         daddr6.sin6_port = htons(dest_port);
408                         have_ipv6 = 1;
409                 }
410                 cur = cur->ai_next;
411         }
412         if (addrs)
413                 freeaddrinfo(addrs);
414
415         do_ipv4 &= have_ipv4;
416         do_ipv6 &= have_ipv6;
417 }
418
419 static void do_main(int family)
420 {
421         fprintf(stderr, "family:       %s\n",
422                         family == PF_INET ? "INET" : "INET6");
423
424         fprintf(stderr, "test SND\n");
425         do_test(family, SOF_TIMESTAMPING_TX_SOFTWARE);
426
427         fprintf(stderr, "test ENQ\n");
428         do_test(family, SOF_TIMESTAMPING_TX_SCHED);
429
430         fprintf(stderr, "test ENQ + SND\n");
431         do_test(family, SOF_TIMESTAMPING_TX_SCHED |
432                         SOF_TIMESTAMPING_TX_SOFTWARE);
433
434         if (cfg_proto == SOCK_STREAM) {
435                 fprintf(stderr, "\ntest ACK\n");
436                 do_test(family, SOF_TIMESTAMPING_TX_ACK);
437
438                 fprintf(stderr, "\ntest SND + ACK\n");
439                 do_test(family, SOF_TIMESTAMPING_TX_SOFTWARE |
440                                 SOF_TIMESTAMPING_TX_ACK);
441
442                 fprintf(stderr, "\ntest ENQ + SND + ACK\n");
443                 do_test(family, SOF_TIMESTAMPING_TX_SCHED |
444                                 SOF_TIMESTAMPING_TX_SOFTWARE |
445                                 SOF_TIMESTAMPING_TX_ACK);
446         }
447 }
448
449 const char *sock_names[] = { NULL, "TCP", "UDP", "RAW" };
450
451 int main(int argc, char **argv)
452 {
453         if (argc == 1)
454                 usage(argv[0]);
455
456         parse_opt(argc, argv);
457         resolve_hostname(argv[argc - 1]);
458
459         fprintf(stderr, "protocol:     %s\n", sock_names[cfg_proto]);
460         fprintf(stderr, "payload:      %u\n", cfg_payload_len);
461         fprintf(stderr, "server port:  %u\n", dest_port);
462         fprintf(stderr, "\n");
463
464         if (do_ipv4)
465                 do_main(PF_INET);
466         if (do_ipv6)
467                 do_main(PF_INET6);
468
469         return 0;
470 }