]> rtime.felk.cvut.cz Git - socketcan-devel.git/blob - can-utils/can-calc-bit-timing.c
can-calc-bit-timing: use algorithm from the kernel
[socketcan-devel.git] / can-utils / 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         void (*printf_btr)(struct can_bittiming *bt, int hdr);
102 };
103
104 /*
105  * CAN clock parameters
106  */
107 struct can_clock {
108         __u32 freq;             /* CAN system clock frequency in Hz */
109 };
110
111
112 /*
113  * minimal structs, just enough to be source level compatible
114  */
115 struct can_priv {
116         const struct can_bittiming_const *bittiming_const;
117         struct can_clock clock;
118 };
119
120 struct net_device {
121         struct can_priv priv;
122 };
123
124 static inline void *netdev_priv(const struct net_device *dev)
125 {
126         return (void *)&dev->priv;
127 }
128
129 static void print_usage(char* cmd)
130 {
131         printf("Usage: %s [options] [<CAN-contoller-name>]\n"
132                "\tOptions:\n"
133                "\t-q           : don't print header line\n"
134                "\t-l           : list all support CAN controller names\n"
135                "\t-b <bitrate> : bit-rate in bits/sec\n"
136                "\t-s <samp_pt> : sample-point in one-tenth of a percent\n"
137                "\t               or 0 for CIA recommended sample points\n"
138                "\t-c <clock>   : real CAN system clock in Hz\n",
139                cmd);
140
141         exit(1);
142 }
143
144 static void printf_btr_sja1000(struct can_bittiming *bt, int hdr)
145 {
146         uint8_t btr0, btr1;
147
148         if (hdr) {
149                 printf("BTR0 BTR1");
150         } else {
151                 btr0 = ((bt->brp - 1) & 0x3f) | (((bt->sjw - 1) & 0x3) << 6);
152                 btr1 = ((bt->prop_seg + bt->phase_seg1 - 1) & 0xf) |
153                         (((bt->phase_seg2 - 1) & 0x7) << 4);
154                 printf("0x%02x 0x%02x", btr0, btr1);
155         }
156 }
157
158 static void printf_btr_at91(struct can_bittiming *bt, int hdr)
159 {
160         if (hdr) {
161                 printf("CAN_BR");
162         } else {
163                 uint32_t br = ((bt->phase_seg2 - 1) |
164                                ((bt->phase_seg1 - 1) << 4) |
165                                ((bt->prop_seg - 1) << 8) |
166                                ((bt->sjw - 1) << 12) |
167                                ((bt->brp - 1) << 16));
168                 printf("0x%08x", br);
169         }
170 }
171
172 static void printf_btr_mcp251x(struct can_bittiming *bt, int hdr)
173 {
174         uint8_t cnf1, cnf2, cnf3;
175
176         if (hdr) {
177                 printf("CNF1 CNF2 CNF3");
178         } else {
179                 cnf1 = ((bt->sjw - 1) << 6) | bt->brp;
180                 cnf2 = 0x80 | ((bt->phase_seg1 - 1) << 3) | (bt->prop_seg - 1);
181                 cnf3 = bt->phase_seg2 - 1;
182                 printf("0x%02x 0x%02x 0x%02x", cnf1, cnf2, cnf3);
183         }
184 }
185
186 static void printf_btr_rtcantl1(struct can_bittiming *bt, int hdr)
187 {
188         uint16_t bcr0, bcr1;
189
190         if (hdr) {
191                 printf("__BCR0 __BCR1");
192         } else {
193                 bcr1 = ((((bt->prop_seg + bt->phase_seg1 - 1) & 0x0F) << 12) |
194                         (((bt->phase_seg2 - 1) & 0x07) << 8) |
195                         (((bt->sjw - 1) & 0x03) << 4));
196                 bcr0 =  ((bt->brp - 1) & 0xFF);
197                 printf("0x%04x 0x%04x", bcr0, bcr1);
198         }
199 }
200
201 static struct can_bittiming_const can_calc_consts[] = {
202         {
203                 .name = "sja1000",
204                 .tseg1_min = 1,
205                 .tseg1_max = 16,
206                 .tseg2_min = 1,
207                 .tseg2_max = 8,
208                 .sjw_max = 4,
209                 .brp_min = 1,
210                 .brp_max = 64,
211                 .brp_inc = 1,
212
213                 .printf_btr = printf_btr_sja1000,
214         },
215         {
216                 .name = "mscan",
217                 .tseg1_min = 4,
218                 .tseg1_max = 16,
219                 .tseg2_min = 2,
220                 .tseg2_max = 8,
221                 .sjw_max = 4,
222                 .brp_min = 1,
223                 .brp_max = 64,
224                 .brp_inc = 1,
225
226                 .printf_btr = printf_btr_sja1000,
227         },
228         {
229                 .name = "at91",
230                 .tseg1_min = 4,
231                 .tseg1_max = 16,
232                 .tseg2_min = 2,
233                 .tseg2_max = 8,
234                 .sjw_max = 4,
235                 .brp_min = 2,
236                 .brp_max = 128,
237                 .brp_inc = 1,
238
239                 .printf_btr = printf_btr_at91,
240         },
241         {
242                 .name = "mcp251x",
243                 .tseg1_min = 3,
244                 .tseg1_max = 16,
245                 .tseg2_min = 2,
246                 .tseg2_max = 8,
247                 .sjw_max = 4,
248                 .brp_min = 1,
249                 .brp_max = 64,
250                 .brp_inc = 1,
251
252                 .printf_btr = printf_btr_mcp251x,
253         },
254         {
255                 .name = "rtcantl1",
256                 .tseg1_min = 4,
257                 .tseg1_max = 16,
258                 .tseg2_min = 2,
259                 .tseg2_max = 8,
260                 .sjw_max = 4,
261                 .brp_min = 1,
262                 .brp_max = 256,
263                 .brp_inc = 1,
264
265                 .printf_btr = printf_btr_rtcantl1,
266         },
267 };
268
269 static long common_bitrates[] = {
270         1000000,
271         800000,
272         500000,
273         250000,
274         125000,
275         100000,
276         50000,
277         20000,
278         10000,
279 };
280
281 #define CAN_CALC_MAX_ERROR 50 /* in one-tenth of a percent */
282
283 static int can_update_spt(const struct can_bittiming_const *btc,
284                           int sampl_pt, int tseg, int *tseg1, int *tseg2)
285 {
286         *tseg2 = tseg + 1 - (sampl_pt * (tseg + 1)) / 1000;
287         if (*tseg2 < btc->tseg2_min)
288                 *tseg2 = btc->tseg2_min;
289         if (*tseg2 > btc->tseg2_max)
290                 *tseg2 = btc->tseg2_max;
291         *tseg1 = tseg - *tseg2;
292         if (*tseg1 > btc->tseg1_max) {
293                 *tseg1 = btc->tseg1_max;
294                 *tseg2 = tseg - *tseg1;
295         }
296         return 1000 * (tseg + 1 - *tseg2) / (tseg + 1);
297 }
298
299 static int can_calc_bittiming(struct net_device *dev, struct can_bittiming *bt)
300 {
301         struct can_priv *priv = netdev_priv(dev);
302         const struct can_bittiming_const *btc = priv->bittiming_const;
303         long rate, best_rate = 0;
304         long best_error = 1000000000, error = 0;
305         int best_tseg = 0, best_brp = 0, brp = 0;
306         int tsegall, tseg = 0, tseg1 = 0, tseg2 = 0;
307         int spt_error = 1000, spt = 0, sampl_pt;
308         u64 v64;
309
310         if (!priv->bittiming_const)
311                 return -ENOTSUPP;
312
313         /* Use CIA recommended sample points */
314         if (bt->sample_point) {
315                 sampl_pt = bt->sample_point;
316         } else {
317                 if (bt->bitrate > 800000)
318                         sampl_pt = 750;
319                 else if (bt->bitrate > 500000)
320                         sampl_pt = 800;
321                 else
322                         sampl_pt = 875;
323         }
324
325         /* tseg even = round down, odd = round up */
326         for (tseg = (btc->tseg1_max + btc->tseg2_max) * 2 + 1;
327              tseg >= (btc->tseg1_min + btc->tseg2_min) * 2; tseg--) {
328                 tsegall = 1 + tseg / 2;
329                 /* Compute all possible tseg choices (tseg=tseg1+tseg2) */
330                 brp = priv->clock.freq / (tsegall * bt->bitrate) + tseg % 2;
331                 /* chose brp step which is possible in system */
332                 brp = (brp / btc->brp_inc) * btc->brp_inc;
333                 if ((brp < btc->brp_min) || (brp > btc->brp_max))
334                         continue;
335                 rate = priv->clock.freq / (brp * tsegall);
336                 error = bt->bitrate - rate;
337                 /* tseg brp biterror */
338                 if (error < 0)
339                         error = -error;
340                 if (error > best_error)
341                         continue;
342                 best_error = error;
343                 if (error == 0) {
344                         spt = can_update_spt(btc, sampl_pt, tseg / 2,
345                                              &tseg1, &tseg2);
346                         error = sampl_pt - spt;
347                         if (error < 0)
348                                 error = -error;
349                         if (error > spt_error)
350                                 continue;
351                         spt_error = error;
352                 }
353                 best_tseg = tseg / 2;
354                 best_brp = brp;
355                 best_rate = rate;
356                 if (error == 0)
357                         break;
358         }
359
360         if (best_error) {
361                 /* Error in one-tenth of a percent */
362                 error = (best_error * 1000) / bt->bitrate;
363                 if (error > CAN_CALC_MAX_ERROR) {
364                         dev_err(dev->dev.parent,
365                                 "bitrate error %ld.%ld%% too high\n",
366                                 error / 10, error % 10);
367                         return -EDOM;
368                 } else {
369                         dev_warn(dev->dev.parent, "bitrate error %ld.%ld%%\n",
370                                  error / 10, error % 10);
371                 }
372         }
373
374         /* real sample point */
375         bt->sample_point = can_update_spt(btc, sampl_pt, best_tseg,
376                                           &tseg1, &tseg2);
377
378         v64 = (u64)best_brp * 1000000000UL;
379         do_div(v64, priv->clock.freq);
380         bt->tq = (u32)v64;
381         bt->prop_seg = tseg1 / 2;
382         bt->phase_seg1 = tseg1 - bt->prop_seg;
383         bt->phase_seg2 = tseg2;
384         bt->sjw = 1;
385         bt->brp = best_brp;
386
387         /* real bit-rate */
388         bt->bitrate = priv->clock.freq / (bt->brp * (tseg1 + tseg2 + 1));
389
390         return 0;
391 }
392
393 static void print_bit_timing(const struct can_bittiming_const *btc,
394                              __u32 bitrate, __u32 sample_point, __u32 ref_clk,
395                              int quiet)
396 {
397         struct net_device dev = {
398                 .priv.bittiming_const = btc,
399                 .priv.clock.freq = ref_clk,
400         };
401         struct can_bittiming bt = {
402                 .bitrate = bitrate,
403                 .sample_point = sample_point,
404         };
405         long rate_error;
406
407         if (!quiet) {
408                 printf("Bit timing parameters for %s using %dHz\n",
409                        btc->name, ref_clk);
410                 printf("Bitrate TQ[ns] PrS PhS1 PhS2 SJW BRP SampP Error ");
411                 btc->printf_btr(&bt, 1);
412                 printf("\n");
413         }
414
415         if (can_calc_bittiming(&dev, &bt)) {
416                 printf("%7d ***bitrate not possible***\n", bitrate);
417                 return;
418         }
419
420         rate_error = abs((__s32)(bitrate - bt.bitrate));
421
422         printf("%7d %6d %3d %4d %4d %3d %3d %2d.%d%% %4.1f%% ",
423                bitrate, bt.tq, bt.prop_seg, bt.phase_seg1,
424                bt.phase_seg2, bt.sjw, bt.brp,
425                bt.sample_point / 10, bt.sample_point % 10,
426                100.0 * rate_error / bitrate);
427         btc->printf_btr(&bt, 0);
428         printf("\n");
429 }
430
431 int main(int argc, char *argv[])
432 {
433         long bitrate = 0;
434         long ref_clk = 8000000;
435         int sampl_pt = 0;
436         int quiet = 0;
437         int list = 0;
438         char *name = NULL;
439         int i, opt;
440
441         const struct can_bittiming_const *btc = NULL;
442
443         while ((opt = getopt(argc, argv, "b:c:lps:")) != -1) {
444                 switch (opt) {
445                 case 'b':
446                         bitrate = atoi(optarg);
447                         break;
448
449                 case 'c':
450                         ref_clk = atoi(optarg);
451                         break;
452
453                 case 'l':
454                         list = 1;
455                         break;
456
457                 case 'q':
458                         quiet = 1;
459                         break;
460
461                 case 's':
462                         sampl_pt = atoi(optarg);
463                         break;
464
465                 default:
466                         print_usage(argv[0]);
467                         break;
468                 }
469         }
470
471         if (argc > optind + 1)
472                 print_usage(argv[0]);
473
474         if (argc == optind + 1)
475                 name = argv[optind];
476
477         if (list) {
478                 for (i = 0; i < sizeof(can_calc_consts) /
479                              sizeof(struct can_bittiming_const); i++)
480                         printf("%s\n", can_calc_consts[i].name);
481                 return 0;
482         }
483
484         if (sampl_pt && (sampl_pt >= 1000 || sampl_pt < 100))
485                 print_usage(argv[0]);
486
487         if (name) {
488                 for (i = 0; i < sizeof(can_calc_consts) /
489                              sizeof(struct can_bittiming_const); i++) {
490                         if (!strcmp(can_calc_consts[i].name, name)) {
491                                 btc = &can_calc_consts[i];
492                                 break;
493                         }
494                 }
495                 if (!btc)
496                         print_usage(argv[0]);
497
498         } else {
499                 btc = &can_calc_consts[0];
500         }
501
502         if (bitrate) {
503                 print_bit_timing(btc, bitrate, sampl_pt, ref_clk, quiet);
504         } else {
505                 for (i = 0; i < sizeof(common_bitrates) / sizeof(long); i++)
506                         print_bit_timing(btc, common_bitrates[i], sampl_pt,
507                                          ref_clk, i);
508         }
509
510         return 0;
511 }