blob: 05a2c873af56d127d072e20be36b4fb79bcbffbf [file] [log] [blame]
b.liue9582032025-04-17 19:18:16 +08001// SPDX-License-Identifier: GPL-2.0-only
2/* Copyright (C) 2005 Marc Kleine-Budde, Pengutronix
3 * Copyright (C) 2006 Andrey Volkov, Varma Electronics
4 * Copyright (C) 2008-2009 Wolfgang Grandegger <wg@grandegger.com>
5 */
6
7#include <linux/module.h>
8#include <linux/kernel.h>
9#include <linux/slab.h>
10#include <linux/netdevice.h>
11#include <linux/if_arp.h>
12#include <linux/workqueue.h>
13#include <linux/can.h>
14#include <linux/can/can-ml.h>
15#include <linux/can/dev.h>
16#include <linux/can/skb.h>
17#include <linux/can/netlink.h>
18#include <linux/can/led.h>
19#include <linux/of.h>
20#include <net/rtnetlink.h>
21
22#define MOD_DESC "CAN device driver interface"
23
24MODULE_DESCRIPTION(MOD_DESC);
25MODULE_LICENSE("GPL v2");
26MODULE_AUTHOR("Wolfgang Grandegger <wg@grandegger.com>");
27
28/* CAN DLC to real data length conversion helpers */
29
30static const u8 dlc2len[] = {0, 1, 2, 3, 4, 5, 6, 7,
31 8, 12, 16, 20, 24, 32, 48, 64};
32
33/* get data length from can_dlc with sanitized can_dlc */
34u8 can_dlc2len(u8 can_dlc)
35{
36 return dlc2len[can_dlc & 0x0F];
37}
38EXPORT_SYMBOL_GPL(can_dlc2len);
39
40static const u8 len2dlc[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, /* 0 - 8 */
41 9, 9, 9, 9, /* 9 - 12 */
42 10, 10, 10, 10, /* 13 - 16 */
43 11, 11, 11, 11, /* 17 - 20 */
44 12, 12, 12, 12, /* 21 - 24 */
45 13, 13, 13, 13, 13, 13, 13, 13, /* 25 - 32 */
46 14, 14, 14, 14, 14, 14, 14, 14, /* 33 - 40 */
47 14, 14, 14, 14, 14, 14, 14, 14, /* 41 - 48 */
48 15, 15, 15, 15, 15, 15, 15, 15, /* 49 - 56 */
49 15, 15, 15, 15, 15, 15, 15, 15}; /* 57 - 64 */
50
51/* map the sanitized data length to an appropriate data length code */
52u8 can_len2dlc(u8 len)
53{
54 if (unlikely(len > 64))
55 return 0xF;
56
57 return len2dlc[len];
58}
59EXPORT_SYMBOL_GPL(can_len2dlc);
60
61#ifdef CONFIG_CAN_CALC_BITTIMING
62#define CAN_CALC_MAX_ERROR 50 /* in one-tenth of a percent */
63#define CAN_CALC_SYNC_SEG 1
64
65/* Bit-timing calculation derived from:
66 *
67 * Code based on LinCAN sources and H8S2638 project
68 * Copyright 2004-2006 Pavel Pisa - DCE FELK CVUT cz
69 * Copyright 2005 Stanislav Marek
70 * email: pisa@cmp.felk.cvut.cz
71 *
72 * Calculates proper bit-timing parameters for a specified bit-rate
73 * and sample-point, which can then be used to set the bit-timing
74 * registers of the CAN controller. You can find more information
75 * in the header file linux/can/netlink.h.
76 */
77static int
78can_update_sample_point(const struct can_bittiming_const *btc,
79 unsigned int sample_point_nominal, unsigned int tseg,
80 unsigned int *tseg1_ptr, unsigned int *tseg2_ptr,
81 unsigned int *sample_point_error_ptr)
82{
83 unsigned int sample_point_error, best_sample_point_error = UINT_MAX;
84 unsigned int sample_point, best_sample_point = 0;
85 unsigned int tseg1, tseg2;
86 int i;
87
88 for (i = 0; i <= 1; i++) {
89 tseg2 = tseg + CAN_CALC_SYNC_SEG -
90 (sample_point_nominal * (tseg + CAN_CALC_SYNC_SEG)) /
91 1000 - i;
92 tseg2 = clamp(tseg2, btc->tseg2_min, btc->tseg2_max);
93 tseg1 = tseg - tseg2;
94 if (tseg1 > btc->tseg1_max) {
95 tseg1 = btc->tseg1_max;
96 tseg2 = tseg - tseg1;
97 }
98
99 sample_point = 1000 * (tseg + CAN_CALC_SYNC_SEG - tseg2) /
100 (tseg + CAN_CALC_SYNC_SEG);
101 sample_point_error = abs(sample_point_nominal - sample_point);
102
103 if (sample_point <= sample_point_nominal &&
104 sample_point_error < best_sample_point_error) {
105 best_sample_point = sample_point;
106 best_sample_point_error = sample_point_error;
107 *tseg1_ptr = tseg1;
108 *tseg2_ptr = tseg2;
109 }
110 }
111
112 if (sample_point_error_ptr)
113 *sample_point_error_ptr = best_sample_point_error;
114
115 return best_sample_point;
116}
117
118static int can_calc_bittiming(struct net_device *dev, struct can_bittiming *bt,
119 const struct can_bittiming_const *btc)
120{
121 struct can_priv *priv = netdev_priv(dev);
122 unsigned int bitrate; /* current bitrate */
123 unsigned int bitrate_error; /* difference between current and nominal value */
124 unsigned int best_bitrate_error = UINT_MAX;
125 unsigned int sample_point_error; /* difference between current and nominal value */
126 unsigned int best_sample_point_error = UINT_MAX;
127 unsigned int sample_point_nominal; /* nominal sample point */
128 unsigned int best_tseg = 0; /* current best value for tseg */
129 unsigned int best_brp = 0; /* current best value for brp */
130 unsigned int brp, tsegall, tseg, tseg1 = 0, tseg2 = 0;
131 u64 v64;
132
133 /* Use CiA recommended sample points */
134 if (bt->sample_point) {
135 sample_point_nominal = bt->sample_point;
136 } else {
137 if (bt->bitrate > 800000)
138 sample_point_nominal = 750;
139 else if (bt->bitrate > 500000)
140 sample_point_nominal = 800;
141 else
142 sample_point_nominal = 875;
143 }
144
145 /* tseg even = round down, odd = round up */
146 for (tseg = (btc->tseg1_max + btc->tseg2_max) * 2 + 1;
147 tseg >= (btc->tseg1_min + btc->tseg2_min) * 2; tseg--) {
148 tsegall = CAN_CALC_SYNC_SEG + tseg / 2;
149
150 /* Compute all possible tseg choices (tseg=tseg1+tseg2) */
151 brp = priv->clock.freq / (tsegall * bt->bitrate) + tseg % 2;
152
153 /* choose brp step which is possible in system */
154 brp = (brp / btc->brp_inc) * btc->brp_inc;
155 if (brp < btc->brp_min || brp > btc->brp_max)
156 continue;
157
158 bitrate = priv->clock.freq / (brp * tsegall);
159 bitrate_error = abs(bt->bitrate - bitrate);
160
161 /* tseg brp biterror */
162 if (bitrate_error > best_bitrate_error)
163 continue;
164
165 /* reset sample point error if we have a better bitrate */
166 if (bitrate_error < best_bitrate_error)
167 best_sample_point_error = UINT_MAX;
168
169 can_update_sample_point(btc, sample_point_nominal, tseg / 2,
170 &tseg1, &tseg2, &sample_point_error);
171 if (sample_point_error > best_sample_point_error)
172 continue;
173
174 best_sample_point_error = sample_point_error;
175 best_bitrate_error = bitrate_error;
176 best_tseg = tseg / 2;
177 best_brp = brp;
178
179 if (bitrate_error == 0 && sample_point_error == 0)
180 break;
181 }
182
183 if (best_bitrate_error) {
184 /* Error in one-tenth of a percent */
185 v64 = (u64)best_bitrate_error * 1000;
186 do_div(v64, bt->bitrate);
187 bitrate_error = (u32)v64;
188 if (bitrate_error > CAN_CALC_MAX_ERROR) {
189 netdev_err(dev,
190 "bitrate error %d.%d%% too high\n",
191 bitrate_error / 10, bitrate_error % 10);
192 return -EDOM;
193 }
194 netdev_warn(dev, "bitrate error %d.%d%%\n",
195 bitrate_error / 10, bitrate_error % 10);
196 }
197
198 /* real sample point */
199 bt->sample_point = can_update_sample_point(btc, sample_point_nominal,
200 best_tseg, &tseg1, &tseg2,
201 NULL);
202
203 v64 = (u64)best_brp * 1000 * 1000 * 1000;
204 do_div(v64, priv->clock.freq);
205 bt->tq = (u32)v64;
206 bt->prop_seg = tseg1 / 2;
207 bt->phase_seg1 = tseg1 - bt->prop_seg;
208 bt->phase_seg2 = tseg2;
209
210 /* check for sjw user settings */
211 if (!bt->sjw || !btc->sjw_max) {
212 bt->sjw = 1;
213 } else {
214 /* bt->sjw is at least 1 -> sanitize upper bound to sjw_max */
215 if (bt->sjw > btc->sjw_max)
216 bt->sjw = btc->sjw_max;
217 /* bt->sjw must not be higher than tseg2 */
218 if (tseg2 < bt->sjw)
219 bt->sjw = tseg2;
220 }
221
222 bt->brp = best_brp;
223
224 /* real bitrate */
225 bt->bitrate = priv->clock.freq /
226 (bt->brp * (CAN_CALC_SYNC_SEG + tseg1 + tseg2));
227
228 return 0;
229}
230#else /* !CONFIG_CAN_CALC_BITTIMING */
231static int can_calc_bittiming(struct net_device *dev, struct can_bittiming *bt,
232 const struct can_bittiming_const *btc)
233{
234 netdev_err(dev, "bit-timing calculation not available\n");
235 return -EINVAL;
236}
237#endif /* CONFIG_CAN_CALC_BITTIMING */
238
239/* Checks the validity of the specified bit-timing parameters prop_seg,
240 * phase_seg1, phase_seg2 and sjw and tries to determine the bitrate
241 * prescaler value brp. You can find more information in the header
242 * file linux/can/netlink.h.
243 */
244static int can_fixup_bittiming(struct net_device *dev, struct can_bittiming *bt,
245 const struct can_bittiming_const *btc)
246{
247 struct can_priv *priv = netdev_priv(dev);
248 int tseg1, alltseg;
249 u64 brp64;
250
251 tseg1 = bt->prop_seg + bt->phase_seg1;
252 if (!bt->sjw)
253 bt->sjw = 1;
254 if (bt->sjw > btc->sjw_max ||
255 tseg1 < btc->tseg1_min || tseg1 > btc->tseg1_max ||
256 bt->phase_seg2 < btc->tseg2_min || bt->phase_seg2 > btc->tseg2_max)
257 return -ERANGE;
258
259 brp64 = (u64)priv->clock.freq * (u64)bt->tq;
260 if (btc->brp_inc > 1)
261 do_div(brp64, btc->brp_inc);
262 brp64 += 500000000UL - 1;
263 do_div(brp64, 1000000000UL); /* the practicable BRP */
264 if (btc->brp_inc > 1)
265 brp64 *= btc->brp_inc;
266 bt->brp = (u32)brp64;
267
268 if (bt->brp < btc->brp_min || bt->brp > btc->brp_max)
269 return -EINVAL;
270
271 alltseg = bt->prop_seg + bt->phase_seg1 + bt->phase_seg2 + 1;
272 bt->bitrate = priv->clock.freq / (bt->brp * alltseg);
273 bt->sample_point = ((tseg1 + 1) * 1000) / alltseg;
274
275 return 0;
276}
277
278/* Checks the validity of predefined bitrate settings */
279static int
280can_validate_bitrate(struct net_device *dev, struct can_bittiming *bt,
281 const u32 *bitrate_const,
282 const unsigned int bitrate_const_cnt)
283{
284 struct can_priv *priv = netdev_priv(dev);
285 unsigned int i;
286
287 for (i = 0; i < bitrate_const_cnt; i++) {
288 if (bt->bitrate == bitrate_const[i])
289 break;
290 }
291
292 if (i >= priv->bitrate_const_cnt)
293 return -EINVAL;
294
295 return 0;
296}
297
298static int can_get_bittiming(struct net_device *dev, struct can_bittiming *bt,
299 const struct can_bittiming_const *btc,
300 const u32 *bitrate_const,
301 const unsigned int bitrate_const_cnt)
302{
303 int err;
304
305 /* Depending on the given can_bittiming parameter structure the CAN
306 * timing parameters are calculated based on the provided bitrate OR
307 * alternatively the CAN timing parameters (tq, prop_seg, etc.) are
308 * provided directly which are then checked and fixed up.
309 */
310 if (!bt->tq && bt->bitrate && btc)
311 err = can_calc_bittiming(dev, bt, btc);
312 else if (bt->tq && !bt->bitrate && btc)
313 err = can_fixup_bittiming(dev, bt, btc);
314 else if (!bt->tq && bt->bitrate && bitrate_const)
315 err = can_validate_bitrate(dev, bt, bitrate_const,
316 bitrate_const_cnt);
317 else
318 err = -EINVAL;
319
320 return err;
321}
322
323static void can_update_state_error_stats(struct net_device *dev,
324 enum can_state new_state)
325{
326 struct can_priv *priv = netdev_priv(dev);
327
328 if (new_state <= priv->state)
329 return;
330
331 switch (new_state) {
332 case CAN_STATE_ERROR_WARNING:
333 priv->can_stats.error_warning++;
334 break;
335 case CAN_STATE_ERROR_PASSIVE:
336 priv->can_stats.error_passive++;
337 break;
338 case CAN_STATE_BUS_OFF:
339 priv->can_stats.bus_off++;
340 break;
341 default:
342 break;
343 }
344}
345
346static int can_tx_state_to_frame(struct net_device *dev, enum can_state state)
347{
348 switch (state) {
349 case CAN_STATE_ERROR_ACTIVE:
350 return CAN_ERR_CRTL_ACTIVE;
351 case CAN_STATE_ERROR_WARNING:
352 return CAN_ERR_CRTL_TX_WARNING;
353 case CAN_STATE_ERROR_PASSIVE:
354 return CAN_ERR_CRTL_TX_PASSIVE;
355 default:
356 return 0;
357 }
358}
359
360static int can_rx_state_to_frame(struct net_device *dev, enum can_state state)
361{
362 switch (state) {
363 case CAN_STATE_ERROR_ACTIVE:
364 return CAN_ERR_CRTL_ACTIVE;
365 case CAN_STATE_ERROR_WARNING:
366 return CAN_ERR_CRTL_RX_WARNING;
367 case CAN_STATE_ERROR_PASSIVE:
368 return CAN_ERR_CRTL_RX_PASSIVE;
369 default:
370 return 0;
371 }
372}
373
374void can_change_state(struct net_device *dev, struct can_frame *cf,
375 enum can_state tx_state, enum can_state rx_state)
376{
377 struct can_priv *priv = netdev_priv(dev);
378 enum can_state new_state = max(tx_state, rx_state);
379
380 if (unlikely(new_state == priv->state)) {
381 netdev_warn(dev, "%s: oops, state did not change", __func__);
382 return;
383 }
384
385 netdev_dbg(dev, "New error state: %d\n", new_state);
386
387 can_update_state_error_stats(dev, new_state);
388 priv->state = new_state;
389
390 if (!cf)
391 return;
392
393 if (unlikely(new_state == CAN_STATE_BUS_OFF)) {
394 cf->can_id |= CAN_ERR_BUSOFF;
395 return;
396 }
397
398 cf->can_id |= CAN_ERR_CRTL;
399 cf->data[1] |= tx_state >= rx_state ?
400 can_tx_state_to_frame(dev, tx_state) : 0;
401 cf->data[1] |= tx_state <= rx_state ?
402 can_rx_state_to_frame(dev, rx_state) : 0;
403}
404EXPORT_SYMBOL_GPL(can_change_state);
405
406/* Local echo of CAN messages
407 *
408 * CAN network devices *should* support a local echo functionality
409 * (see Documentation/networking/can.rst). To test the handling of CAN
410 * interfaces that do not support the local echo both driver types are
411 * implemented. In the case that the driver does not support the echo
412 * the IFF_ECHO remains clear in dev->flags. This causes the PF_CAN core
413 * to perform the echo as a fallback solution.
414 */
415static void can_flush_echo_skb(struct net_device *dev)
416{
417 struct can_priv *priv = netdev_priv(dev);
418 struct net_device_stats *stats = &dev->stats;
419 int i;
420
421 for (i = 0; i < priv->echo_skb_max; i++) {
422 if (priv->echo_skb[i]) {
423 kfree_skb(priv->echo_skb[i]);
424 priv->echo_skb[i] = NULL;
425 stats->tx_dropped++;
426 stats->tx_aborted_errors++;
427 }
428 }
429}
430
431/* Put the skb on the stack to be looped backed locally lateron
432 *
433 * The function is typically called in the start_xmit function
434 * of the device driver. The driver must protect access to
435 * priv->echo_skb, if necessary.
436 */
437void can_put_echo_skb(struct sk_buff *skb, struct net_device *dev,
438 unsigned int idx)
439{
440 struct can_priv *priv = netdev_priv(dev);
441
442 BUG_ON(idx >= priv->echo_skb_max);
443
444 /* check flag whether this packet has to be looped back */
445 if (!(dev->flags & IFF_ECHO) || skb->pkt_type != PACKET_LOOPBACK ||
446 (skb->protocol != htons(ETH_P_CAN) &&
447 skb->protocol != htons(ETH_P_CANFD))) {
448 kfree_skb(skb);
449 return;
450 }
451
452 if (!priv->echo_skb[idx]) {
453 skb = can_create_echo_skb(skb);
454 if (!skb)
455 return;
456
457 /* make settings for echo to reduce code in irq context */
458 skb->pkt_type = PACKET_BROADCAST;
459 skb->ip_summed = CHECKSUM_UNNECESSARY;
460 skb->dev = dev;
461
462 /* save this skb for tx interrupt echo handling */
463 priv->echo_skb[idx] = skb;
464 } else {
465 /* locking problem with netif_stop_queue() ?? */
466 netdev_err(dev, "%s: BUG! echo_skb is occupied!\n", __func__);
467 kfree_skb(skb);
468 }
469}
470EXPORT_SYMBOL_GPL(can_put_echo_skb);
471
472struct sk_buff *
473__can_get_echo_skb(struct net_device *dev, unsigned int idx, u8 *len_ptr)
474{
475 struct can_priv *priv = netdev_priv(dev);
476
477 if (idx >= priv->echo_skb_max) {
478 netdev_err(dev, "%s: BUG! Trying to access can_priv::echo_skb out of bounds (%u/max %u)\n",
479 __func__, idx, priv->echo_skb_max);
480 return NULL;
481 }
482
483 if (priv->echo_skb[idx]) {
484 /* Using "struct canfd_frame::len" for the frame
485 * length is supported on both CAN and CANFD frames.
486 */
487 struct sk_buff *skb = priv->echo_skb[idx];
488 struct canfd_frame *cf = (struct canfd_frame *)skb->data;
489
490 /* get the real payload length for netdev statistics */
491 if (cf->can_id & CAN_RTR_FLAG)
492 *len_ptr = 0;
493 else
494 *len_ptr = cf->len;
495
496 priv->echo_skb[idx] = NULL;
497
498 return skb;
499 }
500
501 return NULL;
502}
503
504/* Get the skb from the stack and loop it back locally
505 *
506 * The function is typically called when the TX done interrupt
507 * is handled in the device driver. The driver must protect
508 * access to priv->echo_skb, if necessary.
509 */
510unsigned int can_get_echo_skb(struct net_device *dev, unsigned int idx)
511{
512 struct sk_buff *skb;
513 u8 len;
514
515 skb = __can_get_echo_skb(dev, idx, &len);
516 if (!skb)
517 return 0;
518
519 skb_get(skb);
520 if (netif_rx(skb) == NET_RX_SUCCESS)
521 dev_consume_skb_any(skb);
522 else
523 dev_kfree_skb_any(skb);
524
525 return len;
526}
527EXPORT_SYMBOL_GPL(can_get_echo_skb);
528
529/* Remove the skb from the stack and free it.
530 *
531 * The function is typically called when TX failed.
532 */
533void can_free_echo_skb(struct net_device *dev, unsigned int idx)
534{
535 struct can_priv *priv = netdev_priv(dev);
536
537 BUG_ON(idx >= priv->echo_skb_max);
538
539 if (priv->echo_skb[idx]) {
540 dev_kfree_skb_any(priv->echo_skb[idx]);
541 priv->echo_skb[idx] = NULL;
542 }
543}
544EXPORT_SYMBOL_GPL(can_free_echo_skb);
545
546/* CAN device restart for bus-off recovery */
547static void can_restart(struct net_device *dev)
548{
549 struct can_priv *priv = netdev_priv(dev);
550 struct net_device_stats *stats = &dev->stats;
551 struct sk_buff *skb;
552 struct can_frame *cf;
553 int err;
554
555 if (netif_carrier_ok(dev))
556 netdev_err(dev, "Attempt to restart for bus-off recovery, but carrier is OK?\n");
557
558 /* No synchronization needed because the device is bus-off and
559 * no messages can come in or go out.
560 */
561 can_flush_echo_skb(dev);
562
563 /* send restart message upstream */
564 skb = alloc_can_err_skb(dev, &cf);
565 if (!skb) {
566 err = -ENOMEM;
567 goto restart;
568 }
569 cf->can_id |= CAN_ERR_RESTARTED;
570
571 stats->rx_packets++;
572 stats->rx_bytes += cf->can_dlc;
573
574 netif_rx_ni(skb);
575
576restart:
577 netdev_dbg(dev, "restarted\n");
578 priv->can_stats.restarts++;
579
580 /* Now restart the device */
581 netif_carrier_on(dev);
582 err = priv->do_set_mode(dev, CAN_MODE_START);
583 if (err) {
584 netdev_err(dev, "Error %d during restart", err);
585 netif_carrier_off(dev);
586 }
587}
588
589static void can_restart_work(struct work_struct *work)
590{
591 struct delayed_work *dwork = to_delayed_work(work);
592 struct can_priv *priv = container_of(dwork, struct can_priv,
593 restart_work);
594
595 can_restart(priv->dev);
596}
597
598int can_restart_now(struct net_device *dev)
599{
600 struct can_priv *priv = netdev_priv(dev);
601
602 /* A manual restart is only permitted if automatic restart is
603 * disabled and the device is in the bus-off state
604 */
605 if (priv->restart_ms)
606 return -EINVAL;
607 if (priv->state != CAN_STATE_BUS_OFF)
608 return -EBUSY;
609
610 cancel_delayed_work_sync(&priv->restart_work);
611 can_restart(dev);
612
613 return 0;
614}
615
616/* CAN bus-off
617 *
618 * This functions should be called when the device goes bus-off to
619 * tell the netif layer that no more packets can be sent or received.
620 * If enabled, a timer is started to trigger bus-off recovery.
621 */
622void can_bus_off(struct net_device *dev)
623{
624 struct can_priv *priv = netdev_priv(dev);
625
626 netdev_info(dev, "bus-off\n");
627
628 netif_carrier_off(dev);
629
630 if (priv->restart_ms)
631 schedule_delayed_work(&priv->restart_work,
632 msecs_to_jiffies(priv->restart_ms));
633}
634EXPORT_SYMBOL_GPL(can_bus_off);
635
636static void can_setup(struct net_device *dev)
637{
638 dev->type = ARPHRD_CAN;
639 dev->mtu = CAN_MTU;
640 dev->hard_header_len = 0;
641 dev->addr_len = 0;
642 dev->tx_queue_len = 10;
643
644 /* New-style flags. */
645 dev->flags = IFF_NOARP;
646 dev->features = NETIF_F_HW_CSUM;
647}
648
649struct sk_buff *alloc_can_skb(struct net_device *dev, struct can_frame **cf)
650{
651 struct sk_buff *skb;
652
653 skb = netdev_alloc_skb(dev, sizeof(struct can_skb_priv) +
654 sizeof(struct can_frame));
655 if (unlikely(!skb))
656 return NULL;
657
658 skb->protocol = htons(ETH_P_CAN);
659 skb->pkt_type = PACKET_BROADCAST;
660 skb->ip_summed = CHECKSUM_UNNECESSARY;
661
662 skb_reset_mac_header(skb);
663 skb_reset_network_header(skb);
664 skb_reset_transport_header(skb);
665
666 can_skb_reserve(skb);
667 can_skb_prv(skb)->ifindex = dev->ifindex;
668 can_skb_prv(skb)->skbcnt = 0;
669
670 *cf = skb_put_zero(skb, sizeof(struct can_frame));
671
672 return skb;
673}
674EXPORT_SYMBOL_GPL(alloc_can_skb);
675
676struct sk_buff *alloc_canfd_skb(struct net_device *dev,
677 struct canfd_frame **cfd)
678{
679 struct sk_buff *skb;
680
681 skb = netdev_alloc_skb(dev, sizeof(struct can_skb_priv) +
682 sizeof(struct canfd_frame));
683 if (unlikely(!skb))
684 return NULL;
685
686 skb->protocol = htons(ETH_P_CANFD);
687 skb->pkt_type = PACKET_BROADCAST;
688 skb->ip_summed = CHECKSUM_UNNECESSARY;
689
690 skb_reset_mac_header(skb);
691 skb_reset_network_header(skb);
692 skb_reset_transport_header(skb);
693
694 can_skb_reserve(skb);
695 can_skb_prv(skb)->ifindex = dev->ifindex;
696 can_skb_prv(skb)->skbcnt = 0;
697
698 *cfd = skb_put_zero(skb, sizeof(struct canfd_frame));
699
700 return skb;
701}
702EXPORT_SYMBOL_GPL(alloc_canfd_skb);
703
704struct sk_buff *alloc_can_err_skb(struct net_device *dev, struct can_frame **cf)
705{
706 struct sk_buff *skb;
707
708 skb = alloc_can_skb(dev, cf);
709 if (unlikely(!skb))
710 return NULL;
711
712 (*cf)->can_id = CAN_ERR_FLAG;
713 (*cf)->can_dlc = CAN_ERR_DLC;
714
715 return skb;
716}
717EXPORT_SYMBOL_GPL(alloc_can_err_skb);
718
719/* Allocate and setup space for the CAN network device */
720struct net_device *alloc_candev_mqs(int sizeof_priv, unsigned int echo_skb_max,
721 unsigned int txqs, unsigned int rxqs)
722{
723 struct can_ml_priv *can_ml;
724 struct net_device *dev;
725 struct can_priv *priv;
726 int size;
727
728 /* We put the driver's priv, the CAN mid layer priv and the
729 * echo skb into the netdevice's priv. The memory layout for
730 * the netdev_priv is like this:
731 *
732 * +-------------------------+
733 * | driver's priv |
734 * +-------------------------+
735 * | struct can_ml_priv |
736 * +-------------------------+
737 * | array of struct sk_buff |
738 * +-------------------------+
739 */
740
741 size = ALIGN(sizeof_priv, NETDEV_ALIGN) + sizeof(struct can_ml_priv);
742
743 if (echo_skb_max)
744 size = ALIGN(size, sizeof(struct sk_buff *)) +
745 echo_skb_max * sizeof(struct sk_buff *);
746
747 dev = alloc_netdev_mqs(size, "can%d", NET_NAME_UNKNOWN, can_setup,
748 txqs, rxqs);
749 if (!dev)
750 return NULL;
751
752 priv = netdev_priv(dev);
753 priv->dev = dev;
754
755 can_ml = (void *)priv + ALIGN(sizeof_priv, NETDEV_ALIGN);
756 can_set_ml_priv(dev, can_ml);
757
758 if (echo_skb_max) {
759 priv->echo_skb_max = echo_skb_max;
760 priv->echo_skb = (void *)priv +
761 (size - echo_skb_max * sizeof(struct sk_buff *));
762 }
763
764 priv->state = CAN_STATE_STOPPED;
765
766 INIT_DELAYED_WORK(&priv->restart_work, can_restart_work);
767
768 return dev;
769}
770EXPORT_SYMBOL_GPL(alloc_candev_mqs);
771
772/* Free space of the CAN network device */
773void free_candev(struct net_device *dev)
774{
775 free_netdev(dev);
776}
777EXPORT_SYMBOL_GPL(free_candev);
778
779/* changing MTU and control mode for CAN/CANFD devices */
780int can_change_mtu(struct net_device *dev, int new_mtu)
781{
782 struct can_priv *priv = netdev_priv(dev);
783
784 /* Do not allow changing the MTU while running */
785 if (dev->flags & IFF_UP)
786 return -EBUSY;
787
788 /* allow change of MTU according to the CANFD ability of the device */
789 switch (new_mtu) {
790 case CAN_MTU:
791 /* 'CANFD-only' controllers can not switch to CAN_MTU */
792 if (priv->ctrlmode_static & CAN_CTRLMODE_FD)
793 return -EINVAL;
794
795 priv->ctrlmode &= ~CAN_CTRLMODE_FD;
796 break;
797
798 case CANFD_MTU:
799 /* check for potential CANFD ability */
800 if (!(priv->ctrlmode_supported & CAN_CTRLMODE_FD) &&
801 !(priv->ctrlmode_static & CAN_CTRLMODE_FD))
802 return -EINVAL;
803
804 priv->ctrlmode |= CAN_CTRLMODE_FD;
805 break;
806
807 default:
808 return -EINVAL;
809 }
810
811 dev->mtu = new_mtu;
812 return 0;
813}
814EXPORT_SYMBOL_GPL(can_change_mtu);
815
816/* Common open function when the device gets opened.
817 *
818 * This function should be called in the open function of the device
819 * driver.
820 */
821int open_candev(struct net_device *dev)
822{
823 struct can_priv *priv = netdev_priv(dev);
824
825 if (!priv->bittiming.bitrate) {
826 netdev_err(dev, "bit-timing not yet defined\n");
827 return -EINVAL;
828 }
829
830 /* For CAN FD the data bitrate has to be >= the arbitration bitrate */
831 if ((priv->ctrlmode & CAN_CTRLMODE_FD) &&
832 (!priv->data_bittiming.bitrate ||
833 priv->data_bittiming.bitrate < priv->bittiming.bitrate)) {
834 netdev_err(dev, "incorrect/missing data bit-timing\n");
835 return -EINVAL;
836 }
837
838 /* Switch carrier on if device was stopped while in bus-off state */
839 if (!netif_carrier_ok(dev))
840 netif_carrier_on(dev);
841
842 return 0;
843}
844EXPORT_SYMBOL_GPL(open_candev);
845
846#ifdef CONFIG_OF
847/* Common function that can be used to understand the limitation of
848 * a transceiver when it provides no means to determine these limitations
849 * at runtime.
850 */
851void of_can_transceiver(struct net_device *dev)
852{
853 struct device_node *dn;
854 struct can_priv *priv = netdev_priv(dev);
855 struct device_node *np = dev->dev.parent->of_node;
856 int ret;
857
858 dn = of_get_child_by_name(np, "can-transceiver");
859 if (!dn)
860 return;
861
862 ret = of_property_read_u32(dn, "max-bitrate", &priv->bitrate_max);
863 of_node_put(dn);
864 if ((ret && ret != -EINVAL) || (!ret && !priv->bitrate_max))
865 netdev_warn(dev, "Invalid value for transceiver max bitrate. Ignoring bitrate limit.\n");
866}
867EXPORT_SYMBOL_GPL(of_can_transceiver);
868#endif
869
870/* Common close function for cleanup before the device gets closed.
871 *
872 * This function should be called in the close function of the device
873 * driver.
874 */
875void close_candev(struct net_device *dev)
876{
877 struct can_priv *priv = netdev_priv(dev);
878
879 cancel_delayed_work_sync(&priv->restart_work);
880 can_flush_echo_skb(dev);
881}
882EXPORT_SYMBOL_GPL(close_candev);
883
884/* CAN netlink interface */
885static const struct nla_policy can_policy[IFLA_CAN_MAX + 1] = {
886 [IFLA_CAN_STATE] = { .type = NLA_U32 },
887 [IFLA_CAN_CTRLMODE] = { .len = sizeof(struct can_ctrlmode) },
888 [IFLA_CAN_RESTART_MS] = { .type = NLA_U32 },
889 [IFLA_CAN_RESTART] = { .type = NLA_U32 },
890 [IFLA_CAN_BITTIMING] = { .len = sizeof(struct can_bittiming) },
891 [IFLA_CAN_BITTIMING_CONST]
892 = { .len = sizeof(struct can_bittiming_const) },
893 [IFLA_CAN_CLOCK] = { .len = sizeof(struct can_clock) },
894 [IFLA_CAN_BERR_COUNTER] = { .len = sizeof(struct can_berr_counter) },
895 [IFLA_CAN_DATA_BITTIMING]
896 = { .len = sizeof(struct can_bittiming) },
897 [IFLA_CAN_DATA_BITTIMING_CONST]
898 = { .len = sizeof(struct can_bittiming_const) },
899 [IFLA_CAN_TERMINATION] = { .type = NLA_U16 },
900};
901
902static int can_validate(struct nlattr *tb[], struct nlattr *data[],
903 struct netlink_ext_ack *extack)
904{
905 bool is_can_fd = false;
906
907 /* Make sure that valid CAN FD configurations always consist of
908 * - nominal/arbitration bittiming
909 * - data bittiming
910 * - control mode with CAN_CTRLMODE_FD set
911 */
912
913 if (!data)
914 return 0;
915
916 if (data[IFLA_CAN_CTRLMODE]) {
917 struct can_ctrlmode *cm = nla_data(data[IFLA_CAN_CTRLMODE]);
918
919 is_can_fd = cm->flags & cm->mask & CAN_CTRLMODE_FD;
920 }
921
922 if (is_can_fd) {
923 if (!data[IFLA_CAN_BITTIMING] || !data[IFLA_CAN_DATA_BITTIMING])
924 return -EOPNOTSUPP;
925 }
926
927 if (data[IFLA_CAN_DATA_BITTIMING]) {
928 if (!is_can_fd || !data[IFLA_CAN_BITTIMING])
929 return -EOPNOTSUPP;
930 }
931
932 return 0;
933}
934
935static int can_changelink(struct net_device *dev, struct nlattr *tb[],
936 struct nlattr *data[],
937 struct netlink_ext_ack *extack)
938{
939 struct can_priv *priv = netdev_priv(dev);
940 int err;
941
942 /* We need synchronization with dev->stop() */
943 ASSERT_RTNL();
944
945 if (data[IFLA_CAN_BITTIMING]) {
946 struct can_bittiming bt;
947
948 /* Do not allow changing bittiming while running */
949 if (dev->flags & IFF_UP)
950 return -EBUSY;
951
952 /* Calculate bittiming parameters based on
953 * bittiming_const if set, otherwise pass bitrate
954 * directly via do_set_bitrate(). Bail out if neither
955 * is given.
956 */
957 if (!priv->bittiming_const && !priv->do_set_bittiming)
958 return -EOPNOTSUPP;
959
960 memcpy(&bt, nla_data(data[IFLA_CAN_BITTIMING]), sizeof(bt));
961 err = can_get_bittiming(dev, &bt,
962 priv->bittiming_const,
963 priv->bitrate_const,
964 priv->bitrate_const_cnt);
965 if (err)
966 return err;
967
968 if (priv->bitrate_max && bt.bitrate > priv->bitrate_max) {
969 netdev_err(dev, "arbitration bitrate surpasses transceiver capabilities of %d bps\n",
970 priv->bitrate_max);
971 return -EINVAL;
972 }
973
974 memcpy(&priv->bittiming, &bt, sizeof(bt));
975
976 if (priv->do_set_bittiming) {
977 /* Finally, set the bit-timing registers */
978 err = priv->do_set_bittiming(dev);
979 if (err)
980 return err;
981 }
982 }
983
984 if (data[IFLA_CAN_CTRLMODE]) {
985 struct can_ctrlmode *cm;
986 u32 ctrlstatic;
987 u32 maskedflags;
988
989 /* Do not allow changing controller mode while running */
990 if (dev->flags & IFF_UP)
991 return -EBUSY;
992 cm = nla_data(data[IFLA_CAN_CTRLMODE]);
993 ctrlstatic = priv->ctrlmode_static;
994 maskedflags = cm->flags & cm->mask;
995
996 /* check whether provided bits are allowed to be passed */
997 if (cm->mask & ~(priv->ctrlmode_supported | ctrlstatic))
998 return -EOPNOTSUPP;
999
1000 /* do not check for static fd-non-iso if 'fd' is disabled */
1001 if (!(maskedflags & CAN_CTRLMODE_FD))
1002 ctrlstatic &= ~CAN_CTRLMODE_FD_NON_ISO;
1003
1004 /* make sure static options are provided by configuration */
1005 if ((maskedflags & ctrlstatic) != ctrlstatic)
1006 return -EOPNOTSUPP;
1007
1008 /* clear bits to be modified and copy the flag values */
1009 priv->ctrlmode &= ~cm->mask;
1010 priv->ctrlmode |= maskedflags;
1011
1012 /* CAN_CTRLMODE_FD can only be set when driver supports FD */
1013 if (priv->ctrlmode & CAN_CTRLMODE_FD)
1014 dev->mtu = CANFD_MTU;
1015 else
1016 dev->mtu = CAN_MTU;
1017 }
1018
1019 if (data[IFLA_CAN_RESTART_MS]) {
1020 /* Do not allow changing restart delay while running */
1021 if (dev->flags & IFF_UP)
1022 return -EBUSY;
1023 priv->restart_ms = nla_get_u32(data[IFLA_CAN_RESTART_MS]);
1024 }
1025
1026 if (data[IFLA_CAN_RESTART]) {
1027 /* Do not allow a restart while not running */
1028 if (!(dev->flags & IFF_UP))
1029 return -EINVAL;
1030 err = can_restart_now(dev);
1031 if (err)
1032 return err;
1033 }
1034
1035 if (data[IFLA_CAN_DATA_BITTIMING]) {
1036 struct can_bittiming dbt;
1037
1038 /* Do not allow changing bittiming while running */
1039 if (dev->flags & IFF_UP)
1040 return -EBUSY;
1041
1042 /* Calculate bittiming parameters based on
1043 * data_bittiming_const if set, otherwise pass bitrate
1044 * directly via do_set_bitrate(). Bail out if neither
1045 * is given.
1046 */
1047 if (!priv->data_bittiming_const && !priv->do_set_data_bittiming)
1048 return -EOPNOTSUPP;
1049
1050 memcpy(&dbt, nla_data(data[IFLA_CAN_DATA_BITTIMING]),
1051 sizeof(dbt));
1052 err = can_get_bittiming(dev, &dbt,
1053 priv->data_bittiming_const,
1054 priv->data_bitrate_const,
1055 priv->data_bitrate_const_cnt);
1056 if (err)
1057 return err;
1058
1059 if (priv->bitrate_max && dbt.bitrate > priv->bitrate_max) {
1060 netdev_err(dev, "canfd data bitrate surpasses transceiver capabilities of %d bps\n",
1061 priv->bitrate_max);
1062 return -EINVAL;
1063 }
1064
1065 memcpy(&priv->data_bittiming, &dbt, sizeof(dbt));
1066
1067 if (priv->do_set_data_bittiming) {
1068 /* Finally, set the bit-timing registers */
1069 err = priv->do_set_data_bittiming(dev);
1070 if (err)
1071 return err;
1072 }
1073 }
1074
1075 if (data[IFLA_CAN_TERMINATION]) {
1076 const u16 termval = nla_get_u16(data[IFLA_CAN_TERMINATION]);
1077 const unsigned int num_term = priv->termination_const_cnt;
1078 unsigned int i;
1079
1080 if (!priv->do_set_termination)
1081 return -EOPNOTSUPP;
1082
1083 /* check whether given value is supported by the interface */
1084 for (i = 0; i < num_term; i++) {
1085 if (termval == priv->termination_const[i])
1086 break;
1087 }
1088 if (i >= num_term)
1089 return -EINVAL;
1090
1091 /* Finally, set the termination value */
1092 err = priv->do_set_termination(dev, termval);
1093 if (err)
1094 return err;
1095
1096 priv->termination = termval;
1097 }
1098
1099 return 0;
1100}
1101
1102static size_t can_get_size(const struct net_device *dev)
1103{
1104 struct can_priv *priv = netdev_priv(dev);
1105 size_t size = 0;
1106
1107 if (priv->bittiming.bitrate) /* IFLA_CAN_BITTIMING */
1108 size += nla_total_size(sizeof(struct can_bittiming));
1109 if (priv->bittiming_const) /* IFLA_CAN_BITTIMING_CONST */
1110 size += nla_total_size(sizeof(struct can_bittiming_const));
1111 size += nla_total_size(sizeof(struct can_clock)); /* IFLA_CAN_CLOCK */
1112 size += nla_total_size(sizeof(u32)); /* IFLA_CAN_STATE */
1113 size += nla_total_size(sizeof(struct can_ctrlmode)); /* IFLA_CAN_CTRLMODE */
1114 size += nla_total_size(sizeof(u32)); /* IFLA_CAN_RESTART_MS */
1115 if (priv->do_get_berr_counter) /* IFLA_CAN_BERR_COUNTER */
1116 size += nla_total_size(sizeof(struct can_berr_counter));
1117 if (priv->data_bittiming.bitrate) /* IFLA_CAN_DATA_BITTIMING */
1118 size += nla_total_size(sizeof(struct can_bittiming));
1119 if (priv->data_bittiming_const) /* IFLA_CAN_DATA_BITTIMING_CONST */
1120 size += nla_total_size(sizeof(struct can_bittiming_const));
1121 if (priv->termination_const) {
1122 size += nla_total_size(sizeof(priv->termination)); /* IFLA_CAN_TERMINATION */
1123 size += nla_total_size(sizeof(*priv->termination_const) * /* IFLA_CAN_TERMINATION_CONST */
1124 priv->termination_const_cnt);
1125 }
1126 if (priv->bitrate_const) /* IFLA_CAN_BITRATE_CONST */
1127 size += nla_total_size(sizeof(*priv->bitrate_const) *
1128 priv->bitrate_const_cnt);
1129 if (priv->data_bitrate_const) /* IFLA_CAN_DATA_BITRATE_CONST */
1130 size += nla_total_size(sizeof(*priv->data_bitrate_const) *
1131 priv->data_bitrate_const_cnt);
1132 size += sizeof(priv->bitrate_max); /* IFLA_CAN_BITRATE_MAX */
1133
1134 return size;
1135}
1136
1137static int can_fill_info(struct sk_buff *skb, const struct net_device *dev)
1138{
1139 struct can_priv *priv = netdev_priv(dev);
1140 struct can_ctrlmode cm = {.flags = priv->ctrlmode};
1141 struct can_berr_counter bec = { };
1142 enum can_state state = priv->state;
1143
1144 if (priv->do_get_state)
1145 priv->do_get_state(dev, &state);
1146
1147 if ((priv->bittiming.bitrate &&
1148 nla_put(skb, IFLA_CAN_BITTIMING,
1149 sizeof(priv->bittiming), &priv->bittiming)) ||
1150
1151 (priv->bittiming_const &&
1152 nla_put(skb, IFLA_CAN_BITTIMING_CONST,
1153 sizeof(*priv->bittiming_const), priv->bittiming_const)) ||
1154
1155 nla_put(skb, IFLA_CAN_CLOCK, sizeof(priv->clock), &priv->clock) ||
1156 nla_put_u32(skb, IFLA_CAN_STATE, state) ||
1157 nla_put(skb, IFLA_CAN_CTRLMODE, sizeof(cm), &cm) ||
1158 nla_put_u32(skb, IFLA_CAN_RESTART_MS, priv->restart_ms) ||
1159
1160 (priv->do_get_berr_counter &&
1161 !priv->do_get_berr_counter(dev, &bec) &&
1162 nla_put(skb, IFLA_CAN_BERR_COUNTER, sizeof(bec), &bec)) ||
1163
1164 (priv->data_bittiming.bitrate &&
1165 nla_put(skb, IFLA_CAN_DATA_BITTIMING,
1166 sizeof(priv->data_bittiming), &priv->data_bittiming)) ||
1167
1168 (priv->data_bittiming_const &&
1169 nla_put(skb, IFLA_CAN_DATA_BITTIMING_CONST,
1170 sizeof(*priv->data_bittiming_const),
1171 priv->data_bittiming_const)) ||
1172
1173 (priv->termination_const &&
1174 (nla_put_u16(skb, IFLA_CAN_TERMINATION, priv->termination) ||
1175 nla_put(skb, IFLA_CAN_TERMINATION_CONST,
1176 sizeof(*priv->termination_const) *
1177 priv->termination_const_cnt,
1178 priv->termination_const))) ||
1179
1180 (priv->bitrate_const &&
1181 nla_put(skb, IFLA_CAN_BITRATE_CONST,
1182 sizeof(*priv->bitrate_const) *
1183 priv->bitrate_const_cnt,
1184 priv->bitrate_const)) ||
1185
1186 (priv->data_bitrate_const &&
1187 nla_put(skb, IFLA_CAN_DATA_BITRATE_CONST,
1188 sizeof(*priv->data_bitrate_const) *
1189 priv->data_bitrate_const_cnt,
1190 priv->data_bitrate_const)) ||
1191
1192 (nla_put(skb, IFLA_CAN_BITRATE_MAX,
1193 sizeof(priv->bitrate_max),
1194 &priv->bitrate_max))
1195 )
1196
1197 return -EMSGSIZE;
1198
1199 return 0;
1200}
1201
1202static size_t can_get_xstats_size(const struct net_device *dev)
1203{
1204 return sizeof(struct can_device_stats);
1205}
1206
1207static int can_fill_xstats(struct sk_buff *skb, const struct net_device *dev)
1208{
1209 struct can_priv *priv = netdev_priv(dev);
1210
1211 if (nla_put(skb, IFLA_INFO_XSTATS,
1212 sizeof(priv->can_stats), &priv->can_stats))
1213 goto nla_put_failure;
1214 return 0;
1215
1216nla_put_failure:
1217 return -EMSGSIZE;
1218}
1219
1220static int can_newlink(struct net *src_net, struct net_device *dev,
1221 struct nlattr *tb[], struct nlattr *data[],
1222 struct netlink_ext_ack *extack)
1223{
1224 return -EOPNOTSUPP;
1225}
1226
1227static void can_dellink(struct net_device *dev, struct list_head *head)
1228{
1229}
1230
1231static struct rtnl_link_ops can_link_ops __read_mostly = {
1232 .kind = "can",
1233 .netns_refund = true,
1234 .maxtype = IFLA_CAN_MAX,
1235 .policy = can_policy,
1236 .setup = can_setup,
1237 .validate = can_validate,
1238 .newlink = can_newlink,
1239 .changelink = can_changelink,
1240 .dellink = can_dellink,
1241 .get_size = can_get_size,
1242 .fill_info = can_fill_info,
1243 .get_xstats_size = can_get_xstats_size,
1244 .fill_xstats = can_fill_xstats,
1245};
1246
1247/* Register the CAN network device */
1248int register_candev(struct net_device *dev)
1249{
1250 struct can_priv *priv = netdev_priv(dev);
1251
1252 /* Ensure termination_const, termination_const_cnt and
1253 * do_set_termination consistency. All must be either set or
1254 * unset.
1255 */
1256 if ((!priv->termination_const != !priv->termination_const_cnt) ||
1257 (!priv->termination_const != !priv->do_set_termination))
1258 return -EINVAL;
1259
1260 if (!priv->bitrate_const != !priv->bitrate_const_cnt)
1261 return -EINVAL;
1262
1263 if (!priv->data_bitrate_const != !priv->data_bitrate_const_cnt)
1264 return -EINVAL;
1265
1266 dev->rtnl_link_ops = &can_link_ops;
1267 netif_carrier_off(dev);
1268
1269 return register_netdev(dev);
1270}
1271EXPORT_SYMBOL_GPL(register_candev);
1272
1273/* Unregister the CAN network device */
1274void unregister_candev(struct net_device *dev)
1275{
1276 unregister_netdev(dev);
1277}
1278EXPORT_SYMBOL_GPL(unregister_candev);
1279
1280/* Test if a network device is a candev based device
1281 * and return the can_priv* if so.
1282 */
1283struct can_priv *safe_candev_priv(struct net_device *dev)
1284{
1285 if (dev->type != ARPHRD_CAN || dev->rtnl_link_ops != &can_link_ops)
1286 return NULL;
1287
1288 return netdev_priv(dev);
1289}
1290EXPORT_SYMBOL_GPL(safe_candev_priv);
1291
1292static __init int can_dev_init(void)
1293{
1294 int err;
1295
1296 can_led_notifier_init();
1297
1298 err = rtnl_link_register(&can_link_ops);
1299 if (!err)
1300 pr_info(MOD_DESC "\n");
1301
1302 return err;
1303}
1304module_init(can_dev_init);
1305
1306static __exit void can_dev_exit(void)
1307{
1308 rtnl_link_unregister(&can_link_ops);
1309
1310 can_led_notifier_exit();
1311}
1312module_exit(can_dev_exit);
1313
1314MODULE_ALIAS_RTNL_LINK("can");