xref: /linux/drivers/net/can/dev/dev.c (revision 442bc81bd344dc52c37d8f80b854cc6da062b2d0)
1 // 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/kernel.h>
8 #include <linux/slab.h>
9 #include <linux/netdevice.h>
10 #include <linux/if_arp.h>
11 #include <linux/workqueue.h>
12 #include <linux/can.h>
13 #include <linux/can/can-ml.h>
14 #include <linux/can/dev.h>
15 #include <linux/can/skb.h>
16 #include <linux/gpio/consumer.h>
17 #include <linux/of.h>
18 
can_update_state_error_stats(struct net_device * dev,enum can_state new_state)19 static void can_update_state_error_stats(struct net_device *dev,
20 					 enum can_state new_state)
21 {
22 	struct can_priv *priv = netdev_priv(dev);
23 
24 	if (new_state <= priv->state)
25 		return;
26 
27 	switch (new_state) {
28 	case CAN_STATE_ERROR_WARNING:
29 		priv->can_stats.error_warning++;
30 		break;
31 	case CAN_STATE_ERROR_PASSIVE:
32 		priv->can_stats.error_passive++;
33 		break;
34 	case CAN_STATE_BUS_OFF:
35 		priv->can_stats.bus_off++;
36 		break;
37 	default:
38 		break;
39 	}
40 }
41 
can_tx_state_to_frame(struct net_device * dev,enum can_state state)42 static int can_tx_state_to_frame(struct net_device *dev, enum can_state state)
43 {
44 	switch (state) {
45 	case CAN_STATE_ERROR_ACTIVE:
46 		return CAN_ERR_CRTL_ACTIVE;
47 	case CAN_STATE_ERROR_WARNING:
48 		return CAN_ERR_CRTL_TX_WARNING;
49 	case CAN_STATE_ERROR_PASSIVE:
50 		return CAN_ERR_CRTL_TX_PASSIVE;
51 	default:
52 		return 0;
53 	}
54 }
55 
can_rx_state_to_frame(struct net_device * dev,enum can_state state)56 static int can_rx_state_to_frame(struct net_device *dev, enum can_state state)
57 {
58 	switch (state) {
59 	case CAN_STATE_ERROR_ACTIVE:
60 		return CAN_ERR_CRTL_ACTIVE;
61 	case CAN_STATE_ERROR_WARNING:
62 		return CAN_ERR_CRTL_RX_WARNING;
63 	case CAN_STATE_ERROR_PASSIVE:
64 		return CAN_ERR_CRTL_RX_PASSIVE;
65 	default:
66 		return 0;
67 	}
68 }
69 
can_get_state_str(const enum can_state state)70 const char *can_get_state_str(const enum can_state state)
71 {
72 	switch (state) {
73 	case CAN_STATE_ERROR_ACTIVE:
74 		return "Error Active";
75 	case CAN_STATE_ERROR_WARNING:
76 		return "Error Warning";
77 	case CAN_STATE_ERROR_PASSIVE:
78 		return "Error Passive";
79 	case CAN_STATE_BUS_OFF:
80 		return "Bus Off";
81 	case CAN_STATE_STOPPED:
82 		return "Stopped";
83 	case CAN_STATE_SLEEPING:
84 		return "Sleeping";
85 	default:
86 		return "<unknown>";
87 	}
88 }
89 EXPORT_SYMBOL_GPL(can_get_state_str);
90 
can_state_err_to_state(u16 err)91 static enum can_state can_state_err_to_state(u16 err)
92 {
93 	if (err < CAN_ERROR_WARNING_THRESHOLD)
94 		return CAN_STATE_ERROR_ACTIVE;
95 	if (err < CAN_ERROR_PASSIVE_THRESHOLD)
96 		return CAN_STATE_ERROR_WARNING;
97 	if (err < CAN_BUS_OFF_THRESHOLD)
98 		return CAN_STATE_ERROR_PASSIVE;
99 
100 	return CAN_STATE_BUS_OFF;
101 }
102 
can_state_get_by_berr_counter(const struct net_device * dev,const struct can_berr_counter * bec,enum can_state * tx_state,enum can_state * rx_state)103 void can_state_get_by_berr_counter(const struct net_device *dev,
104 				   const struct can_berr_counter *bec,
105 				   enum can_state *tx_state,
106 				   enum can_state *rx_state)
107 {
108 	*tx_state = can_state_err_to_state(bec->txerr);
109 	*rx_state = can_state_err_to_state(bec->rxerr);
110 }
111 EXPORT_SYMBOL_GPL(can_state_get_by_berr_counter);
112 
can_change_state(struct net_device * dev,struct can_frame * cf,enum can_state tx_state,enum can_state rx_state)113 void can_change_state(struct net_device *dev, struct can_frame *cf,
114 		      enum can_state tx_state, enum can_state rx_state)
115 {
116 	struct can_priv *priv = netdev_priv(dev);
117 	enum can_state new_state = max(tx_state, rx_state);
118 
119 	if (unlikely(new_state == priv->state)) {
120 		netdev_warn(dev, "%s: oops, state did not change", __func__);
121 		return;
122 	}
123 
124 	netdev_dbg(dev, "Controller changed from %s State (%d) into %s State (%d).\n",
125 		   can_get_state_str(priv->state), priv->state,
126 		   can_get_state_str(new_state), new_state);
127 
128 	can_update_state_error_stats(dev, new_state);
129 	priv->state = new_state;
130 
131 	if (!cf)
132 		return;
133 
134 	if (unlikely(new_state == CAN_STATE_BUS_OFF)) {
135 		cf->can_id |= CAN_ERR_BUSOFF;
136 		return;
137 	}
138 
139 	cf->can_id |= CAN_ERR_CRTL;
140 	cf->data[1] |= tx_state >= rx_state ?
141 		       can_tx_state_to_frame(dev, tx_state) : 0;
142 	cf->data[1] |= tx_state <= rx_state ?
143 		       can_rx_state_to_frame(dev, rx_state) : 0;
144 }
145 EXPORT_SYMBOL_GPL(can_change_state);
146 
147 /* CAN device restart for bus-off recovery */
can_restart(struct net_device * dev)148 static void can_restart(struct net_device *dev)
149 {
150 	struct can_priv *priv = netdev_priv(dev);
151 	struct sk_buff *skb;
152 	struct can_frame *cf;
153 	int err;
154 
155 	if (netif_carrier_ok(dev))
156 		netdev_err(dev, "Attempt to restart for bus-off recovery, but carrier is OK?\n");
157 
158 	/* No synchronization needed because the device is bus-off and
159 	 * no messages can come in or go out.
160 	 */
161 	can_flush_echo_skb(dev);
162 
163 	/* send restart message upstream */
164 	skb = alloc_can_err_skb(dev, &cf);
165 	if (skb) {
166 		cf->can_id |= CAN_ERR_RESTARTED;
167 		netif_rx(skb);
168 	}
169 
170 	/* Now restart the device */
171 	netif_carrier_on(dev);
172 	err = priv->do_set_mode(dev, CAN_MODE_START);
173 	if (err) {
174 		netdev_err(dev, "Restart failed, error %pe\n", ERR_PTR(err));
175 		netif_carrier_off(dev);
176 	} else {
177 		netdev_dbg(dev, "Restarted\n");
178 		priv->can_stats.restarts++;
179 	}
180 }
181 
can_restart_work(struct work_struct * work)182 static void can_restart_work(struct work_struct *work)
183 {
184 	struct delayed_work *dwork = to_delayed_work(work);
185 	struct can_priv *priv = container_of(dwork, struct can_priv,
186 					     restart_work);
187 
188 	can_restart(priv->dev);
189 }
190 
can_restart_now(struct net_device * dev)191 int can_restart_now(struct net_device *dev)
192 {
193 	struct can_priv *priv = netdev_priv(dev);
194 
195 	/* A manual restart is only permitted if automatic restart is
196 	 * disabled and the device is in the bus-off state
197 	 */
198 	if (priv->restart_ms)
199 		return -EINVAL;
200 	if (priv->state != CAN_STATE_BUS_OFF)
201 		return -EBUSY;
202 
203 	cancel_delayed_work_sync(&priv->restart_work);
204 	can_restart(dev);
205 
206 	return 0;
207 }
208 
209 /* CAN bus-off
210  *
211  * This functions should be called when the device goes bus-off to
212  * tell the netif layer that no more packets can be sent or received.
213  * If enabled, a timer is started to trigger bus-off recovery.
214  */
can_bus_off(struct net_device * dev)215 void can_bus_off(struct net_device *dev)
216 {
217 	struct can_priv *priv = netdev_priv(dev);
218 
219 	if (priv->restart_ms)
220 		netdev_info(dev, "bus-off, scheduling restart in %d ms\n",
221 			    priv->restart_ms);
222 	else
223 		netdev_info(dev, "bus-off\n");
224 
225 	netif_carrier_off(dev);
226 
227 	if (priv->restart_ms)
228 		schedule_delayed_work(&priv->restart_work,
229 				      msecs_to_jiffies(priv->restart_ms));
230 }
231 EXPORT_SYMBOL_GPL(can_bus_off);
232 
can_setup(struct net_device * dev)233 void can_setup(struct net_device *dev)
234 {
235 	dev->type = ARPHRD_CAN;
236 	dev->mtu = CAN_MTU;
237 	dev->hard_header_len = 0;
238 	dev->addr_len = 0;
239 	dev->tx_queue_len = 10;
240 
241 	/* New-style flags. */
242 	dev->flags = IFF_NOARP;
243 	dev->features = NETIF_F_HW_CSUM;
244 }
245 
246 /* Allocate and setup space for the CAN network device */
alloc_candev_mqs(int sizeof_priv,unsigned int echo_skb_max,unsigned int txqs,unsigned int rxqs)247 struct net_device *alloc_candev_mqs(int sizeof_priv, unsigned int echo_skb_max,
248 				    unsigned int txqs, unsigned int rxqs)
249 {
250 	struct can_ml_priv *can_ml;
251 	struct net_device *dev;
252 	struct can_priv *priv;
253 	int size;
254 
255 	/* We put the driver's priv, the CAN mid layer priv and the
256 	 * echo skb into the netdevice's priv. The memory layout for
257 	 * the netdev_priv is like this:
258 	 *
259 	 * +-------------------------+
260 	 * | driver's priv           |
261 	 * +-------------------------+
262 	 * | struct can_ml_priv      |
263 	 * +-------------------------+
264 	 * | array of struct sk_buff |
265 	 * +-------------------------+
266 	 */
267 
268 	size = ALIGN(sizeof_priv, NETDEV_ALIGN) + sizeof(struct can_ml_priv);
269 
270 	if (echo_skb_max)
271 		size = ALIGN(size, sizeof(struct sk_buff *)) +
272 			echo_skb_max * sizeof(struct sk_buff *);
273 
274 	dev = alloc_netdev_mqs(size, "can%d", NET_NAME_UNKNOWN, can_setup,
275 			       txqs, rxqs);
276 	if (!dev)
277 		return NULL;
278 
279 	priv = netdev_priv(dev);
280 	priv->dev = dev;
281 
282 	can_ml = (void *)priv + ALIGN(sizeof_priv, NETDEV_ALIGN);
283 	can_set_ml_priv(dev, can_ml);
284 
285 	if (echo_skb_max) {
286 		priv->echo_skb_max = echo_skb_max;
287 		priv->echo_skb = (void *)priv +
288 			(size - echo_skb_max * sizeof(struct sk_buff *));
289 	}
290 
291 	priv->state = CAN_STATE_STOPPED;
292 
293 	INIT_DELAYED_WORK(&priv->restart_work, can_restart_work);
294 
295 	return dev;
296 }
297 EXPORT_SYMBOL_GPL(alloc_candev_mqs);
298 
299 /* Free space of the CAN network device */
free_candev(struct net_device * dev)300 void free_candev(struct net_device *dev)
301 {
302 	free_netdev(dev);
303 }
304 EXPORT_SYMBOL_GPL(free_candev);
305 
306 /* changing MTU and control mode for CAN/CANFD devices */
can_change_mtu(struct net_device * dev,int new_mtu)307 int can_change_mtu(struct net_device *dev, int new_mtu)
308 {
309 	struct can_priv *priv = netdev_priv(dev);
310 	u32 ctrlmode_static = can_get_static_ctrlmode(priv);
311 
312 	/* Do not allow changing the MTU while running */
313 	if (dev->flags & IFF_UP)
314 		return -EBUSY;
315 
316 	/* allow change of MTU according to the CANFD ability of the device */
317 	switch (new_mtu) {
318 	case CAN_MTU:
319 		/* 'CANFD-only' controllers can not switch to CAN_MTU */
320 		if (ctrlmode_static & CAN_CTRLMODE_FD)
321 			return -EINVAL;
322 
323 		priv->ctrlmode &= ~CAN_CTRLMODE_FD;
324 		break;
325 
326 	case CANFD_MTU:
327 		/* check for potential CANFD ability */
328 		if (!(priv->ctrlmode_supported & CAN_CTRLMODE_FD) &&
329 		    !(ctrlmode_static & CAN_CTRLMODE_FD))
330 			return -EINVAL;
331 
332 		priv->ctrlmode |= CAN_CTRLMODE_FD;
333 		break;
334 
335 	default:
336 		return -EINVAL;
337 	}
338 
339 	WRITE_ONCE(dev->mtu, new_mtu);
340 	return 0;
341 }
342 EXPORT_SYMBOL_GPL(can_change_mtu);
343 
344 /* generic implementation of netdev_ops::ndo_eth_ioctl for CAN devices
345  * supporting hardware timestamps
346  */
can_eth_ioctl_hwts(struct net_device * netdev,struct ifreq * ifr,int cmd)347 int can_eth_ioctl_hwts(struct net_device *netdev, struct ifreq *ifr, int cmd)
348 {
349 	struct hwtstamp_config hwts_cfg = { 0 };
350 
351 	switch (cmd) {
352 	case SIOCSHWTSTAMP: /* set */
353 		if (copy_from_user(&hwts_cfg, ifr->ifr_data, sizeof(hwts_cfg)))
354 			return -EFAULT;
355 		if (hwts_cfg.tx_type == HWTSTAMP_TX_ON &&
356 		    hwts_cfg.rx_filter == HWTSTAMP_FILTER_ALL)
357 			return 0;
358 		return -ERANGE;
359 
360 	case SIOCGHWTSTAMP: /* get */
361 		hwts_cfg.tx_type = HWTSTAMP_TX_ON;
362 		hwts_cfg.rx_filter = HWTSTAMP_FILTER_ALL;
363 		if (copy_to_user(ifr->ifr_data, &hwts_cfg, sizeof(hwts_cfg)))
364 			return -EFAULT;
365 		return 0;
366 
367 	default:
368 		return -EOPNOTSUPP;
369 	}
370 }
371 EXPORT_SYMBOL(can_eth_ioctl_hwts);
372 
373 /* generic implementation of ethtool_ops::get_ts_info for CAN devices
374  * supporting hardware timestamps
375  */
can_ethtool_op_get_ts_info_hwts(struct net_device * dev,struct kernel_ethtool_ts_info * info)376 int can_ethtool_op_get_ts_info_hwts(struct net_device *dev,
377 				    struct kernel_ethtool_ts_info *info)
378 {
379 	info->so_timestamping =
380 		SOF_TIMESTAMPING_TX_SOFTWARE |
381 		SOF_TIMESTAMPING_TX_HARDWARE |
382 		SOF_TIMESTAMPING_RX_HARDWARE |
383 		SOF_TIMESTAMPING_RAW_HARDWARE;
384 	info->tx_types = BIT(HWTSTAMP_TX_ON);
385 	info->rx_filters = BIT(HWTSTAMP_FILTER_ALL);
386 
387 	return 0;
388 }
389 EXPORT_SYMBOL(can_ethtool_op_get_ts_info_hwts);
390 
391 /* Common open function when the device gets opened.
392  *
393  * This function should be called in the open function of the device
394  * driver.
395  */
open_candev(struct net_device * dev)396 int open_candev(struct net_device *dev)
397 {
398 	struct can_priv *priv = netdev_priv(dev);
399 
400 	if (!priv->bittiming.bitrate) {
401 		netdev_err(dev, "bit-timing not yet defined\n");
402 		return -EINVAL;
403 	}
404 
405 	/* For CAN FD the data bitrate has to be >= the arbitration bitrate */
406 	if ((priv->ctrlmode & CAN_CTRLMODE_FD) &&
407 	    (!priv->data_bittiming.bitrate ||
408 	     priv->data_bittiming.bitrate < priv->bittiming.bitrate)) {
409 		netdev_err(dev, "incorrect/missing data bit-timing\n");
410 		return -EINVAL;
411 	}
412 
413 	/* Switch carrier on if device was stopped while in bus-off state */
414 	if (!netif_carrier_ok(dev))
415 		netif_carrier_on(dev);
416 
417 	return 0;
418 }
419 EXPORT_SYMBOL_GPL(open_candev);
420 
421 #ifdef CONFIG_OF
422 /* Common function that can be used to understand the limitation of
423  * a transceiver when it provides no means to determine these limitations
424  * at runtime.
425  */
of_can_transceiver(struct net_device * dev)426 void of_can_transceiver(struct net_device *dev)
427 {
428 	struct device_node *dn;
429 	struct can_priv *priv = netdev_priv(dev);
430 	struct device_node *np = dev->dev.parent->of_node;
431 	int ret;
432 
433 	dn = of_get_child_by_name(np, "can-transceiver");
434 	if (!dn)
435 		return;
436 
437 	ret = of_property_read_u32(dn, "max-bitrate", &priv->bitrate_max);
438 	of_node_put(dn);
439 	if ((ret && ret != -EINVAL) || (!ret && !priv->bitrate_max))
440 		netdev_warn(dev, "Invalid value for transceiver max bitrate. Ignoring bitrate limit.\n");
441 }
442 EXPORT_SYMBOL_GPL(of_can_transceiver);
443 #endif
444 
445 /* Common close function for cleanup before the device gets closed.
446  *
447  * This function should be called in the close function of the device
448  * driver.
449  */
close_candev(struct net_device * dev)450 void close_candev(struct net_device *dev)
451 {
452 	struct can_priv *priv = netdev_priv(dev);
453 
454 	cancel_delayed_work_sync(&priv->restart_work);
455 	can_flush_echo_skb(dev);
456 }
457 EXPORT_SYMBOL_GPL(close_candev);
458 
can_set_termination(struct net_device * ndev,u16 term)459 static int can_set_termination(struct net_device *ndev, u16 term)
460 {
461 	struct can_priv *priv = netdev_priv(ndev);
462 	int set;
463 
464 	if (term == priv->termination_gpio_ohms[CAN_TERMINATION_GPIO_ENABLED])
465 		set = 1;
466 	else
467 		set = 0;
468 
469 	gpiod_set_value_cansleep(priv->termination_gpio, set);
470 
471 	return 0;
472 }
473 
can_get_termination(struct net_device * ndev)474 static int can_get_termination(struct net_device *ndev)
475 {
476 	struct can_priv *priv = netdev_priv(ndev);
477 	struct device *dev = ndev->dev.parent;
478 	struct gpio_desc *gpio;
479 	u32 term;
480 	int ret;
481 
482 	/* Disabling termination by default is the safe choice: Else if many
483 	 * bus participants enable it, no communication is possible at all.
484 	 */
485 	gpio = devm_gpiod_get_optional(dev, "termination", GPIOD_OUT_LOW);
486 	if (IS_ERR(gpio))
487 		return dev_err_probe(dev, PTR_ERR(gpio),
488 				     "Cannot get termination-gpios\n");
489 
490 	if (!gpio)
491 		return 0;
492 
493 	ret = device_property_read_u32(dev, "termination-ohms", &term);
494 	if (ret) {
495 		netdev_err(ndev, "Cannot get termination-ohms: %pe\n",
496 			   ERR_PTR(ret));
497 		return ret;
498 	}
499 
500 	if (term > U16_MAX) {
501 		netdev_err(ndev, "Invalid termination-ohms value (%u > %u)\n",
502 			   term, U16_MAX);
503 		return -EINVAL;
504 	}
505 
506 	priv->termination_const_cnt = ARRAY_SIZE(priv->termination_gpio_ohms);
507 	priv->termination_const = priv->termination_gpio_ohms;
508 	priv->termination_gpio = gpio;
509 	priv->termination_gpio_ohms[CAN_TERMINATION_GPIO_DISABLED] =
510 		CAN_TERMINATION_DISABLED;
511 	priv->termination_gpio_ohms[CAN_TERMINATION_GPIO_ENABLED] = term;
512 	priv->do_set_termination = can_set_termination;
513 
514 	return 0;
515 }
516 
517 static bool
can_bittiming_const_valid(const struct can_bittiming_const * btc)518 can_bittiming_const_valid(const struct can_bittiming_const *btc)
519 {
520 	if (!btc)
521 		return true;
522 
523 	if (!btc->sjw_max)
524 		return false;
525 
526 	return true;
527 }
528 
529 /* Register the CAN network device */
register_candev(struct net_device * dev)530 int register_candev(struct net_device *dev)
531 {
532 	struct can_priv *priv = netdev_priv(dev);
533 	int err;
534 
535 	/* Ensure termination_const, termination_const_cnt and
536 	 * do_set_termination consistency. All must be either set or
537 	 * unset.
538 	 */
539 	if ((!priv->termination_const != !priv->termination_const_cnt) ||
540 	    (!priv->termination_const != !priv->do_set_termination))
541 		return -EINVAL;
542 
543 	if (!priv->bitrate_const != !priv->bitrate_const_cnt)
544 		return -EINVAL;
545 
546 	if (!priv->data_bitrate_const != !priv->data_bitrate_const_cnt)
547 		return -EINVAL;
548 
549 	/* We only support either fixed bit rates or bit timing const. */
550 	if ((priv->bitrate_const || priv->data_bitrate_const) &&
551 	    (priv->bittiming_const || priv->data_bittiming_const))
552 		return -EINVAL;
553 
554 	if (!can_bittiming_const_valid(priv->bittiming_const) ||
555 	    !can_bittiming_const_valid(priv->data_bittiming_const))
556 		return -EINVAL;
557 
558 	if (!priv->termination_const) {
559 		err = can_get_termination(dev);
560 		if (err)
561 			return err;
562 	}
563 
564 	dev->rtnl_link_ops = &can_link_ops;
565 	netif_carrier_off(dev);
566 
567 	return register_netdev(dev);
568 }
569 EXPORT_SYMBOL_GPL(register_candev);
570 
571 /* Unregister the CAN network device */
unregister_candev(struct net_device * dev)572 void unregister_candev(struct net_device *dev)
573 {
574 	unregister_netdev(dev);
575 }
576 EXPORT_SYMBOL_GPL(unregister_candev);
577 
578 /* Test if a network device is a candev based device
579  * and return the can_priv* if so.
580  */
safe_candev_priv(struct net_device * dev)581 struct can_priv *safe_candev_priv(struct net_device *dev)
582 {
583 	if (dev->type != ARPHRD_CAN || dev->rtnl_link_ops != &can_link_ops)
584 		return NULL;
585 
586 	return netdev_priv(dev);
587 }
588 EXPORT_SYMBOL_GPL(safe_candev_priv);
589 
can_dev_init(void)590 static __init int can_dev_init(void)
591 {
592 	int err;
593 
594 	err = can_netlink_register();
595 	if (!err)
596 		pr_info("CAN device driver interface\n");
597 
598 	return err;
599 }
600 module_init(can_dev_init);
601 
can_dev_exit(void)602 static __exit void can_dev_exit(void)
603 {
604 	can_netlink_unregister();
605 }
606 module_exit(can_dev_exit);
607 
608 MODULE_ALIAS_RTNL_LINK("can");
609