]> rtime.felk.cvut.cz Git - sojka/can-utils.git/blob - cangen.c
can-utils: AOSP build clean up
[sojka/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, "         -R            (send RTR frame)\n");
88         fprintf(stderr, "         -m            (mix -e -f -R frames)\n");
89         fprintf(stderr, "         -I <mode>     (CAN ID"
90                 " generation mode - see below)\n");
91         fprintf(stderr, "         -L <mode>     (CAN data length code (dlc)"
92                 " generation mode - see below)\n");
93         fprintf(stderr, "         -D <mode>     (CAN data (payload)"
94                 " generation mode - see below)\n");
95         fprintf(stderr, "         -p <timeout>  (poll on -ENOBUFS to write frames"
96                 " with <timeout> ms)\n");
97         fprintf(stderr, "         -n <count>    (terminate after <count> CAN frames "
98                 "- default infinite)\n");
99         fprintf(stderr, "         -i            (ignore -ENOBUFS return values on"
100                 " write() syscalls)\n");
101         fprintf(stderr, "         -x            (disable local loopback of "
102                 "generated CAN frames)\n");
103         fprintf(stderr, "         -v            (increment verbose level for "
104                 "printing sent CAN frames)\n\n");
105         fprintf(stderr, "Generation modes:\n");
106         fprintf(stderr, "'r'        => random values (default)\n");
107         fprintf(stderr, "'i'        => increment values\n");
108         fprintf(stderr, "<hexvalue> => fix value using <hexvalue>\n\n");
109         fprintf(stderr, "When incrementing the CAN data the data length code "
110                 "minimum is set to 1.\n");
111         fprintf(stderr, "CAN IDs and data content are given and expected in hexadecimal values.\n\n");
112         fprintf(stderr, "Examples:\n");
113         fprintf(stderr, "%s vcan0 -g 4 -I 42A -L 1 -D i -v -v   ", prg);
114         fprintf(stderr, "(fixed CAN ID and length, inc. data)\n");
115         fprintf(stderr, "%s vcan0 -e -L i -v -v -v              ", prg);
116         fprintf(stderr, "(generate EFF frames, incr. length)\n");
117         fprintf(stderr, "%s vcan0 -D 11223344DEADBEEF -L 8      ", prg);
118         fprintf(stderr, "(fixed CAN data payload and length)\n");
119         fprintf(stderr, "%s vcan0 -g 0 -i -x                    ", prg);
120         fprintf(stderr, "(full load test ignoring -ENOBUFS)\n");
121         fprintf(stderr, "%s vcan0 -g 0 -p 10 -x                 ", prg);
122         fprintf(stderr, "(full load test with polling, 10ms timeout)\n");
123         fprintf(stderr, "%s vcan0                               ", prg);
124         fprintf(stderr, "(my favourite default :)\n\n");
125 }
126
127 void sigterm(int signo)
128 {
129         running = 0;
130 }
131
132 int main(int argc, char **argv)
133 {
134         double gap = DEFAULT_GAP;
135         unsigned long polltimeout = 0;
136         unsigned char ignore_enobufs = 0;
137         unsigned char extended = 0;
138         unsigned char canfd = 0;
139         unsigned char mix = 0;
140         unsigned char id_mode = MODE_RANDOM;
141         unsigned char data_mode = MODE_RANDOM;
142         unsigned char dlc_mode = MODE_RANDOM;
143         unsigned char loopback_disable = 0;
144         unsigned char verbose = 0;
145         unsigned char rtr_frame = 0;
146         int count = 0;
147         int mtu, maxdlen;
148         uint64_t incdata = 0;
149         int incdlc = 0;
150         unsigned char fixdata[CANFD_MAX_DLEN];
151
152         int opt;
153         int s; /* socket */
154         struct pollfd fds;
155
156         struct sockaddr_can addr;
157         static struct canfd_frame frame;
158         int nbytes;
159         int i;
160         struct ifreq ifr;
161
162         struct timespec ts;
163         struct timeval now;
164
165         /* set seed value for pseudo random numbers */
166         gettimeofday(&now, NULL);
167         srandom(now.tv_usec);
168
169         signal(SIGTERM, sigterm);
170         signal(SIGHUP, sigterm);
171         signal(SIGINT, sigterm);
172
173         while ((opt = getopt(argc, argv, "ig:efmI:L:D:xp:n:vRh?")) != -1) {
174                 switch (opt) {
175
176                 case 'i':
177                         ignore_enobufs = 1;
178                         break;
179
180                 case 'g':
181                         gap = strtod(optarg, NULL);
182                         break;
183
184                 case 'e':
185                         extended = 1;
186                         break;
187
188                 case 'f':
189                         canfd = 1;
190                         break;
191
192                 case 'm':
193                         mix = 1;
194                         canfd = 1; /* to switch the socket into CAN FD mode */
195                         break;
196
197                 case 'I':
198                         if (optarg[0] == 'r') {
199                                 id_mode = MODE_RANDOM;
200                         } else if (optarg[0] == 'i') {
201                                 id_mode = MODE_INCREMENT;
202                         } else {
203                                 id_mode = MODE_FIX;
204                                 frame.can_id = strtoul(optarg, NULL, 16);
205                         }
206                         break;
207
208                 case 'L':
209                         if (optarg[0] == 'r') {
210                                 dlc_mode = MODE_RANDOM;
211                         } else if (optarg[0] == 'i') {
212                                 dlc_mode = MODE_INCREMENT;
213                         } else {
214                                 dlc_mode = MODE_FIX;
215                                 frame.len = atoi(optarg) & 0xFF; /* is cut to 8 / 64 later */
216                         }
217                         break;
218
219                 case 'D':
220                         if (optarg[0] == 'r') {
221                                 data_mode = MODE_RANDOM;
222                         } else if (optarg[0] == 'i') {
223                                 data_mode = MODE_INCREMENT;
224                         } else {
225                                 data_mode = MODE_FIX;
226                                 if (hexstring2data(optarg, fixdata, CANFD_MAX_DLEN)) {
227                                         printf ("wrong fix data definition\n");
228                                         return 1;
229                                 }
230                         }
231                         break;
232
233                 case 'v':
234                         verbose++;
235                         break;
236
237                 case 'x':
238                         loopback_disable = 1;
239                         break;
240
241                 case 'R':
242                         rtr_frame = 1;
243                         break;
244
245                 case 'p':
246                         polltimeout = strtoul(optarg, NULL, 10);
247                         break;
248
249                 case 'n':
250                         count = atoi(optarg);
251                         if (count < 1) {
252                                 print_usage(basename(argv[0]));
253                                 return 1;
254                         }
255                         break;
256
257                 case '?':
258                 case 'h':
259                 default:
260                         print_usage(basename(argv[0]));
261                         return 1;
262                         break;
263                 }
264         }
265
266         if (optind == argc) {
267                 print_usage(basename(argv[0]));
268                 return 1;
269         }
270
271         ts.tv_sec = gap / 1000;
272         ts.tv_nsec = (long)(((long long)(gap * 1000000)) % 1000000000ll);
273
274         /* recognize obviously missing commandline option */
275         if (id_mode == MODE_FIX && frame.can_id > 0x7FF && !extended) {
276                 printf("The given CAN-ID is greater than 0x7FF and "
277                        "the '-e' option is not set.\n");
278                 return 1;
279         }
280
281         if (strlen(argv[optind]) >= IFNAMSIZ) {
282                 printf("Name of CAN device '%s' is too long!\n\n", argv[optind]);
283                 return 1;
284         }
285
286         if ((s = socket(PF_CAN, SOCK_RAW, CAN_RAW)) < 0) {
287                 perror("socket");
288                 return 1;
289         }
290
291         addr.can_family = AF_CAN;
292
293         strcpy(ifr.ifr_name, argv[optind]);
294         if (ioctl(s, SIOCGIFINDEX, &ifr) < 0) {
295                 perror("SIOCGIFINDEX");
296                 return 1;
297         }
298         addr.can_ifindex = ifr.ifr_ifindex;
299
300         /* disable default receive filter on this RAW socket */
301         /* This is obsolete as we do not read from the socket at all, but for */
302         /* this reason we can remove the receive list in the Kernel to save a */
303         /* little (really a very little!) CPU usage.                          */
304         setsockopt(s, SOL_CAN_RAW, CAN_RAW_FILTER, NULL, 0);
305
306         if (loopback_disable) {
307                 int loopback = 0;
308
309                 setsockopt(s, SOL_CAN_RAW, CAN_RAW_LOOPBACK,
310                            &loopback, sizeof(loopback));
311         }
312
313         if (canfd) {
314                 int enable_canfd = 1;
315
316                 /* check if the frame fits into the CAN netdevice */
317                 if (ioctl(s, SIOCGIFMTU, &ifr) < 0) {
318                         perror("SIOCGIFMTU");
319                         return 1;
320                 }
321
322                 if (ifr.ifr_mtu != CANFD_MTU) {
323                         printf("CAN interface ist not CAN FD capable - sorry.\n");
324                         return 1;
325                 }
326
327                 /* interface is ok - try to switch the socket into CAN FD mode */
328                 if (setsockopt(s, SOL_CAN_RAW, CAN_RAW_FD_FRAMES, &enable_canfd, sizeof(enable_canfd))){
329                         printf("error when enabling CAN FD support\n");
330                         return 1;
331                 }
332
333                 /* ensure discrete CAN FD length values 0..8, 12, 16, 20, 24, 32, 64 */
334                 frame.len = can_dlc2len(can_len2dlc(frame.len));
335         } else {
336                 /* sanitize CAN 2.0 frame length */
337                 if (frame.len > 8)
338                         frame.len = 8;
339         }
340
341         if (bind(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
342                 perror("bind");
343                 return 1;
344         }
345
346         if (polltimeout) {
347                 fds.fd = s;
348                 fds.events = POLLOUT;
349         }
350
351         while (running) {
352
353                 if (count && (--count == 0))
354                         running = 0;
355
356                 if (canfd){
357                         mtu = CANFD_MTU;
358                         maxdlen = CANFD_MAX_DLEN;
359                 } else {
360                         mtu = CAN_MTU;
361                         maxdlen = CAN_MAX_DLEN;
362                 }
363
364                 if (id_mode == MODE_RANDOM)
365                         frame.can_id = random();
366
367                 if (extended) {
368                         frame.can_id &= CAN_EFF_MASK;
369                         frame.can_id |= CAN_EFF_FLAG;
370                 } else
371                         frame.can_id &= CAN_SFF_MASK;
372
373                 if (rtr_frame && !canfd)
374                         frame.can_id |= CAN_RTR_FLAG;
375
376                 if (dlc_mode == MODE_RANDOM) {
377
378                         if (canfd)
379                                 frame.len = can_dlc2len(random() & 0xF);
380                         else {
381                                 frame.len = random() & 0xF;
382                                 if (frame.len & 8)
383                                         frame.len = 8; /* for about 50% of the frames */
384                         }
385                 }
386
387                 if (data_mode == MODE_INCREMENT && !frame.len)
388                         frame.len = 1; /* min dlc value for incr. data */
389
390                 if (data_mode == MODE_RANDOM) {
391
392                         /* that's what the 64 bit alignment of data[] is for ... :) */
393                         *(unsigned long*)(&frame.data[0]) = random();
394                         *(unsigned long*)(&frame.data[4]) = random();
395
396                         /* omit extra random number generation for CAN FD */
397                         if (canfd && frame.len > 8) {
398                                 memcpy(&frame.data[8], &frame.data[0], 8);
399                                 memcpy(&frame.data[16], &frame.data[0], 16);
400                                 memcpy(&frame.data[32], &frame.data[0], 32);
401                         }
402                 }
403
404                 if (data_mode == MODE_FIX)
405                         memcpy(frame.data, fixdata, CANFD_MAX_DLEN);
406
407                 /* set unused payload data to zero like the CAN driver does it on rx */
408                 if (frame.len < maxdlen)
409                         memset(&frame.data[frame.len], 0, maxdlen - frame.len);
410
411                 if (verbose) {
412
413                         printf("  %s  ", argv[optind]);
414
415                         if (verbose > 1)
416                                 fprint_long_canframe(stdout, &frame, "\n", (verbose > 2)?1:0, maxdlen);
417                         else
418                                 fprint_canframe(stdout, &frame, "\n", 1, maxdlen);
419                 }
420
421 resend:
422                 nbytes = write(s, &frame, mtu);
423                 if (nbytes < 0) {
424                         if (errno != ENOBUFS) {
425                                 perror("write");
426                                 return 1;
427                         }
428                         if (!ignore_enobufs && !polltimeout) {
429                                 perror("write");
430                                 return 1;
431                         }
432                         if (polltimeout) {
433                                 /* wait for the write socket (with timeout) */
434                                 if (poll(&fds, 1, polltimeout) < 0) {
435                                         perror("poll");
436                                         return 1;
437                                 } else
438                                         goto resend;
439                         } else
440                                 enobufs_count++;
441
442                 } else if (nbytes < mtu) {
443                         fprintf(stderr, "write: incomplete CAN frame\n");
444                         return 1;
445                 }
446
447                 if (gap) /* gap == 0 => performance test :-] */
448                         if (nanosleep(&ts, NULL))
449                                 return 1;
450                     
451                 if (id_mode == MODE_INCREMENT)
452                         frame.can_id++;
453
454                 if (dlc_mode == MODE_INCREMENT) {
455
456                         incdlc++;
457
458                         if (canfd && !mix) {
459                                 incdlc &= 0xF;
460                                 frame.len = can_dlc2len(incdlc);
461                         } else {
462                                 incdlc %= 9;
463                                 frame.len = incdlc;
464                         }
465                 }
466
467                 if (data_mode == MODE_INCREMENT) {
468
469                         incdata++;
470
471                         for (i=0; i<8 ;i++)
472                                 frame.data[i] = (incdata >> i*8) & 0xFFULL;
473                 }
474
475                 if (mix) {
476                         i = random();
477                         extended = i&1;
478                         canfd = i&2;
479                         rtr_frame = ((i&12) == 12); /* reduce RTR frames to 1/4 */
480                 }
481         }
482
483         if (enobufs_count)
484                 printf("\nCounted %llu ENOBUFS return values on write().\n\n",
485                        enobufs_count);
486
487         close(s);
488
489         return 0;
490 }