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