]> rtime.felk.cvut.cz Git - can-utils.git/blob - cangen.c
candump: Enable HW timestamping before using it
[can-utils.git] / cangen.c
1 /*
2  * cangen.c - CAN frames generator for testing purposes
3  *
4  * Copyright (c) 2002-2007 Volkswagen Group Electronic Research
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of Volkswagen nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * Alternatively, provided that this notice is retained in full, this
20  * software may be distributed under the terms of the GNU General
21  * Public License ("GPL") version 2, in which case the provisions of the
22  * GPL apply INSTEAD OF those given above.
23  *
24  * The provided data structures and external interfaces from this code
25  * are not restricted to be used by modules with a GPL compatible license.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
32  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
33  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
37  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
38  * DAMAGE.
39  *
40  * Send feedback to <linux-can@vger.kernel.org>
41  *
42  */
43
44 #include <stdio.h>
45 #include <stdlib.h>
46 #include <stdint.h>
47 #include <unistd.h>
48 #include <string.h>
49 #include <signal.h>
50 #include <poll.h>
51 #include <ctype.h>
52 #include <libgen.h>
53 #include <time.h>
54 #include <errno.h>
55
56 #include <sys/time.h>
57 #include <sys/types.h>
58 #include <sys/socket.h>
59 #include <sys/ioctl.h>
60 #include <sys/uio.h>
61 #include <net/if.h>
62
63 #include <linux/can.h>
64 #include <linux/can/raw.h>
65 #include "lib.h"
66
67 #define DEFAULT_GAP 200 /* ms */
68
69 #define MODE_RANDOM     0
70 #define MODE_INCREMENT  1
71 #define MODE_FIX        2
72
73 extern int optind, opterr, optopt;
74
75 static volatile int running = 1;
76 static unsigned long long enobufs_count;
77
78 void print_usage(char *prg)
79 {
80         fprintf(stderr, "\n%s: generate CAN frames\n\n", prg);
81         fprintf(stderr, "Usage: %s [options] <CAN interface>\n", prg);
82         fprintf(stderr, "Options: -g <ms>       (gap in milli seconds "
83                 "- default: %d ms)\n", DEFAULT_GAP);
84         fprintf(stderr, "         -e            (generate extended frame mode "
85                 "(EFF) CAN frames)\n");
86         fprintf(stderr, "         -f            (generate CAN FD CAN frames)\n");
87         fprintf(stderr, "         -b            (generate CAN FD CAN frames"
88                 " with bitrate switch (BRS))\n");
89         fprintf(stderr, "         -R            (send RTR frame)\n");
90         fprintf(stderr, "         -m            (mix -e -f -b -R frames)\n");
91         fprintf(stderr, "         -I <mode>     (CAN ID"
92                 " generation mode - see below)\n");
93         fprintf(stderr, "         -L <mode>     (CAN data length code (dlc)"
94                 " generation mode - see below)\n");
95         fprintf(stderr, "         -D <mode>     (CAN data (payload)"
96                 " generation mode - see below)\n");
97         fprintf(stderr, "         -p <timeout>  (poll on -ENOBUFS to write frames"
98                 " with <timeout> ms)\n");
99         fprintf(stderr, "         -n <count>    (terminate after <count> CAN frames "
100                 "- default infinite)\n");
101         fprintf(stderr, "         -i            (ignore -ENOBUFS return values on"
102                 " write() syscalls)\n");
103         fprintf(stderr, "         -x            (disable local loopback of "
104                 "generated CAN frames)\n");
105         fprintf(stderr, "         -v            (increment verbose level for "
106                 "printing sent CAN frames)\n\n");
107         fprintf(stderr, "Generation modes:\n");
108         fprintf(stderr, "'r'        => random values (default)\n");
109         fprintf(stderr, "'i'        => increment values\n");
110         fprintf(stderr, "<hexvalue> => fix value using <hexvalue>\n\n");
111         fprintf(stderr, "When incrementing the CAN data the data length code "
112                 "minimum is set to 1.\n");
113         fprintf(stderr, "CAN IDs and data content are given and expected in hexadecimal values.\n\n");
114         fprintf(stderr, "Examples:\n");
115         fprintf(stderr, "%s vcan0 -g 4 -I 42A -L 1 -D i -v -v   ", prg);
116         fprintf(stderr, "(fixed CAN ID and length, inc. data)\n");
117         fprintf(stderr, "%s vcan0 -e -L i -v -v -v              ", prg);
118         fprintf(stderr, "(generate EFF frames, incr. length)\n");
119         fprintf(stderr, "%s vcan0 -D 11223344DEADBEEF -L 8      ", prg);
120         fprintf(stderr, "(fixed CAN data payload and length)\n");
121         fprintf(stderr, "%s vcan0 -g 0 -i -x                    ", prg);
122         fprintf(stderr, "(full load test ignoring -ENOBUFS)\n");
123         fprintf(stderr, "%s vcan0 -g 0 -p 10 -x                 ", prg);
124         fprintf(stderr, "(full load test with polling, 10ms timeout)\n");
125         fprintf(stderr, "%s vcan0                               ", prg);
126         fprintf(stderr, "(my favourite default :)\n\n");
127 }
128
129 void sigterm(int signo)
130 {
131         running = 0;
132 }
133
134 int main(int argc, char **argv)
135 {
136         double gap = DEFAULT_GAP;
137         unsigned long polltimeout = 0;
138         unsigned char ignore_enobufs = 0;
139         unsigned char extended = 0;
140         unsigned char canfd = 0;
141         unsigned char brs = 0;
142         unsigned char mix = 0;
143         unsigned char id_mode = MODE_RANDOM;
144         unsigned char data_mode = MODE_RANDOM;
145         unsigned char dlc_mode = MODE_RANDOM;
146         unsigned char loopback_disable = 0;
147         unsigned char verbose = 0;
148         unsigned char rtr_frame = 0;
149         int count = 0;
150         int mtu, maxdlen;
151         uint64_t incdata = 0;
152         int incdlc = 0;
153         unsigned char fixdata[CANFD_MAX_DLEN];
154
155         int opt;
156         int s; /* socket */
157         struct pollfd fds;
158
159         struct sockaddr_can addr;
160         static struct canfd_frame frame;
161         int nbytes;
162         int i;
163         struct ifreq ifr;
164
165         struct timespec ts;
166         struct timeval now;
167
168         /* set seed value for pseudo random numbers */
169         gettimeofday(&now, NULL);
170         srandom(now.tv_usec);
171
172         signal(SIGTERM, sigterm);
173         signal(SIGHUP, sigterm);
174         signal(SIGINT, sigterm);
175
176         while ((opt = getopt(argc, argv, "ig:ebfmI:L:D:xp:n:vRh?")) != -1) {
177                 switch (opt) {
178
179                 case 'i':
180                         ignore_enobufs = 1;
181                         break;
182
183                 case 'g':
184                         gap = strtod(optarg, NULL);
185                         break;
186
187                 case 'e':
188                         extended = 1;
189                         break;
190
191                 case 'f':
192                         canfd = 1;
193                         break;
194
195                 case 'b':
196                         brs = 1; /* bitrate switch implies CAN FD */
197                         canfd = 1;
198                         break;
199
200                 case 'm':
201                         mix = 1;
202                         canfd = 1; /* to switch the socket into CAN FD mode */
203                         break;
204
205                 case 'I':
206                         if (optarg[0] == 'r') {
207                                 id_mode = MODE_RANDOM;
208                         } else if (optarg[0] == 'i') {
209                                 id_mode = MODE_INCREMENT;
210                         } else {
211                                 id_mode = MODE_FIX;
212                                 frame.can_id = strtoul(optarg, NULL, 16);
213                         }
214                         break;
215
216                 case 'L':
217                         if (optarg[0] == 'r') {
218                                 dlc_mode = MODE_RANDOM;
219                         } else if (optarg[0] == 'i') {
220                                 dlc_mode = MODE_INCREMENT;
221                         } else {
222                                 dlc_mode = MODE_FIX;
223                                 frame.len = atoi(optarg) & 0xFF; /* is cut to 8 / 64 later */
224                         }
225                         break;
226
227                 case 'D':
228                         if (optarg[0] == 'r') {
229                                 data_mode = MODE_RANDOM;
230                         } else if (optarg[0] == 'i') {
231                                 data_mode = MODE_INCREMENT;
232                         } else {
233                                 data_mode = MODE_FIX;
234                                 if (hexstring2data(optarg, fixdata, CANFD_MAX_DLEN)) {
235                                         printf ("wrong fix data definition\n");
236                                         return 1;
237                                 }
238                         }
239                         break;
240
241                 case 'v':
242                         verbose++;
243                         break;
244
245                 case 'x':
246                         loopback_disable = 1;
247                         break;
248
249                 case 'R':
250                         rtr_frame = 1;
251                         break;
252
253                 case 'p':
254                         polltimeout = strtoul(optarg, NULL, 10);
255                         break;
256
257                 case 'n':
258                         count = atoi(optarg);
259                         if (count < 1) {
260                                 print_usage(basename(argv[0]));
261                                 return 1;
262                         }
263                         break;
264
265                 case '?':
266                 case 'h':
267                 default:
268                         print_usage(basename(argv[0]));
269                         return 1;
270                         break;
271                 }
272         }
273
274         if (optind == argc) {
275                 print_usage(basename(argv[0]));
276                 return 1;
277         }
278
279         ts.tv_sec = gap / 1000;
280         ts.tv_nsec = (long)(((long long)(gap * 1000000)) % 1000000000ll);
281
282         /* recognize obviously missing commandline option */
283         if (id_mode == MODE_FIX && frame.can_id > 0x7FF && !extended) {
284                 printf("The given CAN-ID is greater than 0x7FF and "
285                        "the '-e' option is not set.\n");
286                 return 1;
287         }
288
289         if (strlen(argv[optind]) >= IFNAMSIZ) {
290                 printf("Name of CAN device '%s' is too long!\n\n", argv[optind]);
291                 return 1;
292         }
293
294         if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
295                 perror("socket");
296                 return 1;
297         }
298
299         addr.can_family = AF_CAN;
300
301         strcpy(ifr.ifr_name, argv[optind]);
302         if (ioctl(s, SIOCGIFINDEX, &ifr) < 0) {
303                 perror("SIOCGIFINDEX");
304                 return 1;
305         }
306         addr.can_ifindex = ifr.ifr_ifindex;
307
308         /* disable default receive filter on this RAW socket */
309         /* This is obsolete as we do not read from the socket at all, but for */
310         /* this reason we can remove the receive list in the Kernel to save a */
311         /* little (really a very little!) CPU usage.                          */
312         setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
313
314         if (loopback_disable) {
315                 int loopback = 0;
316
317                 setsockopt(s, SOL_CAN_RAW, CAN_RAW_LOOPBACK,
318                            &loopback, sizeof(loopback));
319         }
320
321         if (canfd) {
322                 int enable_canfd = 1;
323
324                 /* check if the frame fits into the CAN netdevice */
325                 if (ioctl(s, SIOCGIFMTU, &ifr) < 0) {
326                         perror("SIOCGIFMTU");
327                         return 1;
328                 }
329
330                 if (ifr.ifr_mtu != CANFD_MTU) {
331                         printf("CAN interface ist not CAN FD capable - sorry.\n");
332                         return 1;
333                 }
334
335                 /* interface is ok - try to switch the socket into CAN FD mode */
336                 if (setsockopt(s, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &enable_canfd, sizeof(enable_canfd))){
337                         printf("error when enabling CAN FD support\n");
338                         return 1;
339                 }
340
341                 /* ensure discrete CAN FD length values 0..8, 12, 16, 20, 24, 32, 64 */
342                 frame.len = can_dlc2len(can_len2dlc(frame.len));
343         } else {
344                 /* sanitize CAN 2.0 frame length */
345                 if (frame.len > 8)
346                         frame.len = 8;
347         }
348
349         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
350                 perror("bind");
351                 return 1;
352         }
353
354         if (polltimeout) {
355                 fds.fd = s;
356                 fds.events = POLLOUT;
357         }
358
359         while (running) {
360                 frame.flags = 0;
361
362                 if (count && (--count == 0))
363                         running = 0;
364
365                 if (canfd){
366                         mtu = CANFD_MTU;
367                         maxdlen = CANFD_MAX_DLEN;
368                         if (brs)
369                                 frame.flags |= CANFD_BRS;
370                 } else {
371                         mtu = CAN_MTU;
372                         maxdlen = CAN_MAX_DLEN;
373                 }
374
375                 if (id_mode == MODE_RANDOM)
376                         frame.can_id = random();
377
378                 if (extended) {
379                         frame.can_id &= CAN_EFF_MASK;
380                         frame.can_id |= CAN_EFF_FLAG;
381                 } else
382                         frame.can_id &= CAN_SFF_MASK;
383
384                 if (rtr_frame && !canfd)
385                         frame.can_id |= CAN_RTR_FLAG;
386
387                 if (dlc_mode == MODE_RANDOM) {
388
389                         if (canfd)
390                                 frame.len = can_dlc2len(random() & 0xF);
391                         else {
392                                 frame.len = random() & 0xF;
393                                 if (frame.len & 8)
394                                         frame.len = 8; /* for about 50% of the frames */
395                         }
396                 }
397
398                 if (data_mode == MODE_INCREMENT && !frame.len)
399                         frame.len = 1; /* min dlc value for incr. data */
400
401                 if (data_mode == MODE_RANDOM) {
402
403                         /* that's what the 64 bit alignment of data[] is for ... :) */
404                         *(unsigned long*)(&frame.data[0]) = random();
405                         *(unsigned long*)(&frame.data[4]) = random();
406
407                         /* omit extra random number generation for CAN FD */
408                         if (canfd && frame.len > 8) {
409                                 memcpy(&frame.data[8], &frame.data[0], 8);
410                                 memcpy(&frame.data[16], &frame.data[0], 16);
411                                 memcpy(&frame.data[32], &frame.data[0], 32);
412                         }
413                 }
414
415                 if (data_mode == MODE_FIX)
416                         memcpy(frame.data, fixdata, CANFD_MAX_DLEN);
417
418                 /* set unused payload data to zero like the CAN driver does it on rx */
419                 if (frame.len < maxdlen)
420                         memset(&frame.data[frame.len], 0, maxdlen - frame.len);
421
422                 if (verbose) {
423
424                         printf("  %s  ", argv[optind]);
425
426                         if (verbose > 1)
427                                 fprint_long_canframe(stdout, &frame, "\n", (verbose > 2)?1:0, maxdlen);
428                         else
429                                 fprint_canframe(stdout, &frame, "\n", 1, maxdlen);
430                 }
431
432 resend:
433                 nbytes = write(s, &frame, mtu);
434                 if (nbytes < 0) {
435                         if (errno != ENOBUFS) {
436                                 perror("write");
437                                 return 1;
438                         }
439                         if (!ignore_enobufs && !polltimeout) {
440                                 perror("write");
441                                 return 1;
442                         }
443                         if (polltimeout) {
444                                 /* wait for the write socket (with timeout) */
445                                 if (poll(&fds, 1, polltimeout) < 0) {
446                                         perror("poll");
447                                         return 1;
448                                 } else
449                                         goto resend;
450                         } else
451                                 enobufs_count++;
452
453                 } else if (nbytes < mtu) {
454                         fprintf(stderr, "write: incomplete CAN frame\n");
455                         return 1;
456                 }
457
458                 if (gap) /* gap == 0 => performance test :-] */
459                         if (nanosleep(&ts, NULL))
460                                 return 1;
461
462                 if (id_mode == MODE_INCREMENT)
463                         frame.can_id++;
464
465                 if (dlc_mode == MODE_INCREMENT) {
466
467                         incdlc++;
468
469                         if (canfd && !mix) {
470                                 incdlc &= 0xF;
471                                 frame.len = can_dlc2len(incdlc);
472                         } else {
473                                 incdlc %= 9;
474                                 frame.len = incdlc;
475                         }
476                 }
477
478                 if (data_mode == MODE_INCREMENT) {
479
480                         incdata++;
481
482                         for (i=0; i<8 ;i++)
483                                 frame.data[i] = (incdata >> i*8) & 0xFFULL;
484                 }
485
486                 if (mix) {
487                         i = random();
488                         extended = i&1;
489                         canfd = i&2;
490                         if (canfd)
491                                 brs = i&4;
492                         rtr_frame = ((i&24) == 24); /* reduce RTR frames to 1/4 */
493                 }
494         }
495
496         if (enobufs_count)
497                 printf("\nCounted %llu ENOBUFS return values on write().\n\n",
498                        enobufs_count);
499
500         close(s);
501
502         return 0;
503 }