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