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