xref: /linux/net/packet/af_packet.c (revision 7f71507851fc7764b36a3221839607d3a45c2025)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * INET		An implementation of the TCP/IP protocol suite for the LINUX
4  *		operating system.  INET is implemented using the  BSD Socket
5  *		interface as the means of communication with the user level.
6  *
7  *		PACKET - implements raw packet sockets.
8  *
9  * Authors:	Ross Biro
10  *		Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
11  *		Alan Cox, <gw4pts@gw4pts.ampr.org>
12  *
13  * Fixes:
14  *		Alan Cox	:	verify_area() now used correctly
15  *		Alan Cox	:	new skbuff lists, look ma no backlogs!
16  *		Alan Cox	:	tidied skbuff lists.
17  *		Alan Cox	:	Now uses generic datagram routines I
18  *					added. Also fixed the peek/read crash
19  *					from all old Linux datagram code.
20  *		Alan Cox	:	Uses the improved datagram code.
21  *		Alan Cox	:	Added NULL's for socket options.
22  *		Alan Cox	:	Re-commented the code.
23  *		Alan Cox	:	Use new kernel side addressing
24  *		Rob Janssen	:	Correct MTU usage.
25  *		Dave Platt	:	Counter leaks caused by incorrect
26  *					interrupt locking and some slightly
27  *					dubious gcc output. Can you read
28  *					compiler: it said _VOLATILE_
29  *	Richard Kooijman	:	Timestamp fixes.
30  *		Alan Cox	:	New buffers. Use sk->mac.raw.
31  *		Alan Cox	:	sendmsg/recvmsg support.
32  *		Alan Cox	:	Protocol setting support
33  *	Alexey Kuznetsov	:	Untied from IPv4 stack.
34  *	Cyrus Durgin		:	Fixed kerneld for kmod.
35  *	Michal Ostrowski        :       Module initialization cleanup.
36  *         Ulises Alonso        :       Frame number limit removal and
37  *                                      packet_set_ring memory leak.
38  *		Eric Biederman	:	Allow for > 8 byte hardware addresses.
39  *					The convention is that longer addresses
40  *					will simply extend the hardware address
41  *					byte arrays at the end of sockaddr_ll
42  *					and packet_mreq.
43  *		Johann Baudy	:	Added TX RING.
44  *		Chetan Loke	:	Implemented TPACKET_V3 block abstraction
45  *					layer.
46  *					Copyright (C) 2011, <lokec@ccs.neu.edu>
47  */
48 
49 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
50 
51 #include <linux/ethtool.h>
52 #include <linux/filter.h>
53 #include <linux/types.h>
54 #include <linux/mm.h>
55 #include <linux/capability.h>
56 #include <linux/fcntl.h>
57 #include <linux/socket.h>
58 #include <linux/in.h>
59 #include <linux/inet.h>
60 #include <linux/netdevice.h>
61 #include <linux/if_packet.h>
62 #include <linux/wireless.h>
63 #include <linux/kernel.h>
64 #include <linux/kmod.h>
65 #include <linux/slab.h>
66 #include <linux/vmalloc.h>
67 #include <net/net_namespace.h>
68 #include <net/ip.h>
69 #include <net/protocol.h>
70 #include <linux/skbuff.h>
71 #include <net/sock.h>
72 #include <linux/errno.h>
73 #include <linux/timer.h>
74 #include <linux/uaccess.h>
75 #include <asm/ioctls.h>
76 #include <asm/page.h>
77 #include <asm/cacheflush.h>
78 #include <asm/io.h>
79 #include <linux/proc_fs.h>
80 #include <linux/seq_file.h>
81 #include <linux/poll.h>
82 #include <linux/module.h>
83 #include <linux/init.h>
84 #include <linux/mutex.h>
85 #include <linux/if_vlan.h>
86 #include <linux/virtio_net.h>
87 #include <linux/errqueue.h>
88 #include <linux/net_tstamp.h>
89 #include <linux/percpu.h>
90 #ifdef CONFIG_INET
91 #include <net/inet_common.h>
92 #endif
93 #include <linux/bpf.h>
94 #include <net/compat.h>
95 #include <linux/netfilter_netdev.h>
96 
97 #include "internal.h"
98 
99 /*
100    Assumptions:
101    - If the device has no dev->header_ops->create, there is no LL header
102      visible above the device. In this case, its hard_header_len should be 0.
103      The device may prepend its own header internally. In this case, its
104      needed_headroom should be set to the space needed for it to add its
105      internal header.
106      For example, a WiFi driver pretending to be an Ethernet driver should
107      set its hard_header_len to be the Ethernet header length, and set its
108      needed_headroom to be (the real WiFi header length - the fake Ethernet
109      header length).
110    - packet socket receives packets with pulled ll header,
111      so that SOCK_RAW should push it back.
112 
113 On receive:
114 -----------
115 
116 Incoming, dev_has_header(dev) == true
117    mac_header -> ll header
118    data       -> data
119 
120 Outgoing, dev_has_header(dev) == true
121    mac_header -> ll header
122    data       -> ll header
123 
124 Incoming, dev_has_header(dev) == false
125    mac_header -> data
126      However drivers often make it point to the ll header.
127      This is incorrect because the ll header should be invisible to us.
128    data       -> data
129 
130 Outgoing, dev_has_header(dev) == false
131    mac_header -> data. ll header is invisible to us.
132    data       -> data
133 
134 Resume
135   If dev_has_header(dev) == false we are unable to restore the ll header,
136     because it is invisible to us.
137 
138 
139 On transmit:
140 ------------
141 
142 dev_has_header(dev) == true
143    mac_header -> ll header
144    data       -> ll header
145 
146 dev_has_header(dev) == false (ll header is invisible to us)
147    mac_header -> data
148    data       -> data
149 
150    We should set network_header on output to the correct position,
151    packet classifier depends on it.
152  */
153 
154 /* Private packet socket structures. */
155 
156 /* identical to struct packet_mreq except it has
157  * a longer address field.
158  */
159 struct packet_mreq_max {
160 	int		mr_ifindex;
161 	unsigned short	mr_type;
162 	unsigned short	mr_alen;
163 	unsigned char	mr_address[MAX_ADDR_LEN];
164 };
165 
166 union tpacket_uhdr {
167 	struct tpacket_hdr  *h1;
168 	struct tpacket2_hdr *h2;
169 	struct tpacket3_hdr *h3;
170 	void *raw;
171 };
172 
173 static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
174 		int closing, int tx_ring);
175 
176 #define V3_ALIGNMENT	(8)
177 
178 #define BLK_HDR_LEN	(ALIGN(sizeof(struct tpacket_block_desc), V3_ALIGNMENT))
179 
180 #define BLK_PLUS_PRIV(sz_of_priv) \
181 	(BLK_HDR_LEN + ALIGN((sz_of_priv), V3_ALIGNMENT))
182 
183 #define BLOCK_STATUS(x)	((x)->hdr.bh1.block_status)
184 #define BLOCK_NUM_PKTS(x)	((x)->hdr.bh1.num_pkts)
185 #define BLOCK_O2FP(x)		((x)->hdr.bh1.offset_to_first_pkt)
186 #define BLOCK_LEN(x)		((x)->hdr.bh1.blk_len)
187 #define BLOCK_SNUM(x)		((x)->hdr.bh1.seq_num)
188 #define BLOCK_O2PRIV(x)	((x)->offset_to_priv)
189 
190 struct packet_sock;
191 static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
192 		       struct packet_type *pt, struct net_device *orig_dev);
193 
194 static void *packet_previous_frame(struct packet_sock *po,
195 		struct packet_ring_buffer *rb,
196 		int status);
197 static void packet_increment_head(struct packet_ring_buffer *buff);
198 static int prb_curr_blk_in_use(struct tpacket_block_desc *);
199 static void *prb_dispatch_next_block(struct tpacket_kbdq_core *,
200 			struct packet_sock *);
201 static void prb_retire_current_block(struct tpacket_kbdq_core *,
202 		struct packet_sock *, unsigned int status);
203 static int prb_queue_frozen(struct tpacket_kbdq_core *);
204 static void prb_open_block(struct tpacket_kbdq_core *,
205 		struct tpacket_block_desc *);
206 static void prb_retire_rx_blk_timer_expired(struct timer_list *);
207 static void _prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core *);
208 static void prb_fill_rxhash(struct tpacket_kbdq_core *, struct tpacket3_hdr *);
209 static void prb_clear_rxhash(struct tpacket_kbdq_core *,
210 		struct tpacket3_hdr *);
211 static void prb_fill_vlan_info(struct tpacket_kbdq_core *,
212 		struct tpacket3_hdr *);
213 static void packet_flush_mclist(struct sock *sk);
214 static u16 packet_pick_tx_queue(struct sk_buff *skb);
215 
216 struct packet_skb_cb {
217 	union {
218 		struct sockaddr_pkt pkt;
219 		union {
220 			/* Trick: alias skb original length with
221 			 * ll.sll_family and ll.protocol in order
222 			 * to save room.
223 			 */
224 			unsigned int origlen;
225 			struct sockaddr_ll ll;
226 		};
227 	} sa;
228 };
229 
230 #define vio_le() virtio_legacy_is_little_endian()
231 
232 #define PACKET_SKB_CB(__skb)	((struct packet_skb_cb *)((__skb)->cb))
233 
234 #define GET_PBDQC_FROM_RB(x)	((struct tpacket_kbdq_core *)(&(x)->prb_bdqc))
235 #define GET_PBLOCK_DESC(x, bid)	\
236 	((struct tpacket_block_desc *)((x)->pkbdq[(bid)].buffer))
237 #define GET_CURR_PBLOCK_DESC_FROM_CORE(x)	\
238 	((struct tpacket_block_desc *)((x)->pkbdq[(x)->kactive_blk_num].buffer))
239 #define GET_NEXT_PRB_BLK_NUM(x) \
240 	(((x)->kactive_blk_num < ((x)->knum_blocks-1)) ? \
241 	((x)->kactive_blk_num+1) : 0)
242 
243 static void __fanout_unlink(struct sock *sk, struct packet_sock *po);
244 static void __fanout_link(struct sock *sk, struct packet_sock *po);
245 
246 #ifdef CONFIG_NETFILTER_EGRESS
247 static noinline struct sk_buff *nf_hook_direct_egress(struct sk_buff *skb)
248 {
249 	struct sk_buff *next, *head = NULL, *tail;
250 	int rc;
251 
252 	rcu_read_lock();
253 	for (; skb != NULL; skb = next) {
254 		next = skb->next;
255 		skb_mark_not_on_list(skb);
256 
257 		if (!nf_hook_egress(skb, &rc, skb->dev))
258 			continue;
259 
260 		if (!head)
261 			head = skb;
262 		else
263 			tail->next = skb;
264 
265 		tail = skb;
266 	}
267 	rcu_read_unlock();
268 
269 	return head;
270 }
271 #endif
272 
273 static int packet_xmit(const struct packet_sock *po, struct sk_buff *skb)
274 {
275 	if (!packet_sock_flag(po, PACKET_SOCK_QDISC_BYPASS))
276 		return dev_queue_xmit(skb);
277 
278 #ifdef CONFIG_NETFILTER_EGRESS
279 	if (nf_hook_egress_active()) {
280 		skb = nf_hook_direct_egress(skb);
281 		if (!skb)
282 			return NET_XMIT_DROP;
283 	}
284 #endif
285 	return dev_direct_xmit(skb, packet_pick_tx_queue(skb));
286 }
287 
288 static struct net_device *packet_cached_dev_get(struct packet_sock *po)
289 {
290 	struct net_device *dev;
291 
292 	rcu_read_lock();
293 	dev = rcu_dereference(po->cached_dev);
294 	dev_hold(dev);
295 	rcu_read_unlock();
296 
297 	return dev;
298 }
299 
300 static void packet_cached_dev_assign(struct packet_sock *po,
301 				     struct net_device *dev)
302 {
303 	rcu_assign_pointer(po->cached_dev, dev);
304 }
305 
306 static void packet_cached_dev_reset(struct packet_sock *po)
307 {
308 	RCU_INIT_POINTER(po->cached_dev, NULL);
309 }
310 
311 static u16 packet_pick_tx_queue(struct sk_buff *skb)
312 {
313 	struct net_device *dev = skb->dev;
314 	const struct net_device_ops *ops = dev->netdev_ops;
315 	int cpu = raw_smp_processor_id();
316 	u16 queue_index;
317 
318 #ifdef CONFIG_XPS
319 	skb->sender_cpu = cpu + 1;
320 #endif
321 	skb_record_rx_queue(skb, cpu % dev->real_num_tx_queues);
322 	if (ops->ndo_select_queue) {
323 		queue_index = ops->ndo_select_queue(dev, skb, NULL);
324 		queue_index = netdev_cap_txqueue(dev, queue_index);
325 	} else {
326 		queue_index = netdev_pick_tx(dev, skb, NULL);
327 	}
328 
329 	return queue_index;
330 }
331 
332 /* __register_prot_hook must be invoked through register_prot_hook
333  * or from a context in which asynchronous accesses to the packet
334  * socket is not possible (packet_create()).
335  */
336 static void __register_prot_hook(struct sock *sk)
337 {
338 	struct packet_sock *po = pkt_sk(sk);
339 
340 	if (!packet_sock_flag(po, PACKET_SOCK_RUNNING)) {
341 		if (po->fanout)
342 			__fanout_link(sk, po);
343 		else
344 			dev_add_pack(&po->prot_hook);
345 
346 		sock_hold(sk);
347 		packet_sock_flag_set(po, PACKET_SOCK_RUNNING, 1);
348 	}
349 }
350 
351 static void register_prot_hook(struct sock *sk)
352 {
353 	lockdep_assert_held_once(&pkt_sk(sk)->bind_lock);
354 	__register_prot_hook(sk);
355 }
356 
357 /* If the sync parameter is true, we will temporarily drop
358  * the po->bind_lock and do a synchronize_net to make sure no
359  * asynchronous packet processing paths still refer to the elements
360  * of po->prot_hook.  If the sync parameter is false, it is the
361  * callers responsibility to take care of this.
362  */
363 static void __unregister_prot_hook(struct sock *sk, bool sync)
364 {
365 	struct packet_sock *po = pkt_sk(sk);
366 
367 	lockdep_assert_held_once(&po->bind_lock);
368 
369 	packet_sock_flag_set(po, PACKET_SOCK_RUNNING, 0);
370 
371 	if (po->fanout)
372 		__fanout_unlink(sk, po);
373 	else
374 		__dev_remove_pack(&po->prot_hook);
375 
376 	__sock_put(sk);
377 
378 	if (sync) {
379 		spin_unlock(&po->bind_lock);
380 		synchronize_net();
381 		spin_lock(&po->bind_lock);
382 	}
383 }
384 
385 static void unregister_prot_hook(struct sock *sk, bool sync)
386 {
387 	struct packet_sock *po = pkt_sk(sk);
388 
389 	if (packet_sock_flag(po, PACKET_SOCK_RUNNING))
390 		__unregister_prot_hook(sk, sync);
391 }
392 
393 static inline struct page * __pure pgv_to_page(void *addr)
394 {
395 	if (is_vmalloc_addr(addr))
396 		return vmalloc_to_page(addr);
397 	return virt_to_page(addr);
398 }
399 
400 static void __packet_set_status(struct packet_sock *po, void *frame, int status)
401 {
402 	union tpacket_uhdr h;
403 
404 	/* WRITE_ONCE() are paired with READ_ONCE() in __packet_get_status */
405 
406 	h.raw = frame;
407 	switch (po->tp_version) {
408 	case TPACKET_V1:
409 		WRITE_ONCE(h.h1->tp_status, status);
410 		flush_dcache_page(pgv_to_page(&h.h1->tp_status));
411 		break;
412 	case TPACKET_V2:
413 		WRITE_ONCE(h.h2->tp_status, status);
414 		flush_dcache_page(pgv_to_page(&h.h2->tp_status));
415 		break;
416 	case TPACKET_V3:
417 		WRITE_ONCE(h.h3->tp_status, status);
418 		flush_dcache_page(pgv_to_page(&h.h3->tp_status));
419 		break;
420 	default:
421 		WARN(1, "TPACKET version not supported.\n");
422 		BUG();
423 	}
424 
425 	smp_wmb();
426 }
427 
428 static int __packet_get_status(const struct packet_sock *po, void *frame)
429 {
430 	union tpacket_uhdr h;
431 
432 	smp_rmb();
433 
434 	/* READ_ONCE() are paired with WRITE_ONCE() in __packet_set_status */
435 
436 	h.raw = frame;
437 	switch (po->tp_version) {
438 	case TPACKET_V1:
439 		flush_dcache_page(pgv_to_page(&h.h1->tp_status));
440 		return READ_ONCE(h.h1->tp_status);
441 	case TPACKET_V2:
442 		flush_dcache_page(pgv_to_page(&h.h2->tp_status));
443 		return READ_ONCE(h.h2->tp_status);
444 	case TPACKET_V3:
445 		flush_dcache_page(pgv_to_page(&h.h3->tp_status));
446 		return READ_ONCE(h.h3->tp_status);
447 	default:
448 		WARN(1, "TPACKET version not supported.\n");
449 		BUG();
450 		return 0;
451 	}
452 }
453 
454 static __u32 tpacket_get_timestamp(struct sk_buff *skb, struct timespec64 *ts,
455 				   unsigned int flags)
456 {
457 	struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);
458 
459 	if (shhwtstamps &&
460 	    (flags & SOF_TIMESTAMPING_RAW_HARDWARE) &&
461 	    ktime_to_timespec64_cond(shhwtstamps->hwtstamp, ts))
462 		return TP_STATUS_TS_RAW_HARDWARE;
463 
464 	if ((flags & SOF_TIMESTAMPING_SOFTWARE) &&
465 	    ktime_to_timespec64_cond(skb_tstamp(skb), ts))
466 		return TP_STATUS_TS_SOFTWARE;
467 
468 	return 0;
469 }
470 
471 static __u32 __packet_set_timestamp(struct packet_sock *po, void *frame,
472 				    struct sk_buff *skb)
473 {
474 	union tpacket_uhdr h;
475 	struct timespec64 ts;
476 	__u32 ts_status;
477 
478 	if (!(ts_status = tpacket_get_timestamp(skb, &ts, READ_ONCE(po->tp_tstamp))))
479 		return 0;
480 
481 	h.raw = frame;
482 	/*
483 	 * versions 1 through 3 overflow the timestamps in y2106, since they
484 	 * all store the seconds in a 32-bit unsigned integer.
485 	 * If we create a version 4, that should have a 64-bit timestamp,
486 	 * either 64-bit seconds + 32-bit nanoseconds, or just 64-bit
487 	 * nanoseconds.
488 	 */
489 	switch (po->tp_version) {
490 	case TPACKET_V1:
491 		h.h1->tp_sec = ts.tv_sec;
492 		h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
493 		break;
494 	case TPACKET_V2:
495 		h.h2->tp_sec = ts.tv_sec;
496 		h.h2->tp_nsec = ts.tv_nsec;
497 		break;
498 	case TPACKET_V3:
499 		h.h3->tp_sec = ts.tv_sec;
500 		h.h3->tp_nsec = ts.tv_nsec;
501 		break;
502 	default:
503 		WARN(1, "TPACKET version not supported.\n");
504 		BUG();
505 	}
506 
507 	/* one flush is safe, as both fields always lie on the same cacheline */
508 	flush_dcache_page(pgv_to_page(&h.h1->tp_sec));
509 	smp_wmb();
510 
511 	return ts_status;
512 }
513 
514 static void *packet_lookup_frame(const struct packet_sock *po,
515 				 const struct packet_ring_buffer *rb,
516 				 unsigned int position,
517 				 int status)
518 {
519 	unsigned int pg_vec_pos, frame_offset;
520 	union tpacket_uhdr h;
521 
522 	pg_vec_pos = position / rb->frames_per_block;
523 	frame_offset = position % rb->frames_per_block;
524 
525 	h.raw = rb->pg_vec[pg_vec_pos].buffer +
526 		(frame_offset * rb->frame_size);
527 
528 	if (status != __packet_get_status(po, h.raw))
529 		return NULL;
530 
531 	return h.raw;
532 }
533 
534 static void *packet_current_frame(struct packet_sock *po,
535 		struct packet_ring_buffer *rb,
536 		int status)
537 {
538 	return packet_lookup_frame(po, rb, rb->head, status);
539 }
540 
541 static u16 vlan_get_tci(struct sk_buff *skb, struct net_device *dev)
542 {
543 	u8 *skb_orig_data = skb->data;
544 	int skb_orig_len = skb->len;
545 	struct vlan_hdr vhdr, *vh;
546 	unsigned int header_len;
547 
548 	if (!dev)
549 		return 0;
550 
551 	/* In the SOCK_DGRAM scenario, skb data starts at the network
552 	 * protocol, which is after the VLAN headers. The outer VLAN
553 	 * header is at the hard_header_len offset in non-variable
554 	 * length link layer headers. If it's a VLAN device, the
555 	 * min_header_len should be used to exclude the VLAN header
556 	 * size.
557 	 */
558 	if (dev->min_header_len == dev->hard_header_len)
559 		header_len = dev->hard_header_len;
560 	else if (is_vlan_dev(dev))
561 		header_len = dev->min_header_len;
562 	else
563 		return 0;
564 
565 	skb_push(skb, skb->data - skb_mac_header(skb));
566 	vh = skb_header_pointer(skb, header_len, sizeof(vhdr), &vhdr);
567 	if (skb_orig_data != skb->data) {
568 		skb->data = skb_orig_data;
569 		skb->len = skb_orig_len;
570 	}
571 	if (unlikely(!vh))
572 		return 0;
573 
574 	return ntohs(vh->h_vlan_TCI);
575 }
576 
577 static __be16 vlan_get_protocol_dgram(struct sk_buff *skb)
578 {
579 	__be16 proto = skb->protocol;
580 
581 	if (unlikely(eth_type_vlan(proto))) {
582 		u8 *skb_orig_data = skb->data;
583 		int skb_orig_len = skb->len;
584 
585 		skb_push(skb, skb->data - skb_mac_header(skb));
586 		proto = __vlan_get_protocol(skb, proto, NULL);
587 		if (skb_orig_data != skb->data) {
588 			skb->data = skb_orig_data;
589 			skb->len = skb_orig_len;
590 		}
591 	}
592 
593 	return proto;
594 }
595 
596 static void prb_del_retire_blk_timer(struct tpacket_kbdq_core *pkc)
597 {
598 	del_timer_sync(&pkc->retire_blk_timer);
599 }
600 
601 static void prb_shutdown_retire_blk_timer(struct packet_sock *po,
602 		struct sk_buff_head *rb_queue)
603 {
604 	struct tpacket_kbdq_core *pkc;
605 
606 	pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
607 
608 	spin_lock_bh(&rb_queue->lock);
609 	pkc->delete_blk_timer = 1;
610 	spin_unlock_bh(&rb_queue->lock);
611 
612 	prb_del_retire_blk_timer(pkc);
613 }
614 
615 static void prb_setup_retire_blk_timer(struct packet_sock *po)
616 {
617 	struct tpacket_kbdq_core *pkc;
618 
619 	pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
620 	timer_setup(&pkc->retire_blk_timer, prb_retire_rx_blk_timer_expired,
621 		    0);
622 	pkc->retire_blk_timer.expires = jiffies;
623 }
624 
625 static int prb_calc_retire_blk_tmo(struct packet_sock *po,
626 				int blk_size_in_bytes)
627 {
628 	struct net_device *dev;
629 	unsigned int mbits, div;
630 	struct ethtool_link_ksettings ecmd;
631 	int err;
632 
633 	rtnl_lock();
634 	dev = __dev_get_by_index(sock_net(&po->sk), po->ifindex);
635 	if (unlikely(!dev)) {
636 		rtnl_unlock();
637 		return DEFAULT_PRB_RETIRE_TOV;
638 	}
639 	err = __ethtool_get_link_ksettings(dev, &ecmd);
640 	rtnl_unlock();
641 	if (err)
642 		return DEFAULT_PRB_RETIRE_TOV;
643 
644 	/* If the link speed is so slow you don't really
645 	 * need to worry about perf anyways
646 	 */
647 	if (ecmd.base.speed < SPEED_1000 ||
648 	    ecmd.base.speed == SPEED_UNKNOWN)
649 		return DEFAULT_PRB_RETIRE_TOV;
650 
651 	div = ecmd.base.speed / 1000;
652 	mbits = (blk_size_in_bytes * 8) / (1024 * 1024);
653 
654 	if (div)
655 		mbits /= div;
656 
657 	if (div)
658 		return mbits + 1;
659 	return mbits;
660 }
661 
662 static void prb_init_ft_ops(struct tpacket_kbdq_core *p1,
663 			union tpacket_req_u *req_u)
664 {
665 	p1->feature_req_word = req_u->req3.tp_feature_req_word;
666 }
667 
668 static void init_prb_bdqc(struct packet_sock *po,
669 			struct packet_ring_buffer *rb,
670 			struct pgv *pg_vec,
671 			union tpacket_req_u *req_u)
672 {
673 	struct tpacket_kbdq_core *p1 = GET_PBDQC_FROM_RB(rb);
674 	struct tpacket_block_desc *pbd;
675 
676 	memset(p1, 0x0, sizeof(*p1));
677 
678 	p1->knxt_seq_num = 1;
679 	p1->pkbdq = pg_vec;
680 	pbd = (struct tpacket_block_desc *)pg_vec[0].buffer;
681 	p1->pkblk_start	= pg_vec[0].buffer;
682 	p1->kblk_size = req_u->req3.tp_block_size;
683 	p1->knum_blocks	= req_u->req3.tp_block_nr;
684 	p1->hdrlen = po->tp_hdrlen;
685 	p1->version = po->tp_version;
686 	p1->last_kactive_blk_num = 0;
687 	po->stats.stats3.tp_freeze_q_cnt = 0;
688 	if (req_u->req3.tp_retire_blk_tov)
689 		p1->retire_blk_tov = req_u->req3.tp_retire_blk_tov;
690 	else
691 		p1->retire_blk_tov = prb_calc_retire_blk_tmo(po,
692 						req_u->req3.tp_block_size);
693 	p1->tov_in_jiffies = msecs_to_jiffies(p1->retire_blk_tov);
694 	p1->blk_sizeof_priv = req_u->req3.tp_sizeof_priv;
695 	rwlock_init(&p1->blk_fill_in_prog_lock);
696 
697 	p1->max_frame_len = p1->kblk_size - BLK_PLUS_PRIV(p1->blk_sizeof_priv);
698 	prb_init_ft_ops(p1, req_u);
699 	prb_setup_retire_blk_timer(po);
700 	prb_open_block(p1, pbd);
701 }
702 
703 /*  Do NOT update the last_blk_num first.
704  *  Assumes sk_buff_head lock is held.
705  */
706 static void _prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core *pkc)
707 {
708 	mod_timer(&pkc->retire_blk_timer,
709 			jiffies + pkc->tov_in_jiffies);
710 	pkc->last_kactive_blk_num = pkc->kactive_blk_num;
711 }
712 
713 /*
714  * Timer logic:
715  * 1) We refresh the timer only when we open a block.
716  *    By doing this we don't waste cycles refreshing the timer
717  *	  on packet-by-packet basis.
718  *
719  * With a 1MB block-size, on a 1Gbps line, it will take
720  * i) ~8 ms to fill a block + ii) memcpy etc.
721  * In this cut we are not accounting for the memcpy time.
722  *
723  * So, if the user sets the 'tmo' to 10ms then the timer
724  * will never fire while the block is still getting filled
725  * (which is what we want). However, the user could choose
726  * to close a block early and that's fine.
727  *
728  * But when the timer does fire, we check whether or not to refresh it.
729  * Since the tmo granularity is in msecs, it is not too expensive
730  * to refresh the timer, lets say every '8' msecs.
731  * Either the user can set the 'tmo' or we can derive it based on
732  * a) line-speed and b) block-size.
733  * prb_calc_retire_blk_tmo() calculates the tmo.
734  *
735  */
736 static void prb_retire_rx_blk_timer_expired(struct timer_list *t)
737 {
738 	struct packet_sock *po =
739 		from_timer(po, t, rx_ring.prb_bdqc.retire_blk_timer);
740 	struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
741 	unsigned int frozen;
742 	struct tpacket_block_desc *pbd;
743 
744 	spin_lock(&po->sk.sk_receive_queue.lock);
745 
746 	frozen = prb_queue_frozen(pkc);
747 	pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
748 
749 	if (unlikely(pkc->delete_blk_timer))
750 		goto out;
751 
752 	/* We only need to plug the race when the block is partially filled.
753 	 * tpacket_rcv:
754 	 *		lock(); increment BLOCK_NUM_PKTS; unlock()
755 	 *		copy_bits() is in progress ...
756 	 *		timer fires on other cpu:
757 	 *		we can't retire the current block because copy_bits
758 	 *		is in progress.
759 	 *
760 	 */
761 	if (BLOCK_NUM_PKTS(pbd)) {
762 		/* Waiting for skb_copy_bits to finish... */
763 		write_lock(&pkc->blk_fill_in_prog_lock);
764 		write_unlock(&pkc->blk_fill_in_prog_lock);
765 	}
766 
767 	if (pkc->last_kactive_blk_num == pkc->kactive_blk_num) {
768 		if (!frozen) {
769 			if (!BLOCK_NUM_PKTS(pbd)) {
770 				/* An empty block. Just refresh the timer. */
771 				goto refresh_timer;
772 			}
773 			prb_retire_current_block(pkc, po, TP_STATUS_BLK_TMO);
774 			if (!prb_dispatch_next_block(pkc, po))
775 				goto refresh_timer;
776 			else
777 				goto out;
778 		} else {
779 			/* Case 1. Queue was frozen because user-space was
780 			 *	   lagging behind.
781 			 */
782 			if (prb_curr_blk_in_use(pbd)) {
783 				/*
784 				 * Ok, user-space is still behind.
785 				 * So just refresh the timer.
786 				 */
787 				goto refresh_timer;
788 			} else {
789 			       /* Case 2. queue was frozen,user-space caught up,
790 				* now the link went idle && the timer fired.
791 				* We don't have a block to close.So we open this
792 				* block and restart the timer.
793 				* opening a block thaws the queue,restarts timer
794 				* Thawing/timer-refresh is a side effect.
795 				*/
796 				prb_open_block(pkc, pbd);
797 				goto out;
798 			}
799 		}
800 	}
801 
802 refresh_timer:
803 	_prb_refresh_rx_retire_blk_timer(pkc);
804 
805 out:
806 	spin_unlock(&po->sk.sk_receive_queue.lock);
807 }
808 
809 static void prb_flush_block(struct tpacket_kbdq_core *pkc1,
810 		struct tpacket_block_desc *pbd1, __u32 status)
811 {
812 	/* Flush everything minus the block header */
813 
814 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
815 	u8 *start, *end;
816 
817 	start = (u8 *)pbd1;
818 
819 	/* Skip the block header(we know header WILL fit in 4K) */
820 	start += PAGE_SIZE;
821 
822 	end = (u8 *)PAGE_ALIGN((unsigned long)pkc1->pkblk_end);
823 	for (; start < end; start += PAGE_SIZE)
824 		flush_dcache_page(pgv_to_page(start));
825 
826 	smp_wmb();
827 #endif
828 
829 	/* Now update the block status. */
830 
831 	BLOCK_STATUS(pbd1) = status;
832 
833 	/* Flush the block header */
834 
835 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
836 	start = (u8 *)pbd1;
837 	flush_dcache_page(pgv_to_page(start));
838 
839 	smp_wmb();
840 #endif
841 }
842 
843 /*
844  * Side effect:
845  *
846  * 1) flush the block
847  * 2) Increment active_blk_num
848  *
849  * Note:We DONT refresh the timer on purpose.
850  *	Because almost always the next block will be opened.
851  */
852 static void prb_close_block(struct tpacket_kbdq_core *pkc1,
853 		struct tpacket_block_desc *pbd1,
854 		struct packet_sock *po, unsigned int stat)
855 {
856 	__u32 status = TP_STATUS_USER | stat;
857 
858 	struct tpacket3_hdr *last_pkt;
859 	struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
860 	struct sock *sk = &po->sk;
861 
862 	if (atomic_read(&po->tp_drops))
863 		status |= TP_STATUS_LOSING;
864 
865 	last_pkt = (struct tpacket3_hdr *)pkc1->prev;
866 	last_pkt->tp_next_offset = 0;
867 
868 	/* Get the ts of the last pkt */
869 	if (BLOCK_NUM_PKTS(pbd1)) {
870 		h1->ts_last_pkt.ts_sec = last_pkt->tp_sec;
871 		h1->ts_last_pkt.ts_nsec	= last_pkt->tp_nsec;
872 	} else {
873 		/* Ok, we tmo'd - so get the current time.
874 		 *
875 		 * It shouldn't really happen as we don't close empty
876 		 * blocks. See prb_retire_rx_blk_timer_expired().
877 		 */
878 		struct timespec64 ts;
879 		ktime_get_real_ts64(&ts);
880 		h1->ts_last_pkt.ts_sec = ts.tv_sec;
881 		h1->ts_last_pkt.ts_nsec	= ts.tv_nsec;
882 	}
883 
884 	smp_wmb();
885 
886 	/* Flush the block */
887 	prb_flush_block(pkc1, pbd1, status);
888 
889 	sk->sk_data_ready(sk);
890 
891 	pkc1->kactive_blk_num = GET_NEXT_PRB_BLK_NUM(pkc1);
892 }
893 
894 static void prb_thaw_queue(struct tpacket_kbdq_core *pkc)
895 {
896 	pkc->reset_pending_on_curr_blk = 0;
897 }
898 
899 /*
900  * Side effect of opening a block:
901  *
902  * 1) prb_queue is thawed.
903  * 2) retire_blk_timer is refreshed.
904  *
905  */
906 static void prb_open_block(struct tpacket_kbdq_core *pkc1,
907 	struct tpacket_block_desc *pbd1)
908 {
909 	struct timespec64 ts;
910 	struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
911 
912 	smp_rmb();
913 
914 	/* We could have just memset this but we will lose the
915 	 * flexibility of making the priv area sticky
916 	 */
917 
918 	BLOCK_SNUM(pbd1) = pkc1->knxt_seq_num++;
919 	BLOCK_NUM_PKTS(pbd1) = 0;
920 	BLOCK_LEN(pbd1) = BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
921 
922 	ktime_get_real_ts64(&ts);
923 
924 	h1->ts_first_pkt.ts_sec = ts.tv_sec;
925 	h1->ts_first_pkt.ts_nsec = ts.tv_nsec;
926 
927 	pkc1->pkblk_start = (char *)pbd1;
928 	pkc1->nxt_offset = pkc1->pkblk_start + BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
929 
930 	BLOCK_O2FP(pbd1) = (__u32)BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
931 	BLOCK_O2PRIV(pbd1) = BLK_HDR_LEN;
932 
933 	pbd1->version = pkc1->version;
934 	pkc1->prev = pkc1->nxt_offset;
935 	pkc1->pkblk_end = pkc1->pkblk_start + pkc1->kblk_size;
936 
937 	prb_thaw_queue(pkc1);
938 	_prb_refresh_rx_retire_blk_timer(pkc1);
939 
940 	smp_wmb();
941 }
942 
943 /*
944  * Queue freeze logic:
945  * 1) Assume tp_block_nr = 8 blocks.
946  * 2) At time 't0', user opens Rx ring.
947  * 3) Some time past 't0', kernel starts filling blocks starting from 0 .. 7
948  * 4) user-space is either sleeping or processing block '0'.
949  * 5) tpacket_rcv is currently filling block '7', since there is no space left,
950  *    it will close block-7,loop around and try to fill block '0'.
951  *    call-flow:
952  *    __packet_lookup_frame_in_block
953  *      prb_retire_current_block()
954  *      prb_dispatch_next_block()
955  *        |->(BLOCK_STATUS == USER) evaluates to true
956  *    5.1) Since block-0 is currently in-use, we just freeze the queue.
957  * 6) Now there are two cases:
958  *    6.1) Link goes idle right after the queue is frozen.
959  *         But remember, the last open_block() refreshed the timer.
960  *         When this timer expires,it will refresh itself so that we can
961  *         re-open block-0 in near future.
962  *    6.2) Link is busy and keeps on receiving packets. This is a simple
963  *         case and __packet_lookup_frame_in_block will check if block-0
964  *         is free and can now be re-used.
965  */
966 static void prb_freeze_queue(struct tpacket_kbdq_core *pkc,
967 				  struct packet_sock *po)
968 {
969 	pkc->reset_pending_on_curr_blk = 1;
970 	po->stats.stats3.tp_freeze_q_cnt++;
971 }
972 
973 #define TOTAL_PKT_LEN_INCL_ALIGN(length) (ALIGN((length), V3_ALIGNMENT))
974 
975 /*
976  * If the next block is free then we will dispatch it
977  * and return a good offset.
978  * Else, we will freeze the queue.
979  * So, caller must check the return value.
980  */
981 static void *prb_dispatch_next_block(struct tpacket_kbdq_core *pkc,
982 		struct packet_sock *po)
983 {
984 	struct tpacket_block_desc *pbd;
985 
986 	smp_rmb();
987 
988 	/* 1. Get current block num */
989 	pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
990 
991 	/* 2. If this block is currently in_use then freeze the queue */
992 	if (TP_STATUS_USER & BLOCK_STATUS(pbd)) {
993 		prb_freeze_queue(pkc, po);
994 		return NULL;
995 	}
996 
997 	/*
998 	 * 3.
999 	 * open this block and return the offset where the first packet
1000 	 * needs to get stored.
1001 	 */
1002 	prb_open_block(pkc, pbd);
1003 	return (void *)pkc->nxt_offset;
1004 }
1005 
1006 static void prb_retire_current_block(struct tpacket_kbdq_core *pkc,
1007 		struct packet_sock *po, unsigned int status)
1008 {
1009 	struct tpacket_block_desc *pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
1010 
1011 	/* retire/close the current block */
1012 	if (likely(TP_STATUS_KERNEL == BLOCK_STATUS(pbd))) {
1013 		/*
1014 		 * Plug the case where copy_bits() is in progress on
1015 		 * cpu-0 and tpacket_rcv() got invoked on cpu-1, didn't
1016 		 * have space to copy the pkt in the current block and
1017 		 * called prb_retire_current_block()
1018 		 *
1019 		 * We don't need to worry about the TMO case because
1020 		 * the timer-handler already handled this case.
1021 		 */
1022 		if (!(status & TP_STATUS_BLK_TMO)) {
1023 			/* Waiting for skb_copy_bits to finish... */
1024 			write_lock(&pkc->blk_fill_in_prog_lock);
1025 			write_unlock(&pkc->blk_fill_in_prog_lock);
1026 		}
1027 		prb_close_block(pkc, pbd, po, status);
1028 		return;
1029 	}
1030 }
1031 
1032 static int prb_curr_blk_in_use(struct tpacket_block_desc *pbd)
1033 {
1034 	return TP_STATUS_USER & BLOCK_STATUS(pbd);
1035 }
1036 
1037 static int prb_queue_frozen(struct tpacket_kbdq_core *pkc)
1038 {
1039 	return pkc->reset_pending_on_curr_blk;
1040 }
1041 
1042 static void prb_clear_blk_fill_status(struct packet_ring_buffer *rb)
1043 	__releases(&pkc->blk_fill_in_prog_lock)
1044 {
1045 	struct tpacket_kbdq_core *pkc  = GET_PBDQC_FROM_RB(rb);
1046 
1047 	read_unlock(&pkc->blk_fill_in_prog_lock);
1048 }
1049 
1050 static void prb_fill_rxhash(struct tpacket_kbdq_core *pkc,
1051 			struct tpacket3_hdr *ppd)
1052 {
1053 	ppd->hv1.tp_rxhash = skb_get_hash(pkc->skb);
1054 }
1055 
1056 static void prb_clear_rxhash(struct tpacket_kbdq_core *pkc,
1057 			struct tpacket3_hdr *ppd)
1058 {
1059 	ppd->hv1.tp_rxhash = 0;
1060 }
1061 
1062 static void prb_fill_vlan_info(struct tpacket_kbdq_core *pkc,
1063 			struct tpacket3_hdr *ppd)
1064 {
1065 	struct packet_sock *po = container_of(pkc, struct packet_sock, rx_ring.prb_bdqc);
1066 
1067 	if (skb_vlan_tag_present(pkc->skb)) {
1068 		ppd->hv1.tp_vlan_tci = skb_vlan_tag_get(pkc->skb);
1069 		ppd->hv1.tp_vlan_tpid = ntohs(pkc->skb->vlan_proto);
1070 		ppd->tp_status = TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
1071 	} else if (unlikely(po->sk.sk_type == SOCK_DGRAM && eth_type_vlan(pkc->skb->protocol))) {
1072 		ppd->hv1.tp_vlan_tci = vlan_get_tci(pkc->skb, pkc->skb->dev);
1073 		ppd->hv1.tp_vlan_tpid = ntohs(pkc->skb->protocol);
1074 		ppd->tp_status = TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
1075 	} else {
1076 		ppd->hv1.tp_vlan_tci = 0;
1077 		ppd->hv1.tp_vlan_tpid = 0;
1078 		ppd->tp_status = TP_STATUS_AVAILABLE;
1079 	}
1080 }
1081 
1082 static void prb_run_all_ft_ops(struct tpacket_kbdq_core *pkc,
1083 			struct tpacket3_hdr *ppd)
1084 {
1085 	ppd->hv1.tp_padding = 0;
1086 	prb_fill_vlan_info(pkc, ppd);
1087 
1088 	if (pkc->feature_req_word & TP_FT_REQ_FILL_RXHASH)
1089 		prb_fill_rxhash(pkc, ppd);
1090 	else
1091 		prb_clear_rxhash(pkc, ppd);
1092 }
1093 
1094 static void prb_fill_curr_block(char *curr,
1095 				struct tpacket_kbdq_core *pkc,
1096 				struct tpacket_block_desc *pbd,
1097 				unsigned int len)
1098 	__acquires(&pkc->blk_fill_in_prog_lock)
1099 {
1100 	struct tpacket3_hdr *ppd;
1101 
1102 	ppd  = (struct tpacket3_hdr *)curr;
1103 	ppd->tp_next_offset = TOTAL_PKT_LEN_INCL_ALIGN(len);
1104 	pkc->prev = curr;
1105 	pkc->nxt_offset += TOTAL_PKT_LEN_INCL_ALIGN(len);
1106 	BLOCK_LEN(pbd) += TOTAL_PKT_LEN_INCL_ALIGN(len);
1107 	BLOCK_NUM_PKTS(pbd) += 1;
1108 	read_lock(&pkc->blk_fill_in_prog_lock);
1109 	prb_run_all_ft_ops(pkc, ppd);
1110 }
1111 
1112 /* Assumes caller has the sk->rx_queue.lock */
1113 static void *__packet_lookup_frame_in_block(struct packet_sock *po,
1114 					    struct sk_buff *skb,
1115 					    unsigned int len
1116 					    )
1117 {
1118 	struct tpacket_kbdq_core *pkc;
1119 	struct tpacket_block_desc *pbd;
1120 	char *curr, *end;
1121 
1122 	pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
1123 	pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
1124 
1125 	/* Queue is frozen when user space is lagging behind */
1126 	if (prb_queue_frozen(pkc)) {
1127 		/*
1128 		 * Check if that last block which caused the queue to freeze,
1129 		 * is still in_use by user-space.
1130 		 */
1131 		if (prb_curr_blk_in_use(pbd)) {
1132 			/* Can't record this packet */
1133 			return NULL;
1134 		} else {
1135 			/*
1136 			 * Ok, the block was released by user-space.
1137 			 * Now let's open that block.
1138 			 * opening a block also thaws the queue.
1139 			 * Thawing is a side effect.
1140 			 */
1141 			prb_open_block(pkc, pbd);
1142 		}
1143 	}
1144 
1145 	smp_mb();
1146 	curr = pkc->nxt_offset;
1147 	pkc->skb = skb;
1148 	end = (char *)pbd + pkc->kblk_size;
1149 
1150 	/* first try the current block */
1151 	if (curr+TOTAL_PKT_LEN_INCL_ALIGN(len) < end) {
1152 		prb_fill_curr_block(curr, pkc, pbd, len);
1153 		return (void *)curr;
1154 	}
1155 
1156 	/* Ok, close the current block */
1157 	prb_retire_current_block(pkc, po, 0);
1158 
1159 	/* Now, try to dispatch the next block */
1160 	curr = (char *)prb_dispatch_next_block(pkc, po);
1161 	if (curr) {
1162 		pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
1163 		prb_fill_curr_block(curr, pkc, pbd, len);
1164 		return (void *)curr;
1165 	}
1166 
1167 	/*
1168 	 * No free blocks are available.user_space hasn't caught up yet.
1169 	 * Queue was just frozen and now this packet will get dropped.
1170 	 */
1171 	return NULL;
1172 }
1173 
1174 static void *packet_current_rx_frame(struct packet_sock *po,
1175 					    struct sk_buff *skb,
1176 					    int status, unsigned int len)
1177 {
1178 	char *curr = NULL;
1179 	switch (po->tp_version) {
1180 	case TPACKET_V1:
1181 	case TPACKET_V2:
1182 		curr = packet_lookup_frame(po, &po->rx_ring,
1183 					po->rx_ring.head, status);
1184 		return curr;
1185 	case TPACKET_V3:
1186 		return __packet_lookup_frame_in_block(po, skb, len);
1187 	default:
1188 		WARN(1, "TPACKET version not supported\n");
1189 		BUG();
1190 		return NULL;
1191 	}
1192 }
1193 
1194 static void *prb_lookup_block(const struct packet_sock *po,
1195 			      const struct packet_ring_buffer *rb,
1196 			      unsigned int idx,
1197 			      int status)
1198 {
1199 	struct tpacket_kbdq_core *pkc  = GET_PBDQC_FROM_RB(rb);
1200 	struct tpacket_block_desc *pbd = GET_PBLOCK_DESC(pkc, idx);
1201 
1202 	if (status != BLOCK_STATUS(pbd))
1203 		return NULL;
1204 	return pbd;
1205 }
1206 
1207 static int prb_previous_blk_num(struct packet_ring_buffer *rb)
1208 {
1209 	unsigned int prev;
1210 	if (rb->prb_bdqc.kactive_blk_num)
1211 		prev = rb->prb_bdqc.kactive_blk_num-1;
1212 	else
1213 		prev = rb->prb_bdqc.knum_blocks-1;
1214 	return prev;
1215 }
1216 
1217 /* Assumes caller has held the rx_queue.lock */
1218 static void *__prb_previous_block(struct packet_sock *po,
1219 					 struct packet_ring_buffer *rb,
1220 					 int status)
1221 {
1222 	unsigned int previous = prb_previous_blk_num(rb);
1223 	return prb_lookup_block(po, rb, previous, status);
1224 }
1225 
1226 static void *packet_previous_rx_frame(struct packet_sock *po,
1227 					     struct packet_ring_buffer *rb,
1228 					     int status)
1229 {
1230 	if (po->tp_version <= TPACKET_V2)
1231 		return packet_previous_frame(po, rb, status);
1232 
1233 	return __prb_previous_block(po, rb, status);
1234 }
1235 
1236 static void packet_increment_rx_head(struct packet_sock *po,
1237 					    struct packet_ring_buffer *rb)
1238 {
1239 	switch (po->tp_version) {
1240 	case TPACKET_V1:
1241 	case TPACKET_V2:
1242 		return packet_increment_head(rb);
1243 	case TPACKET_V3:
1244 	default:
1245 		WARN(1, "TPACKET version not supported.\n");
1246 		BUG();
1247 		return;
1248 	}
1249 }
1250 
1251 static void *packet_previous_frame(struct packet_sock *po,
1252 		struct packet_ring_buffer *rb,
1253 		int status)
1254 {
1255 	unsigned int previous = rb->head ? rb->head - 1 : rb->frame_max;
1256 	return packet_lookup_frame(po, rb, previous, status);
1257 }
1258 
1259 static void packet_increment_head(struct packet_ring_buffer *buff)
1260 {
1261 	buff->head = buff->head != buff->frame_max ? buff->head+1 : 0;
1262 }
1263 
1264 static void packet_inc_pending(struct packet_ring_buffer *rb)
1265 {
1266 	this_cpu_inc(*rb->pending_refcnt);
1267 }
1268 
1269 static void packet_dec_pending(struct packet_ring_buffer *rb)
1270 {
1271 	this_cpu_dec(*rb->pending_refcnt);
1272 }
1273 
1274 static unsigned int packet_read_pending(const struct packet_ring_buffer *rb)
1275 {
1276 	unsigned int refcnt = 0;
1277 	int cpu;
1278 
1279 	/* We don't use pending refcount in rx_ring. */
1280 	if (rb->pending_refcnt == NULL)
1281 		return 0;
1282 
1283 	for_each_possible_cpu(cpu)
1284 		refcnt += *per_cpu_ptr(rb->pending_refcnt, cpu);
1285 
1286 	return refcnt;
1287 }
1288 
1289 static int packet_alloc_pending(struct packet_sock *po)
1290 {
1291 	po->rx_ring.pending_refcnt = NULL;
1292 
1293 	po->tx_ring.pending_refcnt = alloc_percpu(unsigned int);
1294 	if (unlikely(po->tx_ring.pending_refcnt == NULL))
1295 		return -ENOBUFS;
1296 
1297 	return 0;
1298 }
1299 
1300 static void packet_free_pending(struct packet_sock *po)
1301 {
1302 	free_percpu(po->tx_ring.pending_refcnt);
1303 }
1304 
1305 #define ROOM_POW_OFF	2
1306 #define ROOM_NONE	0x0
1307 #define ROOM_LOW	0x1
1308 #define ROOM_NORMAL	0x2
1309 
1310 static bool __tpacket_has_room(const struct packet_sock *po, int pow_off)
1311 {
1312 	int idx, len;
1313 
1314 	len = READ_ONCE(po->rx_ring.frame_max) + 1;
1315 	idx = READ_ONCE(po->rx_ring.head);
1316 	if (pow_off)
1317 		idx += len >> pow_off;
1318 	if (idx >= len)
1319 		idx -= len;
1320 	return packet_lookup_frame(po, &po->rx_ring, idx, TP_STATUS_KERNEL);
1321 }
1322 
1323 static bool __tpacket_v3_has_room(const struct packet_sock *po, int pow_off)
1324 {
1325 	int idx, len;
1326 
1327 	len = READ_ONCE(po->rx_ring.prb_bdqc.knum_blocks);
1328 	idx = READ_ONCE(po->rx_ring.prb_bdqc.kactive_blk_num);
1329 	if (pow_off)
1330 		idx += len >> pow_off;
1331 	if (idx >= len)
1332 		idx -= len;
1333 	return prb_lookup_block(po, &po->rx_ring, idx, TP_STATUS_KERNEL);
1334 }
1335 
1336 static int __packet_rcv_has_room(const struct packet_sock *po,
1337 				 const struct sk_buff *skb)
1338 {
1339 	const struct sock *sk = &po->sk;
1340 	int ret = ROOM_NONE;
1341 
1342 	if (po->prot_hook.func != tpacket_rcv) {
1343 		int rcvbuf = READ_ONCE(sk->sk_rcvbuf);
1344 		int avail = rcvbuf - atomic_read(&sk->sk_rmem_alloc)
1345 				   - (skb ? skb->truesize : 0);
1346 
1347 		if (avail > (rcvbuf >> ROOM_POW_OFF))
1348 			return ROOM_NORMAL;
1349 		else if (avail > 0)
1350 			return ROOM_LOW;
1351 		else
1352 			return ROOM_NONE;
1353 	}
1354 
1355 	if (po->tp_version == TPACKET_V3) {
1356 		if (__tpacket_v3_has_room(po, ROOM_POW_OFF))
1357 			ret = ROOM_NORMAL;
1358 		else if (__tpacket_v3_has_room(po, 0))
1359 			ret = ROOM_LOW;
1360 	} else {
1361 		if (__tpacket_has_room(po, ROOM_POW_OFF))
1362 			ret = ROOM_NORMAL;
1363 		else if (__tpacket_has_room(po, 0))
1364 			ret = ROOM_LOW;
1365 	}
1366 
1367 	return ret;
1368 }
1369 
1370 static int packet_rcv_has_room(struct packet_sock *po, struct sk_buff *skb)
1371 {
1372 	bool pressure;
1373 	int ret;
1374 
1375 	ret = __packet_rcv_has_room(po, skb);
1376 	pressure = ret != ROOM_NORMAL;
1377 
1378 	if (packet_sock_flag(po, PACKET_SOCK_PRESSURE) != pressure)
1379 		packet_sock_flag_set(po, PACKET_SOCK_PRESSURE, pressure);
1380 
1381 	return ret;
1382 }
1383 
1384 static void packet_rcv_try_clear_pressure(struct packet_sock *po)
1385 {
1386 	if (packet_sock_flag(po, PACKET_SOCK_PRESSURE) &&
1387 	    __packet_rcv_has_room(po, NULL) == ROOM_NORMAL)
1388 		packet_sock_flag_set(po, PACKET_SOCK_PRESSURE, false);
1389 }
1390 
1391 static void packet_sock_destruct(struct sock *sk)
1392 {
1393 	skb_queue_purge(&sk->sk_error_queue);
1394 
1395 	WARN_ON(atomic_read(&sk->sk_rmem_alloc));
1396 	WARN_ON(refcount_read(&sk->sk_wmem_alloc));
1397 
1398 	if (!sock_flag(sk, SOCK_DEAD)) {
1399 		pr_err("Attempt to release alive packet socket: %p\n", sk);
1400 		return;
1401 	}
1402 }
1403 
1404 static bool fanout_flow_is_huge(struct packet_sock *po, struct sk_buff *skb)
1405 {
1406 	u32 *history = po->rollover->history;
1407 	u32 victim, rxhash;
1408 	int i, count = 0;
1409 
1410 	rxhash = skb_get_hash(skb);
1411 	for (i = 0; i < ROLLOVER_HLEN; i++)
1412 		if (READ_ONCE(history[i]) == rxhash)
1413 			count++;
1414 
1415 	victim = get_random_u32_below(ROLLOVER_HLEN);
1416 
1417 	/* Avoid dirtying the cache line if possible */
1418 	if (READ_ONCE(history[victim]) != rxhash)
1419 		WRITE_ONCE(history[victim], rxhash);
1420 
1421 	return count > (ROLLOVER_HLEN >> 1);
1422 }
1423 
1424 static unsigned int fanout_demux_hash(struct packet_fanout *f,
1425 				      struct sk_buff *skb,
1426 				      unsigned int num)
1427 {
1428 	return reciprocal_scale(__skb_get_hash_symmetric(skb), num);
1429 }
1430 
1431 static unsigned int fanout_demux_lb(struct packet_fanout *f,
1432 				    struct sk_buff *skb,
1433 				    unsigned int num)
1434 {
1435 	unsigned int val = atomic_inc_return(&f->rr_cur);
1436 
1437 	return val % num;
1438 }
1439 
1440 static unsigned int fanout_demux_cpu(struct packet_fanout *f,
1441 				     struct sk_buff *skb,
1442 				     unsigned int num)
1443 {
1444 	return smp_processor_id() % num;
1445 }
1446 
1447 static unsigned int fanout_demux_rnd(struct packet_fanout *f,
1448 				     struct sk_buff *skb,
1449 				     unsigned int num)
1450 {
1451 	return get_random_u32_below(num);
1452 }
1453 
1454 static unsigned int fanout_demux_rollover(struct packet_fanout *f,
1455 					  struct sk_buff *skb,
1456 					  unsigned int idx, bool try_self,
1457 					  unsigned int num)
1458 {
1459 	struct packet_sock *po, *po_next, *po_skip = NULL;
1460 	unsigned int i, j, room = ROOM_NONE;
1461 
1462 	po = pkt_sk(rcu_dereference(f->arr[idx]));
1463 
1464 	if (try_self) {
1465 		room = packet_rcv_has_room(po, skb);
1466 		if (room == ROOM_NORMAL ||
1467 		    (room == ROOM_LOW && !fanout_flow_is_huge(po, skb)))
1468 			return idx;
1469 		po_skip = po;
1470 	}
1471 
1472 	i = j = min_t(int, po->rollover->sock, num - 1);
1473 	do {
1474 		po_next = pkt_sk(rcu_dereference(f->arr[i]));
1475 		if (po_next != po_skip &&
1476 		    !packet_sock_flag(po_next, PACKET_SOCK_PRESSURE) &&
1477 		    packet_rcv_has_room(po_next, skb) == ROOM_NORMAL) {
1478 			if (i != j)
1479 				po->rollover->sock = i;
1480 			atomic_long_inc(&po->rollover->num);
1481 			if (room == ROOM_LOW)
1482 				atomic_long_inc(&po->rollover->num_huge);
1483 			return i;
1484 		}
1485 
1486 		if (++i == num)
1487 			i = 0;
1488 	} while (i != j);
1489 
1490 	atomic_long_inc(&po->rollover->num_failed);
1491 	return idx;
1492 }
1493 
1494 static unsigned int fanout_demux_qm(struct packet_fanout *f,
1495 				    struct sk_buff *skb,
1496 				    unsigned int num)
1497 {
1498 	return skb_get_queue_mapping(skb) % num;
1499 }
1500 
1501 static unsigned int fanout_demux_bpf(struct packet_fanout *f,
1502 				     struct sk_buff *skb,
1503 				     unsigned int num)
1504 {
1505 	struct bpf_prog *prog;
1506 	unsigned int ret = 0;
1507 
1508 	rcu_read_lock();
1509 	prog = rcu_dereference(f->bpf_prog);
1510 	if (prog)
1511 		ret = bpf_prog_run_clear_cb(prog, skb) % num;
1512 	rcu_read_unlock();
1513 
1514 	return ret;
1515 }
1516 
1517 static bool fanout_has_flag(struct packet_fanout *f, u16 flag)
1518 {
1519 	return f->flags & (flag >> 8);
1520 }
1521 
1522 static int packet_rcv_fanout(struct sk_buff *skb, struct net_device *dev,
1523 			     struct packet_type *pt, struct net_device *orig_dev)
1524 {
1525 	struct packet_fanout *f = pt->af_packet_priv;
1526 	unsigned int num = READ_ONCE(f->num_members);
1527 	struct net *net = read_pnet(&f->net);
1528 	struct packet_sock *po;
1529 	unsigned int idx;
1530 
1531 	if (!net_eq(dev_net(dev), net) || !num) {
1532 		kfree_skb(skb);
1533 		return 0;
1534 	}
1535 
1536 	if (fanout_has_flag(f, PACKET_FANOUT_FLAG_DEFRAG)) {
1537 		skb = ip_check_defrag(net, skb, IP_DEFRAG_AF_PACKET);
1538 		if (!skb)
1539 			return 0;
1540 	}
1541 	switch (f->type) {
1542 	case PACKET_FANOUT_HASH:
1543 	default:
1544 		idx = fanout_demux_hash(f, skb, num);
1545 		break;
1546 	case PACKET_FANOUT_LB:
1547 		idx = fanout_demux_lb(f, skb, num);
1548 		break;
1549 	case PACKET_FANOUT_CPU:
1550 		idx = fanout_demux_cpu(f, skb, num);
1551 		break;
1552 	case PACKET_FANOUT_RND:
1553 		idx = fanout_demux_rnd(f, skb, num);
1554 		break;
1555 	case PACKET_FANOUT_QM:
1556 		idx = fanout_demux_qm(f, skb, num);
1557 		break;
1558 	case PACKET_FANOUT_ROLLOVER:
1559 		idx = fanout_demux_rollover(f, skb, 0, false, num);
1560 		break;
1561 	case PACKET_FANOUT_CBPF:
1562 	case PACKET_FANOUT_EBPF:
1563 		idx = fanout_demux_bpf(f, skb, num);
1564 		break;
1565 	}
1566 
1567 	if (fanout_has_flag(f, PACKET_FANOUT_FLAG_ROLLOVER))
1568 		idx = fanout_demux_rollover(f, skb, idx, true, num);
1569 
1570 	po = pkt_sk(rcu_dereference(f->arr[idx]));
1571 	return po->prot_hook.func(skb, dev, &po->prot_hook, orig_dev);
1572 }
1573 
1574 DEFINE_MUTEX(fanout_mutex);
1575 EXPORT_SYMBOL_GPL(fanout_mutex);
1576 static LIST_HEAD(fanout_list);
1577 static u16 fanout_next_id;
1578 
1579 static void __fanout_link(struct sock *sk, struct packet_sock *po)
1580 {
1581 	struct packet_fanout *f = po->fanout;
1582 
1583 	spin_lock(&f->lock);
1584 	rcu_assign_pointer(f->arr[f->num_members], sk);
1585 	smp_wmb();
1586 	f->num_members++;
1587 	if (f->num_members == 1)
1588 		dev_add_pack(&f->prot_hook);
1589 	spin_unlock(&f->lock);
1590 }
1591 
1592 static void __fanout_unlink(struct sock *sk, struct packet_sock *po)
1593 {
1594 	struct packet_fanout *f = po->fanout;
1595 	int i;
1596 
1597 	spin_lock(&f->lock);
1598 	for (i = 0; i < f->num_members; i++) {
1599 		if (rcu_dereference_protected(f->arr[i],
1600 					      lockdep_is_held(&f->lock)) == sk)
1601 			break;
1602 	}
1603 	BUG_ON(i >= f->num_members);
1604 	rcu_assign_pointer(f->arr[i],
1605 			   rcu_dereference_protected(f->arr[f->num_members - 1],
1606 						     lockdep_is_held(&f->lock)));
1607 	f->num_members--;
1608 	if (f->num_members == 0)
1609 		__dev_remove_pack(&f->prot_hook);
1610 	spin_unlock(&f->lock);
1611 }
1612 
1613 static bool match_fanout_group(struct packet_type *ptype, struct sock *sk)
1614 {
1615 	if (sk->sk_family != PF_PACKET)
1616 		return false;
1617 
1618 	return ptype->af_packet_priv == pkt_sk(sk)->fanout;
1619 }
1620 
1621 static void fanout_init_data(struct packet_fanout *f)
1622 {
1623 	switch (f->type) {
1624 	case PACKET_FANOUT_LB:
1625 		atomic_set(&f->rr_cur, 0);
1626 		break;
1627 	case PACKET_FANOUT_CBPF:
1628 	case PACKET_FANOUT_EBPF:
1629 		RCU_INIT_POINTER(f->bpf_prog, NULL);
1630 		break;
1631 	}
1632 }
1633 
1634 static void __fanout_set_data_bpf(struct packet_fanout *f, struct bpf_prog *new)
1635 {
1636 	struct bpf_prog *old;
1637 
1638 	spin_lock(&f->lock);
1639 	old = rcu_dereference_protected(f->bpf_prog, lockdep_is_held(&f->lock));
1640 	rcu_assign_pointer(f->bpf_prog, new);
1641 	spin_unlock(&f->lock);
1642 
1643 	if (old) {
1644 		synchronize_net();
1645 		bpf_prog_destroy(old);
1646 	}
1647 }
1648 
1649 static int fanout_set_data_cbpf(struct packet_sock *po, sockptr_t data,
1650 				unsigned int len)
1651 {
1652 	struct bpf_prog *new;
1653 	struct sock_fprog fprog;
1654 	int ret;
1655 
1656 	if (sock_flag(&po->sk, SOCK_FILTER_LOCKED))
1657 		return -EPERM;
1658 
1659 	ret = copy_bpf_fprog_from_user(&fprog, data, len);
1660 	if (ret)
1661 		return ret;
1662 
1663 	ret = bpf_prog_create_from_user(&new, &fprog, NULL, false);
1664 	if (ret)
1665 		return ret;
1666 
1667 	__fanout_set_data_bpf(po->fanout, new);
1668 	return 0;
1669 }
1670 
1671 static int fanout_set_data_ebpf(struct packet_sock *po, sockptr_t data,
1672 				unsigned int len)
1673 {
1674 	struct bpf_prog *new;
1675 	u32 fd;
1676 
1677 	if (sock_flag(&po->sk, SOCK_FILTER_LOCKED))
1678 		return -EPERM;
1679 	if (len != sizeof(fd))
1680 		return -EINVAL;
1681 	if (copy_from_sockptr(&fd, data, len))
1682 		return -EFAULT;
1683 
1684 	new = bpf_prog_get_type(fd, BPF_PROG_TYPE_SOCKET_FILTER);
1685 	if (IS_ERR(new))
1686 		return PTR_ERR(new);
1687 
1688 	__fanout_set_data_bpf(po->fanout, new);
1689 	return 0;
1690 }
1691 
1692 static int fanout_set_data(struct packet_sock *po, sockptr_t data,
1693 			   unsigned int len)
1694 {
1695 	switch (po->fanout->type) {
1696 	case PACKET_FANOUT_CBPF:
1697 		return fanout_set_data_cbpf(po, data, len);
1698 	case PACKET_FANOUT_EBPF:
1699 		return fanout_set_data_ebpf(po, data, len);
1700 	default:
1701 		return -EINVAL;
1702 	}
1703 }
1704 
1705 static void fanout_release_data(struct packet_fanout *f)
1706 {
1707 	switch (f->type) {
1708 	case PACKET_FANOUT_CBPF:
1709 	case PACKET_FANOUT_EBPF:
1710 		__fanout_set_data_bpf(f, NULL);
1711 	}
1712 }
1713 
1714 static bool __fanout_id_is_free(struct sock *sk, u16 candidate_id)
1715 {
1716 	struct packet_fanout *f;
1717 
1718 	list_for_each_entry(f, &fanout_list, list) {
1719 		if (f->id == candidate_id &&
1720 		    read_pnet(&f->net) == sock_net(sk)) {
1721 			return false;
1722 		}
1723 	}
1724 	return true;
1725 }
1726 
1727 static bool fanout_find_new_id(struct sock *sk, u16 *new_id)
1728 {
1729 	u16 id = fanout_next_id;
1730 
1731 	do {
1732 		if (__fanout_id_is_free(sk, id)) {
1733 			*new_id = id;
1734 			fanout_next_id = id + 1;
1735 			return true;
1736 		}
1737 
1738 		id++;
1739 	} while (id != fanout_next_id);
1740 
1741 	return false;
1742 }
1743 
1744 static int fanout_add(struct sock *sk, struct fanout_args *args)
1745 {
1746 	struct packet_rollover *rollover = NULL;
1747 	struct packet_sock *po = pkt_sk(sk);
1748 	u16 type_flags = args->type_flags;
1749 	struct packet_fanout *f, *match;
1750 	u8 type = type_flags & 0xff;
1751 	u8 flags = type_flags >> 8;
1752 	u16 id = args->id;
1753 	int err;
1754 
1755 	switch (type) {
1756 	case PACKET_FANOUT_ROLLOVER:
1757 		if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)
1758 			return -EINVAL;
1759 		break;
1760 	case PACKET_FANOUT_HASH:
1761 	case PACKET_FANOUT_LB:
1762 	case PACKET_FANOUT_CPU:
1763 	case PACKET_FANOUT_RND:
1764 	case PACKET_FANOUT_QM:
1765 	case PACKET_FANOUT_CBPF:
1766 	case PACKET_FANOUT_EBPF:
1767 		break;
1768 	default:
1769 		return -EINVAL;
1770 	}
1771 
1772 	mutex_lock(&fanout_mutex);
1773 
1774 	err = -EALREADY;
1775 	if (po->fanout)
1776 		goto out;
1777 
1778 	if (type == PACKET_FANOUT_ROLLOVER ||
1779 	    (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)) {
1780 		err = -ENOMEM;
1781 		rollover = kzalloc(sizeof(*rollover), GFP_KERNEL);
1782 		if (!rollover)
1783 			goto out;
1784 		atomic_long_set(&rollover->num, 0);
1785 		atomic_long_set(&rollover->num_huge, 0);
1786 		atomic_long_set(&rollover->num_failed, 0);
1787 	}
1788 
1789 	if (type_flags & PACKET_FANOUT_FLAG_UNIQUEID) {
1790 		if (id != 0) {
1791 			err = -EINVAL;
1792 			goto out;
1793 		}
1794 		if (!fanout_find_new_id(sk, &id)) {
1795 			err = -ENOMEM;
1796 			goto out;
1797 		}
1798 		/* ephemeral flag for the first socket in the group: drop it */
1799 		flags &= ~(PACKET_FANOUT_FLAG_UNIQUEID >> 8);
1800 	}
1801 
1802 	match = NULL;
1803 	list_for_each_entry(f, &fanout_list, list) {
1804 		if (f->id == id &&
1805 		    read_pnet(&f->net) == sock_net(sk)) {
1806 			match = f;
1807 			break;
1808 		}
1809 	}
1810 	err = -EINVAL;
1811 	if (match) {
1812 		if (match->flags != flags)
1813 			goto out;
1814 		if (args->max_num_members &&
1815 		    args->max_num_members != match->max_num_members)
1816 			goto out;
1817 	} else {
1818 		if (args->max_num_members > PACKET_FANOUT_MAX)
1819 			goto out;
1820 		if (!args->max_num_members)
1821 			/* legacy PACKET_FANOUT_MAX */
1822 			args->max_num_members = 256;
1823 		err = -ENOMEM;
1824 		match = kvzalloc(struct_size(match, arr, args->max_num_members),
1825 				 GFP_KERNEL);
1826 		if (!match)
1827 			goto out;
1828 		write_pnet(&match->net, sock_net(sk));
1829 		match->id = id;
1830 		match->type = type;
1831 		match->flags = flags;
1832 		INIT_LIST_HEAD(&match->list);
1833 		spin_lock_init(&match->lock);
1834 		refcount_set(&match->sk_ref, 0);
1835 		fanout_init_data(match);
1836 		match->prot_hook.type = po->prot_hook.type;
1837 		match->prot_hook.dev = po->prot_hook.dev;
1838 		match->prot_hook.func = packet_rcv_fanout;
1839 		match->prot_hook.af_packet_priv = match;
1840 		match->prot_hook.af_packet_net = read_pnet(&match->net);
1841 		match->prot_hook.id_match = match_fanout_group;
1842 		match->max_num_members = args->max_num_members;
1843 		match->prot_hook.ignore_outgoing = type_flags & PACKET_FANOUT_FLAG_IGNORE_OUTGOING;
1844 		list_add(&match->list, &fanout_list);
1845 	}
1846 	err = -EINVAL;
1847 
1848 	spin_lock(&po->bind_lock);
1849 	if (po->num &&
1850 	    match->type == type &&
1851 	    match->prot_hook.type == po->prot_hook.type &&
1852 	    match->prot_hook.dev == po->prot_hook.dev) {
1853 		err = -ENOSPC;
1854 		if (refcount_read(&match->sk_ref) < match->max_num_members) {
1855 			/* Paired with packet_setsockopt(PACKET_FANOUT_DATA) */
1856 			WRITE_ONCE(po->fanout, match);
1857 
1858 			po->rollover = rollover;
1859 			rollover = NULL;
1860 			refcount_set(&match->sk_ref, refcount_read(&match->sk_ref) + 1);
1861 			if (packet_sock_flag(po, PACKET_SOCK_RUNNING)) {
1862 				__dev_remove_pack(&po->prot_hook);
1863 				__fanout_link(sk, po);
1864 			}
1865 			err = 0;
1866 		}
1867 	}
1868 	spin_unlock(&po->bind_lock);
1869 
1870 	if (err && !refcount_read(&match->sk_ref)) {
1871 		list_del(&match->list);
1872 		kvfree(match);
1873 	}
1874 
1875 out:
1876 	kfree(rollover);
1877 	mutex_unlock(&fanout_mutex);
1878 	return err;
1879 }
1880 
1881 /* If pkt_sk(sk)->fanout->sk_ref is zero, this function removes
1882  * pkt_sk(sk)->fanout from fanout_list and returns pkt_sk(sk)->fanout.
1883  * It is the responsibility of the caller to call fanout_release_data() and
1884  * free the returned packet_fanout (after synchronize_net())
1885  */
1886 static struct packet_fanout *fanout_release(struct sock *sk)
1887 {
1888 	struct packet_sock *po = pkt_sk(sk);
1889 	struct packet_fanout *f;
1890 
1891 	mutex_lock(&fanout_mutex);
1892 	f = po->fanout;
1893 	if (f) {
1894 		po->fanout = NULL;
1895 
1896 		if (refcount_dec_and_test(&f->sk_ref))
1897 			list_del(&f->list);
1898 		else
1899 			f = NULL;
1900 	}
1901 	mutex_unlock(&fanout_mutex);
1902 
1903 	return f;
1904 }
1905 
1906 static bool packet_extra_vlan_len_allowed(const struct net_device *dev,
1907 					  struct sk_buff *skb)
1908 {
1909 	/* Earlier code assumed this would be a VLAN pkt, double-check
1910 	 * this now that we have the actual packet in hand. We can only
1911 	 * do this check on Ethernet devices.
1912 	 */
1913 	if (unlikely(dev->type != ARPHRD_ETHER))
1914 		return false;
1915 
1916 	skb_reset_mac_header(skb);
1917 	return likely(eth_hdr(skb)->h_proto == htons(ETH_P_8021Q));
1918 }
1919 
1920 static const struct proto_ops packet_ops;
1921 
1922 static const struct proto_ops packet_ops_spkt;
1923 
1924 static int packet_rcv_spkt(struct sk_buff *skb, struct net_device *dev,
1925 			   struct packet_type *pt, struct net_device *orig_dev)
1926 {
1927 	struct sock *sk;
1928 	struct sockaddr_pkt *spkt;
1929 
1930 	/*
1931 	 *	When we registered the protocol we saved the socket in the data
1932 	 *	field for just this event.
1933 	 */
1934 
1935 	sk = pt->af_packet_priv;
1936 
1937 	/*
1938 	 *	Yank back the headers [hope the device set this
1939 	 *	right or kerboom...]
1940 	 *
1941 	 *	Incoming packets have ll header pulled,
1942 	 *	push it back.
1943 	 *
1944 	 *	For outgoing ones skb->data == skb_mac_header(skb)
1945 	 *	so that this procedure is noop.
1946 	 */
1947 
1948 	if (skb->pkt_type == PACKET_LOOPBACK)
1949 		goto out;
1950 
1951 	if (!net_eq(dev_net(dev), sock_net(sk)))
1952 		goto out;
1953 
1954 	skb = skb_share_check(skb, GFP_ATOMIC);
1955 	if (skb == NULL)
1956 		goto oom;
1957 
1958 	/* drop any routing info */
1959 	skb_dst_drop(skb);
1960 
1961 	/* drop conntrack reference */
1962 	nf_reset_ct(skb);
1963 
1964 	spkt = &PACKET_SKB_CB(skb)->sa.pkt;
1965 
1966 	skb_push(skb, skb->data - skb_mac_header(skb));
1967 
1968 	/*
1969 	 *	The SOCK_PACKET socket receives _all_ frames.
1970 	 */
1971 
1972 	spkt->spkt_family = dev->type;
1973 	strscpy(spkt->spkt_device, dev->name, sizeof(spkt->spkt_device));
1974 	spkt->spkt_protocol = skb->protocol;
1975 
1976 	/*
1977 	 *	Charge the memory to the socket. This is done specifically
1978 	 *	to prevent sockets using all the memory up.
1979 	 */
1980 
1981 	if (sock_queue_rcv_skb(sk, skb) == 0)
1982 		return 0;
1983 
1984 out:
1985 	kfree_skb(skb);
1986 oom:
1987 	return 0;
1988 }
1989 
1990 static void packet_parse_headers(struct sk_buff *skb, struct socket *sock)
1991 {
1992 	int depth;
1993 
1994 	if ((!skb->protocol || skb->protocol == htons(ETH_P_ALL)) &&
1995 	    sock->type == SOCK_RAW) {
1996 		skb_reset_mac_header(skb);
1997 		skb->protocol = dev_parse_header_protocol(skb);
1998 	}
1999 
2000 	/* Move network header to the right position for VLAN tagged packets */
2001 	if (likely(skb->dev->type == ARPHRD_ETHER) &&
2002 	    eth_type_vlan(skb->protocol) &&
2003 	    vlan_get_protocol_and_depth(skb, skb->protocol, &depth) != 0)
2004 		skb_set_network_header(skb, depth);
2005 
2006 	skb_probe_transport_header(skb);
2007 }
2008 
2009 /*
2010  *	Output a raw packet to a device layer. This bypasses all the other
2011  *	protocol layers and you must therefore supply it with a complete frame
2012  */
2013 
2014 static int packet_sendmsg_spkt(struct socket *sock, struct msghdr *msg,
2015 			       size_t len)
2016 {
2017 	struct sock *sk = sock->sk;
2018 	DECLARE_SOCKADDR(struct sockaddr_pkt *, saddr, msg->msg_name);
2019 	struct sk_buff *skb = NULL;
2020 	struct net_device *dev;
2021 	struct sockcm_cookie sockc;
2022 	__be16 proto = 0;
2023 	int err;
2024 	int extra_len = 0;
2025 
2026 	/*
2027 	 *	Get and verify the address.
2028 	 */
2029 
2030 	if (saddr) {
2031 		if (msg->msg_namelen < sizeof(struct sockaddr))
2032 			return -EINVAL;
2033 		if (msg->msg_namelen == sizeof(struct sockaddr_pkt))
2034 			proto = saddr->spkt_protocol;
2035 	} else
2036 		return -ENOTCONN;	/* SOCK_PACKET must be sent giving an address */
2037 
2038 	/*
2039 	 *	Find the device first to size check it
2040 	 */
2041 
2042 	saddr->spkt_device[sizeof(saddr->spkt_device) - 1] = 0;
2043 retry:
2044 	rcu_read_lock();
2045 	dev = dev_get_by_name_rcu(sock_net(sk), saddr->spkt_device);
2046 	err = -ENODEV;
2047 	if (dev == NULL)
2048 		goto out_unlock;
2049 
2050 	err = -ENETDOWN;
2051 	if (!(dev->flags & IFF_UP))
2052 		goto out_unlock;
2053 
2054 	/*
2055 	 * You may not queue a frame bigger than the mtu. This is the lowest level
2056 	 * raw protocol and you must do your own fragmentation at this level.
2057 	 */
2058 
2059 	if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
2060 		if (!netif_supports_nofcs(dev)) {
2061 			err = -EPROTONOSUPPORT;
2062 			goto out_unlock;
2063 		}
2064 		extra_len = 4; /* We're doing our own CRC */
2065 	}
2066 
2067 	err = -EMSGSIZE;
2068 	if (len > dev->mtu + dev->hard_header_len + VLAN_HLEN + extra_len)
2069 		goto out_unlock;
2070 
2071 	if (!skb) {
2072 		size_t reserved = LL_RESERVED_SPACE(dev);
2073 		int tlen = dev->needed_tailroom;
2074 		unsigned int hhlen = dev->header_ops ? dev->hard_header_len : 0;
2075 
2076 		rcu_read_unlock();
2077 		skb = sock_wmalloc(sk, len + reserved + tlen, 0, GFP_KERNEL);
2078 		if (skb == NULL)
2079 			return -ENOBUFS;
2080 		/* FIXME: Save some space for broken drivers that write a hard
2081 		 * header at transmission time by themselves. PPP is the notable
2082 		 * one here. This should really be fixed at the driver level.
2083 		 */
2084 		skb_reserve(skb, reserved);
2085 		skb_reset_network_header(skb);
2086 
2087 		/* Try to align data part correctly */
2088 		if (hhlen) {
2089 			skb->data -= hhlen;
2090 			skb->tail -= hhlen;
2091 			if (len < hhlen)
2092 				skb_reset_network_header(skb);
2093 		}
2094 		err = memcpy_from_msg(skb_put(skb, len), msg, len);
2095 		if (err)
2096 			goto out_free;
2097 		goto retry;
2098 	}
2099 
2100 	if (!dev_validate_header(dev, skb->data, len) || !skb->len) {
2101 		err = -EINVAL;
2102 		goto out_unlock;
2103 	}
2104 	if (len > (dev->mtu + dev->hard_header_len + extra_len) &&
2105 	    !packet_extra_vlan_len_allowed(dev, skb)) {
2106 		err = -EMSGSIZE;
2107 		goto out_unlock;
2108 	}
2109 
2110 	sockcm_init(&sockc, sk);
2111 	if (msg->msg_controllen) {
2112 		err = sock_cmsg_send(sk, msg, &sockc);
2113 		if (unlikely(err))
2114 			goto out_unlock;
2115 	}
2116 
2117 	skb->protocol = proto;
2118 	skb->dev = dev;
2119 	skb->priority = READ_ONCE(sk->sk_priority);
2120 	skb->mark = READ_ONCE(sk->sk_mark);
2121 	skb_set_delivery_type_by_clockid(skb, sockc.transmit_time, sk->sk_clockid);
2122 	skb_setup_tx_timestamp(skb, &sockc);
2123 
2124 	if (unlikely(extra_len == 4))
2125 		skb->no_fcs = 1;
2126 
2127 	packet_parse_headers(skb, sock);
2128 
2129 	dev_queue_xmit(skb);
2130 	rcu_read_unlock();
2131 	return len;
2132 
2133 out_unlock:
2134 	rcu_read_unlock();
2135 out_free:
2136 	kfree_skb(skb);
2137 	return err;
2138 }
2139 
2140 static unsigned int run_filter(struct sk_buff *skb,
2141 			       const struct sock *sk,
2142 			       unsigned int res)
2143 {
2144 	struct sk_filter *filter;
2145 
2146 	rcu_read_lock();
2147 	filter = rcu_dereference(sk->sk_filter);
2148 	if (filter != NULL)
2149 		res = bpf_prog_run_clear_cb(filter->prog, skb);
2150 	rcu_read_unlock();
2151 
2152 	return res;
2153 }
2154 
2155 static int packet_rcv_vnet(struct msghdr *msg, const struct sk_buff *skb,
2156 			   size_t *len, int vnet_hdr_sz)
2157 {
2158 	struct virtio_net_hdr_mrg_rxbuf vnet_hdr = { .num_buffers = 0 };
2159 
2160 	if (*len < vnet_hdr_sz)
2161 		return -EINVAL;
2162 	*len -= vnet_hdr_sz;
2163 
2164 	if (virtio_net_hdr_from_skb(skb, (struct virtio_net_hdr *)&vnet_hdr, vio_le(), true, 0))
2165 		return -EINVAL;
2166 
2167 	return memcpy_to_msg(msg, (void *)&vnet_hdr, vnet_hdr_sz);
2168 }
2169 
2170 /*
2171  * This function makes lazy skb cloning in hope that most of packets
2172  * are discarded by BPF.
2173  *
2174  * Note tricky part: we DO mangle shared skb! skb->data, skb->len
2175  * and skb->cb are mangled. It works because (and until) packets
2176  * falling here are owned by current CPU. Output packets are cloned
2177  * by dev_queue_xmit_nit(), input packets are processed by net_bh
2178  * sequentially, so that if we return skb to original state on exit,
2179  * we will not harm anyone.
2180  */
2181 
2182 static int packet_rcv(struct sk_buff *skb, struct net_device *dev,
2183 		      struct packet_type *pt, struct net_device *orig_dev)
2184 {
2185 	enum skb_drop_reason drop_reason = SKB_CONSUMED;
2186 	struct sock *sk = NULL;
2187 	struct sockaddr_ll *sll;
2188 	struct packet_sock *po;
2189 	u8 *skb_head = skb->data;
2190 	int skb_len = skb->len;
2191 	unsigned int snaplen, res;
2192 
2193 	if (skb->pkt_type == PACKET_LOOPBACK)
2194 		goto drop;
2195 
2196 	sk = pt->af_packet_priv;
2197 	po = pkt_sk(sk);
2198 
2199 	if (!net_eq(dev_net(dev), sock_net(sk)))
2200 		goto drop;
2201 
2202 	skb->dev = dev;
2203 
2204 	if (dev_has_header(dev)) {
2205 		/* The device has an explicit notion of ll header,
2206 		 * exported to higher levels.
2207 		 *
2208 		 * Otherwise, the device hides details of its frame
2209 		 * structure, so that corresponding packet head is
2210 		 * never delivered to user.
2211 		 */
2212 		if (sk->sk_type != SOCK_DGRAM)
2213 			skb_push(skb, skb->data - skb_mac_header(skb));
2214 		else if (skb->pkt_type == PACKET_OUTGOING) {
2215 			/* Special case: outgoing packets have ll header at head */
2216 			skb_pull(skb, skb_network_offset(skb));
2217 		}
2218 	}
2219 
2220 	snaplen = skb_frags_readable(skb) ? skb->len : skb_headlen(skb);
2221 
2222 	res = run_filter(skb, sk, snaplen);
2223 	if (!res)
2224 		goto drop_n_restore;
2225 	if (snaplen > res)
2226 		snaplen = res;
2227 
2228 	if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
2229 		goto drop_n_acct;
2230 
2231 	if (skb_shared(skb)) {
2232 		struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
2233 		if (nskb == NULL)
2234 			goto drop_n_acct;
2235 
2236 		if (skb_head != skb->data) {
2237 			skb->data = skb_head;
2238 			skb->len = skb_len;
2239 		}
2240 		consume_skb(skb);
2241 		skb = nskb;
2242 	}
2243 
2244 	sock_skb_cb_check_size(sizeof(*PACKET_SKB_CB(skb)) + MAX_ADDR_LEN - 8);
2245 
2246 	sll = &PACKET_SKB_CB(skb)->sa.ll;
2247 	sll->sll_hatype = dev->type;
2248 	sll->sll_pkttype = skb->pkt_type;
2249 	if (unlikely(packet_sock_flag(po, PACKET_SOCK_ORIGDEV)))
2250 		sll->sll_ifindex = orig_dev->ifindex;
2251 	else
2252 		sll->sll_ifindex = dev->ifindex;
2253 
2254 	sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
2255 
2256 	/* sll->sll_family and sll->sll_protocol are set in packet_recvmsg().
2257 	 * Use their space for storing the original skb length.
2258 	 */
2259 	PACKET_SKB_CB(skb)->sa.origlen = skb->len;
2260 
2261 	if (pskb_trim(skb, snaplen))
2262 		goto drop_n_acct;
2263 
2264 	skb_set_owner_r(skb, sk);
2265 	skb->dev = NULL;
2266 	skb_dst_drop(skb);
2267 
2268 	/* drop conntrack reference */
2269 	nf_reset_ct(skb);
2270 
2271 	spin_lock(&sk->sk_receive_queue.lock);
2272 	po->stats.stats1.tp_packets++;
2273 	sock_skb_set_dropcount(sk, skb);
2274 	skb_clear_delivery_time(skb);
2275 	__skb_queue_tail(&sk->sk_receive_queue, skb);
2276 	spin_unlock(&sk->sk_receive_queue.lock);
2277 	sk->sk_data_ready(sk);
2278 	return 0;
2279 
2280 drop_n_acct:
2281 	atomic_inc(&po->tp_drops);
2282 	atomic_inc(&sk->sk_drops);
2283 	drop_reason = SKB_DROP_REASON_PACKET_SOCK_ERROR;
2284 
2285 drop_n_restore:
2286 	if (skb_head != skb->data && skb_shared(skb)) {
2287 		skb->data = skb_head;
2288 		skb->len = skb_len;
2289 	}
2290 drop:
2291 	sk_skb_reason_drop(sk, skb, drop_reason);
2292 	return 0;
2293 }
2294 
2295 static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
2296 		       struct packet_type *pt, struct net_device *orig_dev)
2297 {
2298 	enum skb_drop_reason drop_reason = SKB_CONSUMED;
2299 	struct sock *sk = NULL;
2300 	struct packet_sock *po;
2301 	struct sockaddr_ll *sll;
2302 	union tpacket_uhdr h;
2303 	u8 *skb_head = skb->data;
2304 	int skb_len = skb->len;
2305 	unsigned int snaplen, res;
2306 	unsigned long status = TP_STATUS_USER;
2307 	unsigned short macoff, hdrlen;
2308 	unsigned int netoff;
2309 	struct sk_buff *copy_skb = NULL;
2310 	struct timespec64 ts;
2311 	__u32 ts_status;
2312 	unsigned int slot_id = 0;
2313 	int vnet_hdr_sz = 0;
2314 
2315 	/* struct tpacket{2,3}_hdr is aligned to a multiple of TPACKET_ALIGNMENT.
2316 	 * We may add members to them until current aligned size without forcing
2317 	 * userspace to call getsockopt(..., PACKET_HDRLEN, ...).
2318 	 */
2319 	BUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h2)) != 32);
2320 	BUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h3)) != 48);
2321 
2322 	if (skb->pkt_type == PACKET_LOOPBACK)
2323 		goto drop;
2324 
2325 	sk = pt->af_packet_priv;
2326 	po = pkt_sk(sk);
2327 
2328 	if (!net_eq(dev_net(dev), sock_net(sk)))
2329 		goto drop;
2330 
2331 	if (dev_has_header(dev)) {
2332 		if (sk->sk_type != SOCK_DGRAM)
2333 			skb_push(skb, skb->data - skb_mac_header(skb));
2334 		else if (skb->pkt_type == PACKET_OUTGOING) {
2335 			/* Special case: outgoing packets have ll header at head */
2336 			skb_pull(skb, skb_network_offset(skb));
2337 		}
2338 	}
2339 
2340 	snaplen = skb_frags_readable(skb) ? skb->len : skb_headlen(skb);
2341 
2342 	res = run_filter(skb, sk, snaplen);
2343 	if (!res)
2344 		goto drop_n_restore;
2345 
2346 	/* If we are flooded, just give up */
2347 	if (__packet_rcv_has_room(po, skb) == ROOM_NONE) {
2348 		atomic_inc(&po->tp_drops);
2349 		goto drop_n_restore;
2350 	}
2351 
2352 	if (skb->ip_summed == CHECKSUM_PARTIAL)
2353 		status |= TP_STATUS_CSUMNOTREADY;
2354 	else if (skb->pkt_type != PACKET_OUTGOING &&
2355 		 skb_csum_unnecessary(skb))
2356 		status |= TP_STATUS_CSUM_VALID;
2357 	if (skb_is_gso(skb) && skb_is_gso_tcp(skb))
2358 		status |= TP_STATUS_GSO_TCP;
2359 
2360 	if (snaplen > res)
2361 		snaplen = res;
2362 
2363 	if (sk->sk_type == SOCK_DGRAM) {
2364 		macoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +
2365 				  po->tp_reserve;
2366 	} else {
2367 		unsigned int maclen = skb_network_offset(skb);
2368 		netoff = TPACKET_ALIGN(po->tp_hdrlen +
2369 				       (maclen < 16 ? 16 : maclen)) +
2370 				       po->tp_reserve;
2371 		vnet_hdr_sz = READ_ONCE(po->vnet_hdr_sz);
2372 		if (vnet_hdr_sz)
2373 			netoff += vnet_hdr_sz;
2374 		macoff = netoff - maclen;
2375 	}
2376 	if (netoff > USHRT_MAX) {
2377 		atomic_inc(&po->tp_drops);
2378 		goto drop_n_restore;
2379 	}
2380 	if (po->tp_version <= TPACKET_V2) {
2381 		if (macoff + snaplen > po->rx_ring.frame_size) {
2382 			if (READ_ONCE(po->copy_thresh) &&
2383 			    atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) {
2384 				if (skb_shared(skb)) {
2385 					copy_skb = skb_clone(skb, GFP_ATOMIC);
2386 				} else {
2387 					copy_skb = skb_get(skb);
2388 					skb_head = skb->data;
2389 				}
2390 				if (copy_skb) {
2391 					memset(&PACKET_SKB_CB(copy_skb)->sa.ll, 0,
2392 					       sizeof(PACKET_SKB_CB(copy_skb)->sa.ll));
2393 					skb_set_owner_r(copy_skb, sk);
2394 				}
2395 			}
2396 			snaplen = po->rx_ring.frame_size - macoff;
2397 			if ((int)snaplen < 0) {
2398 				snaplen = 0;
2399 				vnet_hdr_sz = 0;
2400 			}
2401 		}
2402 	} else if (unlikely(macoff + snaplen >
2403 			    GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len)) {
2404 		u32 nval;
2405 
2406 		nval = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len - macoff;
2407 		pr_err_once("tpacket_rcv: packet too big, clamped from %u to %u. macoff=%u\n",
2408 			    snaplen, nval, macoff);
2409 		snaplen = nval;
2410 		if (unlikely((int)snaplen < 0)) {
2411 			snaplen = 0;
2412 			macoff = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len;
2413 			vnet_hdr_sz = 0;
2414 		}
2415 	}
2416 	spin_lock(&sk->sk_receive_queue.lock);
2417 	h.raw = packet_current_rx_frame(po, skb,
2418 					TP_STATUS_KERNEL, (macoff+snaplen));
2419 	if (!h.raw)
2420 		goto drop_n_account;
2421 
2422 	if (po->tp_version <= TPACKET_V2) {
2423 		slot_id = po->rx_ring.head;
2424 		if (test_bit(slot_id, po->rx_ring.rx_owner_map))
2425 			goto drop_n_account;
2426 		__set_bit(slot_id, po->rx_ring.rx_owner_map);
2427 	}
2428 
2429 	if (vnet_hdr_sz &&
2430 	    virtio_net_hdr_from_skb(skb, h.raw + macoff -
2431 				    sizeof(struct virtio_net_hdr),
2432 				    vio_le(), true, 0)) {
2433 		if (po->tp_version == TPACKET_V3)
2434 			prb_clear_blk_fill_status(&po->rx_ring);
2435 		goto drop_n_account;
2436 	}
2437 
2438 	if (po->tp_version <= TPACKET_V2) {
2439 		packet_increment_rx_head(po, &po->rx_ring);
2440 	/*
2441 	 * LOSING will be reported till you read the stats,
2442 	 * because it's COR - Clear On Read.
2443 	 * Anyways, moving it for V1/V2 only as V3 doesn't need this
2444 	 * at packet level.
2445 	 */
2446 		if (atomic_read(&po->tp_drops))
2447 			status |= TP_STATUS_LOSING;
2448 	}
2449 
2450 	po->stats.stats1.tp_packets++;
2451 	if (copy_skb) {
2452 		status |= TP_STATUS_COPY;
2453 		skb_clear_delivery_time(copy_skb);
2454 		__skb_queue_tail(&sk->sk_receive_queue, copy_skb);
2455 	}
2456 	spin_unlock(&sk->sk_receive_queue.lock);
2457 
2458 	skb_copy_bits(skb, 0, h.raw + macoff, snaplen);
2459 
2460 	/* Always timestamp; prefer an existing software timestamp taken
2461 	 * closer to the time of capture.
2462 	 */
2463 	ts_status = tpacket_get_timestamp(skb, &ts,
2464 					  READ_ONCE(po->tp_tstamp) |
2465 					  SOF_TIMESTAMPING_SOFTWARE);
2466 	if (!ts_status)
2467 		ktime_get_real_ts64(&ts);
2468 
2469 	status |= ts_status;
2470 
2471 	switch (po->tp_version) {
2472 	case TPACKET_V1:
2473 		h.h1->tp_len = skb->len;
2474 		h.h1->tp_snaplen = snaplen;
2475 		h.h1->tp_mac = macoff;
2476 		h.h1->tp_net = netoff;
2477 		h.h1->tp_sec = ts.tv_sec;
2478 		h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
2479 		hdrlen = sizeof(*h.h1);
2480 		break;
2481 	case TPACKET_V2:
2482 		h.h2->tp_len = skb->len;
2483 		h.h2->tp_snaplen = snaplen;
2484 		h.h2->tp_mac = macoff;
2485 		h.h2->tp_net = netoff;
2486 		h.h2->tp_sec = ts.tv_sec;
2487 		h.h2->tp_nsec = ts.tv_nsec;
2488 		if (skb_vlan_tag_present(skb)) {
2489 			h.h2->tp_vlan_tci = skb_vlan_tag_get(skb);
2490 			h.h2->tp_vlan_tpid = ntohs(skb->vlan_proto);
2491 			status |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
2492 		} else if (unlikely(sk->sk_type == SOCK_DGRAM && eth_type_vlan(skb->protocol))) {
2493 			h.h2->tp_vlan_tci = vlan_get_tci(skb, skb->dev);
2494 			h.h2->tp_vlan_tpid = ntohs(skb->protocol);
2495 			status |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
2496 		} else {
2497 			h.h2->tp_vlan_tci = 0;
2498 			h.h2->tp_vlan_tpid = 0;
2499 		}
2500 		memset(h.h2->tp_padding, 0, sizeof(h.h2->tp_padding));
2501 		hdrlen = sizeof(*h.h2);
2502 		break;
2503 	case TPACKET_V3:
2504 		/* tp_nxt_offset,vlan are already populated above.
2505 		 * So DONT clear those fields here
2506 		 */
2507 		h.h3->tp_status |= status;
2508 		h.h3->tp_len = skb->len;
2509 		h.h3->tp_snaplen = snaplen;
2510 		h.h3->tp_mac = macoff;
2511 		h.h3->tp_net = netoff;
2512 		h.h3->tp_sec  = ts.tv_sec;
2513 		h.h3->tp_nsec = ts.tv_nsec;
2514 		memset(h.h3->tp_padding, 0, sizeof(h.h3->tp_padding));
2515 		hdrlen = sizeof(*h.h3);
2516 		break;
2517 	default:
2518 		BUG();
2519 	}
2520 
2521 	sll = h.raw + TPACKET_ALIGN(hdrlen);
2522 	sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
2523 	sll->sll_family = AF_PACKET;
2524 	sll->sll_hatype = dev->type;
2525 	sll->sll_protocol = (sk->sk_type == SOCK_DGRAM) ?
2526 		vlan_get_protocol_dgram(skb) : skb->protocol;
2527 	sll->sll_pkttype = skb->pkt_type;
2528 	if (unlikely(packet_sock_flag(po, PACKET_SOCK_ORIGDEV)))
2529 		sll->sll_ifindex = orig_dev->ifindex;
2530 	else
2531 		sll->sll_ifindex = dev->ifindex;
2532 
2533 	smp_mb();
2534 
2535 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
2536 	if (po->tp_version <= TPACKET_V2) {
2537 		u8 *start, *end;
2538 
2539 		end = (u8 *) PAGE_ALIGN((unsigned long) h.raw +
2540 					macoff + snaplen);
2541 
2542 		for (start = h.raw; start < end; start += PAGE_SIZE)
2543 			flush_dcache_page(pgv_to_page(start));
2544 	}
2545 	smp_wmb();
2546 #endif
2547 
2548 	if (po->tp_version <= TPACKET_V2) {
2549 		spin_lock(&sk->sk_receive_queue.lock);
2550 		__packet_set_status(po, h.raw, status);
2551 		__clear_bit(slot_id, po->rx_ring.rx_owner_map);
2552 		spin_unlock(&sk->sk_receive_queue.lock);
2553 		sk->sk_data_ready(sk);
2554 	} else if (po->tp_version == TPACKET_V3) {
2555 		prb_clear_blk_fill_status(&po->rx_ring);
2556 	}
2557 
2558 drop_n_restore:
2559 	if (skb_head != skb->data && skb_shared(skb)) {
2560 		skb->data = skb_head;
2561 		skb->len = skb_len;
2562 	}
2563 drop:
2564 	sk_skb_reason_drop(sk, skb, drop_reason);
2565 	return 0;
2566 
2567 drop_n_account:
2568 	spin_unlock(&sk->sk_receive_queue.lock);
2569 	atomic_inc(&po->tp_drops);
2570 	drop_reason = SKB_DROP_REASON_PACKET_SOCK_ERROR;
2571 
2572 	sk->sk_data_ready(sk);
2573 	sk_skb_reason_drop(sk, copy_skb, drop_reason);
2574 	goto drop_n_restore;
2575 }
2576 
2577 static void tpacket_destruct_skb(struct sk_buff *skb)
2578 {
2579 	struct packet_sock *po = pkt_sk(skb->sk);
2580 
2581 	if (likely(po->tx_ring.pg_vec)) {
2582 		void *ph;
2583 		__u32 ts;
2584 
2585 		ph = skb_zcopy_get_nouarg(skb);
2586 		packet_dec_pending(&po->tx_ring);
2587 
2588 		ts = __packet_set_timestamp(po, ph, skb);
2589 		__packet_set_status(po, ph, TP_STATUS_AVAILABLE | ts);
2590 
2591 		complete(&po->skb_completion);
2592 	}
2593 
2594 	sock_wfree(skb);
2595 }
2596 
2597 static int __packet_snd_vnet_parse(struct virtio_net_hdr *vnet_hdr, size_t len)
2598 {
2599 	if ((vnet_hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
2600 	    (__virtio16_to_cpu(vio_le(), vnet_hdr->csum_start) +
2601 	     __virtio16_to_cpu(vio_le(), vnet_hdr->csum_offset) + 2 >
2602 	      __virtio16_to_cpu(vio_le(), vnet_hdr->hdr_len)))
2603 		vnet_hdr->hdr_len = __cpu_to_virtio16(vio_le(),
2604 			 __virtio16_to_cpu(vio_le(), vnet_hdr->csum_start) +
2605 			__virtio16_to_cpu(vio_le(), vnet_hdr->csum_offset) + 2);
2606 
2607 	if (__virtio16_to_cpu(vio_le(), vnet_hdr->hdr_len) > len)
2608 		return -EINVAL;
2609 
2610 	return 0;
2611 }
2612 
2613 static int packet_snd_vnet_parse(struct msghdr *msg, size_t *len,
2614 				 struct virtio_net_hdr *vnet_hdr, int vnet_hdr_sz)
2615 {
2616 	int ret;
2617 
2618 	if (*len < vnet_hdr_sz)
2619 		return -EINVAL;
2620 	*len -= vnet_hdr_sz;
2621 
2622 	if (!copy_from_iter_full(vnet_hdr, sizeof(*vnet_hdr), &msg->msg_iter))
2623 		return -EFAULT;
2624 
2625 	ret = __packet_snd_vnet_parse(vnet_hdr, *len);
2626 	if (ret)
2627 		return ret;
2628 
2629 	/* move iter to point to the start of mac header */
2630 	if (vnet_hdr_sz != sizeof(struct virtio_net_hdr))
2631 		iov_iter_advance(&msg->msg_iter, vnet_hdr_sz - sizeof(struct virtio_net_hdr));
2632 
2633 	return 0;
2634 }
2635 
2636 static int tpacket_fill_skb(struct packet_sock *po, struct sk_buff *skb,
2637 		void *frame, struct net_device *dev, void *data, int tp_len,
2638 		__be16 proto, unsigned char *addr, int hlen, int copylen,
2639 		const struct sockcm_cookie *sockc)
2640 {
2641 	union tpacket_uhdr ph;
2642 	int to_write, offset, len, nr_frags, len_max;
2643 	struct socket *sock = po->sk.sk_socket;
2644 	struct page *page;
2645 	int err;
2646 
2647 	ph.raw = frame;
2648 
2649 	skb->protocol = proto;
2650 	skb->dev = dev;
2651 	skb->priority = READ_ONCE(po->sk.sk_priority);
2652 	skb->mark = READ_ONCE(po->sk.sk_mark);
2653 	skb_set_delivery_type_by_clockid(skb, sockc->transmit_time, po->sk.sk_clockid);
2654 	skb_setup_tx_timestamp(skb, sockc);
2655 	skb_zcopy_set_nouarg(skb, ph.raw);
2656 
2657 	skb_reserve(skb, hlen);
2658 	skb_reset_network_header(skb);
2659 
2660 	to_write = tp_len;
2661 
2662 	if (sock->type == SOCK_DGRAM) {
2663 		err = dev_hard_header(skb, dev, ntohs(proto), addr,
2664 				NULL, tp_len);
2665 		if (unlikely(err < 0))
2666 			return -EINVAL;
2667 	} else if (copylen) {
2668 		int hdrlen = min_t(int, copylen, tp_len);
2669 
2670 		skb_push(skb, dev->hard_header_len);
2671 		skb_put(skb, copylen - dev->hard_header_len);
2672 		err = skb_store_bits(skb, 0, data, hdrlen);
2673 		if (unlikely(err))
2674 			return err;
2675 		if (!dev_validate_header(dev, skb->data, hdrlen))
2676 			return -EINVAL;
2677 
2678 		data += hdrlen;
2679 		to_write -= hdrlen;
2680 	}
2681 
2682 	offset = offset_in_page(data);
2683 	len_max = PAGE_SIZE - offset;
2684 	len = ((to_write > len_max) ? len_max : to_write);
2685 
2686 	skb->data_len = to_write;
2687 	skb->len += to_write;
2688 	skb->truesize += to_write;
2689 	refcount_add(to_write, &po->sk.sk_wmem_alloc);
2690 
2691 	while (likely(to_write)) {
2692 		nr_frags = skb_shinfo(skb)->nr_frags;
2693 
2694 		if (unlikely(nr_frags >= MAX_SKB_FRAGS)) {
2695 			pr_err("Packet exceed the number of skb frags(%u)\n",
2696 			       (unsigned int)MAX_SKB_FRAGS);
2697 			return -EFAULT;
2698 		}
2699 
2700 		page = pgv_to_page(data);
2701 		data += len;
2702 		flush_dcache_page(page);
2703 		get_page(page);
2704 		skb_fill_page_desc(skb, nr_frags, page, offset, len);
2705 		to_write -= len;
2706 		offset = 0;
2707 		len_max = PAGE_SIZE;
2708 		len = ((to_write > len_max) ? len_max : to_write);
2709 	}
2710 
2711 	packet_parse_headers(skb, sock);
2712 
2713 	return tp_len;
2714 }
2715 
2716 static int tpacket_parse_header(struct packet_sock *po, void *frame,
2717 				int size_max, void **data)
2718 {
2719 	union tpacket_uhdr ph;
2720 	int tp_len, off;
2721 
2722 	ph.raw = frame;
2723 
2724 	switch (po->tp_version) {
2725 	case TPACKET_V3:
2726 		if (ph.h3->tp_next_offset != 0) {
2727 			pr_warn_once("variable sized slot not supported");
2728 			return -EINVAL;
2729 		}
2730 		tp_len = ph.h3->tp_len;
2731 		break;
2732 	case TPACKET_V2:
2733 		tp_len = ph.h2->tp_len;
2734 		break;
2735 	default:
2736 		tp_len = ph.h1->tp_len;
2737 		break;
2738 	}
2739 	if (unlikely(tp_len > size_max)) {
2740 		pr_err("packet size is too long (%d > %d)\n", tp_len, size_max);
2741 		return -EMSGSIZE;
2742 	}
2743 
2744 	if (unlikely(packet_sock_flag(po, PACKET_SOCK_TX_HAS_OFF))) {
2745 		int off_min, off_max;
2746 
2747 		off_min = po->tp_hdrlen - sizeof(struct sockaddr_ll);
2748 		off_max = po->tx_ring.frame_size - tp_len;
2749 		if (po->sk.sk_type == SOCK_DGRAM) {
2750 			switch (po->tp_version) {
2751 			case TPACKET_V3:
2752 				off = ph.h3->tp_net;
2753 				break;
2754 			case TPACKET_V2:
2755 				off = ph.h2->tp_net;
2756 				break;
2757 			default:
2758 				off = ph.h1->tp_net;
2759 				break;
2760 			}
2761 		} else {
2762 			switch (po->tp_version) {
2763 			case TPACKET_V3:
2764 				off = ph.h3->tp_mac;
2765 				break;
2766 			case TPACKET_V2:
2767 				off = ph.h2->tp_mac;
2768 				break;
2769 			default:
2770 				off = ph.h1->tp_mac;
2771 				break;
2772 			}
2773 		}
2774 		if (unlikely((off < off_min) || (off_max < off)))
2775 			return -EINVAL;
2776 	} else {
2777 		off = po->tp_hdrlen - sizeof(struct sockaddr_ll);
2778 	}
2779 
2780 	*data = frame + off;
2781 	return tp_len;
2782 }
2783 
2784 static int tpacket_snd(struct packet_sock *po, struct msghdr *msg)
2785 {
2786 	struct sk_buff *skb = NULL;
2787 	struct net_device *dev;
2788 	struct virtio_net_hdr *vnet_hdr = NULL;
2789 	struct sockcm_cookie sockc;
2790 	__be16 proto;
2791 	int err, reserve = 0;
2792 	void *ph;
2793 	DECLARE_SOCKADDR(struct sockaddr_ll *, saddr, msg->msg_name);
2794 	bool need_wait = !(msg->msg_flags & MSG_DONTWAIT);
2795 	int vnet_hdr_sz = READ_ONCE(po->vnet_hdr_sz);
2796 	unsigned char *addr = NULL;
2797 	int tp_len, size_max;
2798 	void *data;
2799 	int len_sum = 0;
2800 	int status = TP_STATUS_AVAILABLE;
2801 	int hlen, tlen, copylen = 0;
2802 	long timeo = 0;
2803 
2804 	mutex_lock(&po->pg_vec_lock);
2805 
2806 	/* packet_sendmsg() check on tx_ring.pg_vec was lockless,
2807 	 * we need to confirm it under protection of pg_vec_lock.
2808 	 */
2809 	if (unlikely(!po->tx_ring.pg_vec)) {
2810 		err = -EBUSY;
2811 		goto out;
2812 	}
2813 	if (likely(saddr == NULL)) {
2814 		dev	= packet_cached_dev_get(po);
2815 		proto	= READ_ONCE(po->num);
2816 	} else {
2817 		err = -EINVAL;
2818 		if (msg->msg_namelen < sizeof(struct sockaddr_ll))
2819 			goto out;
2820 		if (msg->msg_namelen < (saddr->sll_halen
2821 					+ offsetof(struct sockaddr_ll,
2822 						sll_addr)))
2823 			goto out;
2824 		proto	= saddr->sll_protocol;
2825 		dev = dev_get_by_index(sock_net(&po->sk), saddr->sll_ifindex);
2826 		if (po->sk.sk_socket->type == SOCK_DGRAM) {
2827 			if (dev && msg->msg_namelen < dev->addr_len +
2828 				   offsetof(struct sockaddr_ll, sll_addr))
2829 				goto out_put;
2830 			addr = saddr->sll_addr;
2831 		}
2832 	}
2833 
2834 	err = -ENXIO;
2835 	if (unlikely(dev == NULL))
2836 		goto out;
2837 	err = -ENETDOWN;
2838 	if (unlikely(!(dev->flags & IFF_UP)))
2839 		goto out_put;
2840 
2841 	sockcm_init(&sockc, &po->sk);
2842 	if (msg->msg_controllen) {
2843 		err = sock_cmsg_send(&po->sk, msg, &sockc);
2844 		if (unlikely(err))
2845 			goto out_put;
2846 	}
2847 
2848 	if (po->sk.sk_socket->type == SOCK_RAW)
2849 		reserve = dev->hard_header_len;
2850 	size_max = po->tx_ring.frame_size
2851 		- (po->tp_hdrlen - sizeof(struct sockaddr_ll));
2852 
2853 	if ((size_max > dev->mtu + reserve + VLAN_HLEN) && !vnet_hdr_sz)
2854 		size_max = dev->mtu + reserve + VLAN_HLEN;
2855 
2856 	reinit_completion(&po->skb_completion);
2857 
2858 	do {
2859 		ph = packet_current_frame(po, &po->tx_ring,
2860 					  TP_STATUS_SEND_REQUEST);
2861 		if (unlikely(ph == NULL)) {
2862 			if (need_wait && skb) {
2863 				timeo = sock_sndtimeo(&po->sk, msg->msg_flags & MSG_DONTWAIT);
2864 				timeo = wait_for_completion_interruptible_timeout(&po->skb_completion, timeo);
2865 				if (timeo <= 0) {
2866 					err = !timeo ? -ETIMEDOUT : -ERESTARTSYS;
2867 					goto out_put;
2868 				}
2869 			}
2870 			/* check for additional frames */
2871 			continue;
2872 		}
2873 
2874 		skb = NULL;
2875 		tp_len = tpacket_parse_header(po, ph, size_max, &data);
2876 		if (tp_len < 0)
2877 			goto tpacket_error;
2878 
2879 		status = TP_STATUS_SEND_REQUEST;
2880 		hlen = LL_RESERVED_SPACE(dev);
2881 		tlen = dev->needed_tailroom;
2882 		if (vnet_hdr_sz) {
2883 			vnet_hdr = data;
2884 			data += vnet_hdr_sz;
2885 			tp_len -= vnet_hdr_sz;
2886 			if (tp_len < 0 ||
2887 			    __packet_snd_vnet_parse(vnet_hdr, tp_len)) {
2888 				tp_len = -EINVAL;
2889 				goto tpacket_error;
2890 			}
2891 			copylen = __virtio16_to_cpu(vio_le(),
2892 						    vnet_hdr->hdr_len);
2893 		}
2894 		copylen = max_t(int, copylen, dev->hard_header_len);
2895 		skb = sock_alloc_send_skb(&po->sk,
2896 				hlen + tlen + sizeof(struct sockaddr_ll) +
2897 				(copylen - dev->hard_header_len),
2898 				!need_wait, &err);
2899 
2900 		if (unlikely(skb == NULL)) {
2901 			/* we assume the socket was initially writeable ... */
2902 			if (likely(len_sum > 0))
2903 				err = len_sum;
2904 			goto out_status;
2905 		}
2906 		tp_len = tpacket_fill_skb(po, skb, ph, dev, data, tp_len, proto,
2907 					  addr, hlen, copylen, &sockc);
2908 		if (likely(tp_len >= 0) &&
2909 		    tp_len > dev->mtu + reserve &&
2910 		    !vnet_hdr_sz &&
2911 		    !packet_extra_vlan_len_allowed(dev, skb))
2912 			tp_len = -EMSGSIZE;
2913 
2914 		if (unlikely(tp_len < 0)) {
2915 tpacket_error:
2916 			if (packet_sock_flag(po, PACKET_SOCK_TP_LOSS)) {
2917 				__packet_set_status(po, ph,
2918 						TP_STATUS_AVAILABLE);
2919 				packet_increment_head(&po->tx_ring);
2920 				kfree_skb(skb);
2921 				continue;
2922 			} else {
2923 				status = TP_STATUS_WRONG_FORMAT;
2924 				err = tp_len;
2925 				goto out_status;
2926 			}
2927 		}
2928 
2929 		if (vnet_hdr_sz) {
2930 			if (virtio_net_hdr_to_skb(skb, vnet_hdr, vio_le())) {
2931 				tp_len = -EINVAL;
2932 				goto tpacket_error;
2933 			}
2934 			virtio_net_hdr_set_proto(skb, vnet_hdr);
2935 		}
2936 
2937 		skb->destructor = tpacket_destruct_skb;
2938 		__packet_set_status(po, ph, TP_STATUS_SENDING);
2939 		packet_inc_pending(&po->tx_ring);
2940 
2941 		status = TP_STATUS_SEND_REQUEST;
2942 		err = packet_xmit(po, skb);
2943 		if (unlikely(err != 0)) {
2944 			if (err > 0)
2945 				err = net_xmit_errno(err);
2946 			if (err && __packet_get_status(po, ph) ==
2947 				   TP_STATUS_AVAILABLE) {
2948 				/* skb was destructed already */
2949 				skb = NULL;
2950 				goto out_status;
2951 			}
2952 			/*
2953 			 * skb was dropped but not destructed yet;
2954 			 * let's treat it like congestion or err < 0
2955 			 */
2956 			err = 0;
2957 		}
2958 		packet_increment_head(&po->tx_ring);
2959 		len_sum += tp_len;
2960 	} while (likely((ph != NULL) ||
2961 		/* Note: packet_read_pending() might be slow if we have
2962 		 * to call it as it's per_cpu variable, but in fast-path
2963 		 * we already short-circuit the loop with the first
2964 		 * condition, and luckily don't have to go that path
2965 		 * anyway.
2966 		 */
2967 		 (need_wait && packet_read_pending(&po->tx_ring))));
2968 
2969 	err = len_sum;
2970 	goto out_put;
2971 
2972 out_status:
2973 	__packet_set_status(po, ph, status);
2974 	kfree_skb(skb);
2975 out_put:
2976 	dev_put(dev);
2977 out:
2978 	mutex_unlock(&po->pg_vec_lock);
2979 	return err;
2980 }
2981 
2982 static struct sk_buff *packet_alloc_skb(struct sock *sk, size_t prepad,
2983 				        size_t reserve, size_t len,
2984 				        size_t linear, int noblock,
2985 				        int *err)
2986 {
2987 	struct sk_buff *skb;
2988 
2989 	/* Under a page?  Don't bother with paged skb. */
2990 	if (prepad + len < PAGE_SIZE || !linear)
2991 		linear = len;
2992 
2993 	if (len - linear > MAX_SKB_FRAGS * (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER))
2994 		linear = len - MAX_SKB_FRAGS * (PAGE_SIZE << PAGE_ALLOC_COSTLY_ORDER);
2995 	skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
2996 				   err, PAGE_ALLOC_COSTLY_ORDER);
2997 	if (!skb)
2998 		return NULL;
2999 
3000 	skb_reserve(skb, reserve);
3001 	skb_put(skb, linear);
3002 	skb->data_len = len - linear;
3003 	skb->len += len - linear;
3004 
3005 	return skb;
3006 }
3007 
3008 static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len)
3009 {
3010 	struct sock *sk = sock->sk;
3011 	DECLARE_SOCKADDR(struct sockaddr_ll *, saddr, msg->msg_name);
3012 	struct sk_buff *skb;
3013 	struct net_device *dev;
3014 	__be16 proto;
3015 	unsigned char *addr = NULL;
3016 	int err, reserve = 0;
3017 	struct sockcm_cookie sockc;
3018 	struct virtio_net_hdr vnet_hdr = { 0 };
3019 	int offset = 0;
3020 	struct packet_sock *po = pkt_sk(sk);
3021 	int vnet_hdr_sz = READ_ONCE(po->vnet_hdr_sz);
3022 	int hlen, tlen, linear;
3023 	int extra_len = 0;
3024 
3025 	/*
3026 	 *	Get and verify the address.
3027 	 */
3028 
3029 	if (likely(saddr == NULL)) {
3030 		dev	= packet_cached_dev_get(po);
3031 		proto	= READ_ONCE(po->num);
3032 	} else {
3033 		err = -EINVAL;
3034 		if (msg->msg_namelen < sizeof(struct sockaddr_ll))
3035 			goto out;
3036 		if (msg->msg_namelen < (saddr->sll_halen + offsetof(struct sockaddr_ll, sll_addr)))
3037 			goto out;
3038 		proto	= saddr->sll_protocol;
3039 		dev = dev_get_by_index(sock_net(sk), saddr->sll_ifindex);
3040 		if (sock->type == SOCK_DGRAM) {
3041 			if (dev && msg->msg_namelen < dev->addr_len +
3042 				   offsetof(struct sockaddr_ll, sll_addr))
3043 				goto out_unlock;
3044 			addr = saddr->sll_addr;
3045 		}
3046 	}
3047 
3048 	err = -ENXIO;
3049 	if (unlikely(dev == NULL))
3050 		goto out_unlock;
3051 	err = -ENETDOWN;
3052 	if (unlikely(!(dev->flags & IFF_UP)))
3053 		goto out_unlock;
3054 
3055 	sockcm_init(&sockc, sk);
3056 	sockc.mark = READ_ONCE(sk->sk_mark);
3057 	if (msg->msg_controllen) {
3058 		err = sock_cmsg_send(sk, msg, &sockc);
3059 		if (unlikely(err))
3060 			goto out_unlock;
3061 	}
3062 
3063 	if (sock->type == SOCK_RAW)
3064 		reserve = dev->hard_header_len;
3065 	if (vnet_hdr_sz) {
3066 		err = packet_snd_vnet_parse(msg, &len, &vnet_hdr, vnet_hdr_sz);
3067 		if (err)
3068 			goto out_unlock;
3069 	}
3070 
3071 	if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
3072 		if (!netif_supports_nofcs(dev)) {
3073 			err = -EPROTONOSUPPORT;
3074 			goto out_unlock;
3075 		}
3076 		extra_len = 4; /* We're doing our own CRC */
3077 	}
3078 
3079 	err = -EMSGSIZE;
3080 	if (!vnet_hdr.gso_type &&
3081 	    (len > dev->mtu + reserve + VLAN_HLEN + extra_len))
3082 		goto out_unlock;
3083 
3084 	err = -ENOBUFS;
3085 	hlen = LL_RESERVED_SPACE(dev);
3086 	tlen = dev->needed_tailroom;
3087 	linear = __virtio16_to_cpu(vio_le(), vnet_hdr.hdr_len);
3088 	linear = max(linear, min_t(int, len, dev->hard_header_len));
3089 	skb = packet_alloc_skb(sk, hlen + tlen, hlen, len, linear,
3090 			       msg->msg_flags & MSG_DONTWAIT, &err);
3091 	if (skb == NULL)
3092 		goto out_unlock;
3093 
3094 	skb_reset_network_header(skb);
3095 
3096 	err = -EINVAL;
3097 	if (sock->type == SOCK_DGRAM) {
3098 		offset = dev_hard_header(skb, dev, ntohs(proto), addr, NULL, len);
3099 		if (unlikely(offset < 0))
3100 			goto out_free;
3101 	} else if (reserve) {
3102 		skb_reserve(skb, -reserve);
3103 		if (len < reserve + sizeof(struct ipv6hdr) &&
3104 		    dev->min_header_len != dev->hard_header_len)
3105 			skb_reset_network_header(skb);
3106 	}
3107 
3108 	/* Returns -EFAULT on error */
3109 	err = skb_copy_datagram_from_iter(skb, offset, &msg->msg_iter, len);
3110 	if (err)
3111 		goto out_free;
3112 
3113 	if ((sock->type == SOCK_RAW &&
3114 	     !dev_validate_header(dev, skb->data, len)) || !skb->len) {
3115 		err = -EINVAL;
3116 		goto out_free;
3117 	}
3118 
3119 	skb_setup_tx_timestamp(skb, &sockc);
3120 
3121 	if (!vnet_hdr.gso_type && (len > dev->mtu + reserve + extra_len) &&
3122 	    !packet_extra_vlan_len_allowed(dev, skb)) {
3123 		err = -EMSGSIZE;
3124 		goto out_free;
3125 	}
3126 
3127 	skb->protocol = proto;
3128 	skb->dev = dev;
3129 	skb->priority = READ_ONCE(sk->sk_priority);
3130 	skb->mark = sockc.mark;
3131 	skb_set_delivery_type_by_clockid(skb, sockc.transmit_time, sk->sk_clockid);
3132 
3133 	if (unlikely(extra_len == 4))
3134 		skb->no_fcs = 1;
3135 
3136 	packet_parse_headers(skb, sock);
3137 
3138 	if (vnet_hdr_sz) {
3139 		err = virtio_net_hdr_to_skb(skb, &vnet_hdr, vio_le());
3140 		if (err)
3141 			goto out_free;
3142 		len += vnet_hdr_sz;
3143 		virtio_net_hdr_set_proto(skb, &vnet_hdr);
3144 	}
3145 
3146 	err = packet_xmit(po, skb);
3147 
3148 	if (unlikely(err != 0)) {
3149 		if (err > 0)
3150 			err = net_xmit_errno(err);
3151 		if (err)
3152 			goto out_unlock;
3153 	}
3154 
3155 	dev_put(dev);
3156 
3157 	return len;
3158 
3159 out_free:
3160 	kfree_skb(skb);
3161 out_unlock:
3162 	dev_put(dev);
3163 out:
3164 	return err;
3165 }
3166 
3167 static int packet_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
3168 {
3169 	struct sock *sk = sock->sk;
3170 	struct packet_sock *po = pkt_sk(sk);
3171 
3172 	/* Reading tx_ring.pg_vec without holding pg_vec_lock is racy.
3173 	 * tpacket_snd() will redo the check safely.
3174 	 */
3175 	if (data_race(po->tx_ring.pg_vec))
3176 		return tpacket_snd(po, msg);
3177 
3178 	return packet_snd(sock, msg, len);
3179 }
3180 
3181 /*
3182  *	Close a PACKET socket. This is fairly simple. We immediately go
3183  *	to 'closed' state and remove our protocol entry in the device list.
3184  */
3185 
3186 static int packet_release(struct socket *sock)
3187 {
3188 	struct sock *sk = sock->sk;
3189 	struct packet_sock *po;
3190 	struct packet_fanout *f;
3191 	struct net *net;
3192 	union tpacket_req_u req_u;
3193 
3194 	if (!sk)
3195 		return 0;
3196 
3197 	net = sock_net(sk);
3198 	po = pkt_sk(sk);
3199 
3200 	mutex_lock(&net->packet.sklist_lock);
3201 	sk_del_node_init_rcu(sk);
3202 	mutex_unlock(&net->packet.sklist_lock);
3203 
3204 	sock_prot_inuse_add(net, sk->sk_prot, -1);
3205 
3206 	spin_lock(&po->bind_lock);
3207 	unregister_prot_hook(sk, false);
3208 	packet_cached_dev_reset(po);
3209 
3210 	if (po->prot_hook.dev) {
3211 		netdev_put(po->prot_hook.dev, &po->prot_hook.dev_tracker);
3212 		po->prot_hook.dev = NULL;
3213 	}
3214 	spin_unlock(&po->bind_lock);
3215 
3216 	packet_flush_mclist(sk);
3217 
3218 	lock_sock(sk);
3219 	if (po->rx_ring.pg_vec) {
3220 		memset(&req_u, 0, sizeof(req_u));
3221 		packet_set_ring(sk, &req_u, 1, 0);
3222 	}
3223 
3224 	if (po->tx_ring.pg_vec) {
3225 		memset(&req_u, 0, sizeof(req_u));
3226 		packet_set_ring(sk, &req_u, 1, 1);
3227 	}
3228 	release_sock(sk);
3229 
3230 	f = fanout_release(sk);
3231 
3232 	synchronize_net();
3233 
3234 	kfree(po->rollover);
3235 	if (f) {
3236 		fanout_release_data(f);
3237 		kvfree(f);
3238 	}
3239 	/*
3240 	 *	Now the socket is dead. No more input will appear.
3241 	 */
3242 	sock_orphan(sk);
3243 	sock->sk = NULL;
3244 
3245 	/* Purge queues */
3246 
3247 	skb_queue_purge(&sk->sk_receive_queue);
3248 	packet_free_pending(po);
3249 
3250 	sock_put(sk);
3251 	return 0;
3252 }
3253 
3254 /*
3255  *	Attach a packet hook.
3256  */
3257 
3258 static int packet_do_bind(struct sock *sk, const char *name, int ifindex,
3259 			  __be16 proto)
3260 {
3261 	struct packet_sock *po = pkt_sk(sk);
3262 	struct net_device *dev = NULL;
3263 	bool unlisted = false;
3264 	bool need_rehook;
3265 	int ret = 0;
3266 
3267 	lock_sock(sk);
3268 	spin_lock(&po->bind_lock);
3269 	if (!proto)
3270 		proto = po->num;
3271 
3272 	rcu_read_lock();
3273 
3274 	if (po->fanout) {
3275 		ret = -EINVAL;
3276 		goto out_unlock;
3277 	}
3278 
3279 	if (name) {
3280 		dev = dev_get_by_name_rcu(sock_net(sk), name);
3281 		if (!dev) {
3282 			ret = -ENODEV;
3283 			goto out_unlock;
3284 		}
3285 	} else if (ifindex) {
3286 		dev = dev_get_by_index_rcu(sock_net(sk), ifindex);
3287 		if (!dev) {
3288 			ret = -ENODEV;
3289 			goto out_unlock;
3290 		}
3291 	}
3292 
3293 	need_rehook = po->prot_hook.type != proto || po->prot_hook.dev != dev;
3294 
3295 	if (need_rehook) {
3296 		dev_hold(dev);
3297 		if (packet_sock_flag(po, PACKET_SOCK_RUNNING)) {
3298 			rcu_read_unlock();
3299 			/* prevents packet_notifier() from calling
3300 			 * register_prot_hook()
3301 			 */
3302 			WRITE_ONCE(po->num, 0);
3303 			__unregister_prot_hook(sk, true);
3304 			rcu_read_lock();
3305 			if (dev)
3306 				unlisted = !dev_get_by_index_rcu(sock_net(sk),
3307 								 dev->ifindex);
3308 		}
3309 
3310 		BUG_ON(packet_sock_flag(po, PACKET_SOCK_RUNNING));
3311 		WRITE_ONCE(po->num, proto);
3312 		po->prot_hook.type = proto;
3313 
3314 		netdev_put(po->prot_hook.dev, &po->prot_hook.dev_tracker);
3315 
3316 		if (unlikely(unlisted)) {
3317 			po->prot_hook.dev = NULL;
3318 			WRITE_ONCE(po->ifindex, -1);
3319 			packet_cached_dev_reset(po);
3320 		} else {
3321 			netdev_hold(dev, &po->prot_hook.dev_tracker,
3322 				    GFP_ATOMIC);
3323 			po->prot_hook.dev = dev;
3324 			WRITE_ONCE(po->ifindex, dev ? dev->ifindex : 0);
3325 			packet_cached_dev_assign(po, dev);
3326 		}
3327 		dev_put(dev);
3328 	}
3329 
3330 	if (proto == 0 || !need_rehook)
3331 		goto out_unlock;
3332 
3333 	if (!unlisted && (!dev || (dev->flags & IFF_UP))) {
3334 		register_prot_hook(sk);
3335 	} else {
3336 		sk->sk_err = ENETDOWN;
3337 		if (!sock_flag(sk, SOCK_DEAD))
3338 			sk_error_report(sk);
3339 	}
3340 
3341 out_unlock:
3342 	rcu_read_unlock();
3343 	spin_unlock(&po->bind_lock);
3344 	release_sock(sk);
3345 	return ret;
3346 }
3347 
3348 /*
3349  *	Bind a packet socket to a device
3350  */
3351 
3352 static int packet_bind_spkt(struct socket *sock, struct sockaddr *uaddr,
3353 			    int addr_len)
3354 {
3355 	struct sock *sk = sock->sk;
3356 	char name[sizeof(uaddr->sa_data_min) + 1];
3357 
3358 	/*
3359 	 *	Check legality
3360 	 */
3361 
3362 	if (addr_len != sizeof(struct sockaddr))
3363 		return -EINVAL;
3364 	/* uaddr->sa_data comes from the userspace, it's not guaranteed to be
3365 	 * zero-terminated.
3366 	 */
3367 	memcpy(name, uaddr->sa_data, sizeof(uaddr->sa_data_min));
3368 	name[sizeof(uaddr->sa_data_min)] = 0;
3369 
3370 	return packet_do_bind(sk, name, 0, 0);
3371 }
3372 
3373 static int packet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
3374 {
3375 	struct sockaddr_ll *sll = (struct sockaddr_ll *)uaddr;
3376 	struct sock *sk = sock->sk;
3377 
3378 	/*
3379 	 *	Check legality
3380 	 */
3381 
3382 	if (addr_len < sizeof(struct sockaddr_ll))
3383 		return -EINVAL;
3384 	if (sll->sll_family != AF_PACKET)
3385 		return -EINVAL;
3386 
3387 	return packet_do_bind(sk, NULL, sll->sll_ifindex, sll->sll_protocol);
3388 }
3389 
3390 static struct proto packet_proto = {
3391 	.name	  = "PACKET",
3392 	.owner	  = THIS_MODULE,
3393 	.obj_size = sizeof(struct packet_sock),
3394 };
3395 
3396 /*
3397  *	Create a packet of type SOCK_PACKET.
3398  */
3399 
3400 static int packet_create(struct net *net, struct socket *sock, int protocol,
3401 			 int kern)
3402 {
3403 	struct sock *sk;
3404 	struct packet_sock *po;
3405 	__be16 proto = (__force __be16)protocol; /* weird, but documented */
3406 	int err;
3407 
3408 	if (!ns_capable(net->user_ns, CAP_NET_RAW))
3409 		return -EPERM;
3410 	if (sock->type != SOCK_DGRAM && sock->type != SOCK_RAW &&
3411 	    sock->type != SOCK_PACKET)
3412 		return -ESOCKTNOSUPPORT;
3413 
3414 	sock->state = SS_UNCONNECTED;
3415 
3416 	err = -ENOBUFS;
3417 	sk = sk_alloc(net, PF_PACKET, GFP_KERNEL, &packet_proto, kern);
3418 	if (sk == NULL)
3419 		goto out;
3420 
3421 	sock->ops = &packet_ops;
3422 	if (sock->type == SOCK_PACKET)
3423 		sock->ops = &packet_ops_spkt;
3424 
3425 	po = pkt_sk(sk);
3426 	err = packet_alloc_pending(po);
3427 	if (err)
3428 		goto out_sk_free;
3429 
3430 	sock_init_data(sock, sk);
3431 
3432 	init_completion(&po->skb_completion);
3433 	sk->sk_family = PF_PACKET;
3434 	po->num = proto;
3435 
3436 	packet_cached_dev_reset(po);
3437 
3438 	sk->sk_destruct = packet_sock_destruct;
3439 
3440 	/*
3441 	 *	Attach a protocol block
3442 	 */
3443 
3444 	spin_lock_init(&po->bind_lock);
3445 	mutex_init(&po->pg_vec_lock);
3446 	po->rollover = NULL;
3447 	po->prot_hook.func = packet_rcv;
3448 
3449 	if (sock->type == SOCK_PACKET)
3450 		po->prot_hook.func = packet_rcv_spkt;
3451 
3452 	po->prot_hook.af_packet_priv = sk;
3453 	po->prot_hook.af_packet_net = sock_net(sk);
3454 
3455 	if (proto) {
3456 		po->prot_hook.type = proto;
3457 		__register_prot_hook(sk);
3458 	}
3459 
3460 	mutex_lock(&net->packet.sklist_lock);
3461 	sk_add_node_tail_rcu(sk, &net->packet.sklist);
3462 	mutex_unlock(&net->packet.sklist_lock);
3463 
3464 	sock_prot_inuse_add(net, &packet_proto, 1);
3465 
3466 	return 0;
3467 out_sk_free:
3468 	sk_free(sk);
3469 out:
3470 	return err;
3471 }
3472 
3473 /*
3474  *	Pull a packet from our receive queue and hand it to the user.
3475  *	If necessary we block.
3476  */
3477 
3478 static int packet_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
3479 			  int flags)
3480 {
3481 	struct sock *sk = sock->sk;
3482 	struct sk_buff *skb;
3483 	int copied, err;
3484 	int vnet_hdr_len = READ_ONCE(pkt_sk(sk)->vnet_hdr_sz);
3485 	unsigned int origlen = 0;
3486 
3487 	err = -EINVAL;
3488 	if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT|MSG_ERRQUEUE))
3489 		goto out;
3490 
3491 #if 0
3492 	/* What error should we return now? EUNATTACH? */
3493 	if (pkt_sk(sk)->ifindex < 0)
3494 		return -ENODEV;
3495 #endif
3496 
3497 	if (flags & MSG_ERRQUEUE) {
3498 		err = sock_recv_errqueue(sk, msg, len,
3499 					 SOL_PACKET, PACKET_TX_TIMESTAMP);
3500 		goto out;
3501 	}
3502 
3503 	/*
3504 	 *	Call the generic datagram receiver. This handles all sorts
3505 	 *	of horrible races and re-entrancy so we can forget about it
3506 	 *	in the protocol layers.
3507 	 *
3508 	 *	Now it will return ENETDOWN, if device have just gone down,
3509 	 *	but then it will block.
3510 	 */
3511 
3512 	skb = skb_recv_datagram(sk, flags, &err);
3513 
3514 	/*
3515 	 *	An error occurred so return it. Because skb_recv_datagram()
3516 	 *	handles the blocking we don't see and worry about blocking
3517 	 *	retries.
3518 	 */
3519 
3520 	if (skb == NULL)
3521 		goto out;
3522 
3523 	packet_rcv_try_clear_pressure(pkt_sk(sk));
3524 
3525 	if (vnet_hdr_len) {
3526 		err = packet_rcv_vnet(msg, skb, &len, vnet_hdr_len);
3527 		if (err)
3528 			goto out_free;
3529 	}
3530 
3531 	/* You lose any data beyond the buffer you gave. If it worries
3532 	 * a user program they can ask the device for its MTU
3533 	 * anyway.
3534 	 */
3535 	copied = skb->len;
3536 	if (copied > len) {
3537 		copied = len;
3538 		msg->msg_flags |= MSG_TRUNC;
3539 	}
3540 
3541 	err = skb_copy_datagram_msg(skb, 0, msg, copied);
3542 	if (err)
3543 		goto out_free;
3544 
3545 	if (sock->type != SOCK_PACKET) {
3546 		struct sockaddr_ll *sll = &PACKET_SKB_CB(skb)->sa.ll;
3547 
3548 		/* Original length was stored in sockaddr_ll fields */
3549 		origlen = PACKET_SKB_CB(skb)->sa.origlen;
3550 		sll->sll_family = AF_PACKET;
3551 		sll->sll_protocol = (sock->type == SOCK_DGRAM) ?
3552 			vlan_get_protocol_dgram(skb) : skb->protocol;
3553 	}
3554 
3555 	sock_recv_cmsgs(msg, sk, skb);
3556 
3557 	if (msg->msg_name) {
3558 		const size_t max_len = min(sizeof(skb->cb),
3559 					   sizeof(struct sockaddr_storage));
3560 		int copy_len;
3561 
3562 		/* If the address length field is there to be filled
3563 		 * in, we fill it in now.
3564 		 */
3565 		if (sock->type == SOCK_PACKET) {
3566 			__sockaddr_check_size(sizeof(struct sockaddr_pkt));
3567 			msg->msg_namelen = sizeof(struct sockaddr_pkt);
3568 			copy_len = msg->msg_namelen;
3569 		} else {
3570 			struct sockaddr_ll *sll = &PACKET_SKB_CB(skb)->sa.ll;
3571 
3572 			msg->msg_namelen = sll->sll_halen +
3573 				offsetof(struct sockaddr_ll, sll_addr);
3574 			copy_len = msg->msg_namelen;
3575 			if (msg->msg_namelen < sizeof(struct sockaddr_ll)) {
3576 				memset(msg->msg_name +
3577 				       offsetof(struct sockaddr_ll, sll_addr),
3578 				       0, sizeof(sll->sll_addr));
3579 				msg->msg_namelen = sizeof(struct sockaddr_ll);
3580 			}
3581 		}
3582 		if (WARN_ON_ONCE(copy_len > max_len)) {
3583 			copy_len = max_len;
3584 			msg->msg_namelen = copy_len;
3585 		}
3586 		memcpy(msg->msg_name, &PACKET_SKB_CB(skb)->sa, copy_len);
3587 	}
3588 
3589 	if (packet_sock_flag(pkt_sk(sk), PACKET_SOCK_AUXDATA)) {
3590 		struct tpacket_auxdata aux;
3591 
3592 		aux.tp_status = TP_STATUS_USER;
3593 		if (skb->ip_summed == CHECKSUM_PARTIAL)
3594 			aux.tp_status |= TP_STATUS_CSUMNOTREADY;
3595 		else if (skb->pkt_type != PACKET_OUTGOING &&
3596 			 skb_csum_unnecessary(skb))
3597 			aux.tp_status |= TP_STATUS_CSUM_VALID;
3598 		if (skb_is_gso(skb) && skb_is_gso_tcp(skb))
3599 			aux.tp_status |= TP_STATUS_GSO_TCP;
3600 
3601 		aux.tp_len = origlen;
3602 		aux.tp_snaplen = skb->len;
3603 		aux.tp_mac = 0;
3604 		aux.tp_net = skb_network_offset(skb);
3605 		if (skb_vlan_tag_present(skb)) {
3606 			aux.tp_vlan_tci = skb_vlan_tag_get(skb);
3607 			aux.tp_vlan_tpid = ntohs(skb->vlan_proto);
3608 			aux.tp_status |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
3609 		} else if (unlikely(sock->type == SOCK_DGRAM && eth_type_vlan(skb->protocol))) {
3610 			struct sockaddr_ll *sll = &PACKET_SKB_CB(skb)->sa.ll;
3611 			struct net_device *dev;
3612 
3613 			rcu_read_lock();
3614 			dev = dev_get_by_index_rcu(sock_net(sk), sll->sll_ifindex);
3615 			if (dev) {
3616 				aux.tp_vlan_tci = vlan_get_tci(skb, dev);
3617 				aux.tp_vlan_tpid = ntohs(skb->protocol);
3618 				aux.tp_status |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
3619 			} else {
3620 				aux.tp_vlan_tci = 0;
3621 				aux.tp_vlan_tpid = 0;
3622 			}
3623 			rcu_read_unlock();
3624 		} else {
3625 			aux.tp_vlan_tci = 0;
3626 			aux.tp_vlan_tpid = 0;
3627 		}
3628 		put_cmsg(msg, SOL_PACKET, PACKET_AUXDATA, sizeof(aux), &aux);
3629 	}
3630 
3631 	/*
3632 	 *	Free or return the buffer as appropriate. Again this
3633 	 *	hides all the races and re-entrancy issues from us.
3634 	 */
3635 	err = vnet_hdr_len + ((flags&MSG_TRUNC) ? skb->len : copied);
3636 
3637 out_free:
3638 	skb_free_datagram(sk, skb);
3639 out:
3640 	return err;
3641 }
3642 
3643 static int packet_getname_spkt(struct socket *sock, struct sockaddr *uaddr,
3644 			       int peer)
3645 {
3646 	struct net_device *dev;
3647 	struct sock *sk	= sock->sk;
3648 
3649 	if (peer)
3650 		return -EOPNOTSUPP;
3651 
3652 	uaddr->sa_family = AF_PACKET;
3653 	memset(uaddr->sa_data, 0, sizeof(uaddr->sa_data_min));
3654 	rcu_read_lock();
3655 	dev = dev_get_by_index_rcu(sock_net(sk), READ_ONCE(pkt_sk(sk)->ifindex));
3656 	if (dev)
3657 		strscpy(uaddr->sa_data, dev->name, sizeof(uaddr->sa_data_min));
3658 	rcu_read_unlock();
3659 
3660 	return sizeof(*uaddr);
3661 }
3662 
3663 static int packet_getname(struct socket *sock, struct sockaddr *uaddr,
3664 			  int peer)
3665 {
3666 	struct net_device *dev;
3667 	struct sock *sk = sock->sk;
3668 	struct packet_sock *po = pkt_sk(sk);
3669 	DECLARE_SOCKADDR(struct sockaddr_ll *, sll, uaddr);
3670 	int ifindex;
3671 
3672 	if (peer)
3673 		return -EOPNOTSUPP;
3674 
3675 	ifindex = READ_ONCE(po->ifindex);
3676 	sll->sll_family = AF_PACKET;
3677 	sll->sll_ifindex = ifindex;
3678 	sll->sll_protocol = READ_ONCE(po->num);
3679 	sll->sll_pkttype = 0;
3680 	rcu_read_lock();
3681 	dev = dev_get_by_index_rcu(sock_net(sk), ifindex);
3682 	if (dev) {
3683 		sll->sll_hatype = dev->type;
3684 		sll->sll_halen = dev->addr_len;
3685 
3686 		/* Let __fortify_memcpy_chk() know the actual buffer size. */
3687 		memcpy(((struct sockaddr_storage *)sll)->__data +
3688 		       offsetof(struct sockaddr_ll, sll_addr) -
3689 		       offsetofend(struct sockaddr_ll, sll_family),
3690 		       dev->dev_addr, dev->addr_len);
3691 	} else {
3692 		sll->sll_hatype = 0;	/* Bad: we have no ARPHRD_UNSPEC */
3693 		sll->sll_halen = 0;
3694 	}
3695 	rcu_read_unlock();
3696 
3697 	return offsetof(struct sockaddr_ll, sll_addr) + sll->sll_halen;
3698 }
3699 
3700 static int packet_dev_mc(struct net_device *dev, struct packet_mclist *i,
3701 			 int what)
3702 {
3703 	switch (i->type) {
3704 	case PACKET_MR_MULTICAST:
3705 		if (i->alen != dev->addr_len)
3706 			return -EINVAL;
3707 		if (what > 0)
3708 			return dev_mc_add(dev, i->addr);
3709 		else
3710 			return dev_mc_del(dev, i->addr);
3711 		break;
3712 	case PACKET_MR_PROMISC:
3713 		return dev_set_promiscuity(dev, what);
3714 	case PACKET_MR_ALLMULTI:
3715 		return dev_set_allmulti(dev, what);
3716 	case PACKET_MR_UNICAST:
3717 		if (i->alen != dev->addr_len)
3718 			return -EINVAL;
3719 		if (what > 0)
3720 			return dev_uc_add(dev, i->addr);
3721 		else
3722 			return dev_uc_del(dev, i->addr);
3723 		break;
3724 	default:
3725 		break;
3726 	}
3727 	return 0;
3728 }
3729 
3730 static void packet_dev_mclist_delete(struct net_device *dev,
3731 				     struct packet_mclist **mlp)
3732 {
3733 	struct packet_mclist *ml;
3734 
3735 	while ((ml = *mlp) != NULL) {
3736 		if (ml->ifindex == dev->ifindex) {
3737 			packet_dev_mc(dev, ml, -1);
3738 			*mlp = ml->next;
3739 			kfree(ml);
3740 		} else
3741 			mlp = &ml->next;
3742 	}
3743 }
3744 
3745 static int packet_mc_add(struct sock *sk, struct packet_mreq_max *mreq)
3746 {
3747 	struct packet_sock *po = pkt_sk(sk);
3748 	struct packet_mclist *ml, *i;
3749 	struct net_device *dev;
3750 	int err;
3751 
3752 	rtnl_lock();
3753 
3754 	err = -ENODEV;
3755 	dev = __dev_get_by_index(sock_net(sk), mreq->mr_ifindex);
3756 	if (!dev)
3757 		goto done;
3758 
3759 	err = -EINVAL;
3760 	if (mreq->mr_alen > dev->addr_len)
3761 		goto done;
3762 
3763 	err = -ENOBUFS;
3764 	i = kmalloc(sizeof(*i), GFP_KERNEL);
3765 	if (i == NULL)
3766 		goto done;
3767 
3768 	err = 0;
3769 	for (ml = po->mclist; ml; ml = ml->next) {
3770 		if (ml->ifindex == mreq->mr_ifindex &&
3771 		    ml->type == mreq->mr_type &&
3772 		    ml->alen == mreq->mr_alen &&
3773 		    memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
3774 			ml->count++;
3775 			/* Free the new element ... */
3776 			kfree(i);
3777 			goto done;
3778 		}
3779 	}
3780 
3781 	i->type = mreq->mr_type;
3782 	i->ifindex = mreq->mr_ifindex;
3783 	i->alen = mreq->mr_alen;
3784 	memcpy(i->addr, mreq->mr_address, i->alen);
3785 	memset(i->addr + i->alen, 0, sizeof(i->addr) - i->alen);
3786 	i->count = 1;
3787 	i->next = po->mclist;
3788 	po->mclist = i;
3789 	err = packet_dev_mc(dev, i, 1);
3790 	if (err) {
3791 		po->mclist = i->next;
3792 		kfree(i);
3793 	}
3794 
3795 done:
3796 	rtnl_unlock();
3797 	return err;
3798 }
3799 
3800 static int packet_mc_drop(struct sock *sk, struct packet_mreq_max *mreq)
3801 {
3802 	struct packet_mclist *ml, **mlp;
3803 
3804 	rtnl_lock();
3805 
3806 	for (mlp = &pkt_sk(sk)->mclist; (ml = *mlp) != NULL; mlp = &ml->next) {
3807 		if (ml->ifindex == mreq->mr_ifindex &&
3808 		    ml->type == mreq->mr_type &&
3809 		    ml->alen == mreq->mr_alen &&
3810 		    memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
3811 			if (--ml->count == 0) {
3812 				struct net_device *dev;
3813 				*mlp = ml->next;
3814 				dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
3815 				if (dev)
3816 					packet_dev_mc(dev, ml, -1);
3817 				kfree(ml);
3818 			}
3819 			break;
3820 		}
3821 	}
3822 	rtnl_unlock();
3823 	return 0;
3824 }
3825 
3826 static void packet_flush_mclist(struct sock *sk)
3827 {
3828 	struct packet_sock *po = pkt_sk(sk);
3829 	struct packet_mclist *ml;
3830 
3831 	if (!po->mclist)
3832 		return;
3833 
3834 	rtnl_lock();
3835 	while ((ml = po->mclist) != NULL) {
3836 		struct net_device *dev;
3837 
3838 		po->mclist = ml->next;
3839 		dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
3840 		if (dev != NULL)
3841 			packet_dev_mc(dev, ml, -1);
3842 		kfree(ml);
3843 	}
3844 	rtnl_unlock();
3845 }
3846 
3847 static int
3848 packet_setsockopt(struct socket *sock, int level, int optname, sockptr_t optval,
3849 		  unsigned int optlen)
3850 {
3851 	struct sock *sk = sock->sk;
3852 	struct packet_sock *po = pkt_sk(sk);
3853 	int ret;
3854 
3855 	if (level != SOL_PACKET)
3856 		return -ENOPROTOOPT;
3857 
3858 	switch (optname) {
3859 	case PACKET_ADD_MEMBERSHIP:
3860 	case PACKET_DROP_MEMBERSHIP:
3861 	{
3862 		struct packet_mreq_max mreq;
3863 		int len = optlen;
3864 		memset(&mreq, 0, sizeof(mreq));
3865 		if (len < sizeof(struct packet_mreq))
3866 			return -EINVAL;
3867 		if (len > sizeof(mreq))
3868 			len = sizeof(mreq);
3869 		if (copy_from_sockptr(&mreq, optval, len))
3870 			return -EFAULT;
3871 		if (len < (mreq.mr_alen + offsetof(struct packet_mreq, mr_address)))
3872 			return -EINVAL;
3873 		if (optname == PACKET_ADD_MEMBERSHIP)
3874 			ret = packet_mc_add(sk, &mreq);
3875 		else
3876 			ret = packet_mc_drop(sk, &mreq);
3877 		return ret;
3878 	}
3879 
3880 	case PACKET_RX_RING:
3881 	case PACKET_TX_RING:
3882 	{
3883 		union tpacket_req_u req_u;
3884 
3885 		ret = -EINVAL;
3886 		lock_sock(sk);
3887 		switch (po->tp_version) {
3888 		case TPACKET_V1:
3889 		case TPACKET_V2:
3890 			if (optlen < sizeof(req_u.req))
3891 				break;
3892 			ret = copy_from_sockptr(&req_u.req, optval,
3893 						sizeof(req_u.req)) ?
3894 						-EINVAL : 0;
3895 			break;
3896 		case TPACKET_V3:
3897 		default:
3898 			if (optlen < sizeof(req_u.req3))
3899 				break;
3900 			ret = copy_from_sockptr(&req_u.req3, optval,
3901 						sizeof(req_u.req3)) ?
3902 						-EINVAL : 0;
3903 			break;
3904 		}
3905 		if (!ret)
3906 			ret = packet_set_ring(sk, &req_u, 0,
3907 					      optname == PACKET_TX_RING);
3908 		release_sock(sk);
3909 		return ret;
3910 	}
3911 	case PACKET_COPY_THRESH:
3912 	{
3913 		int val;
3914 
3915 		if (optlen != sizeof(val))
3916 			return -EINVAL;
3917 		if (copy_from_sockptr(&val, optval, sizeof(val)))
3918 			return -EFAULT;
3919 
3920 		WRITE_ONCE(pkt_sk(sk)->copy_thresh, val);
3921 		return 0;
3922 	}
3923 	case PACKET_VERSION:
3924 	{
3925 		int val;
3926 
3927 		if (optlen != sizeof(val))
3928 			return -EINVAL;
3929 		if (copy_from_sockptr(&val, optval, sizeof(val)))
3930 			return -EFAULT;
3931 		switch (val) {
3932 		case TPACKET_V1:
3933 		case TPACKET_V2:
3934 		case TPACKET_V3:
3935 			break;
3936 		default:
3937 			return -EINVAL;
3938 		}
3939 		lock_sock(sk);
3940 		if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) {
3941 			ret = -EBUSY;
3942 		} else {
3943 			po->tp_version = val;
3944 			ret = 0;
3945 		}
3946 		release_sock(sk);
3947 		return ret;
3948 	}
3949 	case PACKET_RESERVE:
3950 	{
3951 		unsigned int val;
3952 
3953 		if (optlen != sizeof(val))
3954 			return -EINVAL;
3955 		if (copy_from_sockptr(&val, optval, sizeof(val)))
3956 			return -EFAULT;
3957 		if (val > INT_MAX)
3958 			return -EINVAL;
3959 		lock_sock(sk);
3960 		if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) {
3961 			ret = -EBUSY;
3962 		} else {
3963 			po->tp_reserve = val;
3964 			ret = 0;
3965 		}
3966 		release_sock(sk);
3967 		return ret;
3968 	}
3969 	case PACKET_LOSS:
3970 	{
3971 		unsigned int val;
3972 
3973 		if (optlen != sizeof(val))
3974 			return -EINVAL;
3975 		if (copy_from_sockptr(&val, optval, sizeof(val)))
3976 			return -EFAULT;
3977 
3978 		lock_sock(sk);
3979 		if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) {
3980 			ret = -EBUSY;
3981 		} else {
3982 			packet_sock_flag_set(po, PACKET_SOCK_TP_LOSS, val);
3983 			ret = 0;
3984 		}
3985 		release_sock(sk);
3986 		return ret;
3987 	}
3988 	case PACKET_AUXDATA:
3989 	{
3990 		int val;
3991 
3992 		if (optlen < sizeof(val))
3993 			return -EINVAL;
3994 		if (copy_from_sockptr(&val, optval, sizeof(val)))
3995 			return -EFAULT;
3996 
3997 		packet_sock_flag_set(po, PACKET_SOCK_AUXDATA, val);
3998 		return 0;
3999 	}
4000 	case PACKET_ORIGDEV:
4001 	{
4002 		int val;
4003 
4004 		if (optlen < sizeof(val))
4005 			return -EINVAL;
4006 		if (copy_from_sockptr(&val, optval, sizeof(val)))
4007 			return -EFAULT;
4008 
4009 		packet_sock_flag_set(po, PACKET_SOCK_ORIGDEV, val);
4010 		return 0;
4011 	}
4012 	case PACKET_VNET_HDR:
4013 	case PACKET_VNET_HDR_SZ:
4014 	{
4015 		int val, hdr_len;
4016 
4017 		if (sock->type != SOCK_RAW)
4018 			return -EINVAL;
4019 		if (optlen < sizeof(val))
4020 			return -EINVAL;
4021 		if (copy_from_sockptr(&val, optval, sizeof(val)))
4022 			return -EFAULT;
4023 
4024 		if (optname == PACKET_VNET_HDR_SZ) {
4025 			if (val && val != sizeof(struct virtio_net_hdr) &&
4026 			    val != sizeof(struct virtio_net_hdr_mrg_rxbuf))
4027 				return -EINVAL;
4028 			hdr_len = val;
4029 		} else {
4030 			hdr_len = val ? sizeof(struct virtio_net_hdr) : 0;
4031 		}
4032 		lock_sock(sk);
4033 		if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) {
4034 			ret = -EBUSY;
4035 		} else {
4036 			WRITE_ONCE(po->vnet_hdr_sz, hdr_len);
4037 			ret = 0;
4038 		}
4039 		release_sock(sk);
4040 		return ret;
4041 	}
4042 	case PACKET_TIMESTAMP:
4043 	{
4044 		int val;
4045 
4046 		if (optlen != sizeof(val))
4047 			return -EINVAL;
4048 		if (copy_from_sockptr(&val, optval, sizeof(val)))
4049 			return -EFAULT;
4050 
4051 		WRITE_ONCE(po->tp_tstamp, val);
4052 		return 0;
4053 	}
4054 	case PACKET_FANOUT:
4055 	{
4056 		struct fanout_args args = { 0 };
4057 
4058 		if (optlen != sizeof(int) && optlen != sizeof(args))
4059 			return -EINVAL;
4060 		if (copy_from_sockptr(&args, optval, optlen))
4061 			return -EFAULT;
4062 
4063 		return fanout_add(sk, &args);
4064 	}
4065 	case PACKET_FANOUT_DATA:
4066 	{
4067 		/* Paired with the WRITE_ONCE() in fanout_add() */
4068 		if (!READ_ONCE(po->fanout))
4069 			return -EINVAL;
4070 
4071 		return fanout_set_data(po, optval, optlen);
4072 	}
4073 	case PACKET_IGNORE_OUTGOING:
4074 	{
4075 		int val;
4076 
4077 		if (optlen != sizeof(val))
4078 			return -EINVAL;
4079 		if (copy_from_sockptr(&val, optval, sizeof(val)))
4080 			return -EFAULT;
4081 		if (val < 0 || val > 1)
4082 			return -EINVAL;
4083 
4084 		WRITE_ONCE(po->prot_hook.ignore_outgoing, !!val);
4085 		return 0;
4086 	}
4087 	case PACKET_TX_HAS_OFF:
4088 	{
4089 		unsigned int val;
4090 
4091 		if (optlen != sizeof(val))
4092 			return -EINVAL;
4093 		if (copy_from_sockptr(&val, optval, sizeof(val)))
4094 			return -EFAULT;
4095 
4096 		lock_sock(sk);
4097 		if (!po->rx_ring.pg_vec && !po->tx_ring.pg_vec)
4098 			packet_sock_flag_set(po, PACKET_SOCK_TX_HAS_OFF, val);
4099 
4100 		release_sock(sk);
4101 		return 0;
4102 	}
4103 	case PACKET_QDISC_BYPASS:
4104 	{
4105 		int val;
4106 
4107 		if (optlen != sizeof(val))
4108 			return -EINVAL;
4109 		if (copy_from_sockptr(&val, optval, sizeof(val)))
4110 			return -EFAULT;
4111 
4112 		packet_sock_flag_set(po, PACKET_SOCK_QDISC_BYPASS, val);
4113 		return 0;
4114 	}
4115 	default:
4116 		return -ENOPROTOOPT;
4117 	}
4118 }
4119 
4120 static int packet_getsockopt(struct socket *sock, int level, int optname,
4121 			     char __user *optval, int __user *optlen)
4122 {
4123 	int len;
4124 	int val, lv = sizeof(val);
4125 	struct sock *sk = sock->sk;
4126 	struct packet_sock *po = pkt_sk(sk);
4127 	void *data = &val;
4128 	union tpacket_stats_u st;
4129 	struct tpacket_rollover_stats rstats;
4130 	int drops;
4131 
4132 	if (level != SOL_PACKET)
4133 		return -ENOPROTOOPT;
4134 
4135 	if (get_user(len, optlen))
4136 		return -EFAULT;
4137 
4138 	if (len < 0)
4139 		return -EINVAL;
4140 
4141 	switch (optname) {
4142 	case PACKET_STATISTICS:
4143 		spin_lock_bh(&sk->sk_receive_queue.lock);
4144 		memcpy(&st, &po->stats, sizeof(st));
4145 		memset(&po->stats, 0, sizeof(po->stats));
4146 		spin_unlock_bh(&sk->sk_receive_queue.lock);
4147 		drops = atomic_xchg(&po->tp_drops, 0);
4148 
4149 		if (po->tp_version == TPACKET_V3) {
4150 			lv = sizeof(struct tpacket_stats_v3);
4151 			st.stats3.tp_drops = drops;
4152 			st.stats3.tp_packets += drops;
4153 			data = &st.stats3;
4154 		} else {
4155 			lv = sizeof(struct tpacket_stats);
4156 			st.stats1.tp_drops = drops;
4157 			st.stats1.tp_packets += drops;
4158 			data = &st.stats1;
4159 		}
4160 
4161 		break;
4162 	case PACKET_AUXDATA:
4163 		val = packet_sock_flag(po, PACKET_SOCK_AUXDATA);
4164 		break;
4165 	case PACKET_ORIGDEV:
4166 		val = packet_sock_flag(po, PACKET_SOCK_ORIGDEV);
4167 		break;
4168 	case PACKET_VNET_HDR:
4169 		val = !!READ_ONCE(po->vnet_hdr_sz);
4170 		break;
4171 	case PACKET_VNET_HDR_SZ:
4172 		val = READ_ONCE(po->vnet_hdr_sz);
4173 		break;
4174 	case PACKET_COPY_THRESH:
4175 		val = READ_ONCE(pkt_sk(sk)->copy_thresh);
4176 		break;
4177 	case PACKET_VERSION:
4178 		val = po->tp_version;
4179 		break;
4180 	case PACKET_HDRLEN:
4181 		if (len > sizeof(int))
4182 			len = sizeof(int);
4183 		if (len < sizeof(int))
4184 			return -EINVAL;
4185 		if (copy_from_user(&val, optval, len))
4186 			return -EFAULT;
4187 		switch (val) {
4188 		case TPACKET_V1:
4189 			val = sizeof(struct tpacket_hdr);
4190 			break;
4191 		case TPACKET_V2:
4192 			val = sizeof(struct tpacket2_hdr);
4193 			break;
4194 		case TPACKET_V3:
4195 			val = sizeof(struct tpacket3_hdr);
4196 			break;
4197 		default:
4198 			return -EINVAL;
4199 		}
4200 		break;
4201 	case PACKET_RESERVE:
4202 		val = po->tp_reserve;
4203 		break;
4204 	case PACKET_LOSS:
4205 		val = packet_sock_flag(po, PACKET_SOCK_TP_LOSS);
4206 		break;
4207 	case PACKET_TIMESTAMP:
4208 		val = READ_ONCE(po->tp_tstamp);
4209 		break;
4210 	case PACKET_FANOUT:
4211 		val = (po->fanout ?
4212 		       ((u32)po->fanout->id |
4213 			((u32)po->fanout->type << 16) |
4214 			((u32)po->fanout->flags << 24)) :
4215 		       0);
4216 		break;
4217 	case PACKET_IGNORE_OUTGOING:
4218 		val = READ_ONCE(po->prot_hook.ignore_outgoing);
4219 		break;
4220 	case PACKET_ROLLOVER_STATS:
4221 		if (!po->rollover)
4222 			return -EINVAL;
4223 		rstats.tp_all = atomic_long_read(&po->rollover->num);
4224 		rstats.tp_huge = atomic_long_read(&po->rollover->num_huge);
4225 		rstats.tp_failed = atomic_long_read(&po->rollover->num_failed);
4226 		data = &rstats;
4227 		lv = sizeof(rstats);
4228 		break;
4229 	case PACKET_TX_HAS_OFF:
4230 		val = packet_sock_flag(po, PACKET_SOCK_TX_HAS_OFF);
4231 		break;
4232 	case PACKET_QDISC_BYPASS:
4233 		val = packet_sock_flag(po, PACKET_SOCK_QDISC_BYPASS);
4234 		break;
4235 	default:
4236 		return -ENOPROTOOPT;
4237 	}
4238 
4239 	if (len > lv)
4240 		len = lv;
4241 	if (put_user(len, optlen))
4242 		return -EFAULT;
4243 	if (copy_to_user(optval, data, len))
4244 		return -EFAULT;
4245 	return 0;
4246 }
4247 
4248 static int packet_notifier(struct notifier_block *this,
4249 			   unsigned long msg, void *ptr)
4250 {
4251 	struct sock *sk;
4252 	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
4253 	struct net *net = dev_net(dev);
4254 
4255 	rcu_read_lock();
4256 	sk_for_each_rcu(sk, &net->packet.sklist) {
4257 		struct packet_sock *po = pkt_sk(sk);
4258 
4259 		switch (msg) {
4260 		case NETDEV_UNREGISTER:
4261 			if (po->mclist)
4262 				packet_dev_mclist_delete(dev, &po->mclist);
4263 			fallthrough;
4264 
4265 		case NETDEV_DOWN:
4266 			if (dev->ifindex == po->ifindex) {
4267 				spin_lock(&po->bind_lock);
4268 				if (packet_sock_flag(po, PACKET_SOCK_RUNNING)) {
4269 					__unregister_prot_hook(sk, false);
4270 					sk->sk_err = ENETDOWN;
4271 					if (!sock_flag(sk, SOCK_DEAD))
4272 						sk_error_report(sk);
4273 				}
4274 				if (msg == NETDEV_UNREGISTER) {
4275 					packet_cached_dev_reset(po);
4276 					WRITE_ONCE(po->ifindex, -1);
4277 					netdev_put(po->prot_hook.dev,
4278 						   &po->prot_hook.dev_tracker);
4279 					po->prot_hook.dev = NULL;
4280 				}
4281 				spin_unlock(&po->bind_lock);
4282 			}
4283 			break;
4284 		case NETDEV_UP:
4285 			if (dev->ifindex == po->ifindex) {
4286 				spin_lock(&po->bind_lock);
4287 				if (po->num)
4288 					register_prot_hook(sk);
4289 				spin_unlock(&po->bind_lock);
4290 			}
4291 			break;
4292 		}
4293 	}
4294 	rcu_read_unlock();
4295 	return NOTIFY_DONE;
4296 }
4297 
4298 
4299 static int packet_ioctl(struct socket *sock, unsigned int cmd,
4300 			unsigned long arg)
4301 {
4302 	struct sock *sk = sock->sk;
4303 
4304 	switch (cmd) {
4305 	case SIOCOUTQ:
4306 	{
4307 		int amount = sk_wmem_alloc_get(sk);
4308 
4309 		return put_user(amount, (int __user *)arg);
4310 	}
4311 	case SIOCINQ:
4312 	{
4313 		struct sk_buff *skb;
4314 		int amount = 0;
4315 
4316 		spin_lock_bh(&sk->sk_receive_queue.lock);
4317 		skb = skb_peek(&sk->sk_receive_queue);
4318 		if (skb)
4319 			amount = skb->len;
4320 		spin_unlock_bh(&sk->sk_receive_queue.lock);
4321 		return put_user(amount, (int __user *)arg);
4322 	}
4323 #ifdef CONFIG_INET
4324 	case SIOCADDRT:
4325 	case SIOCDELRT:
4326 	case SIOCDARP:
4327 	case SIOCGARP:
4328 	case SIOCSARP:
4329 	case SIOCGIFADDR:
4330 	case SIOCSIFADDR:
4331 	case SIOCGIFBRDADDR:
4332 	case SIOCSIFBRDADDR:
4333 	case SIOCGIFNETMASK:
4334 	case SIOCSIFNETMASK:
4335 	case SIOCGIFDSTADDR:
4336 	case SIOCSIFDSTADDR:
4337 	case SIOCSIFFLAGS:
4338 		return inet_dgram_ops.ioctl(sock, cmd, arg);
4339 #endif
4340 
4341 	default:
4342 		return -ENOIOCTLCMD;
4343 	}
4344 	return 0;
4345 }
4346 
4347 static __poll_t packet_poll(struct file *file, struct socket *sock,
4348 				poll_table *wait)
4349 {
4350 	struct sock *sk = sock->sk;
4351 	struct packet_sock *po = pkt_sk(sk);
4352 	__poll_t mask = datagram_poll(file, sock, wait);
4353 
4354 	spin_lock_bh(&sk->sk_receive_queue.lock);
4355 	if (po->rx_ring.pg_vec) {
4356 		if (!packet_previous_rx_frame(po, &po->rx_ring,
4357 			TP_STATUS_KERNEL))
4358 			mask |= EPOLLIN | EPOLLRDNORM;
4359 	}
4360 	packet_rcv_try_clear_pressure(po);
4361 	spin_unlock_bh(&sk->sk_receive_queue.lock);
4362 	spin_lock_bh(&sk->sk_write_queue.lock);
4363 	if (po->tx_ring.pg_vec) {
4364 		if (packet_current_frame(po, &po->tx_ring, TP_STATUS_AVAILABLE))
4365 			mask |= EPOLLOUT | EPOLLWRNORM;
4366 	}
4367 	spin_unlock_bh(&sk->sk_write_queue.lock);
4368 	return mask;
4369 }
4370 
4371 
4372 /* Dirty? Well, I still did not learn better way to account
4373  * for user mmaps.
4374  */
4375 
4376 static void packet_mm_open(struct vm_area_struct *vma)
4377 {
4378 	struct file *file = vma->vm_file;
4379 	struct socket *sock = file->private_data;
4380 	struct sock *sk = sock->sk;
4381 
4382 	if (sk)
4383 		atomic_long_inc(&pkt_sk(sk)->mapped);
4384 }
4385 
4386 static void packet_mm_close(struct vm_area_struct *vma)
4387 {
4388 	struct file *file = vma->vm_file;
4389 	struct socket *sock = file->private_data;
4390 	struct sock *sk = sock->sk;
4391 
4392 	if (sk)
4393 		atomic_long_dec(&pkt_sk(sk)->mapped);
4394 }
4395 
4396 static const struct vm_operations_struct packet_mmap_ops = {
4397 	.open	=	packet_mm_open,
4398 	.close	=	packet_mm_close,
4399 };
4400 
4401 static void free_pg_vec(struct pgv *pg_vec, unsigned int order,
4402 			unsigned int len)
4403 {
4404 	int i;
4405 
4406 	for (i = 0; i < len; i++) {
4407 		if (likely(pg_vec[i].buffer)) {
4408 			if (is_vmalloc_addr(pg_vec[i].buffer))
4409 				vfree(pg_vec[i].buffer);
4410 			else
4411 				free_pages((unsigned long)pg_vec[i].buffer,
4412 					   order);
4413 			pg_vec[i].buffer = NULL;
4414 		}
4415 	}
4416 	kfree(pg_vec);
4417 }
4418 
4419 static char *alloc_one_pg_vec_page(unsigned long order)
4420 {
4421 	char *buffer;
4422 	gfp_t gfp_flags = GFP_KERNEL | __GFP_COMP |
4423 			  __GFP_ZERO | __GFP_NOWARN | __GFP_NORETRY;
4424 
4425 	buffer = (char *) __get_free_pages(gfp_flags, order);
4426 	if (buffer)
4427 		return buffer;
4428 
4429 	/* __get_free_pages failed, fall back to vmalloc */
4430 	buffer = vzalloc(array_size((1 << order), PAGE_SIZE));
4431 	if (buffer)
4432 		return buffer;
4433 
4434 	/* vmalloc failed, lets dig into swap here */
4435 	gfp_flags &= ~__GFP_NORETRY;
4436 	buffer = (char *) __get_free_pages(gfp_flags, order);
4437 	if (buffer)
4438 		return buffer;
4439 
4440 	/* complete and utter failure */
4441 	return NULL;
4442 }
4443 
4444 static struct pgv *alloc_pg_vec(struct tpacket_req *req, int order)
4445 {
4446 	unsigned int block_nr = req->tp_block_nr;
4447 	struct pgv *pg_vec;
4448 	int i;
4449 
4450 	pg_vec = kcalloc(block_nr, sizeof(struct pgv), GFP_KERNEL | __GFP_NOWARN);
4451 	if (unlikely(!pg_vec))
4452 		goto out;
4453 
4454 	for (i = 0; i < block_nr; i++) {
4455 		pg_vec[i].buffer = alloc_one_pg_vec_page(order);
4456 		if (unlikely(!pg_vec[i].buffer))
4457 			goto out_free_pgvec;
4458 	}
4459 
4460 out:
4461 	return pg_vec;
4462 
4463 out_free_pgvec:
4464 	free_pg_vec(pg_vec, order, block_nr);
4465 	pg_vec = NULL;
4466 	goto out;
4467 }
4468 
4469 static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
4470 		int closing, int tx_ring)
4471 {
4472 	struct pgv *pg_vec = NULL;
4473 	struct packet_sock *po = pkt_sk(sk);
4474 	unsigned long *rx_owner_map = NULL;
4475 	int was_running, order = 0;
4476 	struct packet_ring_buffer *rb;
4477 	struct sk_buff_head *rb_queue;
4478 	__be16 num;
4479 	int err;
4480 	/* Added to avoid minimal code churn */
4481 	struct tpacket_req *req = &req_u->req;
4482 
4483 	rb = tx_ring ? &po->tx_ring : &po->rx_ring;
4484 	rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue;
4485 
4486 	err = -EBUSY;
4487 	if (!closing) {
4488 		if (atomic_long_read(&po->mapped))
4489 			goto out;
4490 		if (packet_read_pending(rb))
4491 			goto out;
4492 	}
4493 
4494 	if (req->tp_block_nr) {
4495 		unsigned int min_frame_size;
4496 
4497 		/* Sanity tests and some calculations */
4498 		err = -EBUSY;
4499 		if (unlikely(rb->pg_vec))
4500 			goto out;
4501 
4502 		switch (po->tp_version) {
4503 		case TPACKET_V1:
4504 			po->tp_hdrlen = TPACKET_HDRLEN;
4505 			break;
4506 		case TPACKET_V2:
4507 			po->tp_hdrlen = TPACKET2_HDRLEN;
4508 			break;
4509 		case TPACKET_V3:
4510 			po->tp_hdrlen = TPACKET3_HDRLEN;
4511 			break;
4512 		}
4513 
4514 		err = -EINVAL;
4515 		if (unlikely((int)req->tp_block_size <= 0))
4516 			goto out;
4517 		if (unlikely(!PAGE_ALIGNED(req->tp_block_size)))
4518 			goto out;
4519 		min_frame_size = po->tp_hdrlen + po->tp_reserve;
4520 		if (po->tp_version >= TPACKET_V3 &&
4521 		    req->tp_block_size <
4522 		    BLK_PLUS_PRIV((u64)req_u->req3.tp_sizeof_priv) + min_frame_size)
4523 			goto out;
4524 		if (unlikely(req->tp_frame_size < min_frame_size))
4525 			goto out;
4526 		if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1)))
4527 			goto out;
4528 
4529 		rb->frames_per_block = req->tp_block_size / req->tp_frame_size;
4530 		if (unlikely(rb->frames_per_block == 0))
4531 			goto out;
4532 		if (unlikely(rb->frames_per_block > UINT_MAX / req->tp_block_nr))
4533 			goto out;
4534 		if (unlikely((rb->frames_per_block * req->tp_block_nr) !=
4535 					req->tp_frame_nr))
4536 			goto out;
4537 
4538 		err = -ENOMEM;
4539 		order = get_order(req->tp_block_size);
4540 		pg_vec = alloc_pg_vec(req, order);
4541 		if (unlikely(!pg_vec))
4542 			goto out;
4543 		switch (po->tp_version) {
4544 		case TPACKET_V3:
4545 			/* Block transmit is not supported yet */
4546 			if (!tx_ring) {
4547 				init_prb_bdqc(po, rb, pg_vec, req_u);
4548 			} else {
4549 				struct tpacket_req3 *req3 = &req_u->req3;
4550 
4551 				if (req3->tp_retire_blk_tov ||
4552 				    req3->tp_sizeof_priv ||
4553 				    req3->tp_feature_req_word) {
4554 					err = -EINVAL;
4555 					goto out_free_pg_vec;
4556 				}
4557 			}
4558 			break;
4559 		default:
4560 			if (!tx_ring) {
4561 				rx_owner_map = bitmap_alloc(req->tp_frame_nr,
4562 					GFP_KERNEL | __GFP_NOWARN | __GFP_ZERO);
4563 				if (!rx_owner_map)
4564 					goto out_free_pg_vec;
4565 			}
4566 			break;
4567 		}
4568 	}
4569 	/* Done */
4570 	else {
4571 		err = -EINVAL;
4572 		if (unlikely(req->tp_frame_nr))
4573 			goto out;
4574 	}
4575 
4576 
4577 	/* Detach socket from network */
4578 	spin_lock(&po->bind_lock);
4579 	was_running = packet_sock_flag(po, PACKET_SOCK_RUNNING);
4580 	num = po->num;
4581 	if (was_running) {
4582 		WRITE_ONCE(po->num, 0);
4583 		__unregister_prot_hook(sk, false);
4584 	}
4585 	spin_unlock(&po->bind_lock);
4586 
4587 	synchronize_net();
4588 
4589 	err = -EBUSY;
4590 	mutex_lock(&po->pg_vec_lock);
4591 	if (closing || atomic_long_read(&po->mapped) == 0) {
4592 		err = 0;
4593 		spin_lock_bh(&rb_queue->lock);
4594 		swap(rb->pg_vec, pg_vec);
4595 		if (po->tp_version <= TPACKET_V2)
4596 			swap(rb->rx_owner_map, rx_owner_map);
4597 		rb->frame_max = (req->tp_frame_nr - 1);
4598 		rb->head = 0;
4599 		rb->frame_size = req->tp_frame_size;
4600 		spin_unlock_bh(&rb_queue->lock);
4601 
4602 		swap(rb->pg_vec_order, order);
4603 		swap(rb->pg_vec_len, req->tp_block_nr);
4604 
4605 		rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE;
4606 		po->prot_hook.func = (po->rx_ring.pg_vec) ?
4607 						tpacket_rcv : packet_rcv;
4608 		skb_queue_purge(rb_queue);
4609 		if (atomic_long_read(&po->mapped))
4610 			pr_err("packet_mmap: vma is busy: %ld\n",
4611 			       atomic_long_read(&po->mapped));
4612 	}
4613 	mutex_unlock(&po->pg_vec_lock);
4614 
4615 	spin_lock(&po->bind_lock);
4616 	if (was_running) {
4617 		WRITE_ONCE(po->num, num);
4618 		register_prot_hook(sk);
4619 	}
4620 	spin_unlock(&po->bind_lock);
4621 	if (pg_vec && (po->tp_version > TPACKET_V2)) {
4622 		/* Because we don't support block-based V3 on tx-ring */
4623 		if (!tx_ring)
4624 			prb_shutdown_retire_blk_timer(po, rb_queue);
4625 	}
4626 
4627 out_free_pg_vec:
4628 	if (pg_vec) {
4629 		bitmap_free(rx_owner_map);
4630 		free_pg_vec(pg_vec, order, req->tp_block_nr);
4631 	}
4632 out:
4633 	return err;
4634 }
4635 
4636 static int packet_mmap(struct file *file, struct socket *sock,
4637 		struct vm_area_struct *vma)
4638 {
4639 	struct sock *sk = sock->sk;
4640 	struct packet_sock *po = pkt_sk(sk);
4641 	unsigned long size, expected_size;
4642 	struct packet_ring_buffer *rb;
4643 	unsigned long start;
4644 	int err = -EINVAL;
4645 	int i;
4646 
4647 	if (vma->vm_pgoff)
4648 		return -EINVAL;
4649 
4650 	mutex_lock(&po->pg_vec_lock);
4651 
4652 	expected_size = 0;
4653 	for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
4654 		if (rb->pg_vec) {
4655 			expected_size += rb->pg_vec_len
4656 						* rb->pg_vec_pages
4657 						* PAGE_SIZE;
4658 		}
4659 	}
4660 
4661 	if (expected_size == 0)
4662 		goto out;
4663 
4664 	size = vma->vm_end - vma->vm_start;
4665 	if (size != expected_size)
4666 		goto out;
4667 
4668 	start = vma->vm_start;
4669 	for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
4670 		if (rb->pg_vec == NULL)
4671 			continue;
4672 
4673 		for (i = 0; i < rb->pg_vec_len; i++) {
4674 			struct page *page;
4675 			void *kaddr = rb->pg_vec[i].buffer;
4676 			int pg_num;
4677 
4678 			for (pg_num = 0; pg_num < rb->pg_vec_pages; pg_num++) {
4679 				page = pgv_to_page(kaddr);
4680 				err = vm_insert_page(vma, start, page);
4681 				if (unlikely(err))
4682 					goto out;
4683 				start += PAGE_SIZE;
4684 				kaddr += PAGE_SIZE;
4685 			}
4686 		}
4687 	}
4688 
4689 	atomic_long_inc(&po->mapped);
4690 	vma->vm_ops = &packet_mmap_ops;
4691 	err = 0;
4692 
4693 out:
4694 	mutex_unlock(&po->pg_vec_lock);
4695 	return err;
4696 }
4697 
4698 static const struct proto_ops packet_ops_spkt = {
4699 	.family =	PF_PACKET,
4700 	.owner =	THIS_MODULE,
4701 	.release =	packet_release,
4702 	.bind =		packet_bind_spkt,
4703 	.connect =	sock_no_connect,
4704 	.socketpair =	sock_no_socketpair,
4705 	.accept =	sock_no_accept,
4706 	.getname =	packet_getname_spkt,
4707 	.poll =		datagram_poll,
4708 	.ioctl =	packet_ioctl,
4709 	.gettstamp =	sock_gettstamp,
4710 	.listen =	sock_no_listen,
4711 	.shutdown =	sock_no_shutdown,
4712 	.sendmsg =	packet_sendmsg_spkt,
4713 	.recvmsg =	packet_recvmsg,
4714 	.mmap =		sock_no_mmap,
4715 };
4716 
4717 static const struct proto_ops packet_ops = {
4718 	.family =	PF_PACKET,
4719 	.owner =	THIS_MODULE,
4720 	.release =	packet_release,
4721 	.bind =		packet_bind,
4722 	.connect =	sock_no_connect,
4723 	.socketpair =	sock_no_socketpair,
4724 	.accept =	sock_no_accept,
4725 	.getname =	packet_getname,
4726 	.poll =		packet_poll,
4727 	.ioctl =	packet_ioctl,
4728 	.gettstamp =	sock_gettstamp,
4729 	.listen =	sock_no_listen,
4730 	.shutdown =	sock_no_shutdown,
4731 	.setsockopt =	packet_setsockopt,
4732 	.getsockopt =	packet_getsockopt,
4733 	.sendmsg =	packet_sendmsg,
4734 	.recvmsg =	packet_recvmsg,
4735 	.mmap =		packet_mmap,
4736 };
4737 
4738 static const struct net_proto_family packet_family_ops = {
4739 	.family =	PF_PACKET,
4740 	.create =	packet_create,
4741 	.owner	=	THIS_MODULE,
4742 };
4743 
4744 static struct notifier_block packet_netdev_notifier = {
4745 	.notifier_call =	packet_notifier,
4746 };
4747 
4748 #ifdef CONFIG_PROC_FS
4749 
4750 static void *packet_seq_start(struct seq_file *seq, loff_t *pos)
4751 	__acquires(RCU)
4752 {
4753 	struct net *net = seq_file_net(seq);
4754 
4755 	rcu_read_lock();
4756 	return seq_hlist_start_head_rcu(&net->packet.sklist, *pos);
4757 }
4758 
4759 static void *packet_seq_next(struct seq_file *seq, void *v, loff_t *pos)
4760 {
4761 	struct net *net = seq_file_net(seq);
4762 	return seq_hlist_next_rcu(v, &net->packet.sklist, pos);
4763 }
4764 
4765 static void packet_seq_stop(struct seq_file *seq, void *v)
4766 	__releases(RCU)
4767 {
4768 	rcu_read_unlock();
4769 }
4770 
4771 static int packet_seq_show(struct seq_file *seq, void *v)
4772 {
4773 	if (v == SEQ_START_TOKEN)
4774 		seq_printf(seq,
4775 			   "%*sRefCnt Type Proto  Iface R Rmem   User   Inode\n",
4776 			   IS_ENABLED(CONFIG_64BIT) ? -17 : -9, "sk");
4777 	else {
4778 		struct sock *s = sk_entry(v);
4779 		const struct packet_sock *po = pkt_sk(s);
4780 
4781 		seq_printf(seq,
4782 			   "%pK %-6d %-4d %04x   %-5d %1d %-6u %-6u %-6lu\n",
4783 			   s,
4784 			   refcount_read(&s->sk_refcnt),
4785 			   s->sk_type,
4786 			   ntohs(READ_ONCE(po->num)),
4787 			   READ_ONCE(po->ifindex),
4788 			   packet_sock_flag(po, PACKET_SOCK_RUNNING),
4789 			   atomic_read(&s->sk_rmem_alloc),
4790 			   from_kuid_munged(seq_user_ns(seq), sock_i_uid(s)),
4791 			   sock_i_ino(s));
4792 	}
4793 
4794 	return 0;
4795 }
4796 
4797 static const struct seq_operations packet_seq_ops = {
4798 	.start	= packet_seq_start,
4799 	.next	= packet_seq_next,
4800 	.stop	= packet_seq_stop,
4801 	.show	= packet_seq_show,
4802 };
4803 #endif
4804 
4805 static int __net_init packet_net_init(struct net *net)
4806 {
4807 	mutex_init(&net->packet.sklist_lock);
4808 	INIT_HLIST_HEAD(&net->packet.sklist);
4809 
4810 #ifdef CONFIG_PROC_FS
4811 	if (!proc_create_net("packet", 0, net->proc_net, &packet_seq_ops,
4812 			sizeof(struct seq_net_private)))
4813 		return -ENOMEM;
4814 #endif /* CONFIG_PROC_FS */
4815 
4816 	return 0;
4817 }
4818 
4819 static void __net_exit packet_net_exit(struct net *net)
4820 {
4821 	remove_proc_entry("packet", net->proc_net);
4822 	WARN_ON_ONCE(!hlist_empty(&net->packet.sklist));
4823 }
4824 
4825 static struct pernet_operations packet_net_ops = {
4826 	.init = packet_net_init,
4827 	.exit = packet_net_exit,
4828 };
4829 
4830 
4831 static void __exit packet_exit(void)
4832 {
4833 	sock_unregister(PF_PACKET);
4834 	proto_unregister(&packet_proto);
4835 	unregister_netdevice_notifier(&packet_netdev_notifier);
4836 	unregister_pernet_subsys(&packet_net_ops);
4837 }
4838 
4839 static int __init packet_init(void)
4840 {
4841 	int rc;
4842 
4843 	rc = register_pernet_subsys(&packet_net_ops);
4844 	if (rc)
4845 		goto out;
4846 	rc = register_netdevice_notifier(&packet_netdev_notifier);
4847 	if (rc)
4848 		goto out_pernet;
4849 	rc = proto_register(&packet_proto, 0);
4850 	if (rc)
4851 		goto out_notifier;
4852 	rc = sock_register(&packet_family_ops);
4853 	if (rc)
4854 		goto out_proto;
4855 
4856 	return 0;
4857 
4858 out_proto:
4859 	proto_unregister(&packet_proto);
4860 out_notifier:
4861 	unregister_netdevice_notifier(&packet_netdev_notifier);
4862 out_pernet:
4863 	unregister_pernet_subsys(&packet_net_ops);
4864 out:
4865 	return rc;
4866 }
4867 
4868 module_init(packet_init);
4869 module_exit(packet_exit);
4870 MODULE_DESCRIPTION("Packet socket support (AF_PACKET)");
4871 MODULE_LICENSE("GPL");
4872 MODULE_ALIAS_NETPROTO(PF_PACKET);
4873