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