xref: /linux/drivers/net/tap.c (revision 2d7eaeb05ae265bd64270376e6a2c0d80244771f)
1 // SPDX-License-Identifier: GPL-2.0-only
2 #include <linux/etherdevice.h>
3 #include <linux/if_tap.h>
4 #include <linux/if_vlan.h>
5 #include <linux/interrupt.h>
6 #include <linux/nsproxy.h>
7 #include <linux/compat.h>
8 #include <linux/if_tun.h>
9 #include <linux/module.h>
10 #include <linux/skbuff.h>
11 #include <linux/cache.h>
12 #include <linux/sched/signal.h>
13 #include <linux/types.h>
14 #include <linux/slab.h>
15 #include <linux/wait.h>
16 #include <linux/cdev.h>
17 #include <linux/idr.h>
18 #include <linux/fs.h>
19 #include <linux/uio.h>
20 
21 #include <net/gso.h>
22 #include <net/net_namespace.h>
23 #include <net/rtnetlink.h>
24 #include <net/sock.h>
25 #include <net/xdp.h>
26 #include <linux/virtio_net.h>
27 #include <linux/skb_array.h>
28 
29 #include "tun_vnet.h"
30 
31 #define TAP_IFFEATURES (IFF_VNET_HDR | IFF_MULTI_QUEUE)
32 
33 static struct proto tap_proto = {
34 	.name = "tap",
35 	.owner = THIS_MODULE,
36 	.obj_size = sizeof(struct tap_queue),
37 };
38 
39 #define TAP_NUM_DEVS (1U << MINORBITS)
40 
41 static LIST_HEAD(major_list);
42 
43 struct major_info {
44 	struct rcu_head rcu;
45 	dev_t major;
46 	struct idr minor_idr;
47 	spinlock_t minor_lock;
48 	const char *device_name;
49 	struct list_head next;
50 };
51 
52 #define GOODCOPY_LEN 128
53 
54 static const struct proto_ops tap_socket_ops;
55 
56 #define RX_OFFLOADS (NETIF_F_GRO | NETIF_F_LRO)
57 #define TAP_FEATURES (NETIF_F_GSO | NETIF_F_SG | NETIF_F_FRAGLIST)
58 
59 static struct tap_dev *tap_dev_get_rcu(const struct net_device *dev)
60 {
61 	return rcu_dereference(dev->rx_handler_data);
62 }
63 
64 /*
65  * RCU usage:
66  * The tap_queue and the macvlan_dev are loosely coupled, the
67  * pointers from one to the other can only be read while rcu_read_lock
68  * or rtnl is held.
69  *
70  * Both the file and the macvlan_dev hold a reference on the tap_queue
71  * through sock_hold(&q->sk). When the macvlan_dev goes away first,
72  * q->vlan becomes inaccessible. When the files gets closed,
73  * tap_get_queue() fails.
74  *
75  * There may still be references to the struct sock inside of the
76  * queue from outbound SKBs, but these never reference back to the
77  * file or the dev. The data structure is freed through __sk_free
78  * when both our references and any pending SKBs are gone.
79  */
80 
81 static int tap_enable_queue(struct tap_dev *tap, struct file *file,
82 			    struct tap_queue *q)
83 {
84 	int err = -EINVAL;
85 
86 	ASSERT_RTNL();
87 
88 	if (q->enabled)
89 		goto out;
90 
91 	err = 0;
92 	rcu_assign_pointer(tap->taps[tap->numvtaps], q);
93 	q->queue_index = tap->numvtaps;
94 	q->enabled = true;
95 
96 	tap->numvtaps++;
97 out:
98 	return err;
99 }
100 
101 /* Requires RTNL */
102 static int tap_set_queue(struct tap_dev *tap, struct file *file,
103 			 struct tap_queue *q)
104 {
105 	if (tap->numqueues == MAX_TAP_QUEUES)
106 		return -EBUSY;
107 
108 	rcu_assign_pointer(q->tap, tap);
109 	rcu_assign_pointer(tap->taps[tap->numvtaps], q);
110 	sock_hold(&q->sk);
111 
112 	q->file = file;
113 	q->queue_index = tap->numvtaps;
114 	q->enabled = true;
115 	file->private_data = q;
116 	list_add_tail(&q->next, &tap->queue_list);
117 
118 	tap->numvtaps++;
119 	tap->numqueues++;
120 
121 	return 0;
122 }
123 
124 static int tap_disable_queue(struct tap_queue *q)
125 {
126 	struct tap_dev *tap;
127 	struct tap_queue *nq;
128 
129 	ASSERT_RTNL();
130 	if (!q->enabled)
131 		return -EINVAL;
132 
133 	tap = rtnl_dereference(q->tap);
134 
135 	if (tap) {
136 		int index = q->queue_index;
137 		BUG_ON(index >= tap->numvtaps);
138 		nq = rtnl_dereference(tap->taps[tap->numvtaps - 1]);
139 		nq->queue_index = index;
140 
141 		rcu_assign_pointer(tap->taps[index], nq);
142 		RCU_INIT_POINTER(tap->taps[tap->numvtaps - 1], NULL);
143 		q->enabled = false;
144 
145 		tap->numvtaps--;
146 	}
147 
148 	return 0;
149 }
150 
151 /*
152  * The file owning the queue got closed, give up both
153  * the reference that the files holds as well as the
154  * one from the macvlan_dev if that still exists.
155  *
156  * Using the spinlock makes sure that we don't get
157  * to the queue again after destroying it.
158  */
159 static void tap_put_queue(struct tap_queue *q)
160 {
161 	struct tap_dev *tap;
162 
163 	rtnl_lock();
164 	tap = rtnl_dereference(q->tap);
165 
166 	if (tap) {
167 		if (q->enabled)
168 			BUG_ON(tap_disable_queue(q));
169 
170 		tap->numqueues--;
171 		RCU_INIT_POINTER(q->tap, NULL);
172 		sock_put(&q->sk);
173 		list_del_init(&q->next);
174 	}
175 
176 	rtnl_unlock();
177 
178 	synchronize_rcu();
179 	sock_put(&q->sk);
180 }
181 
182 /*
183  * Select a queue based on the rxq of the device on which this packet
184  * arrived. If the incoming device is not mq, calculate a flow hash
185  * to select a queue. If all fails, find the first available queue.
186  * Cache vlan->numvtaps since it can become zero during the execution
187  * of this function.
188  */
189 static struct tap_queue *tap_get_queue(struct tap_dev *tap,
190 				       struct sk_buff *skb)
191 {
192 	struct tap_queue *queue = NULL;
193 	/* Access to taps array is protected by rcu, but access to numvtaps
194 	 * isn't. Below we use it to lookup a queue, but treat it as a hint
195 	 * and validate that the result isn't NULL - in case we are
196 	 * racing against queue removal.
197 	 */
198 	int numvtaps = READ_ONCE(tap->numvtaps);
199 	__u32 rxq;
200 
201 	if (!numvtaps)
202 		goto out;
203 
204 	if (numvtaps == 1)
205 		goto single;
206 
207 	/* Check if we can use flow to select a queue */
208 	rxq = skb_get_hash(skb);
209 	if (rxq) {
210 		queue = rcu_dereference(tap->taps[rxq % numvtaps]);
211 		goto out;
212 	}
213 
214 	if (likely(skb_rx_queue_recorded(skb))) {
215 		rxq = skb_get_rx_queue(skb);
216 
217 		while (unlikely(rxq >= numvtaps))
218 			rxq -= numvtaps;
219 
220 		queue = rcu_dereference(tap->taps[rxq]);
221 		goto out;
222 	}
223 
224 single:
225 	queue = rcu_dereference(tap->taps[0]);
226 out:
227 	return queue;
228 }
229 
230 /*
231  * The net_device is going away, give up the reference
232  * that it holds on all queues and safely set the pointer
233  * from the queues to NULL.
234  */
235 void tap_del_queues(struct tap_dev *tap)
236 {
237 	struct tap_queue *q, *tmp;
238 
239 	ASSERT_RTNL();
240 	list_for_each_entry_safe(q, tmp, &tap->queue_list, next) {
241 		list_del_init(&q->next);
242 		RCU_INIT_POINTER(q->tap, NULL);
243 		if (q->enabled)
244 			tap->numvtaps--;
245 		tap->numqueues--;
246 		sock_put(&q->sk);
247 	}
248 	BUG_ON(tap->numvtaps);
249 	BUG_ON(tap->numqueues);
250 	/* guarantee that any future tap_set_queue will fail */
251 	tap->numvtaps = MAX_TAP_QUEUES;
252 }
253 EXPORT_SYMBOL_GPL(tap_del_queues);
254 
255 rx_handler_result_t tap_handle_frame(struct sk_buff **pskb)
256 {
257 	struct sk_buff *skb = *pskb;
258 	struct net_device *dev = skb->dev;
259 	struct tap_dev *tap;
260 	struct tap_queue *q;
261 	netdev_features_t features = TAP_FEATURES;
262 	enum skb_drop_reason drop_reason;
263 
264 	tap = tap_dev_get_rcu(dev);
265 	if (!tap)
266 		return RX_HANDLER_PASS;
267 
268 	q = tap_get_queue(tap, skb);
269 	if (!q)
270 		return RX_HANDLER_PASS;
271 
272 	skb_push(skb, ETH_HLEN);
273 
274 	/* Apply the forward feature mask so that we perform segmentation
275 	 * according to users wishes.  This only works if VNET_HDR is
276 	 * enabled.
277 	 */
278 	if (q->flags & IFF_VNET_HDR)
279 		features |= tap->tap_features;
280 	if (netif_needs_gso(skb, features)) {
281 		struct sk_buff *segs;
282 		struct sk_buff *next;
283 
284 		segs = __skb_gso_segment(skb, features, false, 0);
285 		if (IS_ERR(segs)) {
286 			drop_reason = SKB_DROP_REASON_SKB_GSO_SEG;
287 			goto drop;
288 		}
289 
290 		if (!segs) {
291 			if (ptr_ring_produce(&q->ring, skb)) {
292 				drop_reason = SKB_DROP_REASON_FULL_RING;
293 				goto drop;
294 			}
295 			goto wake_up;
296 		}
297 
298 		consume_skb(skb);
299 		skb_list_walk_safe(segs, skb, next) {
300 			skb_mark_not_on_list(skb);
301 			if (ptr_ring_produce(&q->ring, skb)) {
302 				drop_reason = SKB_DROP_REASON_FULL_RING;
303 				kfree_skb_reason(skb, drop_reason);
304 				kfree_skb_list_reason(next, drop_reason);
305 				break;
306 			}
307 		}
308 	} else {
309 		/* If we receive a partial checksum and the tap side
310 		 * doesn't support checksum offload, compute the checksum.
311 		 * Note: it doesn't matter which checksum feature to
312 		 *	  check, we either support them all or none.
313 		 */
314 		if (skb->ip_summed == CHECKSUM_PARTIAL &&
315 		    !(features & NETIF_F_CSUM_MASK) &&
316 		    skb_checksum_help(skb)) {
317 			drop_reason = SKB_DROP_REASON_SKB_CSUM;
318 			goto drop;
319 		}
320 		if (ptr_ring_produce(&q->ring, skb)) {
321 			drop_reason = SKB_DROP_REASON_FULL_RING;
322 			goto drop;
323 		}
324 	}
325 
326 wake_up:
327 	wake_up_interruptible_poll(sk_sleep(&q->sk), EPOLLIN | EPOLLRDNORM | EPOLLRDBAND);
328 	return RX_HANDLER_CONSUMED;
329 
330 drop:
331 	/* Count errors/drops only here, thus don't care about args. */
332 	if (tap->count_rx_dropped)
333 		tap->count_rx_dropped(tap);
334 	kfree_skb_reason(skb, drop_reason);
335 	return RX_HANDLER_CONSUMED;
336 }
337 EXPORT_SYMBOL_GPL(tap_handle_frame);
338 
339 static struct major_info *tap_get_major(int major)
340 {
341 	struct major_info *tap_major;
342 
343 	list_for_each_entry_rcu(tap_major, &major_list, next) {
344 		if (tap_major->major == major)
345 			return tap_major;
346 	}
347 
348 	return NULL;
349 }
350 
351 int tap_get_minor(dev_t major, struct tap_dev *tap)
352 {
353 	int retval = -ENOMEM;
354 	struct major_info *tap_major;
355 
356 	rcu_read_lock();
357 	tap_major = tap_get_major(MAJOR(major));
358 	if (!tap_major) {
359 		retval = -EINVAL;
360 		goto unlock;
361 	}
362 
363 	spin_lock(&tap_major->minor_lock);
364 	retval = idr_alloc(&tap_major->minor_idr, tap, 1, TAP_NUM_DEVS, GFP_ATOMIC);
365 	if (retval >= 0) {
366 		tap->minor = retval;
367 	} else if (retval == -ENOSPC) {
368 		netdev_err(tap->dev, "Too many tap devices\n");
369 		retval = -EINVAL;
370 	}
371 	spin_unlock(&tap_major->minor_lock);
372 
373 unlock:
374 	rcu_read_unlock();
375 	return retval < 0 ? retval : 0;
376 }
377 EXPORT_SYMBOL_GPL(tap_get_minor);
378 
379 void tap_free_minor(dev_t major, struct tap_dev *tap)
380 {
381 	struct major_info *tap_major;
382 
383 	rcu_read_lock();
384 	tap_major = tap_get_major(MAJOR(major));
385 	if (!tap_major) {
386 		goto unlock;
387 	}
388 
389 	spin_lock(&tap_major->minor_lock);
390 	if (tap->minor) {
391 		idr_remove(&tap_major->minor_idr, tap->minor);
392 		tap->minor = 0;
393 	}
394 	spin_unlock(&tap_major->minor_lock);
395 
396 unlock:
397 	rcu_read_unlock();
398 }
399 EXPORT_SYMBOL_GPL(tap_free_minor);
400 
401 static struct tap_dev *dev_get_by_tap_file(int major, int minor)
402 {
403 	struct net_device *dev = NULL;
404 	struct tap_dev *tap;
405 	struct major_info *tap_major;
406 
407 	rcu_read_lock();
408 	tap_major = tap_get_major(major);
409 	if (!tap_major) {
410 		tap = NULL;
411 		goto unlock;
412 	}
413 
414 	spin_lock(&tap_major->minor_lock);
415 	tap = idr_find(&tap_major->minor_idr, minor);
416 	if (tap) {
417 		dev = tap->dev;
418 		dev_hold(dev);
419 	}
420 	spin_unlock(&tap_major->minor_lock);
421 
422 unlock:
423 	rcu_read_unlock();
424 	return tap;
425 }
426 
427 static void tap_sock_write_space(struct sock *sk)
428 {
429 	wait_queue_head_t *wqueue;
430 
431 	if (!sock_writeable(sk) ||
432 	    !test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &sk->sk_socket->flags))
433 		return;
434 
435 	wqueue = sk_sleep(sk);
436 	if (wqueue && waitqueue_active(wqueue))
437 		wake_up_interruptible_poll(wqueue, EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND);
438 }
439 
440 static void tap_sock_destruct(struct sock *sk)
441 {
442 	struct tap_queue *q = container_of(sk, struct tap_queue, sk);
443 
444 	ptr_ring_cleanup(&q->ring, __skb_array_destroy_skb);
445 }
446 
447 static int tap_open(struct inode *inode, struct file *file)
448 {
449 	struct net *net = current->nsproxy->net_ns;
450 	struct tap_dev *tap;
451 	struct tap_queue *q;
452 	int err = -ENODEV;
453 
454 	rtnl_lock();
455 	tap = dev_get_by_tap_file(imajor(inode), iminor(inode));
456 	if (!tap)
457 		goto err;
458 
459 	err = -ENOMEM;
460 	q = (struct tap_queue *)sk_alloc(net, AF_UNSPEC, GFP_KERNEL,
461 					     &tap_proto, 0);
462 	if (!q)
463 		goto err;
464 	if (ptr_ring_init(&q->ring, tap->dev->tx_queue_len, GFP_KERNEL)) {
465 		sk_free(&q->sk);
466 		goto err;
467 	}
468 
469 	init_waitqueue_head(&q->sock.wq.wait);
470 	q->sock.type = SOCK_RAW;
471 	q->sock.state = SS_CONNECTED;
472 	q->sock.file = file;
473 	q->sock.ops = &tap_socket_ops;
474 	sock_init_data_uid(&q->sock, &q->sk, current_fsuid());
475 	q->sk.sk_write_space = tap_sock_write_space;
476 	q->sk.sk_destruct = tap_sock_destruct;
477 	q->flags = IFF_VNET_HDR | IFF_NO_PI | IFF_TAP;
478 	q->vnet_hdr_sz = sizeof(struct virtio_net_hdr);
479 
480 	/*
481 	 * so far only KVM virtio_net uses tap, enable zero copy between
482 	 * guest kernel and host kernel when lower device supports zerocopy
483 	 *
484 	 * The macvlan supports zerocopy iff the lower device supports zero
485 	 * copy so we don't have to look at the lower device directly.
486 	 */
487 	if ((tap->dev->features & NETIF_F_HIGHDMA) && (tap->dev->features & NETIF_F_SG))
488 		sock_set_flag(&q->sk, SOCK_ZEROCOPY);
489 
490 	err = tap_set_queue(tap, file, q);
491 	if (err) {
492 		/* tap_sock_destruct() will take care of freeing ptr_ring */
493 		goto err_put;
494 	}
495 
496 	/* tap groks IOCB_NOWAIT just fine, mark it as such */
497 	file->f_mode |= FMODE_NOWAIT;
498 
499 	dev_put(tap->dev);
500 
501 	rtnl_unlock();
502 	return err;
503 
504 err_put:
505 	sock_put(&q->sk);
506 err:
507 	if (tap)
508 		dev_put(tap->dev);
509 
510 	rtnl_unlock();
511 	return err;
512 }
513 
514 static int tap_release(struct inode *inode, struct file *file)
515 {
516 	struct tap_queue *q = file->private_data;
517 	tap_put_queue(q);
518 	return 0;
519 }
520 
521 static __poll_t tap_poll(struct file *file, poll_table *wait)
522 {
523 	struct tap_queue *q = file->private_data;
524 	__poll_t mask = EPOLLERR;
525 
526 	if (!q)
527 		goto out;
528 
529 	mask = 0;
530 	poll_wait(file, &q->sock.wq.wait, wait);
531 
532 	if (!ptr_ring_empty(&q->ring))
533 		mask |= EPOLLIN | EPOLLRDNORM;
534 
535 	if (sock_writeable(&q->sk) ||
536 	    (!test_and_set_bit(SOCKWQ_ASYNC_NOSPACE, &q->sock.flags) &&
537 	     sock_writeable(&q->sk)))
538 		mask |= EPOLLOUT | EPOLLWRNORM;
539 
540 out:
541 	return mask;
542 }
543 
544 static inline struct sk_buff *tap_alloc_skb(struct sock *sk, size_t prepad,
545 					    size_t len, size_t linear,
546 						int noblock, int *err)
547 {
548 	struct sk_buff *skb;
549 
550 	/* Under a page?  Don't bother with paged skb. */
551 	if (prepad + len < PAGE_SIZE || !linear)
552 		linear = len;
553 
554 	if (len - linear > MAX_SKB_FRAGS * (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER))
555 		linear = len - MAX_SKB_FRAGS * (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER);
556 	skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
557 				   err, PAGE_ALLOC_COSTLY_ORDER);
558 	if (!skb)
559 		return NULL;
560 
561 	skb_reserve(skb, prepad);
562 	skb_put(skb, linear);
563 	skb->data_len = len - linear;
564 	skb->len += len - linear;
565 
566 	return skb;
567 }
568 
569 /* Neighbour code has some assumptions on HH_DATA_MOD alignment */
570 #define TAP_RESERVE HH_DATA_OFF(ETH_HLEN)
571 
572 /* Get packet from user space buffer */
573 static ssize_t tap_get_user(struct tap_queue *q, void *msg_control,
574 			    struct iov_iter *from, int noblock)
575 {
576 	int good_linear = SKB_MAX_HEAD(TAP_RESERVE);
577 	struct sk_buff *skb;
578 	struct tap_dev *tap;
579 	unsigned long total_len = iov_iter_count(from);
580 	unsigned long len = total_len;
581 	int err;
582 	struct virtio_net_hdr vnet_hdr = { 0 };
583 	int vnet_hdr_len = 0;
584 	int hdr_len = 0;
585 	int copylen = 0;
586 	int depth;
587 	bool zerocopy = false;
588 	size_t linear;
589 	enum skb_drop_reason drop_reason;
590 
591 	if (q->flags & IFF_VNET_HDR) {
592 		vnet_hdr_len = READ_ONCE(q->vnet_hdr_sz);
593 
594 		hdr_len = tun_vnet_hdr_get(vnet_hdr_len, q->flags, from, &vnet_hdr);
595 		if (hdr_len < 0) {
596 			err = hdr_len;
597 			goto err;
598 		}
599 
600 		len -= vnet_hdr_len;
601 	}
602 
603 	err = -EINVAL;
604 	if (unlikely(len < ETH_HLEN))
605 		goto err;
606 
607 	if (msg_control && sock_flag(&q->sk, SOCK_ZEROCOPY)) {
608 		struct iov_iter i;
609 
610 		copylen = clamp(hdr_len ?: GOODCOPY_LEN, ETH_HLEN, good_linear);
611 		linear = copylen;
612 		i = *from;
613 		iov_iter_advance(&i, copylen);
614 		if (iov_iter_npages(&i, INT_MAX) <= MAX_SKB_FRAGS)
615 			zerocopy = true;
616 	}
617 
618 	if (!zerocopy) {
619 		copylen = len;
620 		linear = clamp(hdr_len, ETH_HLEN, good_linear);
621 	}
622 
623 	skb = tap_alloc_skb(&q->sk, TAP_RESERVE, copylen,
624 			    linear, noblock, &err);
625 	if (!skb)
626 		goto err;
627 
628 	if (zerocopy)
629 		err = zerocopy_sg_from_iter(skb, from);
630 	else
631 		err = skb_copy_datagram_from_iter(skb, 0, from, len);
632 
633 	if (err) {
634 		drop_reason = SKB_DROP_REASON_SKB_UCOPY_FAULT;
635 		goto err_kfree;
636 	}
637 
638 	skb_set_network_header(skb, ETH_HLEN);
639 	skb_reset_mac_header(skb);
640 	skb->protocol = eth_hdr(skb)->h_proto;
641 
642 	rcu_read_lock();
643 	tap = rcu_dereference(q->tap);
644 	if (!tap) {
645 		kfree_skb(skb);
646 		rcu_read_unlock();
647 		return total_len;
648 	}
649 	skb->dev = tap->dev;
650 
651 	if (vnet_hdr_len) {
652 		err = tun_vnet_hdr_to_skb(q->flags, skb, &vnet_hdr);
653 		if (err) {
654 			rcu_read_unlock();
655 			drop_reason = SKB_DROP_REASON_DEV_HDR;
656 			goto err_kfree;
657 		}
658 	}
659 
660 	skb_probe_transport_header(skb);
661 
662 	/* Move network header to the right position for VLAN tagged packets */
663 	if (eth_type_vlan(skb->protocol) &&
664 	    vlan_get_protocol_and_depth(skb, skb->protocol, &depth) != 0)
665 		skb_set_network_header(skb, depth);
666 
667 	/* copy skb_ubuf_info for callback when skb has no error */
668 	if (zerocopy) {
669 		skb_zcopy_init(skb, msg_control);
670 	} else if (msg_control) {
671 		struct ubuf_info *uarg = msg_control;
672 		uarg->ops->complete(NULL, uarg, false);
673 	}
674 
675 	dev_queue_xmit(skb);
676 	rcu_read_unlock();
677 	return total_len;
678 
679 err_kfree:
680 	kfree_skb_reason(skb, drop_reason);
681 
682 err:
683 	rcu_read_lock();
684 	tap = rcu_dereference(q->tap);
685 	if (tap && tap->count_tx_dropped)
686 		tap->count_tx_dropped(tap);
687 	rcu_read_unlock();
688 
689 	return err;
690 }
691 
692 static ssize_t tap_write_iter(struct kiocb *iocb, struct iov_iter *from)
693 {
694 	struct file *file = iocb->ki_filp;
695 	struct tap_queue *q = file->private_data;
696 	int noblock = 0;
697 
698 	if ((file->f_flags & O_NONBLOCK) || (iocb->ki_flags & IOCB_NOWAIT))
699 		noblock = 1;
700 
701 	return tap_get_user(q, NULL, from, noblock);
702 }
703 
704 /* Put packet to the user space buffer */
705 static ssize_t tap_put_user(struct tap_queue *q,
706 			    const struct sk_buff *skb,
707 			    struct iov_iter *iter)
708 {
709 	int ret;
710 	int vnet_hdr_len = 0;
711 	int vlan_offset = 0;
712 	int total;
713 
714 	if (q->flags & IFF_VNET_HDR) {
715 		struct virtio_net_hdr vnet_hdr;
716 
717 		vnet_hdr_len = READ_ONCE(q->vnet_hdr_sz);
718 
719 		ret = tun_vnet_hdr_from_skb(q->flags, NULL, skb, &vnet_hdr);
720 		if (ret)
721 			return ret;
722 
723 		ret = tun_vnet_hdr_put(vnet_hdr_len, iter, &vnet_hdr);
724 		if (ret)
725 			return ret;
726 	}
727 	total = vnet_hdr_len;
728 	total += skb->len;
729 
730 	if (skb_vlan_tag_present(skb)) {
731 		struct {
732 			__be16 h_vlan_proto;
733 			__be16 h_vlan_TCI;
734 		} veth;
735 		veth.h_vlan_proto = skb->vlan_proto;
736 		veth.h_vlan_TCI = htons(skb_vlan_tag_get(skb));
737 
738 		vlan_offset = offsetof(struct vlan_ethhdr, h_vlan_proto);
739 		total += VLAN_HLEN;
740 
741 		ret = skb_copy_datagram_iter(skb, 0, iter, vlan_offset);
742 		if (ret || !iov_iter_count(iter))
743 			goto done;
744 
745 		ret = copy_to_iter(&veth, sizeof(veth), iter);
746 		if (ret != sizeof(veth) || !iov_iter_count(iter))
747 			goto done;
748 	}
749 
750 	ret = skb_copy_datagram_iter(skb, vlan_offset, iter,
751 				     skb->len - vlan_offset);
752 
753 done:
754 	return ret ? ret : total;
755 }
756 
757 static ssize_t tap_do_read(struct tap_queue *q,
758 			   struct iov_iter *to,
759 			   int noblock, struct sk_buff *skb)
760 {
761 	DEFINE_WAIT(wait);
762 	ssize_t ret = 0;
763 
764 	if (!iov_iter_count(to)) {
765 		kfree_skb(skb);
766 		return 0;
767 	}
768 
769 	if (skb)
770 		goto put;
771 
772 	while (1) {
773 		if (!noblock)
774 			prepare_to_wait(sk_sleep(&q->sk), &wait,
775 					TASK_INTERRUPTIBLE);
776 
777 		/* Read frames from the queue */
778 		skb = ptr_ring_consume(&q->ring);
779 		if (skb)
780 			break;
781 		if (noblock) {
782 			ret = -EAGAIN;
783 			break;
784 		}
785 		if (signal_pending(current)) {
786 			ret = -ERESTARTSYS;
787 			break;
788 		}
789 		/* Nothing to read, let's sleep */
790 		schedule();
791 	}
792 	if (!noblock)
793 		finish_wait(sk_sleep(&q->sk), &wait);
794 
795 put:
796 	if (skb) {
797 		ret = tap_put_user(q, skb, to);
798 		if (unlikely(ret < 0))
799 			kfree_skb(skb);
800 		else
801 			consume_skb(skb);
802 	}
803 	return ret;
804 }
805 
806 static ssize_t tap_read_iter(struct kiocb *iocb, struct iov_iter *to)
807 {
808 	struct file *file = iocb->ki_filp;
809 	struct tap_queue *q = file->private_data;
810 	ssize_t len = iov_iter_count(to), ret;
811 	int noblock = 0;
812 
813 	if ((file->f_flags & O_NONBLOCK) || (iocb->ki_flags & IOCB_NOWAIT))
814 		noblock = 1;
815 
816 	ret = tap_do_read(q, to, noblock, NULL);
817 	ret = min_t(ssize_t, ret, len);
818 	if (ret > 0)
819 		iocb->ki_pos = ret;
820 	return ret;
821 }
822 
823 static struct tap_dev *tap_get_tap_dev(struct tap_queue *q)
824 {
825 	struct tap_dev *tap;
826 
827 	ASSERT_RTNL();
828 	tap = rtnl_dereference(q->tap);
829 	if (tap)
830 		dev_hold(tap->dev);
831 
832 	return tap;
833 }
834 
835 static void tap_put_tap_dev(struct tap_dev *tap)
836 {
837 	dev_put(tap->dev);
838 }
839 
840 static int tap_ioctl_set_queue(struct file *file, unsigned int flags)
841 {
842 	struct tap_queue *q = file->private_data;
843 	struct tap_dev *tap;
844 	int ret;
845 
846 	tap = tap_get_tap_dev(q);
847 	if (!tap)
848 		return -EINVAL;
849 
850 	if (flags & IFF_ATTACH_QUEUE)
851 		ret = tap_enable_queue(tap, file, q);
852 	else if (flags & IFF_DETACH_QUEUE)
853 		ret = tap_disable_queue(q);
854 	else
855 		ret = -EINVAL;
856 
857 	tap_put_tap_dev(tap);
858 	return ret;
859 }
860 
861 static int set_offload(struct tap_queue *q, unsigned long arg)
862 {
863 	struct tap_dev *tap;
864 	netdev_features_t features;
865 	netdev_features_t feature_mask = 0;
866 
867 	tap = rtnl_dereference(q->tap);
868 	if (!tap)
869 		return -ENOLINK;
870 
871 	features = tap->dev->features;
872 
873 	if (arg & TUN_F_CSUM) {
874 		feature_mask = NETIF_F_HW_CSUM;
875 
876 		if (arg & (TUN_F_TSO4 | TUN_F_TSO6)) {
877 			if (arg & TUN_F_TSO_ECN)
878 				feature_mask |= NETIF_F_TSO_ECN;
879 			if (arg & TUN_F_TSO4)
880 				feature_mask |= NETIF_F_TSO;
881 			if (arg & TUN_F_TSO6)
882 				feature_mask |= NETIF_F_TSO6;
883 		}
884 
885 		/* TODO: for now USO4 and USO6 should work simultaneously */
886 		if ((arg & (TUN_F_USO4 | TUN_F_USO6)) == (TUN_F_USO4 | TUN_F_USO6))
887 			feature_mask |= NETIF_F_GSO_UDP_L4;
888 	}
889 
890 	/* tun/tap driver inverts the usage for TSO offloads, where
891 	 * setting the TSO bit means that the userspace wants to
892 	 * accept TSO frames and turning it off means that user space
893 	 * does not support TSO.
894 	 * For tap, we have to invert it to mean the same thing.
895 	 * When user space turns off TSO, we turn off GSO/LRO so that
896 	 * user-space will not receive TSO frames.
897 	 */
898 	if (feature_mask & (NETIF_F_TSO | NETIF_F_TSO6 | NETIF_F_GSO_UDP_L4))
899 		features |= RX_OFFLOADS;
900 	else
901 		features &= ~RX_OFFLOADS;
902 
903 	/* tap_features are the same as features on tun/tap and
904 	 * reflect user expectations.
905 	 */
906 	tap->tap_features = feature_mask;
907 	if (tap->update_features)
908 		tap->update_features(tap, features);
909 
910 	return 0;
911 }
912 
913 /*
914  * provide compatibility with generic tun/tap interface
915  */
916 static long tap_ioctl(struct file *file, unsigned int cmd,
917 		      unsigned long arg)
918 {
919 	struct tap_queue *q = file->private_data;
920 	struct tap_dev *tap;
921 	void __user *argp = (void __user *)arg;
922 	struct sockaddr_storage ss = {};
923 	struct ifreq __user *ifr = argp;
924 	unsigned int __user *up = argp;
925 	unsigned short u;
926 	int __user *sp = argp;
927 	int s;
928 	int ret;
929 
930 	switch (cmd) {
931 	case TUNSETIFF:
932 		/* ignore the name, just look at flags */
933 		if (get_user(u, &ifr->ifr_flags))
934 			return -EFAULT;
935 
936 		/* TUNGETIFF may report IFF_DETACH_QUEUE, ignore it here */
937 		u &= ~IFF_DETACH_QUEUE;
938 
939 		ret = 0;
940 		if ((u & ~TAP_IFFEATURES) != (IFF_NO_PI | IFF_TAP))
941 			ret = -EINVAL;
942 		else
943 			q->flags = (q->flags & ~TAP_IFFEATURES) | u;
944 
945 		return ret;
946 
947 	case TUNGETIFF:
948 		rtnl_lock();
949 		tap = tap_get_tap_dev(q);
950 		if (!tap) {
951 			rtnl_unlock();
952 			return -ENOLINK;
953 		}
954 
955 		ret = 0;
956 		u = q->flags;
957 		if (!q->enabled)
958 			u |= IFF_DETACH_QUEUE;
959 		if (copy_to_user(&ifr->ifr_name, tap->dev->name, IFNAMSIZ) ||
960 		    put_user(u, &ifr->ifr_flags))
961 			ret = -EFAULT;
962 		tap_put_tap_dev(tap);
963 		rtnl_unlock();
964 		return ret;
965 
966 	case TUNSETQUEUE:
967 		if (get_user(u, &ifr->ifr_flags))
968 			return -EFAULT;
969 		rtnl_lock();
970 		ret = tap_ioctl_set_queue(file, u);
971 		rtnl_unlock();
972 		return ret;
973 
974 	case TUNGETFEATURES:
975 		if (put_user(IFF_TAP | IFF_NO_PI | TAP_IFFEATURES, up))
976 			return -EFAULT;
977 		return 0;
978 
979 	case TUNSETSNDBUF:
980 		if (get_user(s, sp))
981 			return -EFAULT;
982 		if (s <= 0)
983 			return -EINVAL;
984 
985 		q->sk.sk_sndbuf = s;
986 		return 0;
987 
988 	case TUNSETOFFLOAD:
989 		/* let the user check for future flags */
990 		if (arg & ~(TUN_F_CSUM | TUN_F_TSO4 | TUN_F_TSO6 |
991 			    TUN_F_TSO_ECN | TUN_F_UFO |
992 			    TUN_F_USO4 | TUN_F_USO6))
993 			return -EINVAL;
994 
995 		rtnl_lock();
996 		ret = set_offload(q, arg);
997 		rtnl_unlock();
998 		return ret;
999 
1000 	case SIOCGIFHWADDR:
1001 		rtnl_lock();
1002 		tap = tap_get_tap_dev(q);
1003 		if (!tap) {
1004 			rtnl_unlock();
1005 			return -ENOLINK;
1006 		}
1007 		ret = 0;
1008 		netif_get_mac_address((struct sockaddr *)&ss, dev_net(tap->dev),
1009 				      tap->dev->name);
1010 		if (copy_to_user(&ifr->ifr_name, tap->dev->name, IFNAMSIZ) ||
1011 		    copy_to_user(&ifr->ifr_hwaddr, &ss, sizeof(ifr->ifr_hwaddr)))
1012 			ret = -EFAULT;
1013 		tap_put_tap_dev(tap);
1014 		rtnl_unlock();
1015 		return ret;
1016 
1017 	case SIOCSIFHWADDR:
1018 		if (copy_from_user(&ss, &ifr->ifr_hwaddr, sizeof(ifr->ifr_hwaddr)))
1019 			return -EFAULT;
1020 		rtnl_lock();
1021 		tap = tap_get_tap_dev(q);
1022 		if (!tap) {
1023 			rtnl_unlock();
1024 			return -ENOLINK;
1025 		}
1026 		if (tap->dev->addr_len > sizeof(ifr->ifr_hwaddr))
1027 			ret = -EINVAL;
1028 		else
1029 			ret = dev_set_mac_address_user(tap->dev, &ss, NULL);
1030 		tap_put_tap_dev(tap);
1031 		rtnl_unlock();
1032 		return ret;
1033 
1034 	default:
1035 		return tun_vnet_ioctl(&q->vnet_hdr_sz, &q->flags, cmd, sp);
1036 	}
1037 }
1038 
1039 static const struct file_operations tap_fops = {
1040 	.owner		= THIS_MODULE,
1041 	.open		= tap_open,
1042 	.release	= tap_release,
1043 	.read_iter	= tap_read_iter,
1044 	.write_iter	= tap_write_iter,
1045 	.poll		= tap_poll,
1046 	.unlocked_ioctl	= tap_ioctl,
1047 	.compat_ioctl	= compat_ptr_ioctl,
1048 };
1049 
1050 static int tap_get_user_xdp(struct tap_queue *q, struct xdp_buff *xdp)
1051 {
1052 	struct virtio_net_hdr *gso = xdp->data_hard_start;
1053 	int buflen = xdp->frame_sz;
1054 	int vnet_hdr_len = 0;
1055 	struct tap_dev *tap;
1056 	struct sk_buff *skb;
1057 	int err, depth;
1058 
1059 	if (unlikely(xdp->data_end - xdp->data < ETH_HLEN)) {
1060 		put_page(virt_to_head_page(xdp->data));
1061 		err = -EINVAL;
1062 		goto err;
1063 	}
1064 
1065 	if (q->flags & IFF_VNET_HDR)
1066 		vnet_hdr_len = READ_ONCE(q->vnet_hdr_sz);
1067 
1068 	skb = build_skb(xdp->data_hard_start, buflen);
1069 	if (!skb) {
1070 		put_page(virt_to_head_page(xdp->data));
1071 		err = -ENOMEM;
1072 		goto err;
1073 	}
1074 
1075 	skb_reserve(skb, xdp->data - xdp->data_hard_start);
1076 	skb_put(skb, xdp->data_end - xdp->data);
1077 
1078 	skb_set_network_header(skb, ETH_HLEN);
1079 	skb_reset_mac_header(skb);
1080 	skb->protocol = eth_hdr(skb)->h_proto;
1081 
1082 	rcu_read_lock();
1083 	tap = rcu_dereference(q->tap);
1084 	if (!tap) {
1085 		kfree_skb(skb);
1086 		rcu_read_unlock();
1087 		return 0;
1088 	}
1089 	skb->dev = tap->dev;
1090 
1091 	if (vnet_hdr_len) {
1092 		err = tun_vnet_hdr_to_skb(q->flags, skb, gso);
1093 		if (err) {
1094 			rcu_read_unlock();
1095 			goto err_kfree;
1096 		}
1097 	}
1098 
1099 	skb_probe_transport_header(skb);
1100 
1101 	/* Move network header to the right position for VLAN tagged packets */
1102 	if (eth_type_vlan(skb->protocol) &&
1103 	    vlan_get_protocol_and_depth(skb, skb->protocol, &depth) != 0)
1104 		skb_set_network_header(skb, depth);
1105 
1106 	dev_queue_xmit(skb);
1107 	rcu_read_unlock();
1108 
1109 	return 0;
1110 
1111 err_kfree:
1112 	kfree_skb(skb);
1113 err:
1114 	rcu_read_lock();
1115 	tap = rcu_dereference(q->tap);
1116 	if (tap && tap->count_tx_dropped)
1117 		tap->count_tx_dropped(tap);
1118 	rcu_read_unlock();
1119 	return err;
1120 }
1121 
1122 static int tap_sendmsg(struct socket *sock, struct msghdr *m,
1123 		       size_t total_len)
1124 {
1125 	struct tap_queue *q = container_of(sock, struct tap_queue, sock);
1126 	struct tun_msg_ctl *ctl = m->msg_control;
1127 	struct xdp_buff *xdp;
1128 	int i;
1129 
1130 	if (m->msg_controllen == sizeof(struct tun_msg_ctl) &&
1131 	    ctl && ctl->type == TUN_MSG_PTR) {
1132 		for (i = 0; i < ctl->num; i++) {
1133 			xdp = &((struct xdp_buff *)ctl->ptr)[i];
1134 			tap_get_user_xdp(q, xdp);
1135 		}
1136 		return 0;
1137 	}
1138 
1139 	return tap_get_user(q, ctl ? ctl->ptr : NULL, &m->msg_iter,
1140 			    m->msg_flags & MSG_DONTWAIT);
1141 }
1142 
1143 static int tap_recvmsg(struct socket *sock, struct msghdr *m,
1144 		       size_t total_len, int flags)
1145 {
1146 	struct tap_queue *q = container_of(sock, struct tap_queue, sock);
1147 	struct sk_buff *skb = m->msg_control;
1148 	int ret;
1149 	if (flags & ~(MSG_DONTWAIT|MSG_TRUNC)) {
1150 		kfree_skb(skb);
1151 		return -EINVAL;
1152 	}
1153 	ret = tap_do_read(q, &m->msg_iter, flags & MSG_DONTWAIT, skb);
1154 	if (ret > total_len) {
1155 		m->msg_flags |= MSG_TRUNC;
1156 		ret = flags & MSG_TRUNC ? ret : total_len;
1157 	}
1158 	return ret;
1159 }
1160 
1161 static int tap_peek_len(struct socket *sock)
1162 {
1163 	struct tap_queue *q = container_of(sock, struct tap_queue,
1164 					       sock);
1165 	return PTR_RING_PEEK_CALL(&q->ring, __skb_array_len_with_tag);
1166 }
1167 
1168 /* Ops structure to mimic raw sockets with tun */
1169 static const struct proto_ops tap_socket_ops = {
1170 	.sendmsg = tap_sendmsg,
1171 	.recvmsg = tap_recvmsg,
1172 	.peek_len = tap_peek_len,
1173 };
1174 
1175 /* Get an underlying socket object from tun file.  Returns error unless file is
1176  * attached to a device.  The returned object works like a packet socket, it
1177  * can be used for sock_sendmsg/sock_recvmsg.  The caller is responsible for
1178  * holding a reference to the file for as long as the socket is in use. */
1179 struct socket *tap_get_socket(struct file *file)
1180 {
1181 	struct tap_queue *q;
1182 	if (file->f_op != &tap_fops)
1183 		return ERR_PTR(-EINVAL);
1184 	q = file->private_data;
1185 	if (!q)
1186 		return ERR_PTR(-EBADFD);
1187 	return &q->sock;
1188 }
1189 EXPORT_SYMBOL_GPL(tap_get_socket);
1190 
1191 struct ptr_ring *tap_get_ptr_ring(struct file *file)
1192 {
1193 	struct tap_queue *q;
1194 
1195 	if (file->f_op != &tap_fops)
1196 		return ERR_PTR(-EINVAL);
1197 	q = file->private_data;
1198 	if (!q)
1199 		return ERR_PTR(-EBADFD);
1200 	return &q->ring;
1201 }
1202 EXPORT_SYMBOL_GPL(tap_get_ptr_ring);
1203 
1204 int tap_queue_resize(struct tap_dev *tap)
1205 {
1206 	struct net_device *dev = tap->dev;
1207 	struct tap_queue *q;
1208 	struct ptr_ring **rings;
1209 	int n = tap->numqueues;
1210 	int ret, i = 0;
1211 
1212 	rings = kmalloc_objs(*rings, n);
1213 	if (!rings)
1214 		return -ENOMEM;
1215 
1216 	list_for_each_entry(q, &tap->queue_list, next)
1217 		rings[i++] = &q->ring;
1218 
1219 	ret = ptr_ring_resize_multiple_bh(rings, n,
1220 					  dev->tx_queue_len, GFP_KERNEL,
1221 					  __skb_array_destroy_skb);
1222 
1223 	kfree(rings);
1224 	return ret;
1225 }
1226 EXPORT_SYMBOL_GPL(tap_queue_resize);
1227 
1228 static int tap_list_add(dev_t major, const char *device_name)
1229 {
1230 	struct major_info *tap_major;
1231 
1232 	tap_major = kzalloc_obj(*tap_major, GFP_ATOMIC);
1233 	if (!tap_major)
1234 		return -ENOMEM;
1235 
1236 	tap_major->major = MAJOR(major);
1237 
1238 	idr_init(&tap_major->minor_idr);
1239 	spin_lock_init(&tap_major->minor_lock);
1240 
1241 	tap_major->device_name = device_name;
1242 
1243 	list_add_tail_rcu(&tap_major->next, &major_list);
1244 	return 0;
1245 }
1246 
1247 int tap_create_cdev(struct cdev *tap_cdev, dev_t *tap_major,
1248 		    const char *device_name, struct module *module)
1249 {
1250 	int err;
1251 
1252 	err = alloc_chrdev_region(tap_major, 0, TAP_NUM_DEVS, device_name);
1253 	if (err)
1254 		goto out1;
1255 
1256 	cdev_init(tap_cdev, &tap_fops);
1257 	tap_cdev->owner = module;
1258 	err = cdev_add(tap_cdev, *tap_major, TAP_NUM_DEVS);
1259 	if (err)
1260 		goto out2;
1261 
1262 	err =  tap_list_add(*tap_major, device_name);
1263 	if (err)
1264 		goto out3;
1265 
1266 	return 0;
1267 
1268 out3:
1269 	cdev_del(tap_cdev);
1270 out2:
1271 	unregister_chrdev_region(*tap_major, TAP_NUM_DEVS);
1272 out1:
1273 	return err;
1274 }
1275 EXPORT_SYMBOL_GPL(tap_create_cdev);
1276 
1277 void tap_destroy_cdev(dev_t major, struct cdev *tap_cdev)
1278 {
1279 	struct major_info *tap_major, *tmp;
1280 
1281 	cdev_del(tap_cdev);
1282 	unregister_chrdev_region(major, TAP_NUM_DEVS);
1283 	list_for_each_entry_safe(tap_major, tmp, &major_list, next) {
1284 		if (tap_major->major == MAJOR(major)) {
1285 			idr_destroy(&tap_major->minor_idr);
1286 			list_del_rcu(&tap_major->next);
1287 			kfree_rcu(tap_major, rcu);
1288 		}
1289 	}
1290 }
1291 EXPORT_SYMBOL_GPL(tap_destroy_cdev);
1292 
1293 MODULE_DESCRIPTION("Common library for drivers implementing the TAP interface");
1294 MODULE_AUTHOR("Arnd Bergmann <arnd@arndb.de>");
1295 MODULE_AUTHOR("Sainath Grandhi <sainath.grandhi@intel.com>");
1296 MODULE_LICENSE("GPL");
1297 MODULE_IMPORT_NS("NETDEV_INTERNAL");
1298