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