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