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