xref: /linux/drivers/net/can/virtio_can.c (revision d44ade05aa21468bd30652bc4492891b854a400a)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * CAN bus driver for the Virtio CAN controller
4  *
5  * Copyright (C) 2021-2023 OpenSynergy GmbH
6  * Copyright Red Hat, Inc. 2025
7  */
8 
9 #include <linux/atomic.h>
10 #include <linux/idr.h>
11 #include <linux/interrupt.h>
12 #include <linux/io.h>
13 #include <linux/kernel.h>
14 #include <linux/module.h>
15 #include <linux/mutex.h>
16 #include <linux/netdevice.h>
17 #include <linux/stddef.h>
18 #include <linux/can/dev.h>
19 #include <linux/virtio.h>
20 #include <linux/virtio_ring.h>
21 #include <linux/virtio_can.h>
22 
23 /* CAN device queues */
24 #define VIRTIO_CAN_QUEUE_TX 0
25 #define VIRTIO_CAN_QUEUE_RX 1
26 #define VIRTIO_CAN_QUEUE_CONTROL 2
27 #define VIRTIO_CAN_QUEUE_COUNT 3
28 
29 #define CAN_KNOWN_FLAGS \
30 	(VIRTIO_CAN_FLAGS_EXTENDED |\
31 	 VIRTIO_CAN_FLAGS_FD |\
32 	 VIRTIO_CAN_FLAGS_RTR)
33 
34 /* Max. number of in flight TX messages */
35 #define VIRTIO_CAN_ECHO_SKB_MAX 128
36 
37 struct virtio_can_tx {
38 	unsigned int putidx;
39 	struct virtio_can_tx_in tx_in;
40 	/* Keep virtio_can_tx_out at the end of the structure due to flex array */
41 	struct virtio_can_tx_out tx_out;
42 };
43 
44 struct virtio_can_control {
45 	struct virtio_can_control_out cpkt_out;
46 	struct virtio_can_control_in cpkt_in;
47 };
48 
49 /* virtio_can private data structure */
50 struct virtio_can_priv {
51 	struct can_priv can;	/* must be the first member */
52 	/* NAPI for RX messages */
53 	struct napi_struct napi;
54 	/* NAPI for TX messages */
55 	struct napi_struct napi_tx;
56 	/* The network device we're associated with */
57 	struct net_device *dev;
58 	/* The virtio device we're associated with */
59 	struct virtio_device *vdev;
60 	/* The virtqueues */
61 	struct virtqueue *vqs[VIRTIO_CAN_QUEUE_COUNT];
62 	/* Lock for TX operations */
63 	spinlock_t tx_lock;
64 	/* Control queue lock */
65 	struct mutex ctrl_lock;
66 	/* Wait for control queue processing without polling */
67 	struct completion ctrl_done;
68 	/* Array of receive queue messages */
69 	struct virtio_can_rx *rpkt;
70 	struct virtio_can_control can_ctr_msg;
71 	/* Data to get and maintain the putidx for local TX echo */
72 	struct ida tx_putidx_ida;
73 	/* In flight TX messages */
74 	atomic_t tx_inflight;
75 	/* Packet length */
76 	int rpkt_len;
77 	/* BusOff pending. Reset after successful indication to upper layer */
78 	bool busoff_pending;
79 	/* Tracks whether NAPI instances are currently enabled */
80 	bool napi_active;
81 };
82 
83 static void virtqueue_napi_schedule(struct napi_struct *napi,
84 				    struct virtqueue *vq)
85 {
86 	if (napi_schedule_prep(napi)) {
87 		virtqueue_disable_cb(vq);
88 		__napi_schedule(napi);
89 	}
90 }
91 
92 static void virtqueue_napi_complete(struct napi_struct *napi,
93 				    struct virtqueue *vq, int processed)
94 {
95 	int opaque;
96 
97 	opaque = virtqueue_enable_cb_prepare(vq);
98 	if (napi_complete_done(napi, processed)) {
99 		if (unlikely(virtqueue_poll(vq, opaque)))
100 			virtqueue_napi_schedule(napi, vq);
101 	} else {
102 		virtqueue_disable_cb(vq);
103 	}
104 }
105 
106 static void virtio_can_free_candev(struct net_device *ndev)
107 {
108 	struct virtio_can_priv *priv = netdev_priv(ndev);
109 
110 	ida_destroy(&priv->tx_putidx_ida);
111 	free_candev(ndev);
112 }
113 
114 static void virtio_can_napi_enable(struct virtio_can_priv *priv)
115 {
116 	if (!priv->napi_active) {
117 		napi_enable(&priv->napi);
118 		napi_enable(&priv->napi_tx);
119 		priv->napi_active = true;
120 	}
121 }
122 
123 static void virtio_can_napi_disable(struct virtio_can_priv *priv)
124 {
125 	if (priv->napi_active) {
126 		napi_disable(&priv->napi_tx);
127 		napi_disable(&priv->napi);
128 		priv->napi_active = false;
129 	}
130 }
131 
132 static int virtio_can_alloc_tx_idx(struct virtio_can_priv *priv)
133 {
134 	int tx_idx;
135 
136 	tx_idx = ida_alloc_max(&priv->tx_putidx_ida,
137 			       priv->can.echo_skb_max - 1, GFP_ATOMIC);
138 	if (tx_idx >= 0)
139 		atomic_inc(&priv->tx_inflight);
140 
141 	return tx_idx;
142 }
143 
144 static void virtio_can_free_tx_idx(struct virtio_can_priv *priv,
145 				   unsigned int idx)
146 {
147 	ida_free(&priv->tx_putidx_ida, idx);
148 	atomic_dec(&priv->tx_inflight);
149 }
150 
151 /* Create a scatter-gather list representing our input buffer and put
152  * it in the queue.
153  *
154  * Callers should take appropriate locks.
155  */
156 static int virtio_can_add_inbuf(struct virtqueue *vq, void *buf,
157 				unsigned int size)
158 {
159 	struct scatterlist sg[1];
160 	int ret;
161 
162 	sg_init_one(sg, buf, size);
163 
164 	ret = virtqueue_add_inbuf(vq, sg, 1, buf, GFP_ATOMIC);
165 
166 	return ret;
167 }
168 
169 /* Send a control message with message type either
170  *
171  * - VIRTIO_CAN_SET_CTRL_MODE_START or
172  * - VIRTIO_CAN_SET_CTRL_MODE_STOP.
173  *
174  */
175 static u8 virtio_can_send_ctrl_msg(struct net_device *ndev, u16 msg_type)
176 {
177 	struct scatterlist sg_out, sg_in, *sgs[2] = { &sg_out, &sg_in };
178 	struct virtio_can_priv *priv = netdev_priv(ndev);
179 	struct virtqueue *vq = priv->vqs[VIRTIO_CAN_QUEUE_CONTROL];
180 	struct device *dev = &priv->vdev->dev;
181 	unsigned int len;
182 	int err;
183 
184 	if (!vq)
185 		return VIRTIO_CAN_RESULT_NOT_OK;
186 
187 	guard(mutex)(&priv->ctrl_lock);
188 
189 	priv->can_ctr_msg.cpkt_out.msg_type = cpu_to_le16(msg_type);
190 	sg_init_one(&sg_out, &priv->can_ctr_msg.cpkt_out,
191 		    sizeof(priv->can_ctr_msg.cpkt_out));
192 	sg_init_one(&sg_in, &priv->can_ctr_msg.cpkt_in, sizeof(priv->can_ctr_msg.cpkt_in));
193 
194 	reinit_completion(&priv->ctrl_done);
195 
196 	err = virtqueue_add_sgs(vq, sgs, 1u, 1u, priv, GFP_ATOMIC);
197 	if (err != 0) {
198 		dev_err(dev, "%s(): virtqueue_add_sgs() failed\n", __func__);
199 		return VIRTIO_CAN_RESULT_NOT_OK;
200 	}
201 
202 	if (!virtqueue_kick(vq)) {
203 		dev_err(dev, "%s(): Kick failed\n", __func__);
204 		return VIRTIO_CAN_RESULT_NOT_OK;
205 	}
206 
207 	while (!virtqueue_get_buf(vq, &len) && !virtqueue_is_broken(vq))
208 		wait_for_completion(&priv->ctrl_done);
209 
210 	return priv->can_ctr_msg.cpkt_in.result;
211 }
212 
213 static int virtio_can_start(struct net_device *ndev)
214 {
215 	struct virtio_can_priv *priv = netdev_priv(ndev);
216 	u8 result;
217 
218 	result = virtio_can_send_ctrl_msg(ndev, VIRTIO_CAN_SET_CTRL_MODE_START);
219 	if (result != VIRTIO_CAN_RESULT_OK) {
220 		netdev_err(ndev, "CAN controller start failed\n");
221 		return -EIO;
222 	}
223 
224 	priv->busoff_pending = false;
225 	priv->can.state = CAN_STATE_ERROR_ACTIVE;
226 
227 	return 0;
228 }
229 
230 static int virtio_can_set_mode(struct net_device *dev, enum can_mode mode)
231 {
232 	int err;
233 
234 	switch (mode) {
235 	case CAN_MODE_START:
236 		err = virtio_can_start(dev);
237 		if (err)
238 			return err;
239 		netif_wake_queue(dev);
240 		break;
241 	default:
242 		return -EOPNOTSUPP;
243 	}
244 
245 	return 0;
246 }
247 
248 static int virtio_can_open(struct net_device *ndev)
249 {
250 	struct virtio_can_priv *priv = netdev_priv(ndev);
251 	int err;
252 
253 	err = open_candev(ndev);
254 	if (err)
255 		return err;
256 
257 	err = virtio_can_start(ndev);
258 	if (err) {
259 		close_candev(ndev);
260 		return err;
261 	}
262 
263 	virtio_can_napi_enable(priv);
264 	netif_start_queue(ndev);
265 
266 	return 0;
267 }
268 
269 static int virtio_can_stop(struct net_device *ndev)
270 {
271 	struct virtio_can_priv *priv = netdev_priv(ndev);
272 	struct device *dev = &priv->vdev->dev;
273 	u8 result;
274 
275 	result = virtio_can_send_ctrl_msg(ndev, VIRTIO_CAN_SET_CTRL_MODE_STOP);
276 	if (result != VIRTIO_CAN_RESULT_OK) {
277 		dev_err(dev, "CAN controller stop failed\n");
278 		return -EIO;
279 	}
280 
281 	priv->busoff_pending = false;
282 	priv->can.state = CAN_STATE_STOPPED;
283 
284 	/* Switch carrier off if device was connected to the bus */
285 	if (netif_carrier_ok(ndev))
286 		netif_carrier_off(ndev);
287 
288 	return 0;
289 }
290 
291 static int virtio_can_close(struct net_device *dev)
292 {
293 	struct virtio_can_priv *priv = netdev_priv(dev);
294 
295 	netif_stop_queue(dev);
296 	/* Ignore stop error: ndo_stop must always complete cleanup regardless.
297 	 * virtio_can_stop() already logs the error if it fails.
298 	 */
299 	virtio_can_stop(dev);
300 	virtio_can_napi_disable(priv);
301 	close_candev(dev);
302 
303 	return 0;
304 }
305 
306 static netdev_tx_t virtio_can_start_xmit(struct sk_buff *skb,
307 					 struct net_device *dev)
308 {
309 	struct scatterlist sg_out, sg_in, *sgs[2] = { &sg_out, &sg_in };
310 	const unsigned int hdr_size = sizeof(struct virtio_can_tx_out);
311 	struct canfd_frame *cf = (struct canfd_frame *)skb->data;
312 	struct virtio_can_priv *priv = netdev_priv(dev);
313 	struct virtqueue *vq = priv->vqs[VIRTIO_CAN_QUEUE_TX];
314 	netdev_tx_t xmit_ret = NETDEV_TX_OK;
315 	struct virtio_can_tx *can_tx_msg;
316 	u32 can_flags;
317 	int putidx;
318 	int err;
319 
320 	if (can_dev_dropped_skb(dev, skb))
321 		goto kick; /* No way to return NET_XMIT_DROP here */
322 
323 	/* No local check for CAN_RTR_FLAG or FD frame against negotiated
324 	 * features. The device will reject those anyway if not supported.
325 	 */
326 
327 	can_tx_msg = kzalloc(sizeof(*can_tx_msg) + cf->len, GFP_ATOMIC);
328 	if (!can_tx_msg) {
329 		kfree_skb(skb);
330 		dev->stats.tx_dropped++;
331 		goto kick; /* No way to return NET_XMIT_DROP here */
332 	}
333 
334 	can_tx_msg->tx_out.msg_type = cpu_to_le16(VIRTIO_CAN_TX);
335 	can_tx_msg->tx_out.length = cpu_to_le16(cf->len);
336 	can_flags = 0;
337 
338 	if (cf->can_id & CAN_EFF_FLAG) {
339 		can_flags |= VIRTIO_CAN_FLAGS_EXTENDED;
340 		can_tx_msg->tx_out.can_id = cpu_to_le32(cf->can_id & CAN_EFF_MASK);
341 	} else {
342 		can_tx_msg->tx_out.can_id = cpu_to_le32(cf->can_id & CAN_SFF_MASK);
343 	}
344 	if (cf->can_id & CAN_RTR_FLAG)
345 		can_flags |= VIRTIO_CAN_FLAGS_RTR;
346 	else
347 		memcpy(can_tx_msg->tx_out.sdu, cf->data, cf->len);
348 	if (can_is_canfd_skb(skb))
349 		can_flags |= VIRTIO_CAN_FLAGS_FD;
350 
351 	can_tx_msg->tx_out.flags = cpu_to_le32(can_flags);
352 
353 	sg_init_one(&sg_out, &can_tx_msg->tx_out, hdr_size + cf->len);
354 	sg_init_one(&sg_in, &can_tx_msg->tx_in, sizeof(can_tx_msg->tx_in));
355 
356 	putidx = virtio_can_alloc_tx_idx(priv);
357 
358 	if (unlikely(putidx < 0)) {
359 		/* -ENOMEM or -ENOSPC here. -ENOSPC should not be possible as
360 		 * tx_inflight >= can.echo_skb_max is checked in flow control
361 		 */
362 		WARN_ON_ONCE(putidx == -ENOSPC);
363 		kfree(can_tx_msg);
364 		kfree_skb(skb);
365 		dev->stats.tx_dropped++;
366 		goto kick; /* No way to return NET_XMIT_DROP here */
367 	}
368 
369 	can_tx_msg->putidx = (unsigned int)putidx;
370 
371 	/* Push loopback echo. Will be looped back on TX interrupt/TX NAPI */
372 	err = can_put_echo_skb(skb, dev, can_tx_msg->putidx, 0);
373 	if (unlikely(err)) {
374 		/* skb was already freed by can_put_echo_skb() on error */
375 		virtio_can_free_tx_idx(priv, can_tx_msg->putidx);
376 		kfree(can_tx_msg);
377 		dev->stats.tx_dropped++;
378 		goto kick;
379 	}
380 
381 	/* Protect queue and list operations */
382 	scoped_guard(spinlock_irqsave, &priv->tx_lock)
383 		err = virtqueue_add_sgs(vq, sgs, 1u, 1u, can_tx_msg, GFP_ATOMIC);
384 
385 	if (unlikely(err)) {
386 		/*
387 		 * can_put_echo_skb() already consumed skb via consume_skb(),
388 		 * so returning NETDEV_TX_BUSY would cause the stack to requeue
389 		 * a freed pointer. Drop the frame and return OK instead.
390 		 */
391 		can_free_echo_skb(dev, can_tx_msg->putidx, NULL);
392 		virtio_can_free_tx_idx(priv, can_tx_msg->putidx);
393 		netif_stop_queue(dev);
394 		kfree(can_tx_msg);
395 		dev->stats.tx_dropped++;
396 		/* Expected never to be seen */
397 		netdev_warn(dev, "TX: Stop queue, err = %d\n", err);
398 		goto kick;
399 	}
400 
401 	/* Normal flow control: stop queue when no transmission slots left */
402 	if (atomic_read(&priv->tx_inflight) >= priv->can.echo_skb_max ||
403 	    vq->num_free == 0 || (vq->num_free < ARRAY_SIZE(sgs) &&
404 	    !virtio_has_feature(vq->vdev, VIRTIO_RING_F_INDIRECT_DESC))) {
405 		netif_stop_queue(dev);
406 		netdev_dbg(dev, "TX: Normal stop queue\n");
407 	}
408 
409 kick:
410 	if (netif_queue_stopped(dev) || !netdev_xmit_more()) {
411 		scoped_guard(spinlock_irqsave, &priv->tx_lock) {
412 			if (!virtqueue_kick(vq))
413 				netdev_err(dev, "%s(): Kick failed\n", __func__);
414 		}
415 	}
416 
417 	return xmit_ret;
418 }
419 
420 static const struct net_device_ops virtio_can_netdev_ops = {
421 	.ndo_open = virtio_can_open,
422 	.ndo_stop = virtio_can_close,
423 	.ndo_start_xmit = virtio_can_start_xmit,
424 };
425 
426 static int register_virtio_can_dev(struct net_device *dev)
427 {
428 	dev->flags |= IFF_ECHO;	/* we support local echo */
429 	dev->netdev_ops = &virtio_can_netdev_ops;
430 
431 	return register_candev(dev);
432 }
433 
434 static int virtio_can_read_tx_queue(struct virtqueue *vq)
435 {
436 	struct virtio_can_priv *can_priv = vq->vdev->priv;
437 	struct net_device *dev = can_priv->dev;
438 	struct virtio_can_tx *can_tx_msg;
439 	struct net_device_stats *stats;
440 	unsigned int len;
441 	u8 result;
442 
443 	stats = &dev->stats;
444 
445 	scoped_guard(spinlock_irqsave, &can_priv->tx_lock)
446 		can_tx_msg = virtqueue_get_buf(vq, &len);
447 
448 	if (!can_tx_msg)
449 		return 0;
450 
451 	if (unlikely(len < sizeof(struct virtio_can_tx_in))) {
452 		netdev_err(dev, "TX ACK: Device sent no result code\n");
453 		result = VIRTIO_CAN_RESULT_NOT_OK; /* Keep things going */
454 	} else {
455 		result = can_tx_msg->tx_in.result;
456 	}
457 
458 	if (can_priv->can.state < CAN_STATE_BUS_OFF) {
459 		if (result != VIRTIO_CAN_RESULT_OK) {
460 			struct can_frame *skb_cf;
461 			struct sk_buff *skb = alloc_can_err_skb(dev, &skb_cf);
462 
463 			if (skb) {
464 				skb_cf->can_id |= CAN_ERR_CRTL;
465 				skb_cf->data[1] |= CAN_ERR_CRTL_UNSPEC;
466 				netif_rx(skb);
467 			}
468 			netdev_warn(dev, "TX ACK: Result = %u\n", result);
469 			can_free_echo_skb(dev, can_tx_msg->putidx, NULL);
470 			stats->tx_dropped++;
471 		} else {
472 			stats->tx_bytes += can_get_echo_skb(dev, can_tx_msg->putidx,
473 				NULL);
474 			stats->tx_packets++;
475 		}
476 	} else {
477 		netdev_dbg(dev, "TX ACK: Controller inactive, drop echo\n");
478 		can_free_echo_skb(dev, can_tx_msg->putidx, NULL);
479 		stats->tx_dropped++;
480 	}
481 
482 	virtio_can_free_tx_idx(can_priv, can_tx_msg->putidx);
483 
484 	/* Flow control */
485 	if (netif_queue_stopped(dev)) {
486 		netdev_dbg(dev, "TX ACK: Wake up stopped queue\n");
487 		netif_wake_queue(dev);
488 	}
489 
490 	kfree(can_tx_msg);
491 
492 	return 1; /* Queue was not empty so there may be more data */
493 }
494 
495 static int virtio_can_tx_poll(struct napi_struct *napi, int quota)
496 {
497 	struct net_device *dev = napi->dev;
498 	struct virtio_can_priv *priv = netdev_priv(dev);
499 	struct virtqueue *vq = priv->vqs[VIRTIO_CAN_QUEUE_TX];
500 	int work_done = 0;
501 
502 	while (work_done < quota && virtio_can_read_tx_queue(vq) != 0)
503 		work_done++;
504 
505 	if (work_done < quota)
506 		virtqueue_napi_complete(napi, vq, work_done);
507 
508 	return work_done;
509 }
510 
511 static void virtio_can_tx_intr(struct virtqueue *vq)
512 {
513 	struct virtio_can_priv *can_priv = vq->vdev->priv;
514 
515 	virtqueue_disable_cb(vq);
516 	napi_schedule(&can_priv->napi_tx);
517 }
518 
519 /* This function is the NAPI RX poll function and NAPI guarantees that this
520  * function is not invoked simultaneously on multiple processors.
521  * Read a RX message from the used queue and sends it to the upper layer.
522  */
523 static int virtio_can_read_rx_queue(struct virtqueue *vq)
524 {
525 	const unsigned int header_size = sizeof(struct virtio_can_rx);
526 	struct virtio_can_priv *priv = vq->vdev->priv;
527 	struct net_device *dev = priv->dev;
528 	struct net_device_stats *stats;
529 	struct virtio_can_rx *can_rx;
530 	unsigned int transport_len;
531 	struct canfd_frame *cf;
532 	struct sk_buff *skb;
533 	unsigned int len;
534 	u32 can_flags;
535 	u16 msg_type;
536 	u32 can_id;
537 	int ret;
538 
539 	stats = &dev->stats;
540 
541 	can_rx = virtqueue_get_buf(vq, &transport_len);
542 	if (!can_rx)
543 		return 0; /* No more data */
544 
545 	if (transport_len < header_size) {
546 		netdev_warn(dev, "RX: Message too small\n");
547 		goto putback;
548 	}
549 
550 	if (priv->can.state >= CAN_STATE_ERROR_PASSIVE) {
551 		netdev_dbg(dev, "%s(): Controller not active\n", __func__);
552 		goto putback;
553 	}
554 
555 	msg_type = le16_to_cpu(can_rx->msg_type);
556 	if (msg_type != VIRTIO_CAN_RX) {
557 		netdev_warn(dev, "RX: Got unknown msg_type %04x\n", msg_type);
558 		goto putback;
559 	}
560 
561 	len = le16_to_cpu(can_rx->length);
562 	can_flags = le32_to_cpu(can_rx->flags);
563 	can_id = le32_to_cpu(can_rx->can_id);
564 
565 	if (can_flags & ~CAN_KNOWN_FLAGS) {
566 		stats->rx_dropped++;
567 		netdev_warn(dev, "RX: CAN Id 0x%08x: Invalid flags 0x%x\n",
568 			    can_id, can_flags);
569 		goto putback;
570 	}
571 
572 	if (can_flags & VIRTIO_CAN_FLAGS_EXTENDED) {
573 		can_id &= CAN_EFF_MASK;
574 		can_id |= CAN_EFF_FLAG;
575 	} else {
576 		can_id &= CAN_SFF_MASK;
577 	}
578 
579 	if (can_flags & VIRTIO_CAN_FLAGS_RTR) {
580 		if (!virtio_has_feature(vq->vdev, VIRTIO_CAN_F_RTR_FRAMES)) {
581 			stats->rx_dropped++;
582 			netdev_warn(dev, "RX: CAN Id 0x%08x: RTR not negotiated\n",
583 				    can_id);
584 			goto putback;
585 		}
586 		if (can_flags & VIRTIO_CAN_FLAGS_FD) {
587 			stats->rx_dropped++;
588 			netdev_warn(dev, "RX: CAN Id 0x%08x: RTR with FD not possible\n",
589 				    can_id);
590 			goto putback;
591 		}
592 
593 		if (len > 0xF) {
594 			stats->rx_dropped++;
595 			netdev_warn(dev, "RX: CAN Id 0x%08x: RTR with DLC > 0xF\n",
596 				    can_id);
597 			goto putback;
598 		}
599 
600 		if (len > 0x8)
601 			len = 0x8;
602 
603 		can_id |= CAN_RTR_FLAG;
604 	}
605 
606 	if (transport_len < header_size + len) {
607 		netdev_warn(dev, "RX: Message too small for payload\n");
608 		goto putback;
609 	}
610 
611 	if (can_flags & VIRTIO_CAN_FLAGS_FD) {
612 		if (!virtio_has_feature(vq->vdev, VIRTIO_CAN_F_CAN_FD)) {
613 			stats->rx_dropped++;
614 			netdev_warn(dev, "RX: CAN Id 0x%08x: FD not negotiated\n",
615 				    can_id);
616 			goto putback;
617 		}
618 
619 		if (len > CANFD_MAX_DLEN)
620 			len = CANFD_MAX_DLEN;
621 
622 		skb = alloc_canfd_skb(priv->dev, &cf);
623 	} else {
624 		if (!virtio_has_feature(vq->vdev, VIRTIO_CAN_F_CAN_CLASSIC)) {
625 			stats->rx_dropped++;
626 			netdev_warn(dev, "RX: CAN Id 0x%08x: classic not negotiated\n",
627 				    can_id);
628 			goto putback;
629 		}
630 
631 		if (len > CAN_MAX_DLEN)
632 			len = CAN_MAX_DLEN;
633 
634 		skb = alloc_can_skb(priv->dev, (struct can_frame **)&cf);
635 	}
636 	if (!skb) {
637 		stats->rx_dropped++;
638 		netdev_warn(dev, "RX: No skb available\n");
639 		goto putback;
640 	}
641 
642 	cf->can_id = can_id;
643 	cf->len = len;
644 	if (!(can_flags & VIRTIO_CAN_FLAGS_RTR)) {
645 		/* RTR frames have a DLC but no payload */
646 		memcpy(cf->data, can_rx->sdu, len);
647 	}
648 
649 	if (netif_receive_skb(skb) == NET_RX_SUCCESS) {
650 		stats->rx_packets++;
651 		if (!(can_flags & VIRTIO_CAN_FLAGS_RTR))
652 			stats->rx_bytes += len;
653 	}
654 
655 putback:
656 	/* Put processed RX buffer back into avail queue */
657 	ret = virtio_can_add_inbuf(vq, can_rx,
658 				   priv->rpkt_len);
659 	if (!ret)
660 		virtqueue_kick(vq);
661 	return 1; /* Queue was not empty so there may be more data */
662 }
663 
664 static int virtio_can_handle_busoff(struct net_device *dev)
665 {
666 	struct virtio_can_priv *priv = netdev_priv(dev);
667 	struct can_frame *cf;
668 	struct sk_buff *skb;
669 
670 	if (!priv->busoff_pending)
671 		return 0;
672 
673 	if (priv->can.state < CAN_STATE_BUS_OFF) {
674 		netdev_dbg(dev, "entered error bus off state\n");
675 
676 		/* bus-off state */
677 		priv->can.state = CAN_STATE_BUS_OFF;
678 		priv->can.can_stats.bus_off++;
679 		can_bus_off(dev);
680 	}
681 
682 	/* propagate the error condition to the CAN stack */
683 	skb = alloc_can_err_skb(dev, &cf);
684 	if (unlikely(!skb))
685 		return 0;
686 
687 	/* bus-off state */
688 	cf->can_id |= CAN_ERR_BUSOFF;
689 
690 	/* Ensure that the BusOff indication does not get lost */
691 	if (netif_receive_skb(skb) == NET_RX_SUCCESS)
692 		priv->busoff_pending = false;
693 
694 	return 1;
695 }
696 
697 static int virtio_can_rx_poll(struct napi_struct *napi, int quota)
698 {
699 	struct net_device *dev = napi->dev;
700 	struct virtio_can_priv *priv = netdev_priv(dev);
701 	struct virtqueue *vq = priv->vqs[VIRTIO_CAN_QUEUE_RX];
702 	int work_done = 0;
703 
704 	work_done += virtio_can_handle_busoff(dev);
705 
706 	while (work_done < quota && virtio_can_read_rx_queue(vq) != 0)
707 		work_done++;
708 
709 	if (work_done < quota)
710 		virtqueue_napi_complete(napi, vq, work_done);
711 
712 	return work_done;
713 }
714 
715 static void virtio_can_rx_intr(struct virtqueue *vq)
716 {
717 	struct virtio_can_priv *can_priv = vq->vdev->priv;
718 
719 	virtqueue_disable_cb(vq);
720 	napi_schedule(&can_priv->napi);
721 }
722 
723 static void virtio_can_control_intr(struct virtqueue *vq)
724 {
725 	struct virtio_can_priv *can_priv = vq->vdev->priv;
726 
727 	complete(&can_priv->ctrl_done);
728 }
729 
730 static void virtio_can_config_changed(struct virtio_device *vdev)
731 {
732 	struct virtio_can_priv *can_priv = vdev->priv;
733 	u16 status;
734 
735 	status = virtio_cread16(vdev, offsetof(struct virtio_can_config,
736 					       status));
737 
738 	if (!(status & VIRTIO_CAN_S_CTRL_BUSOFF))
739 		return;
740 
741 	if (!can_priv->busoff_pending &&
742 	    can_priv->can.state < CAN_STATE_BUS_OFF) {
743 		can_priv->busoff_pending = true;
744 		napi_schedule(&can_priv->napi);
745 	}
746 }
747 
748 static void virtio_can_populate_rx_vq(struct virtio_device *vdev)
749 {
750 	struct virtio_can_priv *priv = vdev->priv;
751 	struct virtqueue *vq = priv->vqs[VIRTIO_CAN_QUEUE_RX];
752 	unsigned int buf_size = priv->rpkt_len;
753 	int num_elements = vq->num_free;
754 	u8 *buf = (u8 *)priv->rpkt;
755 	unsigned int idx;
756 	int ret = 0;
757 
758 	for (idx = 0; idx < num_elements; idx++) {
759 		ret = virtio_can_add_inbuf(vq, buf, buf_size);
760 		if (ret < 0) {
761 			dev_dbg(&vdev->dev, "rpkt fill: ret=%d, idx=%u, size=%u\n",
762 				ret, idx, buf_size);
763 			break;
764 		}
765 		buf += buf_size;
766 	}
767 
768 	if (idx > 0)
769 		virtqueue_kick(vq);
770 
771 	dev_dbg(&vdev->dev, "%u rpkt added\n", idx);
772 }
773 
774 static int virtio_can_find_vqs(struct virtio_can_priv *priv)
775 {
776 	struct virtqueue_info vqs_info[] = {
777 		{ "can-tx", virtio_can_tx_intr },
778 		{ "can-rx", virtio_can_rx_intr },
779 		{ "can-state-ctrl", virtio_can_control_intr },
780 	};
781 
782 	/* Find the queues. */
783 	return virtio_find_vqs(priv->vdev, VIRTIO_CAN_QUEUE_COUNT, priv->vqs,
784 			       vqs_info, NULL);
785 }
786 
787 /* Function must not be called before virtio_can_find_vqs() has been run */
788 static void virtio_can_del_vq(struct virtio_device *vdev)
789 {
790 	struct virtio_can_priv *priv = vdev->priv;
791 	struct virtqueue *vq = priv->vqs[VIRTIO_CAN_QUEUE_TX];
792 	struct virtio_can_tx *can_tx_msg;
793 	int q;
794 
795 	if (!vq)
796 		return;
797 
798 	/* Reset the device */
799 	virtio_reset_device(vdev);
800 
801 	/* From here we have dead silence from the device side so no locks
802 	 * are needed to protect against device side events.
803 	 */
804 
805 	/* Free pending TX buffers which were allocated in virtio_can_start_xmit() */
806 	while ((can_tx_msg = virtqueue_detach_unused_buf(vq))) {
807 		can_free_echo_skb(priv->dev, can_tx_msg->putidx, NULL);
808 		virtio_can_free_tx_idx(priv, can_tx_msg->putidx);
809 		kfree(can_tx_msg);
810 	}
811 
812 	/* RX and control queue buffers are managed elsewhere, just detach */
813 	for (q = VIRTIO_CAN_QUEUE_RX; q < VIRTIO_CAN_QUEUE_COUNT; q++)
814 		while (virtqueue_detach_unused_buf(priv->vqs[q]))
815 			;
816 
817 	if (vdev->config->del_vqs)
818 		vdev->config->del_vqs(vdev);
819 
820 	memset(priv->vqs, 0, sizeof(priv->vqs));
821 }
822 
823 static void virtio_can_remove(struct virtio_device *vdev)
824 {
825 	struct virtio_can_priv *priv = vdev->priv;
826 	struct net_device *dev = priv->dev;
827 
828 	unregister_candev(dev);
829 
830 	virtio_can_del_vq(vdev);
831 
832 	virtio_can_free_candev(dev);
833 }
834 
835 static int virtio_can_validate(struct virtio_device *vdev)
836 {
837 	/* CAN needs always access to the config space.
838 	 * Check that the driver can access the config space
839 	 */
840 	if (!vdev->config->get) {
841 		dev_err(&vdev->dev, "%s failure: config access disabled\n",
842 			__func__);
843 		return -EINVAL;
844 	}
845 
846 	if (!virtio_has_feature(vdev, VIRTIO_F_VERSION_1)) {
847 		dev_err(&vdev->dev,
848 			"device does not comply with spec version 1.x\n");
849 		return -EINVAL;
850 	}
851 
852 	return 0;
853 }
854 
855 static int virtio_can_probe(struct virtio_device *vdev)
856 {
857 	struct virtio_can_priv *priv;
858 	struct net_device *dev;
859 	size_t size;
860 	int err;
861 
862 	dev = alloc_candev(sizeof(struct virtio_can_priv),
863 			   VIRTIO_CAN_ECHO_SKB_MAX);
864 	if (!dev)
865 		return -ENOMEM;
866 
867 	priv = netdev_priv(dev);
868 
869 	ida_init(&priv->tx_putidx_ida);
870 
871 	netif_napi_add(dev, &priv->napi, virtio_can_rx_poll);
872 	netif_napi_add(dev, &priv->napi_tx, virtio_can_tx_poll);
873 
874 	SET_NETDEV_DEV(dev, &vdev->dev);
875 
876 	priv->dev = dev;
877 	priv->vdev = vdev;
878 	vdev->priv = priv;
879 
880 	priv->can.do_set_mode = virtio_can_set_mode;
881 	priv->can.bittiming.bitrate = CAN_BITRATE_UNKNOWN;
882 	/* Set Virtio CAN supported operations */
883 	priv->can.ctrlmode_supported = CAN_CTRLMODE_BERR_REPORTING;
884 	if (virtio_has_feature(vdev, VIRTIO_CAN_F_CAN_FD)) {
885 		priv->can.fd.data_bittiming.bitrate = CAN_BITRATE_UNKNOWN;
886 		err = can_set_static_ctrlmode(dev, CAN_CTRLMODE_FD);
887 		if (err != 0)
888 			goto on_failure;
889 	}
890 
891 	/* Initialize virtqueues */
892 	err = virtio_can_find_vqs(priv);
893 	if (err != 0)
894 		goto on_failure;
895 
896 	spin_lock_init(&priv->tx_lock);
897 	mutex_init(&priv->ctrl_lock);
898 
899 	init_completion(&priv->ctrl_done);
900 
901 	priv->rpkt_len = sizeof(struct virtio_can_rx);
902 
903 	if (virtio_has_feature(vdev, VIRTIO_CAN_F_CAN_FD))
904 		priv->rpkt_len += CANFD_MAX_DLEN;
905 	else
906 		priv->rpkt_len += CAN_MAX_DLEN;
907 
908 	size = priv->rpkt_len * priv->vqs[VIRTIO_CAN_QUEUE_RX]->num_free;
909 	priv->rpkt = devm_kzalloc(&vdev->dev, size, GFP_KERNEL);
910 	if (!priv->rpkt) {
911 		virtio_can_del_vq(vdev);
912 		err = -ENOMEM;
913 		goto on_failure;
914 	}
915 	virtio_can_populate_rx_vq(vdev);
916 
917 	err = register_virtio_can_dev(dev);
918 	if (err) {
919 		virtio_can_del_vq(vdev);
920 		goto on_failure;
921 	}
922 
923 	return 0;
924 
925 on_failure:
926 	virtio_can_free_candev(dev);
927 	return err;
928 }
929 
930 static int __maybe_unused virtio_can_freeze(struct virtio_device *vdev)
931 {
932 	struct virtio_can_priv *priv = vdev->priv;
933 	struct net_device *ndev = priv->dev;
934 
935 	if (netif_running(ndev)) {
936 		/* virtio_can_close() calls netif_stop_queue(), virtio_can_stop(),
937 		 * napi_disable() and close_candev(). Call it directly (not via
938 		 * dev_close()) to preserve IFF_UP so that netif_running() returns
939 		 * true in virtio_can_restore() and the device is brought back up.
940 		 */
941 		virtio_can_close(ndev);
942 		netif_device_detach(ndev);
943 	}
944 
945 	priv->can.state = CAN_STATE_SLEEPING;
946 
947 	virtio_can_del_vq(vdev);
948 
949 	return 0;
950 }
951 
952 static int __maybe_unused virtio_can_restore(struct virtio_device *vdev)
953 {
954 	struct virtio_can_priv *priv = vdev->priv;
955 	struct net_device *ndev = priv->dev;
956 	size_t size;
957 	int err;
958 
959 	err = virtio_can_find_vqs(priv);
960 	if (err != 0)
961 		return err;
962 
963 	size = priv->rpkt_len * priv->vqs[VIRTIO_CAN_QUEUE_RX]->num_free;
964 	priv->rpkt = devm_krealloc(&vdev->dev, priv->rpkt, size, GFP_KERNEL | __GFP_ZERO);
965 	if (!priv->rpkt) {
966 		virtio_can_del_vq(vdev);
967 		return -ENOMEM;
968 	}
969 	virtio_can_populate_rx_vq(vdev);
970 
971 	if (netif_running(ndev)) {
972 		/* virtio_can_open() calls open_candev(), virtio_can_start(),
973 		 * napi_enable() and netif_start_queue(). Call it directly (not
974 		 * via dev_open()) since IFF_UP is still set from before freeze.
975 		 */
976 		err = virtio_can_open(ndev);
977 		if (err) {
978 			virtio_can_del_vq(vdev);
979 			return err;
980 		}
981 		netif_device_attach(ndev);
982 	} else {
983 		priv->can.state = CAN_STATE_STOPPED;
984 	}
985 
986 	return 0;
987 }
988 
989 static struct virtio_device_id virtio_can_id_table[] = {
990 	{ VIRTIO_ID_CAN, VIRTIO_DEV_ANY_ID },
991 	{ 0 },
992 };
993 
994 static unsigned int features[] = {
995 	VIRTIO_CAN_F_CAN_CLASSIC,
996 	VIRTIO_CAN_F_CAN_FD,
997 	VIRTIO_CAN_F_LATE_TX_ACK,
998 	VIRTIO_CAN_F_RTR_FRAMES,
999 };
1000 
1001 static struct virtio_driver virtio_can_driver = {
1002 	.feature_table = features,
1003 	.feature_table_size = ARRAY_SIZE(features),
1004 	.driver.name = KBUILD_MODNAME,
1005 	.driver.owner = THIS_MODULE,
1006 	.id_table = virtio_can_id_table,
1007 	.validate = virtio_can_validate,
1008 	.probe = virtio_can_probe,
1009 	.remove = virtio_can_remove,
1010 	.config_changed = virtio_can_config_changed,
1011 #ifdef CONFIG_PM_SLEEP
1012 	.freeze = virtio_can_freeze,
1013 	.restore = virtio_can_restore,
1014 #endif
1015 };
1016 
1017 module_virtio_driver(virtio_can_driver);
1018 MODULE_DEVICE_TABLE(virtio, virtio_can_id_table);
1019 
1020 MODULE_AUTHOR("OpenSynergy GmbH");
1021 MODULE_LICENSE("GPL");
1022 MODULE_DESCRIPTION("CAN bus driver for Virtio CAN controller");
1023