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