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