]> rtime.felk.cvut.cz Git - sojka/can-utils.git/blob - can-calc-bit-timing.c
Fix datatype issue in sscanf() on 64bit systems.
[sojka/can-utils.git] / can-calc-bit-timing.c
1 /* can-calc-bit-timing.c: Calculate CAN bit timing parameters
2  *
3  * Copyright (C) 2008 Wolfgang Grandegger <wg@grandegger.com>
4  *
5  * Derived from:
6  *   can_baud.c - CAN baudrate calculation
7  *   Code based on LinCAN sources and H8S2638 project
8  *   Copyright 2004-2006 Pavel Pisa - DCE FELK CVUT cz
9  *   Copyright 2005      Stanislav Marek
10  *   email:pisa@cmp.felk.cvut.cz
11  *
12  *   This software is released under the GPL-License.
13  */
14
15 #include <errno.h>
16 #include <getopt.h>
17 #include <stdint.h>
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21
22 #include <linux/types.h>
23
24 /* seems not to be defined in errno.h */
25 #ifndef ENOTSUPP
26 #define ENOTSUPP        524     /* Operation is not supported */
27 #endif
28
29 /* usefull defines */
30 #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0]))
31
32 #define do_div(a,b) a = (a) / (b)
33
34 #define abs(x) ({                               \
35                 long __x = (x);                 \
36                 (__x < 0) ? -__x : __x;         \
37         })
38
39 /**
40  * clamp - return a value clamped to a given range with strict typechecking
41  * @val: current value
42  * @min: minimum allowable value
43  * @max: maximum allowable value
44  *
45  * This macro does strict typechecking of min/max to make sure they are of the
46  * same type as val.  See the unnecessary pointer comparisons.
47  */
48 #define clamp(val, min, max) ({                 \
49         typeof(val) __val = (val);              \
50         typeof(min) __min = (min);              \
51         typeof(max) __max = (max);              \
52         (void) (&__val == &__min);              \
53         (void) (&__val == &__max);              \
54         __val = __val < __min ? __min: __val;   \
55         __val > __max ? __max: __val; })
56
57 /* we don't want to see these prints */
58 #define dev_err(dev, format, arg...)    do { } while (0)
59 #define dev_warn(dev, format, arg...)   do { } while (0)
60
61 /* define in-kernel-types */
62 typedef __u64 u64;
63 typedef __u32 u32;
64
65
66 /*
67  * CAN bit-timing parameters
68  *
69  * For futher information, please read chapter "8 BIT TIMING
70  * REQUIREMENTS" of the "Bosch CAN Specification version 2.0"
71  * at http://www.semiconductors.bosch.de/pdf/can2spec.pdf.
72  */
73 struct can_bittiming {
74         __u32 bitrate;          /* Bit-rate in bits/second */
75         __u32 sample_point;     /* Sample point in one-tenth of a percent */
76         __u32 tq;               /* Time quanta (TQ) in nanoseconds */
77         __u32 prop_seg;         /* Propagation segment in TQs */
78         __u32 phase_seg1;       /* Phase buffer segment 1 in TQs */
79         __u32 phase_seg2;       /* Phase buffer segment 2 in TQs */
80         __u32 sjw;              /* Synchronisation jump width in TQs */
81         __u32 brp;              /* Bit-rate prescaler */
82 };
83
84 /*
85  * CAN harware-dependent bit-timing constant
86  *
87  * Used for calculating and checking bit-timing parameters
88  */
89 struct can_bittiming_const {
90         char name[16];          /* Name of the CAN controller hardware */
91         __u32 tseg1_min;        /* Time segement 1 = prop_seg + phase_seg1 */
92         __u32 tseg1_max;
93         __u32 tseg2_min;        /* Time segement 2 = phase_seg2 */
94         __u32 tseg2_max;
95         __u32 sjw_max;          /* Synchronisation jump width */
96         __u32 brp_min;          /* Bit-rate prescaler */
97         __u32 brp_max;
98         __u32 brp_inc;
99
100         /* added for can-calc-bit-timing utility */
101         __u32 ref_clk;          /* CAN system clock frequency in Hz */
102         void (*printf_btr)(struct can_bittiming *bt, int hdr);
103 };
104
105 /*
106  * CAN clock parameters
107  */
108 struct can_clock {
109         __u32 freq;             /* CAN system clock frequency in Hz */
110 };
111
112
113 /*
114  * minimal structs, just enough to be source level compatible
115  */
116 struct can_priv {
117         const struct can_bittiming_const *bittiming_const;
118         struct can_clock clock;
119 };
120
121 struct net_device {
122         struct can_priv priv;
123 };
124
125 static inline void *netdev_priv(const struct net_device *dev)
126 {
127         return (void *)&dev->priv;
128 }
129
130 static void print_usage(char* cmd)
131 {
132         printf("Usage: %s [options] [<CAN-contoller-name>]\n"
133                "\tOptions:\n"
134                "\t-q           : don't print header line\n"
135                "\t-l           : list all support CAN controller names\n"
136                "\t-b <bitrate> : bit-rate in bits/sec\n"
137                "\t-s <samp_pt> : sample-point in one-tenth of a percent\n"
138                "\t               or 0 for CIA recommended sample points\n"
139                "\t-c <clock>   : real CAN system clock in Hz\n",
140                cmd);
141
142         exit(EXIT_FAILURE);
143 }
144
145 static void printf_btr_sja1000(struct can_bittiming *bt, int hdr)
146 {
147         uint8_t btr0, btr1;
148
149         if (hdr) {
150                 printf("BTR0 BTR1");
151         } else {
152                 btr0 = ((bt->brp - 1) & 0x3f) | (((bt->sjw - 1) & 0x3) << 6);
153                 btr1 = ((bt->prop_seg + bt->phase_seg1 - 1) & 0xf) |
154                         (((bt->phase_seg2 - 1) & 0x7) << 4);
155                 printf("0x%02x 0x%02x", btr0, btr1);
156         }
157 }
158
159 static void printf_btr_at91(struct can_bittiming *bt, int hdr)
160 {
161         if (hdr) {
162                 printf("%10s", "CAN_BR");
163         } else {
164                 uint32_t br = ((bt->phase_seg2 - 1) |
165                                ((bt->phase_seg1 - 1) << 4) |
166                                ((bt->prop_seg - 1) << 8) |
167                                ((bt->sjw - 1) << 12) |
168                                ((bt->brp - 1) << 16));
169                 printf("0x%08x", br);
170         }
171 }
172
173 static void printf_btr_flexcan(struct can_bittiming *bt, int hdr)
174 {
175         if (hdr) {
176                 printf("%10s", "CAN_CTRL");
177         } else {
178                 uint32_t ctrl = (((bt->brp        - 1) << 24) |
179                                  ((bt->sjw        - 1) << 22) |
180                                  ((bt->phase_seg1 - 1) << 19) |
181                                  ((bt->phase_seg2 - 1) << 16) |
182                                  ((bt->prop_seg   - 1) <<  0));
183
184                 printf("0x%08x", ctrl);
185         }
186 }
187
188 static void printf_btr_mcp251x(struct can_bittiming *bt, int hdr)
189 {
190         uint8_t cnf1, cnf2, cnf3;
191
192         if (hdr) {
193                 printf("CNF1 CNF2 CNF3");
194         } else {
195                 cnf1 = ((bt->sjw - 1) << 6) | bt->brp;
196                 cnf2 = 0x80 | ((bt->phase_seg1 - 1) << 3) | (bt->prop_seg - 1);
197                 cnf3 = bt->phase_seg2 - 1;
198                 printf("0x%02x 0x%02x 0x%02x", cnf1, cnf2, cnf3);
199         }
200 }
201
202 static struct can_bittiming_const can_calc_consts[] = {
203         {
204                 .name = "sja1000",
205                 .tseg1_min = 1,
206                 .tseg1_max = 16,
207                 .tseg2_min = 1,
208                 .tseg2_max = 8,
209                 .sjw_max = 4,
210                 .brp_min = 1,
211                 .brp_max = 64,
212                 .brp_inc = 1,
213
214                 .ref_clk = 8000000,
215                 .printf_btr = printf_btr_sja1000,
216         },
217         {
218                 .name = "mscan",
219                 .tseg1_min = 4,
220                 .tseg1_max = 16,
221                 .tseg2_min = 2,
222                 .tseg2_max = 8,
223                 .sjw_max = 4,
224                 .brp_min = 1,
225                 .brp_max = 64,
226                 .brp_inc = 1,
227
228                 .ref_clk = 32000000,
229                 .printf_btr = printf_btr_sja1000,
230         },
231         {
232                 .name = "mscan",
233                 .tseg1_min = 4,
234                 .tseg1_max = 16,
235                 .tseg2_min = 2,
236                 .tseg2_max = 8,
237                 .sjw_max = 4,
238                 .brp_min = 1,
239                 .brp_max = 64,
240                 .brp_inc = 1,
241
242                 .ref_clk = 33000000,
243                 .printf_btr = printf_btr_sja1000,
244         },
245         {
246                 .name = "mscan",
247                 .tseg1_min = 4,
248                 .tseg1_max = 16,
249                 .tseg2_min = 2,
250                 .tseg2_max = 8,
251                 .sjw_max = 4,
252                 .brp_min = 1,
253                 .brp_max = 64,
254                 .brp_inc = 1,
255
256                 .ref_clk = 33300000,
257                 .printf_btr = printf_btr_sja1000,
258         },
259         {
260                 .name = "mscan",
261                 .tseg1_min = 4,
262                 .tseg1_max = 16,
263                 .tseg2_min = 2,
264                 .tseg2_max = 8,
265                 .sjw_max = 4,
266                 .brp_min = 1,
267                 .brp_max = 64,
268                 .brp_inc = 1,
269
270                 .ref_clk = 33333333,
271                 .printf_btr = printf_btr_sja1000,
272         },
273         {
274                 .name = "at91",
275                 .tseg1_min = 4,
276                 .tseg1_max = 16,
277                 .tseg2_min = 2,
278                 .tseg2_max = 8,
279                 .sjw_max = 4,
280                 .brp_min = 2,
281                 .brp_max = 128,
282                 .brp_inc = 1,
283
284                 .ref_clk = 100000000,
285                 .printf_btr = printf_btr_at91,
286         },
287         {
288                 .name = "at91",
289                 .tseg1_min = 4,
290                 .tseg1_max = 16,
291                 .tseg2_min = 2,
292                 .tseg2_max = 8,
293                 .sjw_max = 4,
294                 .brp_min = 2,
295                 .brp_max = 128,
296                 .brp_inc = 1,
297
298                 /* real world clock as found on the ronetix PM9263 */
299                 .ref_clk = 99532800,
300                 .printf_btr = printf_btr_at91,
301         },
302         {
303                 .name = "flexcan",
304                 .tseg1_min = 4,
305                 .tseg1_max = 16,
306                 .tseg2_min = 2,
307                 .tseg2_max = 8,
308                 .sjw_max = 4,
309                 .brp_min = 1,
310                 .brp_max = 256,
311                 .brp_inc = 1,
312
313                 .ref_clk = 49875000,
314                 .printf_btr = printf_btr_flexcan,
315         },
316         {
317                 .name = "flexcan",
318                 .tseg1_min = 4,
319                 .tseg1_max = 16,
320                 .tseg2_min = 2,
321                 .tseg2_max = 8,
322                 .sjw_max = 4,
323                 .brp_min = 1,
324                 .brp_max = 256,
325                 .brp_inc = 1,
326
327                 .ref_clk = 66500000,
328                 .printf_btr = printf_btr_flexcan,
329         },
330         {
331                 .name = "mcp251x",
332                 .tseg1_min = 3,
333                 .tseg1_max = 16,
334                 .tseg2_min = 2,
335                 .tseg2_max = 8,
336                 .sjw_max = 4,
337                 .brp_min = 1,
338                 .brp_max = 64,
339                 .brp_inc = 1,
340
341                 .ref_clk = 8000000,
342                 .printf_btr = printf_btr_mcp251x,
343         },
344         {
345                 .name = "mcp251x",
346                 .tseg1_min = 3,
347                 .tseg1_max = 16,
348                 .tseg2_min = 2,
349                 .tseg2_max = 8,
350                 .sjw_max = 4,
351                 .brp_min = 1,
352                 .brp_max = 64,
353                 .brp_inc = 1,
354
355                 .ref_clk = 16000000,
356                 .printf_btr = printf_btr_mcp251x,
357         },
358 };
359
360 static long common_bitrates[] = {
361         1000000,
362         800000,
363         500000,
364         250000,
365         125000,
366         100000,
367         50000,
368         20000,
369         10000,
370 };
371
372 #define CAN_CALC_MAX_ERROR 50 /* in one-tenth of a percent */
373
374 static int can_update_spt(const struct can_bittiming_const *btc,
375                           int sampl_pt, int tseg, int *tseg1, int *tseg2)
376 {
377         *tseg2 = tseg + 1 - (sampl_pt * (tseg + 1)) / 1000;
378         if (*tseg2 < btc->tseg2_min)
379                 *tseg2 = btc->tseg2_min;
380         if (*tseg2 > btc->tseg2_max)
381                 *tseg2 = btc->tseg2_max;
382         *tseg1 = tseg - *tseg2;
383         if (*tseg1 > btc->tseg1_max) {
384                 *tseg1 = btc->tseg1_max;
385                 *tseg2 = tseg - *tseg1;
386         }
387         return 1000 * (tseg + 1 - *tseg2) / (tseg + 1);
388 }
389
390 static int can_calc_bittiming(struct net_device *dev, struct can_bittiming *bt)
391 {
392         struct can_priv *priv = netdev_priv(dev);
393         const struct can_bittiming_const *btc = priv->bittiming_const;
394         long rate, best_rate = 0;
395         long best_error = 1000000000, error = 0;
396         int best_tseg = 0, best_brp = 0, brp = 0;
397         int tsegall, tseg = 0, tseg1 = 0, tseg2 = 0;
398         int spt_error = 1000, spt = 0, sampl_pt;
399         u64 v64;
400
401         if (!priv->bittiming_const)
402                 return -ENOTSUPP;
403
404         /* Use CIA recommended sample points */
405         if (bt->sample_point) {
406                 sampl_pt = bt->sample_point;
407         } else {
408                 if (bt->bitrate > 800000)
409                         sampl_pt = 750;
410                 else if (bt->bitrate > 500000)
411                         sampl_pt = 800;
412                 else
413                         sampl_pt = 875;
414         }
415
416         /* tseg even = round down, odd = round up */
417         for (tseg = (btc->tseg1_max + btc->tseg2_max) * 2 + 1;
418              tseg >= (btc->tseg1_min + btc->tseg2_min) * 2; tseg--) {
419                 tsegall = 1 + tseg / 2;
420                 /* Compute all possible tseg choices (tseg=tseg1+tseg2) */
421                 brp = priv->clock.freq / (tsegall * bt->bitrate) + tseg % 2;
422                 /* chose brp step which is possible in system */
423                 brp = (brp / btc->brp_inc) * btc->brp_inc;
424                 if ((brp < btc->brp_min) || (brp > btc->brp_max))
425                         continue;
426                 rate = priv->clock.freq / (brp * tsegall);
427                 error = bt->bitrate - rate;
428                 /* tseg brp biterror */
429                 if (error < 0)
430                         error = -error;
431                 if (error > best_error)
432                         continue;
433                 best_error = error;
434                 if (error == 0) {
435                         spt = can_update_spt(btc, sampl_pt, tseg / 2,
436                                              &tseg1, &tseg2);
437                         error = sampl_pt - spt;
438                         if (error < 0)
439                                 error = -error;
440                         if (error > spt_error)
441                                 continue;
442                         spt_error = error;
443                 }
444                 best_tseg = tseg / 2;
445                 best_brp = brp;
446                 best_rate = rate;
447                 if (error == 0)
448                         break;
449         }
450
451         if (best_error) {
452                 /* Error in one-tenth of a percent */
453                 error = (best_error * 1000) / bt->bitrate;
454                 if (error > CAN_CALC_MAX_ERROR) {
455                         dev_err(dev->dev.parent,
456                                 "bitrate error %ld.%ld%% too high\n",
457                                 error / 10, error % 10);
458                         return -EDOM;
459                 } else {
460                         dev_warn(dev->dev.parent, "bitrate error %ld.%ld%%\n",
461                                  error / 10, error % 10);
462                 }
463         }
464
465         /* real sample point */
466         bt->sample_point = can_update_spt(btc, sampl_pt, best_tseg,
467                                           &tseg1, &tseg2);
468
469         v64 = (u64)best_brp * 1000000000UL;
470         do_div(v64, priv->clock.freq);
471         bt->tq = (u32)v64;
472         bt->prop_seg = tseg1 / 2;
473         bt->phase_seg1 = tseg1 - bt->prop_seg;
474         bt->phase_seg2 = tseg2;
475         bt->sjw = 1;
476         bt->brp = best_brp;
477
478         /* real bit-rate */
479         bt->bitrate = priv->clock.freq / (bt->brp * (tseg1 + tseg2 + 1));
480
481         return 0;
482 }
483
484 static __u32 get_cia_sample_point(__u32 bitrate)
485 {
486         __u32 sampl_pt;
487
488         if (bitrate > 800000)
489                 sampl_pt = 750;
490         else if (bitrate > 500000)
491                 sampl_pt = 800;
492         else
493                 sampl_pt = 875;
494
495         return sampl_pt;
496 }
497
498 static void print_bit_timing(const struct can_bittiming_const *btc,
499                              __u32 bitrate, __u32 sample_point, __u32 ref_clk,
500                              int quiet)
501 {
502         struct net_device dev = {
503                 .priv.bittiming_const = btc,
504                 .priv.clock.freq = ref_clk,
505         };
506         struct can_bittiming bt = {
507                 .bitrate = bitrate,
508                 .sample_point = sample_point,
509         };
510         long rate_error, spt_error;
511
512         if (!quiet) {
513                 printf("Bit timing parameters for %s with %.6f MHz ref clock\n"
514                        "nominal                                 real Bitrt   nom  real SampP\n"
515                        "Bitrate TQ[ns] PrS PhS1 PhS2 SJW BRP Bitrate Error SampP SampP Error ",
516                        btc->name,
517                        ref_clk / 1000000.0);
518
519                 btc->printf_btr(&bt, 1);
520                 printf("\n");
521         }
522
523         if (can_calc_bittiming(&dev, &bt)) {
524                 printf("%7d ***bitrate not possible***\n", bitrate);
525                 return;
526         }
527
528         /* get nominal sample point */
529         if (!sample_point)
530                 sample_point = get_cia_sample_point(bitrate);
531
532         rate_error = abs((__s32)(bitrate - bt.bitrate));
533         spt_error = abs((__s32)(sample_point - bt.sample_point));
534
535         printf("%7d "
536                "%6d %3d %4d %4d "
537                "%3d %3d "
538                "%7d %4.1f%% "
539                "%4.1f%% %4.1f%% %4.1f%% ",
540                bitrate,
541                bt.tq, bt.prop_seg, bt.phase_seg1, bt.phase_seg2,
542                bt.sjw, bt.brp,
543
544                bt.bitrate,
545                100.0 * rate_error / bitrate,
546
547                sample_point / 10.0,
548                bt.sample_point / 10.0,
549                100.0 * spt_error / sample_point);
550
551         btc->printf_btr(&bt, 0);
552         printf("\n");
553 }
554
555 static void do_list(void)
556 {
557         unsigned int i;
558
559         for (i = 0; i < ARRAY_SIZE(can_calc_consts); i++)
560                 printf("%s\n", can_calc_consts[i].name);
561 }
562
563 int main(int argc, char *argv[])
564 {
565         __u32 bitrate = 0;
566         __u32 opt_ref_clk = 0, ref_clk;
567         int sampl_pt = 0;
568         int quiet = 0;
569         int list = 0;
570         char *name = NULL;
571         unsigned int i, j;
572         int opt, found = 0;
573
574         const struct can_bittiming_const *btc = NULL;
575
576         while ((opt = getopt(argc, argv, "b:c:lps:")) != -1) {
577                 switch (opt) {
578                 case 'b':
579                         bitrate = atoi(optarg);
580                         break;
581
582                 case 'c':
583                         opt_ref_clk = atoi(optarg);
584                         break;
585
586                 case 'l':
587                         list = 1;
588                         break;
589
590                 case 'q':
591                         quiet = 1;
592                         break;
593
594                 case 's':
595                         sampl_pt = atoi(optarg);
596                         break;
597
598                 default:
599                         print_usage(argv[0]);
600                         break;
601                 }
602         }
603
604         if (argc > optind + 1)
605                 print_usage(argv[0]);
606
607         if (argc == optind + 1)
608                 name = argv[optind];
609
610         if (list) {
611                 do_list();
612                 exit(EXIT_SUCCESS);
613         }
614
615         if (sampl_pt && (sampl_pt >= 1000 || sampl_pt < 100))
616                 print_usage(argv[0]);
617
618         for (i = 0; i < ARRAY_SIZE(can_calc_consts); i++) {
619                 if (name && strcmp(can_calc_consts[i].name, name))
620                         continue;
621
622                 found = 1;
623                 btc = &can_calc_consts[i];
624
625                 if (opt_ref_clk)
626                         ref_clk = opt_ref_clk;
627                 else
628                         ref_clk = btc->ref_clk;
629
630                 if (bitrate) {
631                         print_bit_timing(btc, bitrate, sampl_pt, ref_clk, quiet);
632                 } else {
633                         for (j = 0; j < ARRAY_SIZE(common_bitrates); j++)
634                                 print_bit_timing(btc, common_bitrates[j],
635                                                  sampl_pt, ref_clk, j);
636                 }
637                 printf("\n");
638         }
639
640         if (!found) {
641                 printf("error: unknown CAN controller '%s', try one of these:\n\n", name);
642                 do_list();
643                 exit(EXIT_FAILURE);
644         }
645
646         exit(EXIT_SUCCESS);
647 }