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