• 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 <asm/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 
92 #ifdef CONFIG_INET
93 #include <net/inet_common.h>
94 #endif
95 
96 #include "internal.h"
97 
98 /*
99    Assumptions:
100    - if device has no dev->hard_header routine, it adds and removes ll header
101      inside itself. In this case ll header is invisible outside of device,
102      but higher levels still should reserve dev->hard_header_len.
103      Some devices are enough clever to reallocate skb, when header
104      will not fit to reserved space (tunnel), another ones are silly
105      (PPP).
106    - packet socket receives packets with pulled ll header,
107      so that SOCK_RAW should push it back.
108 
109 On receive:
110 -----------
111 
112 Incoming, dev->hard_header!=NULL
113    mac_header -> ll header
114    data       -> data
115 
116 Outgoing, dev->hard_header!=NULL
117    mac_header -> ll header
118    data       -> ll header
119 
120 Incoming, dev->hard_header==NULL
121    mac_header -> UNKNOWN position. It is very likely, that it points to ll
122 		 header.  PPP makes it, that is wrong, because introduce
123 		 assymetry between rx and tx paths.
124    data       -> data
125 
126 Outgoing, dev->hard_header==NULL
127    mac_header -> data. ll header is still not built!
128    data       -> data
129 
130 Resume
131   If dev->hard_header==NULL we are unlikely to restore sensible ll header.
132 
133 
134 On transmit:
135 ------------
136 
137 dev->hard_header != NULL
138    mac_header -> ll header
139    data       -> ll header
140 
141 dev->hard_header == NULL (ll header is added by device, we cannot control it)
142    mac_header -> data
143    data       -> data
144 
145    We should set nh.raw on output to correct posistion,
146    packet classifier depends on it.
147  */
148 
149 /* Private packet socket structures. */
150 
151 /* identical to struct packet_mreq except it has
152  * a longer address field.
153  */
154 struct packet_mreq_max {
155 	int		mr_ifindex;
156 	unsigned short	mr_type;
157 	unsigned short	mr_alen;
158 	unsigned char	mr_address[MAX_ADDR_LEN];
159 };
160 
161 union tpacket_uhdr {
162 	struct tpacket_hdr  *h1;
163 	struct tpacket2_hdr *h2;
164 	struct tpacket3_hdr *h3;
165 	void *raw;
166 };
167 
168 static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
169 		int closing, int tx_ring);
170 
171 #define V3_ALIGNMENT	(8)
172 
173 #define BLK_HDR_LEN	(ALIGN(sizeof(struct tpacket_block_desc), V3_ALIGNMENT))
174 
175 #define BLK_PLUS_PRIV(sz_of_priv) \
176 	(BLK_HDR_LEN + ALIGN((sz_of_priv), V3_ALIGNMENT))
177 
178 #define PGV_FROM_VMALLOC 1
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_snd(struct packet_sock *po, struct msghdr *msg);
190 static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
191 		       struct packet_type *pt, struct net_device *orig_dev);
192 
193 static void *packet_previous_frame(struct packet_sock *po,
194 		struct packet_ring_buffer *rb,
195 		int status);
196 static void packet_increment_head(struct packet_ring_buffer *buff);
197 static int prb_curr_blk_in_use(struct tpacket_kbdq_core *,
198 			struct tpacket_block_desc *);
199 static void *prb_dispatch_next_block(struct tpacket_kbdq_core *,
200 			struct packet_sock *);
201 static void prb_retire_current_block(struct tpacket_kbdq_core *,
202 		struct packet_sock *, unsigned int status);
203 static int prb_queue_frozen(struct tpacket_kbdq_core *);
204 static void prb_open_block(struct tpacket_kbdq_core *,
205 		struct tpacket_block_desc *);
206 static void prb_retire_rx_blk_timer_expired(unsigned long);
207 static void _prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core *);
208 static void prb_init_blk_timer(struct packet_sock *,
209 		struct tpacket_kbdq_core *,
210 		void (*func) (unsigned long));
211 static void prb_fill_rxhash(struct tpacket_kbdq_core *, struct tpacket3_hdr *);
212 static void prb_clear_rxhash(struct tpacket_kbdq_core *,
213 		struct tpacket3_hdr *);
214 static void prb_fill_vlan_info(struct tpacket_kbdq_core *,
215 		struct tpacket3_hdr *);
216 static void packet_flush_mclist(struct sock *sk);
217 
218 struct packet_skb_cb {
219 	unsigned int origlen;
220 	union {
221 		struct sockaddr_pkt pkt;
222 		struct sockaddr_ll ll;
223 	} sa;
224 };
225 
226 #define PACKET_SKB_CB(__skb)	((struct packet_skb_cb *)((__skb)->cb))
227 
228 #define GET_PBDQC_FROM_RB(x)	((struct tpacket_kbdq_core *)(&(x)->prb_bdqc))
229 #define GET_PBLOCK_DESC(x, bid)	\
230 	((struct tpacket_block_desc *)((x)->pkbdq[(bid)].buffer))
231 #define GET_CURR_PBLOCK_DESC_FROM_CORE(x)	\
232 	((struct tpacket_block_desc *)((x)->pkbdq[(x)->kactive_blk_num].buffer))
233 #define GET_NEXT_PRB_BLK_NUM(x) \
234 	(((x)->kactive_blk_num < ((x)->knum_blocks-1)) ? \
235 	((x)->kactive_blk_num+1) : 0)
236 
237 static void __fanout_unlink(struct sock *sk, struct packet_sock *po);
238 static void __fanout_link(struct sock *sk, struct packet_sock *po);
239 
240 /* register_prot_hook must be invoked with the po->bind_lock held,
241  * or from a context in which asynchronous accesses to the packet
242  * socket is not possible (packet_create()).
243  */
register_prot_hook(struct sock * sk)244 static void register_prot_hook(struct sock *sk)
245 {
246 	struct packet_sock *po = pkt_sk(sk);
247 	if (!po->running) {
248 		if (po->fanout)
249 			__fanout_link(sk, po);
250 		else
251 			dev_add_pack(&po->prot_hook);
252 		sock_hold(sk);
253 		po->running = 1;
254 	}
255 }
256 
257 /* {,__}unregister_prot_hook() must be invoked with the po->bind_lock
258  * held.   If the sync parameter is true, we will temporarily drop
259  * the po->bind_lock and do a synchronize_net to make sure no
260  * asynchronous packet processing paths still refer to the elements
261  * of po->prot_hook.  If the sync parameter is false, it is the
262  * callers responsibility to take care of this.
263  */
__unregister_prot_hook(struct sock * sk,bool sync)264 static void __unregister_prot_hook(struct sock *sk, bool sync)
265 {
266 	struct packet_sock *po = pkt_sk(sk);
267 
268 	po->running = 0;
269 	if (po->fanout)
270 		__fanout_unlink(sk, po);
271 	else
272 		__dev_remove_pack(&po->prot_hook);
273 	__sock_put(sk);
274 
275 	if (sync) {
276 		spin_unlock(&po->bind_lock);
277 		synchronize_net();
278 		spin_lock(&po->bind_lock);
279 	}
280 }
281 
unregister_prot_hook(struct sock * sk,bool sync)282 static void unregister_prot_hook(struct sock *sk, bool sync)
283 {
284 	struct packet_sock *po = pkt_sk(sk);
285 
286 	if (po->running)
287 		__unregister_prot_hook(sk, sync);
288 }
289 
pgv_to_page(void * addr)290 static inline __pure struct page *pgv_to_page(void *addr)
291 {
292 	if (is_vmalloc_addr(addr))
293 		return vmalloc_to_page(addr);
294 	return virt_to_page(addr);
295 }
296 
__packet_set_status(struct packet_sock * po,void * frame,int status)297 static void __packet_set_status(struct packet_sock *po, void *frame, int status)
298 {
299 	union tpacket_uhdr h;
300 
301 	h.raw = frame;
302 	switch (po->tp_version) {
303 	case TPACKET_V1:
304 		h.h1->tp_status = status;
305 		flush_dcache_page(pgv_to_page(&h.h1->tp_status));
306 		break;
307 	case TPACKET_V2:
308 		h.h2->tp_status = status;
309 		flush_dcache_page(pgv_to_page(&h.h2->tp_status));
310 		break;
311 	case TPACKET_V3:
312 	default:
313 		WARN(1, "TPACKET version not supported.\n");
314 		BUG();
315 	}
316 
317 	smp_wmb();
318 }
319 
__packet_get_status(struct packet_sock * po,void * frame)320 static int __packet_get_status(struct packet_sock *po, void *frame)
321 {
322 	union tpacket_uhdr h;
323 
324 	smp_rmb();
325 
326 	h.raw = frame;
327 	switch (po->tp_version) {
328 	case TPACKET_V1:
329 		flush_dcache_page(pgv_to_page(&h.h1->tp_status));
330 		return h.h1->tp_status;
331 	case TPACKET_V2:
332 		flush_dcache_page(pgv_to_page(&h.h2->tp_status));
333 		return h.h2->tp_status;
334 	case TPACKET_V3:
335 	default:
336 		WARN(1, "TPACKET version not supported.\n");
337 		BUG();
338 		return 0;
339 	}
340 }
341 
tpacket_get_timestamp(struct sk_buff * skb,struct timespec * ts,unsigned int flags)342 static __u32 tpacket_get_timestamp(struct sk_buff *skb, struct timespec *ts,
343 				   unsigned int flags)
344 {
345 	struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);
346 
347 	if (shhwtstamps) {
348 		if ((flags & SOF_TIMESTAMPING_SYS_HARDWARE) &&
349 		    ktime_to_timespec_cond(shhwtstamps->syststamp, ts))
350 			return TP_STATUS_TS_SYS_HARDWARE;
351 		if ((flags & SOF_TIMESTAMPING_RAW_HARDWARE) &&
352 		    ktime_to_timespec_cond(shhwtstamps->hwtstamp, ts))
353 			return TP_STATUS_TS_RAW_HARDWARE;
354 	}
355 
356 	if (ktime_to_timespec_cond(skb->tstamp, ts))
357 		return TP_STATUS_TS_SOFTWARE;
358 
359 	return 0;
360 }
361 
__packet_set_timestamp(struct packet_sock * po,void * frame,struct sk_buff * skb)362 static __u32 __packet_set_timestamp(struct packet_sock *po, void *frame,
363 				    struct sk_buff *skb)
364 {
365 	union tpacket_uhdr h;
366 	struct timespec ts;
367 	__u32 ts_status;
368 
369 	if (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp)))
370 		return 0;
371 
372 	h.raw = frame;
373 	switch (po->tp_version) {
374 	case TPACKET_V1:
375 		h.h1->tp_sec = ts.tv_sec;
376 		h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
377 		break;
378 	case TPACKET_V2:
379 		h.h2->tp_sec = ts.tv_sec;
380 		h.h2->tp_nsec = ts.tv_nsec;
381 		break;
382 	case TPACKET_V3:
383 	default:
384 		WARN(1, "TPACKET version not supported.\n");
385 		BUG();
386 	}
387 
388 	/* one flush is safe, as both fields always lie on the same cacheline */
389 	flush_dcache_page(pgv_to_page(&h.h1->tp_sec));
390 	smp_wmb();
391 
392 	return ts_status;
393 }
394 
packet_lookup_frame(struct packet_sock * po,struct packet_ring_buffer * rb,unsigned int position,int status)395 static void *packet_lookup_frame(struct packet_sock *po,
396 		struct packet_ring_buffer *rb,
397 		unsigned int position,
398 		int status)
399 {
400 	unsigned int pg_vec_pos, frame_offset;
401 	union tpacket_uhdr h;
402 
403 	pg_vec_pos = position / rb->frames_per_block;
404 	frame_offset = position % rb->frames_per_block;
405 
406 	h.raw = rb->pg_vec[pg_vec_pos].buffer +
407 		(frame_offset * rb->frame_size);
408 
409 	if (status != __packet_get_status(po, h.raw))
410 		return NULL;
411 
412 	return h.raw;
413 }
414 
packet_current_frame(struct packet_sock * po,struct packet_ring_buffer * rb,int status)415 static void *packet_current_frame(struct packet_sock *po,
416 		struct packet_ring_buffer *rb,
417 		int status)
418 {
419 	return packet_lookup_frame(po, rb, rb->head, status);
420 }
421 
prb_del_retire_blk_timer(struct tpacket_kbdq_core * pkc)422 static void prb_del_retire_blk_timer(struct tpacket_kbdq_core *pkc)
423 {
424 	del_timer_sync(&pkc->retire_blk_timer);
425 }
426 
prb_shutdown_retire_blk_timer(struct packet_sock * po,int tx_ring,struct sk_buff_head * rb_queue)427 static void prb_shutdown_retire_blk_timer(struct packet_sock *po,
428 		int tx_ring,
429 		struct sk_buff_head *rb_queue)
430 {
431 	struct tpacket_kbdq_core *pkc;
432 
433 	pkc = tx_ring ? &po->tx_ring.prb_bdqc : &po->rx_ring.prb_bdqc;
434 
435 	spin_lock(&rb_queue->lock);
436 	pkc->delete_blk_timer = 1;
437 	spin_unlock(&rb_queue->lock);
438 
439 	prb_del_retire_blk_timer(pkc);
440 }
441 
prb_init_blk_timer(struct packet_sock * po,struct tpacket_kbdq_core * pkc,void (* func)(unsigned long))442 static void prb_init_blk_timer(struct packet_sock *po,
443 		struct tpacket_kbdq_core *pkc,
444 		void (*func) (unsigned long))
445 {
446 	init_timer(&pkc->retire_blk_timer);
447 	pkc->retire_blk_timer.data = (long)po;
448 	pkc->retire_blk_timer.function = func;
449 	pkc->retire_blk_timer.expires = jiffies;
450 }
451 
prb_setup_retire_blk_timer(struct packet_sock * po,int tx_ring)452 static void prb_setup_retire_blk_timer(struct packet_sock *po, int tx_ring)
453 {
454 	struct tpacket_kbdq_core *pkc;
455 
456 	if (tx_ring)
457 		BUG();
458 
459 	pkc = tx_ring ? &po->tx_ring.prb_bdqc : &po->rx_ring.prb_bdqc;
460 	prb_init_blk_timer(po, pkc, prb_retire_rx_blk_timer_expired);
461 }
462 
prb_calc_retire_blk_tmo(struct packet_sock * po,int blk_size_in_bytes)463 static int prb_calc_retire_blk_tmo(struct packet_sock *po,
464 				int blk_size_in_bytes)
465 {
466 	struct net_device *dev;
467 	unsigned int mbits = 0, msec = 0, div = 0, tmo = 0;
468 	struct ethtool_cmd ecmd;
469 	int err;
470 	u32 speed;
471 
472 	rtnl_lock();
473 	dev = __dev_get_by_index(sock_net(&po->sk), po->ifindex);
474 	if (unlikely(!dev)) {
475 		rtnl_unlock();
476 		return DEFAULT_PRB_RETIRE_TOV;
477 	}
478 	err = __ethtool_get_settings(dev, &ecmd);
479 	speed = ethtool_cmd_speed(&ecmd);
480 	rtnl_unlock();
481 	if (!err) {
482 		/*
483 		 * If the link speed is so slow you don't really
484 		 * need to worry about perf anyways
485 		 */
486 		if (speed < SPEED_1000 || speed == SPEED_UNKNOWN) {
487 			return DEFAULT_PRB_RETIRE_TOV;
488 		} else {
489 			msec = 1;
490 			div = speed / 1000;
491 		}
492 	}
493 
494 	mbits = (blk_size_in_bytes * 8) / (1024 * 1024);
495 
496 	if (div)
497 		mbits /= div;
498 
499 	tmo = mbits * msec;
500 
501 	if (div)
502 		return tmo+1;
503 	return tmo;
504 }
505 
prb_init_ft_ops(struct tpacket_kbdq_core * p1,union tpacket_req_u * req_u)506 static void prb_init_ft_ops(struct tpacket_kbdq_core *p1,
507 			union tpacket_req_u *req_u)
508 {
509 	p1->feature_req_word = req_u->req3.tp_feature_req_word;
510 }
511 
init_prb_bdqc(struct packet_sock * po,struct packet_ring_buffer * rb,struct pgv * pg_vec,union tpacket_req_u * req_u,int tx_ring)512 static void init_prb_bdqc(struct packet_sock *po,
513 			struct packet_ring_buffer *rb,
514 			struct pgv *pg_vec,
515 			union tpacket_req_u *req_u, int tx_ring)
516 {
517 	struct tpacket_kbdq_core *p1 = &rb->prb_bdqc;
518 	struct tpacket_block_desc *pbd;
519 
520 	memset(p1, 0x0, sizeof(*p1));
521 
522 	p1->knxt_seq_num = 1;
523 	p1->pkbdq = pg_vec;
524 	pbd = (struct tpacket_block_desc *)pg_vec[0].buffer;
525 	p1->pkblk_start	= pg_vec[0].buffer;
526 	p1->kblk_size = req_u->req3.tp_block_size;
527 	p1->knum_blocks	= req_u->req3.tp_block_nr;
528 	p1->hdrlen = po->tp_hdrlen;
529 	p1->version = po->tp_version;
530 	p1->last_kactive_blk_num = 0;
531 	po->stats.stats3.tp_freeze_q_cnt = 0;
532 	if (req_u->req3.tp_retire_blk_tov)
533 		p1->retire_blk_tov = req_u->req3.tp_retire_blk_tov;
534 	else
535 		p1->retire_blk_tov = prb_calc_retire_blk_tmo(po,
536 						req_u->req3.tp_block_size);
537 	p1->tov_in_jiffies = msecs_to_jiffies(p1->retire_blk_tov);
538 	p1->blk_sizeof_priv = req_u->req3.tp_sizeof_priv;
539 
540 	p1->max_frame_len = p1->kblk_size - BLK_PLUS_PRIV(p1->blk_sizeof_priv);
541 	prb_init_ft_ops(p1, req_u);
542 	prb_setup_retire_blk_timer(po, tx_ring);
543 	prb_open_block(p1, pbd);
544 }
545 
546 /*  Do NOT update the last_blk_num first.
547  *  Assumes sk_buff_head lock is held.
548  */
_prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core * pkc)549 static void _prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core *pkc)
550 {
551 	mod_timer(&pkc->retire_blk_timer,
552 			jiffies + pkc->tov_in_jiffies);
553 	pkc->last_kactive_blk_num = pkc->kactive_blk_num;
554 }
555 
556 /*
557  * Timer logic:
558  * 1) We refresh the timer only when we open a block.
559  *    By doing this we don't waste cycles refreshing the timer
560  *	  on packet-by-packet basis.
561  *
562  * With a 1MB block-size, on a 1Gbps line, it will take
563  * i) ~8 ms to fill a block + ii) memcpy etc.
564  * In this cut we are not accounting for the memcpy time.
565  *
566  * So, if the user sets the 'tmo' to 10ms then the timer
567  * will never fire while the block is still getting filled
568  * (which is what we want). However, the user could choose
569  * to close a block early and that's fine.
570  *
571  * But when the timer does fire, we check whether or not to refresh it.
572  * Since the tmo granularity is in msecs, it is not too expensive
573  * to refresh the timer, lets say every '8' msecs.
574  * Either the user can set the 'tmo' or we can derive it based on
575  * a) line-speed and b) block-size.
576  * prb_calc_retire_blk_tmo() calculates the tmo.
577  *
578  */
prb_retire_rx_blk_timer_expired(unsigned long data)579 static void prb_retire_rx_blk_timer_expired(unsigned long data)
580 {
581 	struct packet_sock *po = (struct packet_sock *)data;
582 	struct tpacket_kbdq_core *pkc = &po->rx_ring.prb_bdqc;
583 	unsigned int frozen;
584 	struct tpacket_block_desc *pbd;
585 
586 	spin_lock(&po->sk.sk_receive_queue.lock);
587 
588 	frozen = prb_queue_frozen(pkc);
589 	pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
590 
591 	if (unlikely(pkc->delete_blk_timer))
592 		goto out;
593 
594 	/* We only need to plug the race when the block is partially filled.
595 	 * tpacket_rcv:
596 	 *		lock(); increment BLOCK_NUM_PKTS; unlock()
597 	 *		copy_bits() is in progress ...
598 	 *		timer fires on other cpu:
599 	 *		we can't retire the current block because copy_bits
600 	 *		is in progress.
601 	 *
602 	 */
603 	if (BLOCK_NUM_PKTS(pbd)) {
604 		while (atomic_read(&pkc->blk_fill_in_prog)) {
605 			/* Waiting for skb_copy_bits to finish... */
606 			cpu_relax();
607 		}
608 	}
609 
610 	if (pkc->last_kactive_blk_num == pkc->kactive_blk_num) {
611 		if (!frozen) {
612 			prb_retire_current_block(pkc, po, TP_STATUS_BLK_TMO);
613 			if (!prb_dispatch_next_block(pkc, po))
614 				goto refresh_timer;
615 			else
616 				goto out;
617 		} else {
618 			/* Case 1. Queue was frozen because user-space was
619 			 *	   lagging behind.
620 			 */
621 			if (prb_curr_blk_in_use(pkc, pbd)) {
622 				/*
623 				 * Ok, user-space is still behind.
624 				 * So just refresh the timer.
625 				 */
626 				goto refresh_timer;
627 			} else {
628 			       /* Case 2. queue was frozen,user-space caught up,
629 				* now the link went idle && the timer fired.
630 				* We don't have a block to close.So we open this
631 				* block and restart the timer.
632 				* opening a block thaws the queue,restarts timer
633 				* Thawing/timer-refresh is a side effect.
634 				*/
635 				prb_open_block(pkc, pbd);
636 				goto out;
637 			}
638 		}
639 	}
640 
641 refresh_timer:
642 	_prb_refresh_rx_retire_blk_timer(pkc);
643 
644 out:
645 	spin_unlock(&po->sk.sk_receive_queue.lock);
646 }
647 
prb_flush_block(struct tpacket_kbdq_core * pkc1,struct tpacket_block_desc * pbd1,__u32 status)648 static void prb_flush_block(struct tpacket_kbdq_core *pkc1,
649 		struct tpacket_block_desc *pbd1, __u32 status)
650 {
651 	/* Flush everything minus the block header */
652 
653 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
654 	u8 *start, *end;
655 
656 	start = (u8 *)pbd1;
657 
658 	/* Skip the block header(we know header WILL fit in 4K) */
659 	start += PAGE_SIZE;
660 
661 	end = (u8 *)PAGE_ALIGN((unsigned long)pkc1->pkblk_end);
662 	for (; start < end; start += PAGE_SIZE)
663 		flush_dcache_page(pgv_to_page(start));
664 
665 	smp_wmb();
666 #endif
667 
668 	/* Now update the block status. */
669 
670 	BLOCK_STATUS(pbd1) = status;
671 
672 	/* Flush the block header */
673 
674 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
675 	start = (u8 *)pbd1;
676 	flush_dcache_page(pgv_to_page(start));
677 
678 	smp_wmb();
679 #endif
680 }
681 
682 /*
683  * Side effect:
684  *
685  * 1) flush the block
686  * 2) Increment active_blk_num
687  *
688  * Note:We DONT refresh the timer on purpose.
689  *	Because almost always the next block will be opened.
690  */
prb_close_block(struct tpacket_kbdq_core * pkc1,struct tpacket_block_desc * pbd1,struct packet_sock * po,unsigned int stat)691 static void prb_close_block(struct tpacket_kbdq_core *pkc1,
692 		struct tpacket_block_desc *pbd1,
693 		struct packet_sock *po, unsigned int stat)
694 {
695 	__u32 status = TP_STATUS_USER | stat;
696 
697 	struct tpacket3_hdr *last_pkt;
698 	struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
699 
700 	if (po->stats.stats3.tp_drops)
701 		status |= TP_STATUS_LOSING;
702 
703 	last_pkt = (struct tpacket3_hdr *)pkc1->prev;
704 	last_pkt->tp_next_offset = 0;
705 
706 	/* Get the ts of the last pkt */
707 	if (BLOCK_NUM_PKTS(pbd1)) {
708 		h1->ts_last_pkt.ts_sec = last_pkt->tp_sec;
709 		h1->ts_last_pkt.ts_nsec	= last_pkt->tp_nsec;
710 	} else {
711 		/* Ok, we tmo'd - so get the current time */
712 		struct timespec ts;
713 		getnstimeofday(&ts);
714 		h1->ts_last_pkt.ts_sec = ts.tv_sec;
715 		h1->ts_last_pkt.ts_nsec	= ts.tv_nsec;
716 	}
717 
718 	smp_wmb();
719 
720 	/* Flush the block */
721 	prb_flush_block(pkc1, pbd1, status);
722 
723 	pkc1->kactive_blk_num = GET_NEXT_PRB_BLK_NUM(pkc1);
724 }
725 
prb_thaw_queue(struct tpacket_kbdq_core * pkc)726 static void prb_thaw_queue(struct tpacket_kbdq_core *pkc)
727 {
728 	pkc->reset_pending_on_curr_blk = 0;
729 }
730 
731 /*
732  * Side effect of opening a block:
733  *
734  * 1) prb_queue is thawed.
735  * 2) retire_blk_timer is refreshed.
736  *
737  */
prb_open_block(struct tpacket_kbdq_core * pkc1,struct tpacket_block_desc * pbd1)738 static void prb_open_block(struct tpacket_kbdq_core *pkc1,
739 	struct tpacket_block_desc *pbd1)
740 {
741 	struct timespec ts;
742 	struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
743 
744 	smp_rmb();
745 
746 	/* We could have just memset this but we will lose the
747 	 * flexibility of making the priv area sticky
748 	 */
749 
750 	BLOCK_SNUM(pbd1) = pkc1->knxt_seq_num++;
751 	BLOCK_NUM_PKTS(pbd1) = 0;
752 	BLOCK_LEN(pbd1) = BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
753 
754 	getnstimeofday(&ts);
755 
756 	h1->ts_first_pkt.ts_sec = ts.tv_sec;
757 	h1->ts_first_pkt.ts_nsec = ts.tv_nsec;
758 
759 	pkc1->pkblk_start = (char *)pbd1;
760 	pkc1->nxt_offset = pkc1->pkblk_start + BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
761 
762 	BLOCK_O2FP(pbd1) = (__u32)BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
763 	BLOCK_O2PRIV(pbd1) = BLK_HDR_LEN;
764 
765 	pbd1->version = pkc1->version;
766 	pkc1->prev = pkc1->nxt_offset;
767 	pkc1->pkblk_end = pkc1->pkblk_start + pkc1->kblk_size;
768 
769 	prb_thaw_queue(pkc1);
770 	_prb_refresh_rx_retire_blk_timer(pkc1);
771 
772 	smp_wmb();
773 }
774 
775 /*
776  * Queue freeze logic:
777  * 1) Assume tp_block_nr = 8 blocks.
778  * 2) At time 't0', user opens Rx ring.
779  * 3) Some time past 't0', kernel starts filling blocks starting from 0 .. 7
780  * 4) user-space is either sleeping or processing block '0'.
781  * 5) tpacket_rcv is currently filling block '7', since there is no space left,
782  *    it will close block-7,loop around and try to fill block '0'.
783  *    call-flow:
784  *    __packet_lookup_frame_in_block
785  *      prb_retire_current_block()
786  *      prb_dispatch_next_block()
787  *        |->(BLOCK_STATUS == USER) evaluates to true
788  *    5.1) Since block-0 is currently in-use, we just freeze the queue.
789  * 6) Now there are two cases:
790  *    6.1) Link goes idle right after the queue is frozen.
791  *         But remember, the last open_block() refreshed the timer.
792  *         When this timer expires,it will refresh itself so that we can
793  *         re-open block-0 in near future.
794  *    6.2) Link is busy and keeps on receiving packets. This is a simple
795  *         case and __packet_lookup_frame_in_block will check if block-0
796  *         is free and can now be re-used.
797  */
prb_freeze_queue(struct tpacket_kbdq_core * pkc,struct packet_sock * po)798 static void prb_freeze_queue(struct tpacket_kbdq_core *pkc,
799 				  struct packet_sock *po)
800 {
801 	pkc->reset_pending_on_curr_blk = 1;
802 	po->stats.stats3.tp_freeze_q_cnt++;
803 }
804 
805 #define TOTAL_PKT_LEN_INCL_ALIGN(length) (ALIGN((length), V3_ALIGNMENT))
806 
807 /*
808  * If the next block is free then we will dispatch it
809  * and return a good offset.
810  * Else, we will freeze the queue.
811  * So, caller must check the return value.
812  */
prb_dispatch_next_block(struct tpacket_kbdq_core * pkc,struct packet_sock * po)813 static void *prb_dispatch_next_block(struct tpacket_kbdq_core *pkc,
814 		struct packet_sock *po)
815 {
816 	struct tpacket_block_desc *pbd;
817 
818 	smp_rmb();
819 
820 	/* 1. Get current block num */
821 	pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
822 
823 	/* 2. If this block is currently in_use then freeze the queue */
824 	if (TP_STATUS_USER & BLOCK_STATUS(pbd)) {
825 		prb_freeze_queue(pkc, po);
826 		return NULL;
827 	}
828 
829 	/*
830 	 * 3.
831 	 * open this block and return the offset where the first packet
832 	 * needs to get stored.
833 	 */
834 	prb_open_block(pkc, pbd);
835 	return (void *)pkc->nxt_offset;
836 }
837 
prb_retire_current_block(struct tpacket_kbdq_core * pkc,struct packet_sock * po,unsigned int status)838 static void prb_retire_current_block(struct tpacket_kbdq_core *pkc,
839 		struct packet_sock *po, unsigned int status)
840 {
841 	struct tpacket_block_desc *pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
842 
843 	/* retire/close the current block */
844 	if (likely(TP_STATUS_KERNEL == BLOCK_STATUS(pbd))) {
845 		/*
846 		 * Plug the case where copy_bits() is in progress on
847 		 * cpu-0 and tpacket_rcv() got invoked on cpu-1, didn't
848 		 * have space to copy the pkt in the current block and
849 		 * called prb_retire_current_block()
850 		 *
851 		 * We don't need to worry about the TMO case because
852 		 * the timer-handler already handled this case.
853 		 */
854 		if (!(status & TP_STATUS_BLK_TMO)) {
855 			while (atomic_read(&pkc->blk_fill_in_prog)) {
856 				/* Waiting for skb_copy_bits to finish... */
857 				cpu_relax();
858 			}
859 		}
860 		prb_close_block(pkc, pbd, po, status);
861 		return;
862 	}
863 }
864 
prb_curr_blk_in_use(struct tpacket_kbdq_core * pkc,struct tpacket_block_desc * pbd)865 static int prb_curr_blk_in_use(struct tpacket_kbdq_core *pkc,
866 				      struct tpacket_block_desc *pbd)
867 {
868 	return TP_STATUS_USER & BLOCK_STATUS(pbd);
869 }
870 
prb_queue_frozen(struct tpacket_kbdq_core * pkc)871 static int prb_queue_frozen(struct tpacket_kbdq_core *pkc)
872 {
873 	return pkc->reset_pending_on_curr_blk;
874 }
875 
prb_clear_blk_fill_status(struct packet_ring_buffer * rb)876 static void prb_clear_blk_fill_status(struct packet_ring_buffer *rb)
877 {
878 	struct tpacket_kbdq_core *pkc  = GET_PBDQC_FROM_RB(rb);
879 	atomic_dec(&pkc->blk_fill_in_prog);
880 }
881 
prb_fill_rxhash(struct tpacket_kbdq_core * pkc,struct tpacket3_hdr * ppd)882 static void prb_fill_rxhash(struct tpacket_kbdq_core *pkc,
883 			struct tpacket3_hdr *ppd)
884 {
885 	ppd->hv1.tp_rxhash = skb_get_rxhash(pkc->skb);
886 }
887 
prb_clear_rxhash(struct tpacket_kbdq_core * pkc,struct tpacket3_hdr * ppd)888 static void prb_clear_rxhash(struct tpacket_kbdq_core *pkc,
889 			struct tpacket3_hdr *ppd)
890 {
891 	ppd->hv1.tp_rxhash = 0;
892 }
893 
prb_fill_vlan_info(struct tpacket_kbdq_core * pkc,struct tpacket3_hdr * ppd)894 static void prb_fill_vlan_info(struct tpacket_kbdq_core *pkc,
895 			struct tpacket3_hdr *ppd)
896 {
897 	if (vlan_tx_tag_present(pkc->skb)) {
898 		ppd->hv1.tp_vlan_tci = vlan_tx_tag_get(pkc->skb);
899 		ppd->tp_status = TP_STATUS_VLAN_VALID;
900 	} else {
901 		ppd->hv1.tp_vlan_tci = 0;
902 		ppd->tp_status = TP_STATUS_AVAILABLE;
903 	}
904 }
905 
prb_run_all_ft_ops(struct tpacket_kbdq_core * pkc,struct tpacket3_hdr * ppd)906 static void prb_run_all_ft_ops(struct tpacket_kbdq_core *pkc,
907 			struct tpacket3_hdr *ppd)
908 {
909 	prb_fill_vlan_info(pkc, ppd);
910 
911 	if (pkc->feature_req_word & TP_FT_REQ_FILL_RXHASH)
912 		prb_fill_rxhash(pkc, ppd);
913 	else
914 		prb_clear_rxhash(pkc, ppd);
915 }
916 
prb_fill_curr_block(char * curr,struct tpacket_kbdq_core * pkc,struct tpacket_block_desc * pbd,unsigned int len)917 static void prb_fill_curr_block(char *curr,
918 				struct tpacket_kbdq_core *pkc,
919 				struct tpacket_block_desc *pbd,
920 				unsigned int len)
921 {
922 	struct tpacket3_hdr *ppd;
923 
924 	ppd  = (struct tpacket3_hdr *)curr;
925 	ppd->tp_next_offset = TOTAL_PKT_LEN_INCL_ALIGN(len);
926 	pkc->prev = curr;
927 	pkc->nxt_offset += TOTAL_PKT_LEN_INCL_ALIGN(len);
928 	BLOCK_LEN(pbd) += TOTAL_PKT_LEN_INCL_ALIGN(len);
929 	BLOCK_NUM_PKTS(pbd) += 1;
930 	atomic_inc(&pkc->blk_fill_in_prog);
931 	prb_run_all_ft_ops(pkc, ppd);
932 }
933 
934 /* 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)935 static void *__packet_lookup_frame_in_block(struct packet_sock *po,
936 					    struct sk_buff *skb,
937 						int status,
938 					    unsigned int len
939 					    )
940 {
941 	struct tpacket_kbdq_core *pkc;
942 	struct tpacket_block_desc *pbd;
943 	char *curr, *end;
944 
945 	pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
946 	pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
947 
948 	/* Queue is frozen when user space is lagging behind */
949 	if (prb_queue_frozen(pkc)) {
950 		/*
951 		 * Check if that last block which caused the queue to freeze,
952 		 * is still in_use by user-space.
953 		 */
954 		if (prb_curr_blk_in_use(pkc, pbd)) {
955 			/* Can't record this packet */
956 			return NULL;
957 		} else {
958 			/*
959 			 * Ok, the block was released by user-space.
960 			 * Now let's open that block.
961 			 * opening a block also thaws the queue.
962 			 * Thawing is a side effect.
963 			 */
964 			prb_open_block(pkc, pbd);
965 		}
966 	}
967 
968 	smp_mb();
969 	curr = pkc->nxt_offset;
970 	pkc->skb = skb;
971 	end = (char *)pbd + pkc->kblk_size;
972 
973 	/* first try the current block */
974 	if (curr+TOTAL_PKT_LEN_INCL_ALIGN(len) < end) {
975 		prb_fill_curr_block(curr, pkc, pbd, len);
976 		return (void *)curr;
977 	}
978 
979 	/* Ok, close the current block */
980 	prb_retire_current_block(pkc, po, 0);
981 
982 	/* Now, try to dispatch the next block */
983 	curr = (char *)prb_dispatch_next_block(pkc, po);
984 	if (curr) {
985 		pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
986 		prb_fill_curr_block(curr, pkc, pbd, len);
987 		return (void *)curr;
988 	}
989 
990 	/*
991 	 * No free blocks are available.user_space hasn't caught up yet.
992 	 * Queue was just frozen and now this packet will get dropped.
993 	 */
994 	return NULL;
995 }
996 
packet_current_rx_frame(struct packet_sock * po,struct sk_buff * skb,int status,unsigned int len)997 static void *packet_current_rx_frame(struct packet_sock *po,
998 					    struct sk_buff *skb,
999 					    int status, unsigned int len)
1000 {
1001 	char *curr = NULL;
1002 	switch (po->tp_version) {
1003 	case TPACKET_V1:
1004 	case TPACKET_V2:
1005 		curr = packet_lookup_frame(po, &po->rx_ring,
1006 					po->rx_ring.head, status);
1007 		return curr;
1008 	case TPACKET_V3:
1009 		return __packet_lookup_frame_in_block(po, skb, status, len);
1010 	default:
1011 		WARN(1, "TPACKET version not supported\n");
1012 		BUG();
1013 		return NULL;
1014 	}
1015 }
1016 
prb_lookup_block(struct packet_sock * po,struct packet_ring_buffer * rb,unsigned int idx,int status)1017 static void *prb_lookup_block(struct packet_sock *po,
1018 				     struct packet_ring_buffer *rb,
1019 				     unsigned int idx,
1020 				     int status)
1021 {
1022 	struct tpacket_kbdq_core *pkc  = GET_PBDQC_FROM_RB(rb);
1023 	struct tpacket_block_desc *pbd = GET_PBLOCK_DESC(pkc, idx);
1024 
1025 	if (status != BLOCK_STATUS(pbd))
1026 		return NULL;
1027 	return pbd;
1028 }
1029 
prb_previous_blk_num(struct packet_ring_buffer * rb)1030 static int prb_previous_blk_num(struct packet_ring_buffer *rb)
1031 {
1032 	unsigned int prev;
1033 	if (rb->prb_bdqc.kactive_blk_num)
1034 		prev = rb->prb_bdqc.kactive_blk_num-1;
1035 	else
1036 		prev = rb->prb_bdqc.knum_blocks-1;
1037 	return prev;
1038 }
1039 
1040 /* Assumes caller has held the rx_queue.lock */
__prb_previous_block(struct packet_sock * po,struct packet_ring_buffer * rb,int status)1041 static void *__prb_previous_block(struct packet_sock *po,
1042 					 struct packet_ring_buffer *rb,
1043 					 int status)
1044 {
1045 	unsigned int previous = prb_previous_blk_num(rb);
1046 	return prb_lookup_block(po, rb, previous, status);
1047 }
1048 
packet_previous_rx_frame(struct packet_sock * po,struct packet_ring_buffer * rb,int status)1049 static void *packet_previous_rx_frame(struct packet_sock *po,
1050 					     struct packet_ring_buffer *rb,
1051 					     int status)
1052 {
1053 	if (po->tp_version <= TPACKET_V2)
1054 		return packet_previous_frame(po, rb, status);
1055 
1056 	return __prb_previous_block(po, rb, status);
1057 }
1058 
packet_increment_rx_head(struct packet_sock * po,struct packet_ring_buffer * rb)1059 static void packet_increment_rx_head(struct packet_sock *po,
1060 					    struct packet_ring_buffer *rb)
1061 {
1062 	switch (po->tp_version) {
1063 	case TPACKET_V1:
1064 	case TPACKET_V2:
1065 		return packet_increment_head(rb);
1066 	case TPACKET_V3:
1067 	default:
1068 		WARN(1, "TPACKET version not supported.\n");
1069 		BUG();
1070 		return;
1071 	}
1072 }
1073 
packet_previous_frame(struct packet_sock * po,struct packet_ring_buffer * rb,int status)1074 static void *packet_previous_frame(struct packet_sock *po,
1075 		struct packet_ring_buffer *rb,
1076 		int status)
1077 {
1078 	unsigned int previous = rb->head ? rb->head - 1 : rb->frame_max;
1079 	return packet_lookup_frame(po, rb, previous, status);
1080 }
1081 
packet_increment_head(struct packet_ring_buffer * buff)1082 static void packet_increment_head(struct packet_ring_buffer *buff)
1083 {
1084 	buff->head = buff->head != buff->frame_max ? buff->head+1 : 0;
1085 }
1086 
packet_rcv_has_room(struct packet_sock * po,struct sk_buff * skb)1087 static bool packet_rcv_has_room(struct packet_sock *po, struct sk_buff *skb)
1088 {
1089 	struct sock *sk = &po->sk;
1090 	bool has_room;
1091 
1092 	if (po->prot_hook.func != tpacket_rcv)
1093 		return (atomic_read(&sk->sk_rmem_alloc) + skb->truesize)
1094 			<= sk->sk_rcvbuf;
1095 
1096 	spin_lock(&sk->sk_receive_queue.lock);
1097 	if (po->tp_version == TPACKET_V3)
1098 		has_room = prb_lookup_block(po, &po->rx_ring,
1099 					    po->rx_ring.prb_bdqc.kactive_blk_num,
1100 					    TP_STATUS_KERNEL);
1101 	else
1102 		has_room = packet_lookup_frame(po, &po->rx_ring,
1103 					       po->rx_ring.head,
1104 					       TP_STATUS_KERNEL);
1105 	spin_unlock(&sk->sk_receive_queue.lock);
1106 
1107 	return has_room;
1108 }
1109 
packet_sock_destruct(struct sock * sk)1110 static void packet_sock_destruct(struct sock *sk)
1111 {
1112 	skb_queue_purge(&sk->sk_error_queue);
1113 
1114 	WARN_ON(atomic_read(&sk->sk_rmem_alloc));
1115 	WARN_ON(atomic_read(&sk->sk_wmem_alloc));
1116 
1117 	if (!sock_flag(sk, SOCK_DEAD)) {
1118 		pr_err("Attempt to release alive packet socket: %p\n", sk);
1119 		return;
1120 	}
1121 
1122 	sk_refcnt_debug_dec(sk);
1123 }
1124 
fanout_rr_next(struct packet_fanout * f,unsigned int num)1125 static int fanout_rr_next(struct packet_fanout *f, unsigned int num)
1126 {
1127 	int x = atomic_read(&f->rr_cur) + 1;
1128 
1129 	if (x >= num)
1130 		x = 0;
1131 
1132 	return x;
1133 }
1134 
fanout_demux_hash(struct packet_fanout * f,struct sk_buff * skb,unsigned int num)1135 static unsigned int fanout_demux_hash(struct packet_fanout *f,
1136 				      struct sk_buff *skb,
1137 				      unsigned int num)
1138 {
1139 	return (((u64)skb->rxhash) * num) >> 32;
1140 }
1141 
fanout_demux_lb(struct packet_fanout * f,struct sk_buff * skb,unsigned int num)1142 static unsigned int fanout_demux_lb(struct packet_fanout *f,
1143 				    struct sk_buff *skb,
1144 				    unsigned int num)
1145 {
1146 	int cur, old;
1147 
1148 	cur = atomic_read(&f->rr_cur);
1149 	while ((old = atomic_cmpxchg(&f->rr_cur, cur,
1150 				     fanout_rr_next(f, num))) != cur)
1151 		cur = old;
1152 	return cur;
1153 }
1154 
fanout_demux_cpu(struct packet_fanout * f,struct sk_buff * skb,unsigned int num)1155 static unsigned int fanout_demux_cpu(struct packet_fanout *f,
1156 				     struct sk_buff *skb,
1157 				     unsigned int num)
1158 {
1159 	return smp_processor_id() % num;
1160 }
1161 
fanout_demux_rollover(struct packet_fanout * f,struct sk_buff * skb,unsigned int idx,unsigned int skip,unsigned int num)1162 static unsigned int fanout_demux_rollover(struct packet_fanout *f,
1163 					  struct sk_buff *skb,
1164 					  unsigned int idx, unsigned int skip,
1165 					  unsigned int num)
1166 {
1167 	unsigned int i, j;
1168 
1169 	i = j = min_t(int, f->next[idx], num - 1);
1170 	do {
1171 		if (i != skip && packet_rcv_has_room(pkt_sk(f->arr[i]), skb)) {
1172 			if (i != j)
1173 				f->next[idx] = i;
1174 			return i;
1175 		}
1176 		if (++i == num)
1177 			i = 0;
1178 	} while (i != j);
1179 
1180 	return idx;
1181 }
1182 
fanout_has_flag(struct packet_fanout * f,u16 flag)1183 static bool fanout_has_flag(struct packet_fanout *f, u16 flag)
1184 {
1185 	return f->flags & (flag >> 8);
1186 }
1187 
packet_rcv_fanout(struct sk_buff * skb,struct net_device * dev,struct packet_type * pt,struct net_device * orig_dev)1188 static int packet_rcv_fanout(struct sk_buff *skb, struct net_device *dev,
1189 			     struct packet_type *pt, struct net_device *orig_dev)
1190 {
1191 	struct packet_fanout *f = pt->af_packet_priv;
1192 	unsigned int num = f->num_members;
1193 	struct packet_sock *po;
1194 	unsigned int idx;
1195 
1196 	if (!net_eq(dev_net(dev), read_pnet(&f->net)) ||
1197 	    !num) {
1198 		kfree_skb(skb);
1199 		return 0;
1200 	}
1201 
1202 	switch (f->type) {
1203 	case PACKET_FANOUT_HASH:
1204 	default:
1205 		if (fanout_has_flag(f, PACKET_FANOUT_FLAG_DEFRAG)) {
1206 			skb = ip_check_defrag(skb, IP_DEFRAG_AF_PACKET);
1207 			if (!skb)
1208 				return 0;
1209 		}
1210 		skb_get_rxhash(skb);
1211 		idx = fanout_demux_hash(f, skb, num);
1212 		break;
1213 	case PACKET_FANOUT_LB:
1214 		idx = fanout_demux_lb(f, skb, num);
1215 		break;
1216 	case PACKET_FANOUT_CPU:
1217 		idx = fanout_demux_cpu(f, skb, num);
1218 		break;
1219 	case PACKET_FANOUT_ROLLOVER:
1220 		idx = fanout_demux_rollover(f, skb, 0, (unsigned int) -1, num);
1221 		break;
1222 	}
1223 
1224 	po = pkt_sk(f->arr[idx]);
1225 	if (fanout_has_flag(f, PACKET_FANOUT_FLAG_ROLLOVER) &&
1226 	    unlikely(!packet_rcv_has_room(po, skb))) {
1227 		idx = fanout_demux_rollover(f, skb, idx, idx, num);
1228 		po = pkt_sk(f->arr[idx]);
1229 	}
1230 
1231 	return po->prot_hook.func(skb, dev, &po->prot_hook, orig_dev);
1232 }
1233 
1234 DEFINE_MUTEX(fanout_mutex);
1235 EXPORT_SYMBOL_GPL(fanout_mutex);
1236 static LIST_HEAD(fanout_list);
1237 
__fanout_link(struct sock * sk,struct packet_sock * po)1238 static void __fanout_link(struct sock *sk, struct packet_sock *po)
1239 {
1240 	struct packet_fanout *f = po->fanout;
1241 
1242 	spin_lock(&f->lock);
1243 	f->arr[f->num_members] = sk;
1244 	smp_wmb();
1245 	f->num_members++;
1246 	spin_unlock(&f->lock);
1247 }
1248 
__fanout_unlink(struct sock * sk,struct packet_sock * po)1249 static void __fanout_unlink(struct sock *sk, struct packet_sock *po)
1250 {
1251 	struct packet_fanout *f = po->fanout;
1252 	int i;
1253 
1254 	spin_lock(&f->lock);
1255 	for (i = 0; i < f->num_members; i++) {
1256 		if (f->arr[i] == sk)
1257 			break;
1258 	}
1259 	BUG_ON(i >= f->num_members);
1260 	f->arr[i] = f->arr[f->num_members - 1];
1261 	f->num_members--;
1262 	spin_unlock(&f->lock);
1263 }
1264 
match_fanout_group(struct packet_type * ptype,struct sock * sk)1265 static bool match_fanout_group(struct packet_type *ptype, struct sock * sk)
1266 {
1267 	if (ptype->af_packet_priv == (void*)((struct packet_sock *)sk)->fanout)
1268 		return true;
1269 
1270 	return false;
1271 }
1272 
fanout_add(struct sock * sk,u16 id,u16 type_flags)1273 static int fanout_add(struct sock *sk, u16 id, u16 type_flags)
1274 {
1275 	struct packet_sock *po = pkt_sk(sk);
1276 	struct packet_fanout *f, *match;
1277 	u8 type = type_flags & 0xff;
1278 	u8 flags = type_flags >> 8;
1279 	int err;
1280 
1281 	switch (type) {
1282 	case PACKET_FANOUT_ROLLOVER:
1283 		if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)
1284 			return -EINVAL;
1285 	case PACKET_FANOUT_HASH:
1286 	case PACKET_FANOUT_LB:
1287 	case PACKET_FANOUT_CPU:
1288 		break;
1289 	default:
1290 		return -EINVAL;
1291 	}
1292 
1293 	mutex_lock(&fanout_mutex);
1294 
1295 	err = -EINVAL;
1296 	if (!po->running)
1297 		goto out;
1298 
1299 	err = -EALREADY;
1300 	if (po->fanout)
1301 		goto out;
1302 
1303 	match = NULL;
1304 	list_for_each_entry(f, &fanout_list, list) {
1305 		if (f->id == id &&
1306 		    read_pnet(&f->net) == sock_net(sk)) {
1307 			match = f;
1308 			break;
1309 		}
1310 	}
1311 	err = -EINVAL;
1312 	if (match && match->flags != flags)
1313 		goto out;
1314 	if (!match) {
1315 		err = -ENOMEM;
1316 		match = kzalloc(sizeof(*match), GFP_KERNEL);
1317 		if (!match)
1318 			goto out;
1319 		write_pnet(&match->net, sock_net(sk));
1320 		match->id = id;
1321 		match->type = type;
1322 		match->flags = flags;
1323 		atomic_set(&match->rr_cur, 0);
1324 		INIT_LIST_HEAD(&match->list);
1325 		spin_lock_init(&match->lock);
1326 		atomic_set(&match->sk_ref, 0);
1327 		match->prot_hook.type = po->prot_hook.type;
1328 		match->prot_hook.dev = po->prot_hook.dev;
1329 		match->prot_hook.func = packet_rcv_fanout;
1330 		match->prot_hook.af_packet_priv = match;
1331 		match->prot_hook.id_match = match_fanout_group;
1332 		dev_add_pack(&match->prot_hook);
1333 		list_add(&match->list, &fanout_list);
1334 	}
1335 	err = -EINVAL;
1336 	if (match->type == type &&
1337 	    match->prot_hook.type == po->prot_hook.type &&
1338 	    match->prot_hook.dev == po->prot_hook.dev) {
1339 		err = -ENOSPC;
1340 		if (atomic_read(&match->sk_ref) < PACKET_FANOUT_MAX) {
1341 			__dev_remove_pack(&po->prot_hook);
1342 			po->fanout = match;
1343 			atomic_inc(&match->sk_ref);
1344 			__fanout_link(sk, po);
1345 			err = 0;
1346 		}
1347 	}
1348 out:
1349 	mutex_unlock(&fanout_mutex);
1350 	return err;
1351 }
1352 
fanout_release(struct sock * sk)1353 static void fanout_release(struct sock *sk)
1354 {
1355 	struct packet_sock *po = pkt_sk(sk);
1356 	struct packet_fanout *f;
1357 
1358 	mutex_lock(&fanout_mutex);
1359 	f = po->fanout;
1360 	if (f) {
1361 		po->fanout = NULL;
1362 
1363 		if (atomic_dec_and_test(&f->sk_ref)) {
1364 			list_del(&f->list);
1365 			dev_remove_pack(&f->prot_hook);
1366 			kfree(f);
1367 		}
1368 	}
1369 	mutex_unlock(&fanout_mutex);
1370 }
1371 
1372 static const struct proto_ops packet_ops;
1373 
1374 static const struct proto_ops packet_ops_spkt;
1375 
packet_rcv_spkt(struct sk_buff * skb,struct net_device * dev,struct packet_type * pt,struct net_device * orig_dev)1376 static int packet_rcv_spkt(struct sk_buff *skb, struct net_device *dev,
1377 			   struct packet_type *pt, struct net_device *orig_dev)
1378 {
1379 	struct sock *sk;
1380 	struct sockaddr_pkt *spkt;
1381 
1382 	/*
1383 	 *	When we registered the protocol we saved the socket in the data
1384 	 *	field for just this event.
1385 	 */
1386 
1387 	sk = pt->af_packet_priv;
1388 
1389 	/*
1390 	 *	Yank back the headers [hope the device set this
1391 	 *	right or kerboom...]
1392 	 *
1393 	 *	Incoming packets have ll header pulled,
1394 	 *	push it back.
1395 	 *
1396 	 *	For outgoing ones skb->data == skb_mac_header(skb)
1397 	 *	so that this procedure is noop.
1398 	 */
1399 
1400 	if (skb->pkt_type == PACKET_LOOPBACK)
1401 		goto out;
1402 
1403 	if (!net_eq(dev_net(dev), sock_net(sk)))
1404 		goto out;
1405 
1406 	skb = skb_share_check(skb, GFP_ATOMIC);
1407 	if (skb == NULL)
1408 		goto oom;
1409 
1410 	/* drop any routing info */
1411 	skb_dst_drop(skb);
1412 
1413 	/* drop conntrack reference */
1414 	nf_reset(skb);
1415 
1416 	spkt = &PACKET_SKB_CB(skb)->sa.pkt;
1417 
1418 	skb_push(skb, skb->data - skb_mac_header(skb));
1419 
1420 	/*
1421 	 *	The SOCK_PACKET socket receives _all_ frames.
1422 	 */
1423 
1424 	spkt->spkt_family = dev->type;
1425 	strlcpy(spkt->spkt_device, dev->name, sizeof(spkt->spkt_device));
1426 	spkt->spkt_protocol = skb->protocol;
1427 
1428 	/*
1429 	 *	Charge the memory to the socket. This is done specifically
1430 	 *	to prevent sockets using all the memory up.
1431 	 */
1432 
1433 	if (sock_queue_rcv_skb(sk, skb) == 0)
1434 		return 0;
1435 
1436 out:
1437 	kfree_skb(skb);
1438 oom:
1439 	return 0;
1440 }
1441 
1442 
1443 /*
1444  *	Output a raw packet to a device layer. This bypasses all the other
1445  *	protocol layers and you must therefore supply it with a complete frame
1446  */
1447 
packet_sendmsg_spkt(struct kiocb * iocb,struct socket * sock,struct msghdr * msg,size_t len)1448 static int packet_sendmsg_spkt(struct kiocb *iocb, struct socket *sock,
1449 			       struct msghdr *msg, size_t len)
1450 {
1451 	struct sock *sk = sock->sk;
1452 	struct sockaddr_pkt *saddr = (struct sockaddr_pkt *)msg->msg_name;
1453 	struct sk_buff *skb = NULL;
1454 	struct net_device *dev;
1455 	__be16 proto = 0;
1456 	int err;
1457 	int extra_len = 0;
1458 
1459 	/*
1460 	 *	Get and verify the address.
1461 	 */
1462 
1463 	if (saddr) {
1464 		if (msg->msg_namelen < sizeof(struct sockaddr))
1465 			return -EINVAL;
1466 		if (msg->msg_namelen == sizeof(struct sockaddr_pkt))
1467 			proto = saddr->spkt_protocol;
1468 	} else
1469 		return -ENOTCONN;	/* SOCK_PACKET must be sent giving an address */
1470 
1471 	/*
1472 	 *	Find the device first to size check it
1473 	 */
1474 
1475 	saddr->spkt_device[sizeof(saddr->spkt_device) - 1] = 0;
1476 retry:
1477 	rcu_read_lock();
1478 	dev = dev_get_by_name_rcu(sock_net(sk), saddr->spkt_device);
1479 	err = -ENODEV;
1480 	if (dev == NULL)
1481 		goto out_unlock;
1482 
1483 	err = -ENETDOWN;
1484 	if (!(dev->flags & IFF_UP))
1485 		goto out_unlock;
1486 
1487 	/*
1488 	 * You may not queue a frame bigger than the mtu. This is the lowest level
1489 	 * raw protocol and you must do your own fragmentation at this level.
1490 	 */
1491 
1492 	if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
1493 		if (!netif_supports_nofcs(dev)) {
1494 			err = -EPROTONOSUPPORT;
1495 			goto out_unlock;
1496 		}
1497 		extra_len = 4; /* We're doing our own CRC */
1498 	}
1499 
1500 	err = -EMSGSIZE;
1501 	if (len > dev->mtu + dev->hard_header_len + VLAN_HLEN + extra_len)
1502 		goto out_unlock;
1503 
1504 	if (!skb) {
1505 		size_t reserved = LL_RESERVED_SPACE(dev);
1506 		int tlen = dev->needed_tailroom;
1507 		unsigned int hhlen = dev->header_ops ? dev->hard_header_len : 0;
1508 
1509 		rcu_read_unlock();
1510 		skb = sock_wmalloc(sk, len + reserved + tlen, 0, GFP_KERNEL);
1511 		if (skb == NULL)
1512 			return -ENOBUFS;
1513 		/* FIXME: Save some space for broken drivers that write a hard
1514 		 * header at transmission time by themselves. PPP is the notable
1515 		 * one here. This should really be fixed at the driver level.
1516 		 */
1517 		skb_reserve(skb, reserved);
1518 		skb_reset_network_header(skb);
1519 
1520 		/* Try to align data part correctly */
1521 		if (hhlen) {
1522 			skb->data -= hhlen;
1523 			skb->tail -= hhlen;
1524 			if (len < hhlen)
1525 				skb_reset_network_header(skb);
1526 		}
1527 		err = memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len);
1528 		if (err)
1529 			goto out_free;
1530 		goto retry;
1531 	}
1532 
1533 	if (len > (dev->mtu + dev->hard_header_len + extra_len)) {
1534 		/* Earlier code assumed this would be a VLAN pkt,
1535 		 * double-check this now that we have the actual
1536 		 * packet in hand.
1537 		 */
1538 		struct ethhdr *ehdr;
1539 		skb_reset_mac_header(skb);
1540 		ehdr = eth_hdr(skb);
1541 		if (ehdr->h_proto != htons(ETH_P_8021Q)) {
1542 			err = -EMSGSIZE;
1543 			goto out_unlock;
1544 		}
1545 	}
1546 
1547 	skb->protocol = proto;
1548 	skb->dev = dev;
1549 	skb->priority = sk->sk_priority;
1550 	skb->mark = sk->sk_mark;
1551 
1552 	sock_tx_timestamp(sk, &skb_shinfo(skb)->tx_flags);
1553 
1554 	if (unlikely(extra_len == 4))
1555 		skb->no_fcs = 1;
1556 
1557 	skb_probe_transport_header(skb, 0);
1558 
1559 	dev_queue_xmit(skb);
1560 	rcu_read_unlock();
1561 	return len;
1562 
1563 out_unlock:
1564 	rcu_read_unlock();
1565 out_free:
1566 	kfree_skb(skb);
1567 	return err;
1568 }
1569 
run_filter(const struct sk_buff * skb,const struct sock * sk,unsigned int res)1570 static unsigned int run_filter(const struct sk_buff *skb,
1571 				      const struct sock *sk,
1572 				      unsigned int res)
1573 {
1574 	struct sk_filter *filter;
1575 
1576 	rcu_read_lock();
1577 	filter = rcu_dereference(sk->sk_filter);
1578 	if (filter != NULL)
1579 		res = SK_RUN_FILTER(filter, skb);
1580 	rcu_read_unlock();
1581 
1582 	return res;
1583 }
1584 
1585 /*
1586  * This function makes lazy skb cloning in hope that most of packets
1587  * are discarded by BPF.
1588  *
1589  * Note tricky part: we DO mangle shared skb! skb->data, skb->len
1590  * and skb->cb are mangled. It works because (and until) packets
1591  * falling here are owned by current CPU. Output packets are cloned
1592  * by dev_queue_xmit_nit(), input packets are processed by net_bh
1593  * sequencially, so that if we return skb to original state on exit,
1594  * we will not harm anyone.
1595  */
1596 
packet_rcv(struct sk_buff * skb,struct net_device * dev,struct packet_type * pt,struct net_device * orig_dev)1597 static int packet_rcv(struct sk_buff *skb, struct net_device *dev,
1598 		      struct packet_type *pt, struct net_device *orig_dev)
1599 {
1600 	struct sock *sk;
1601 	struct sockaddr_ll *sll;
1602 	struct packet_sock *po;
1603 	u8 *skb_head = skb->data;
1604 	int skb_len = skb->len;
1605 	unsigned int snaplen, res;
1606 
1607 	if (skb->pkt_type == PACKET_LOOPBACK)
1608 		goto drop;
1609 
1610 	sk = pt->af_packet_priv;
1611 	po = pkt_sk(sk);
1612 
1613 	if (!net_eq(dev_net(dev), sock_net(sk)))
1614 		goto drop;
1615 
1616 	skb->dev = dev;
1617 
1618 	if (dev->header_ops) {
1619 		/* The device has an explicit notion of ll header,
1620 		 * exported to higher levels.
1621 		 *
1622 		 * Otherwise, the device hides details of its frame
1623 		 * structure, so that corresponding packet head is
1624 		 * never delivered to user.
1625 		 */
1626 		if (sk->sk_type != SOCK_DGRAM)
1627 			skb_push(skb, skb->data - skb_mac_header(skb));
1628 		else if (skb->pkt_type == PACKET_OUTGOING) {
1629 			/* Special case: outgoing packets have ll header at head */
1630 			skb_pull(skb, skb_network_offset(skb));
1631 		}
1632 	}
1633 
1634 	snaplen = skb->len;
1635 
1636 	res = run_filter(skb, sk, snaplen);
1637 	if (!res)
1638 		goto drop_n_restore;
1639 	if (snaplen > res)
1640 		snaplen = res;
1641 
1642 	if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
1643 		goto drop_n_acct;
1644 
1645 	if (skb_shared(skb)) {
1646 		struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
1647 		if (nskb == NULL)
1648 			goto drop_n_acct;
1649 
1650 		if (skb_head != skb->data) {
1651 			skb->data = skb_head;
1652 			skb->len = skb_len;
1653 		}
1654 		consume_skb(skb);
1655 		skb = nskb;
1656 	}
1657 
1658 	BUILD_BUG_ON(sizeof(*PACKET_SKB_CB(skb)) + MAX_ADDR_LEN - 8 >
1659 		     sizeof(skb->cb));
1660 
1661 	sll = &PACKET_SKB_CB(skb)->sa.ll;
1662 	sll->sll_family = AF_PACKET;
1663 	sll->sll_hatype = dev->type;
1664 	sll->sll_protocol = skb->protocol;
1665 	sll->sll_pkttype = skb->pkt_type;
1666 	if (unlikely(po->origdev))
1667 		sll->sll_ifindex = orig_dev->ifindex;
1668 	else
1669 		sll->sll_ifindex = dev->ifindex;
1670 
1671 	sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
1672 
1673 	PACKET_SKB_CB(skb)->origlen = skb->len;
1674 
1675 	if (pskb_trim(skb, snaplen))
1676 		goto drop_n_acct;
1677 
1678 	skb_set_owner_r(skb, sk);
1679 	skb->dev = NULL;
1680 	skb_dst_drop(skb);
1681 
1682 	/* drop conntrack reference */
1683 	nf_reset(skb);
1684 
1685 	spin_lock(&sk->sk_receive_queue.lock);
1686 	po->stats.stats1.tp_packets++;
1687 	skb->dropcount = atomic_read(&sk->sk_drops);
1688 	__skb_queue_tail(&sk->sk_receive_queue, skb);
1689 	spin_unlock(&sk->sk_receive_queue.lock);
1690 	sk->sk_data_ready(sk, skb->len);
1691 	return 0;
1692 
1693 drop_n_acct:
1694 	spin_lock(&sk->sk_receive_queue.lock);
1695 	po->stats.stats1.tp_drops++;
1696 	atomic_inc(&sk->sk_drops);
1697 	spin_unlock(&sk->sk_receive_queue.lock);
1698 
1699 drop_n_restore:
1700 	if (skb_head != skb->data && skb_shared(skb)) {
1701 		skb->data = skb_head;
1702 		skb->len = skb_len;
1703 	}
1704 drop:
1705 	consume_skb(skb);
1706 	return 0;
1707 }
1708 
tpacket_rcv(struct sk_buff * skb,struct net_device * dev,struct packet_type * pt,struct net_device * orig_dev)1709 static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
1710 		       struct packet_type *pt, struct net_device *orig_dev)
1711 {
1712 	struct sock *sk;
1713 	struct packet_sock *po;
1714 	struct sockaddr_ll *sll;
1715 	union tpacket_uhdr h;
1716 	u8 *skb_head = skb->data;
1717 	int skb_len = skb->len;
1718 	unsigned int snaplen, res;
1719 	unsigned long status = TP_STATUS_USER;
1720 	unsigned short macoff, netoff, hdrlen;
1721 	struct sk_buff *copy_skb = NULL;
1722 	struct timespec ts;
1723 	__u32 ts_status;
1724 
1725 	if (skb->pkt_type == PACKET_LOOPBACK)
1726 		goto drop;
1727 
1728 	sk = pt->af_packet_priv;
1729 	po = pkt_sk(sk);
1730 
1731 	if (!net_eq(dev_net(dev), sock_net(sk)))
1732 		goto drop;
1733 
1734 	if (dev->header_ops) {
1735 		if (sk->sk_type != SOCK_DGRAM)
1736 			skb_push(skb, skb->data - skb_mac_header(skb));
1737 		else if (skb->pkt_type == PACKET_OUTGOING) {
1738 			/* Special case: outgoing packets have ll header at head */
1739 			skb_pull(skb, skb_network_offset(skb));
1740 		}
1741 	}
1742 
1743 	if (skb->ip_summed == CHECKSUM_PARTIAL)
1744 		status |= TP_STATUS_CSUMNOTREADY;
1745 
1746 	snaplen = skb->len;
1747 
1748 	res = run_filter(skb, sk, snaplen);
1749 	if (!res)
1750 		goto drop_n_restore;
1751 	if (snaplen > res)
1752 		snaplen = res;
1753 
1754 	if (sk->sk_type == SOCK_DGRAM) {
1755 		macoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +
1756 				  po->tp_reserve;
1757 	} else {
1758 		unsigned int maclen = skb_network_offset(skb);
1759 		netoff = TPACKET_ALIGN(po->tp_hdrlen +
1760 				       (maclen < 16 ? 16 : maclen)) +
1761 			po->tp_reserve;
1762 		macoff = netoff - maclen;
1763 	}
1764 	if (po->tp_version <= TPACKET_V2) {
1765 		if (macoff + snaplen > po->rx_ring.frame_size) {
1766 			if (po->copy_thresh &&
1767 			    atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) {
1768 				if (skb_shared(skb)) {
1769 					copy_skb = skb_clone(skb, GFP_ATOMIC);
1770 				} else {
1771 					copy_skb = skb_get(skb);
1772 					skb_head = skb->data;
1773 				}
1774 				if (copy_skb)
1775 					skb_set_owner_r(copy_skb, sk);
1776 			}
1777 			snaplen = po->rx_ring.frame_size - macoff;
1778 			if ((int)snaplen < 0)
1779 				snaplen = 0;
1780 		}
1781 	} else if (unlikely(macoff + snaplen >
1782 			    GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len)) {
1783 		u32 nval;
1784 
1785 		nval = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len - macoff;
1786 		pr_err_once("tpacket_rcv: packet too big, clamped from %u to %u. macoff=%u\n",
1787 			    snaplen, nval, macoff);
1788 		snaplen = nval;
1789 		if (unlikely((int)snaplen < 0)) {
1790 			snaplen = 0;
1791 			macoff = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len;
1792 		}
1793 	}
1794 	spin_lock(&sk->sk_receive_queue.lock);
1795 	h.raw = packet_current_rx_frame(po, skb,
1796 					TP_STATUS_KERNEL, (macoff+snaplen));
1797 	if (!h.raw)
1798 		goto ring_is_full;
1799 	if (po->tp_version <= TPACKET_V2) {
1800 		packet_increment_rx_head(po, &po->rx_ring);
1801 	/*
1802 	 * LOSING will be reported till you read the stats,
1803 	 * because it's COR - Clear On Read.
1804 	 * Anyways, moving it for V1/V2 only as V3 doesn't need this
1805 	 * at packet level.
1806 	 */
1807 		if (po->stats.stats1.tp_drops)
1808 			status |= TP_STATUS_LOSING;
1809 	}
1810 	po->stats.stats1.tp_packets++;
1811 	if (copy_skb) {
1812 		status |= TP_STATUS_COPY;
1813 		__skb_queue_tail(&sk->sk_receive_queue, copy_skb);
1814 	}
1815 	spin_unlock(&sk->sk_receive_queue.lock);
1816 
1817 	skb_copy_bits(skb, 0, h.raw + macoff, snaplen);
1818 
1819 	if (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp)))
1820 		getnstimeofday(&ts);
1821 
1822 	status |= ts_status;
1823 
1824 	switch (po->tp_version) {
1825 	case TPACKET_V1:
1826 		h.h1->tp_len = skb->len;
1827 		h.h1->tp_snaplen = snaplen;
1828 		h.h1->tp_mac = macoff;
1829 		h.h1->tp_net = netoff;
1830 		h.h1->tp_sec = ts.tv_sec;
1831 		h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
1832 		hdrlen = sizeof(*h.h1);
1833 		break;
1834 	case TPACKET_V2:
1835 		h.h2->tp_len = skb->len;
1836 		h.h2->tp_snaplen = snaplen;
1837 		h.h2->tp_mac = macoff;
1838 		h.h2->tp_net = netoff;
1839 		h.h2->tp_sec = ts.tv_sec;
1840 		h.h2->tp_nsec = ts.tv_nsec;
1841 		if (vlan_tx_tag_present(skb)) {
1842 			h.h2->tp_vlan_tci = vlan_tx_tag_get(skb);
1843 			status |= TP_STATUS_VLAN_VALID;
1844 		} else {
1845 			h.h2->tp_vlan_tci = 0;
1846 		}
1847 		h.h2->tp_padding = 0;
1848 		hdrlen = sizeof(*h.h2);
1849 		break;
1850 	case TPACKET_V3:
1851 		/* tp_nxt_offset,vlan are already populated above.
1852 		 * So DONT clear those fields here
1853 		 */
1854 		h.h3->tp_status |= status;
1855 		h.h3->tp_len = skb->len;
1856 		h.h3->tp_snaplen = snaplen;
1857 		h.h3->tp_mac = macoff;
1858 		h.h3->tp_net = netoff;
1859 		h.h3->tp_sec  = ts.tv_sec;
1860 		h.h3->tp_nsec = ts.tv_nsec;
1861 		hdrlen = sizeof(*h.h3);
1862 		break;
1863 	default:
1864 		BUG();
1865 	}
1866 
1867 	sll = h.raw + TPACKET_ALIGN(hdrlen);
1868 	sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
1869 	sll->sll_family = AF_PACKET;
1870 	sll->sll_hatype = dev->type;
1871 	sll->sll_protocol = skb->protocol;
1872 	sll->sll_pkttype = skb->pkt_type;
1873 	if (unlikely(po->origdev))
1874 		sll->sll_ifindex = orig_dev->ifindex;
1875 	else
1876 		sll->sll_ifindex = dev->ifindex;
1877 
1878 	smp_mb();
1879 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
1880 	{
1881 		u8 *start, *end;
1882 
1883 		if (po->tp_version <= TPACKET_V2) {
1884 			end = (u8 *)PAGE_ALIGN((unsigned long)h.raw
1885 				+ macoff + snaplen);
1886 			for (start = h.raw; start < end; start += PAGE_SIZE)
1887 				flush_dcache_page(pgv_to_page(start));
1888 		}
1889 		smp_wmb();
1890 	}
1891 #endif
1892 	if (po->tp_version <= TPACKET_V2)
1893 		__packet_set_status(po, h.raw, status);
1894 	else
1895 		prb_clear_blk_fill_status(&po->rx_ring);
1896 
1897 	sk->sk_data_ready(sk, 0);
1898 
1899 drop_n_restore:
1900 	if (skb_head != skb->data && skb_shared(skb)) {
1901 		skb->data = skb_head;
1902 		skb->len = skb_len;
1903 	}
1904 drop:
1905 	kfree_skb(skb);
1906 	return 0;
1907 
1908 ring_is_full:
1909 	po->stats.stats1.tp_drops++;
1910 	spin_unlock(&sk->sk_receive_queue.lock);
1911 
1912 	sk->sk_data_ready(sk, 0);
1913 	kfree_skb(copy_skb);
1914 	goto drop_n_restore;
1915 }
1916 
tpacket_destruct_skb(struct sk_buff * skb)1917 static void tpacket_destruct_skb(struct sk_buff *skb)
1918 {
1919 	struct packet_sock *po = pkt_sk(skb->sk);
1920 	void *ph;
1921 
1922 	if (likely(po->tx_ring.pg_vec)) {
1923 		__u32 ts;
1924 
1925 		ph = skb_shinfo(skb)->destructor_arg;
1926 		BUG_ON(atomic_read(&po->tx_ring.pending) == 0);
1927 		atomic_dec(&po->tx_ring.pending);
1928 
1929 		ts = __packet_set_timestamp(po, ph, skb);
1930 		__packet_set_status(po, ph, TP_STATUS_AVAILABLE | ts);
1931 	}
1932 
1933 	sock_wfree(skb);
1934 }
1935 
tpacket_fill_skb(struct packet_sock * po,struct sk_buff * skb,void * frame,struct net_device * dev,int size_max,__be16 proto,unsigned char * addr,int hlen)1936 static int tpacket_fill_skb(struct packet_sock *po, struct sk_buff *skb,
1937 		void *frame, struct net_device *dev, int size_max,
1938 		__be16 proto, unsigned char *addr, int hlen)
1939 {
1940 	union tpacket_uhdr ph;
1941 	int to_write, offset, len, tp_len, nr_frags, len_max;
1942 	struct socket *sock = po->sk.sk_socket;
1943 	struct page *page;
1944 	void *data;
1945 	int err;
1946 
1947 	ph.raw = frame;
1948 
1949 	skb->protocol = proto;
1950 	skb->dev = dev;
1951 	skb->priority = po->sk.sk_priority;
1952 	skb->mark = po->sk.sk_mark;
1953 	sock_tx_timestamp(&po->sk, &skb_shinfo(skb)->tx_flags);
1954 	skb_shinfo(skb)->destructor_arg = ph.raw;
1955 
1956 	switch (po->tp_version) {
1957 	case TPACKET_V2:
1958 		tp_len = ph.h2->tp_len;
1959 		break;
1960 	default:
1961 		tp_len = ph.h1->tp_len;
1962 		break;
1963 	}
1964 	if (unlikely(tp_len > size_max)) {
1965 		pr_err("packet size is too long (%d > %d)\n", tp_len, size_max);
1966 		return -EMSGSIZE;
1967 	}
1968 
1969 	skb_reserve(skb, hlen);
1970 	skb_reset_network_header(skb);
1971 	skb_probe_transport_header(skb, 0);
1972 
1973 	if (po->tp_tx_has_off) {
1974 		int off_min, off_max, off;
1975 		off_min = po->tp_hdrlen - sizeof(struct sockaddr_ll);
1976 		off_max = po->tx_ring.frame_size - tp_len;
1977 		if (sock->type == SOCK_DGRAM) {
1978 			switch (po->tp_version) {
1979 			case TPACKET_V2:
1980 				off = ph.h2->tp_net;
1981 				break;
1982 			default:
1983 				off = ph.h1->tp_net;
1984 				break;
1985 			}
1986 		} else {
1987 			switch (po->tp_version) {
1988 			case TPACKET_V2:
1989 				off = ph.h2->tp_mac;
1990 				break;
1991 			default:
1992 				off = ph.h1->tp_mac;
1993 				break;
1994 			}
1995 		}
1996 		if (unlikely((off < off_min) || (off_max < off)))
1997 			return -EINVAL;
1998 		data = ph.raw + off;
1999 	} else {
2000 		data = ph.raw + po->tp_hdrlen - sizeof(struct sockaddr_ll);
2001 	}
2002 	to_write = tp_len;
2003 
2004 	if (sock->type == SOCK_DGRAM) {
2005 		err = dev_hard_header(skb, dev, ntohs(proto), addr,
2006 				NULL, tp_len);
2007 		if (unlikely(err < 0))
2008 			return -EINVAL;
2009 	} else if (dev->hard_header_len) {
2010 		/* net device doesn't like empty head */
2011 		if (unlikely(tp_len <= dev->hard_header_len)) {
2012 			pr_err("packet size is too short (%d < %d)\n",
2013 			       tp_len, dev->hard_header_len);
2014 			return -EINVAL;
2015 		}
2016 
2017 		skb_push(skb, dev->hard_header_len);
2018 		err = skb_store_bits(skb, 0, data,
2019 				dev->hard_header_len);
2020 		if (unlikely(err))
2021 			return err;
2022 
2023 		data += dev->hard_header_len;
2024 		to_write -= dev->hard_header_len;
2025 	}
2026 
2027 	offset = offset_in_page(data);
2028 	len_max = PAGE_SIZE - offset;
2029 	len = ((to_write > len_max) ? len_max : to_write);
2030 
2031 	skb->data_len = to_write;
2032 	skb->len += to_write;
2033 	skb->truesize += to_write;
2034 	atomic_add(to_write, &po->sk.sk_wmem_alloc);
2035 
2036 	while (likely(to_write)) {
2037 		nr_frags = skb_shinfo(skb)->nr_frags;
2038 
2039 		if (unlikely(nr_frags >= MAX_SKB_FRAGS)) {
2040 			pr_err("Packet exceed the number of skb frags(%lu)\n",
2041 			       MAX_SKB_FRAGS);
2042 			return -EFAULT;
2043 		}
2044 
2045 		page = pgv_to_page(data);
2046 		data += len;
2047 		flush_dcache_page(page);
2048 		get_page(page);
2049 		skb_fill_page_desc(skb, nr_frags, page, offset, len);
2050 		to_write -= len;
2051 		offset = 0;
2052 		len_max = PAGE_SIZE;
2053 		len = ((to_write > len_max) ? len_max : to_write);
2054 	}
2055 
2056 	return tp_len;
2057 }
2058 
tpacket_snd(struct packet_sock * po,struct msghdr * msg)2059 static int tpacket_snd(struct packet_sock *po, struct msghdr *msg)
2060 {
2061 	struct sk_buff *skb;
2062 	struct net_device *dev;
2063 	__be16 proto;
2064 	bool need_rls_dev = false;
2065 	int err, reserve = 0;
2066 	void *ph;
2067 	struct sockaddr_ll *saddr = (struct sockaddr_ll *)msg->msg_name;
2068 	int tp_len, size_max;
2069 	unsigned char *addr;
2070 	int len_sum = 0;
2071 	int status = TP_STATUS_AVAILABLE;
2072 	int hlen, tlen;
2073 
2074 	mutex_lock(&po->pg_vec_lock);
2075 
2076 	if (saddr == NULL) {
2077 		dev = po->prot_hook.dev;
2078 		proto	= po->num;
2079 		addr	= NULL;
2080 	} else {
2081 		err = -EINVAL;
2082 		if (msg->msg_namelen < sizeof(struct sockaddr_ll))
2083 			goto out;
2084 		if (msg->msg_namelen < (saddr->sll_halen
2085 					+ offsetof(struct sockaddr_ll,
2086 						sll_addr)))
2087 			goto out;
2088 		proto	= saddr->sll_protocol;
2089 		addr	= saddr->sll_addr;
2090 		dev = dev_get_by_index(sock_net(&po->sk), saddr->sll_ifindex);
2091 		need_rls_dev = true;
2092 	}
2093 
2094 	err = -ENXIO;
2095 	if (unlikely(dev == NULL))
2096 		goto out;
2097 
2098 	reserve = dev->hard_header_len;
2099 
2100 	err = -ENETDOWN;
2101 	if (unlikely(!(dev->flags & IFF_UP)))
2102 		goto out_put;
2103 
2104 	size_max = po->tx_ring.frame_size
2105 		- (po->tp_hdrlen - sizeof(struct sockaddr_ll));
2106 
2107 	if (size_max > dev->mtu + reserve)
2108 		size_max = dev->mtu + reserve;
2109 
2110 	do {
2111 		ph = packet_current_frame(po, &po->tx_ring,
2112 				TP_STATUS_SEND_REQUEST);
2113 
2114 		if (unlikely(ph == NULL)) {
2115 			schedule();
2116 			continue;
2117 		}
2118 
2119 		status = TP_STATUS_SEND_REQUEST;
2120 		hlen = LL_RESERVED_SPACE(dev);
2121 		tlen = dev->needed_tailroom;
2122 		skb = sock_alloc_send_skb(&po->sk,
2123 				hlen + tlen + sizeof(struct sockaddr_ll),
2124 				0, &err);
2125 
2126 		if (unlikely(skb == NULL))
2127 			goto out_status;
2128 
2129 		tp_len = tpacket_fill_skb(po, skb, ph, dev, size_max, proto,
2130 				addr, hlen);
2131 
2132 		if (unlikely(tp_len < 0)) {
2133 			if (po->tp_loss) {
2134 				__packet_set_status(po, ph,
2135 						TP_STATUS_AVAILABLE);
2136 				packet_increment_head(&po->tx_ring);
2137 				kfree_skb(skb);
2138 				continue;
2139 			} else {
2140 				status = TP_STATUS_WRONG_FORMAT;
2141 				err = tp_len;
2142 				goto out_status;
2143 			}
2144 		}
2145 
2146 		skb->destructor = tpacket_destruct_skb;
2147 		__packet_set_status(po, ph, TP_STATUS_SENDING);
2148 		atomic_inc(&po->tx_ring.pending);
2149 
2150 		status = TP_STATUS_SEND_REQUEST;
2151 		err = dev_queue_xmit(skb);
2152 		if (unlikely(err > 0)) {
2153 			err = net_xmit_errno(err);
2154 			if (err && __packet_get_status(po, ph) ==
2155 				   TP_STATUS_AVAILABLE) {
2156 				/* skb was destructed already */
2157 				skb = NULL;
2158 				goto out_status;
2159 			}
2160 			/*
2161 			 * skb was dropped but not destructed yet;
2162 			 * let's treat it like congestion or err < 0
2163 			 */
2164 			err = 0;
2165 		}
2166 		packet_increment_head(&po->tx_ring);
2167 		len_sum += tp_len;
2168 	} while (likely((ph != NULL) ||
2169 			((!(msg->msg_flags & MSG_DONTWAIT)) &&
2170 			 (atomic_read(&po->tx_ring.pending))))
2171 		);
2172 
2173 	err = len_sum;
2174 	goto out_put;
2175 
2176 out_status:
2177 	__packet_set_status(po, ph, status);
2178 	kfree_skb(skb);
2179 out_put:
2180 	if (need_rls_dev)
2181 		dev_put(dev);
2182 out:
2183 	mutex_unlock(&po->pg_vec_lock);
2184 	return err;
2185 }
2186 
packet_alloc_skb(struct sock * sk,size_t prepad,size_t reserve,size_t len,size_t linear,int noblock,int * err)2187 static struct sk_buff *packet_alloc_skb(struct sock *sk, size_t prepad,
2188 				        size_t reserve, size_t len,
2189 				        size_t linear, int noblock,
2190 				        int *err)
2191 {
2192 	struct sk_buff *skb;
2193 
2194 	/* Under a page?  Don't bother with paged skb. */
2195 	if (prepad + len < PAGE_SIZE || !linear)
2196 		linear = len;
2197 
2198 	skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
2199 				   err);
2200 	if (!skb)
2201 		return NULL;
2202 
2203 	skb_reserve(skb, reserve);
2204 	skb_put(skb, linear);
2205 	skb->data_len = len - linear;
2206 	skb->len += len - linear;
2207 
2208 	return skb;
2209 }
2210 
packet_snd(struct socket * sock,struct msghdr * msg,size_t len)2211 static int packet_snd(struct socket *sock,
2212 			  struct msghdr *msg, size_t len)
2213 {
2214 	struct sock *sk = sock->sk;
2215 	struct sockaddr_ll *saddr = (struct sockaddr_ll *)msg->msg_name;
2216 	struct sk_buff *skb;
2217 	struct net_device *dev;
2218 	__be16 proto;
2219 	bool need_rls_dev = false;
2220 	unsigned char *addr;
2221 	int err, reserve = 0;
2222 	struct virtio_net_hdr vnet_hdr = { 0 };
2223 	int offset = 0;
2224 	int vnet_hdr_len;
2225 	struct packet_sock *po = pkt_sk(sk);
2226 	unsigned short gso_type = 0;
2227 	int hlen, tlen;
2228 	int extra_len = 0;
2229 
2230 	/*
2231 	 *	Get and verify the address.
2232 	 */
2233 
2234 	if (saddr == NULL) {
2235 		dev = po->prot_hook.dev;
2236 		proto	= po->num;
2237 		addr	= NULL;
2238 	} else {
2239 		err = -EINVAL;
2240 		if (msg->msg_namelen < sizeof(struct sockaddr_ll))
2241 			goto out;
2242 		if (msg->msg_namelen < (saddr->sll_halen + offsetof(struct sockaddr_ll, sll_addr)))
2243 			goto out;
2244 		proto	= saddr->sll_protocol;
2245 		addr	= saddr->sll_addr;
2246 		dev = dev_get_by_index(sock_net(sk), saddr->sll_ifindex);
2247 		need_rls_dev = true;
2248 	}
2249 
2250 	err = -ENXIO;
2251 	if (dev == NULL)
2252 		goto out_unlock;
2253 	if (sock->type == SOCK_RAW)
2254 		reserve = dev->hard_header_len;
2255 
2256 	err = -ENETDOWN;
2257 	if (!(dev->flags & IFF_UP))
2258 		goto out_unlock;
2259 
2260 	if (po->has_vnet_hdr) {
2261 		vnet_hdr_len = sizeof(vnet_hdr);
2262 
2263 		err = -EINVAL;
2264 		if (len < vnet_hdr_len)
2265 			goto out_unlock;
2266 
2267 		len -= vnet_hdr_len;
2268 
2269 		err = memcpy_fromiovec((void *)&vnet_hdr, msg->msg_iov,
2270 				       vnet_hdr_len);
2271 		if (err < 0)
2272 			goto out_unlock;
2273 
2274 		if ((vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
2275 		    (vnet_hdr.csum_start + vnet_hdr.csum_offset + 2 >
2276 		      vnet_hdr.hdr_len))
2277 			vnet_hdr.hdr_len = vnet_hdr.csum_start +
2278 						 vnet_hdr.csum_offset + 2;
2279 
2280 		err = -EINVAL;
2281 		if (vnet_hdr.hdr_len > len)
2282 			goto out_unlock;
2283 
2284 		if (vnet_hdr.gso_type != VIRTIO_NET_HDR_GSO_NONE) {
2285 			switch (vnet_hdr.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
2286 			case VIRTIO_NET_HDR_GSO_TCPV4:
2287 				gso_type = SKB_GSO_TCPV4;
2288 				break;
2289 			case VIRTIO_NET_HDR_GSO_TCPV6:
2290 				gso_type = SKB_GSO_TCPV6;
2291 				break;
2292 			case VIRTIO_NET_HDR_GSO_UDP:
2293 				gso_type = SKB_GSO_UDP;
2294 				break;
2295 			default:
2296 				goto out_unlock;
2297 			}
2298 
2299 			if (vnet_hdr.gso_type & VIRTIO_NET_HDR_GSO_ECN)
2300 				gso_type |= SKB_GSO_TCP_ECN;
2301 
2302 			if (vnet_hdr.gso_size == 0)
2303 				goto out_unlock;
2304 
2305 		}
2306 	}
2307 
2308 	if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
2309 		if (!netif_supports_nofcs(dev)) {
2310 			err = -EPROTONOSUPPORT;
2311 			goto out_unlock;
2312 		}
2313 		extra_len = 4; /* We're doing our own CRC */
2314 	}
2315 
2316 	err = -EMSGSIZE;
2317 	if (!gso_type && (len > dev->mtu + reserve + VLAN_HLEN + extra_len))
2318 		goto out_unlock;
2319 
2320 	err = -ENOBUFS;
2321 	hlen = LL_RESERVED_SPACE(dev);
2322 	tlen = dev->needed_tailroom;
2323 	skb = packet_alloc_skb(sk, hlen + tlen, hlen, len, vnet_hdr.hdr_len,
2324 			       msg->msg_flags & MSG_DONTWAIT, &err);
2325 	if (skb == NULL)
2326 		goto out_unlock;
2327 
2328 	skb_set_network_header(skb, reserve);
2329 
2330 	err = -EINVAL;
2331 	if (sock->type == SOCK_DGRAM &&
2332 	    (offset = dev_hard_header(skb, dev, ntohs(proto), addr, NULL, len)) < 0)
2333 		goto out_free;
2334 
2335 	/* Returns -EFAULT on error */
2336 	err = skb_copy_datagram_from_iovec(skb, offset, msg->msg_iov, 0, len);
2337 	if (err)
2338 		goto out_free;
2339 
2340 	sock_tx_timestamp(sk, &skb_shinfo(skb)->tx_flags);
2341 
2342 	if (!gso_type && (len > dev->mtu + reserve + extra_len)) {
2343 		/* Earlier code assumed this would be a VLAN pkt,
2344 		 * double-check this now that we have the actual
2345 		 * packet in hand.
2346 		 */
2347 		struct ethhdr *ehdr;
2348 		skb_reset_mac_header(skb);
2349 		ehdr = eth_hdr(skb);
2350 		if (ehdr->h_proto != htons(ETH_P_8021Q)) {
2351 			err = -EMSGSIZE;
2352 			goto out_free;
2353 		}
2354 	}
2355 
2356 	skb->protocol = proto;
2357 	skb->dev = dev;
2358 	skb->priority = sk->sk_priority;
2359 	skb->mark = sk->sk_mark;
2360 
2361 	if (po->has_vnet_hdr) {
2362 		if (vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
2363 			if (!skb_partial_csum_set(skb, vnet_hdr.csum_start,
2364 						  vnet_hdr.csum_offset)) {
2365 				err = -EINVAL;
2366 				goto out_free;
2367 			}
2368 		}
2369 
2370 		skb_shinfo(skb)->gso_size = vnet_hdr.gso_size;
2371 		skb_shinfo(skb)->gso_type = gso_type;
2372 
2373 		/* Header must be checked, and gso_segs computed. */
2374 		skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
2375 		skb_shinfo(skb)->gso_segs = 0;
2376 
2377 		len += vnet_hdr_len;
2378 	}
2379 
2380 	skb_probe_transport_header(skb, reserve);
2381 
2382 	if (unlikely(extra_len == 4))
2383 		skb->no_fcs = 1;
2384 
2385 	/*
2386 	 *	Now send it
2387 	 */
2388 
2389 	err = dev_queue_xmit(skb);
2390 	if (err > 0 && (err = net_xmit_errno(err)) != 0)
2391 		goto out_unlock;
2392 
2393 	if (need_rls_dev)
2394 		dev_put(dev);
2395 
2396 	return len;
2397 
2398 out_free:
2399 	kfree_skb(skb);
2400 out_unlock:
2401 	if (dev && need_rls_dev)
2402 		dev_put(dev);
2403 out:
2404 	return err;
2405 }
2406 
packet_sendmsg(struct kiocb * iocb,struct socket * sock,struct msghdr * msg,size_t len)2407 static int packet_sendmsg(struct kiocb *iocb, struct socket *sock,
2408 		struct msghdr *msg, size_t len)
2409 {
2410 	struct sock *sk = sock->sk;
2411 	struct packet_sock *po = pkt_sk(sk);
2412 	if (po->tx_ring.pg_vec)
2413 		return tpacket_snd(po, msg);
2414 	else
2415 		return packet_snd(sock, msg, len);
2416 }
2417 
2418 /*
2419  *	Close a PACKET socket. This is fairly simple. We immediately go
2420  *	to 'closed' state and remove our protocol entry in the device list.
2421  */
2422 
packet_release(struct socket * sock)2423 static int packet_release(struct socket *sock)
2424 {
2425 	struct sock *sk = sock->sk;
2426 	struct packet_sock *po;
2427 	struct net *net;
2428 	union tpacket_req_u req_u;
2429 
2430 	if (!sk)
2431 		return 0;
2432 
2433 	net = sock_net(sk);
2434 	po = pkt_sk(sk);
2435 
2436 	mutex_lock(&net->packet.sklist_lock);
2437 	sk_del_node_init_rcu(sk);
2438 	mutex_unlock(&net->packet.sklist_lock);
2439 
2440 	preempt_disable();
2441 	sock_prot_inuse_add(net, sk->sk_prot, -1);
2442 	preempt_enable();
2443 
2444 	spin_lock(&po->bind_lock);
2445 	unregister_prot_hook(sk, false);
2446 	if (po->prot_hook.dev) {
2447 		dev_put(po->prot_hook.dev);
2448 		po->prot_hook.dev = NULL;
2449 	}
2450 	spin_unlock(&po->bind_lock);
2451 
2452 	packet_flush_mclist(sk);
2453 
2454 	if (po->rx_ring.pg_vec) {
2455 		memset(&req_u, 0, sizeof(req_u));
2456 		packet_set_ring(sk, &req_u, 1, 0);
2457 	}
2458 
2459 	if (po->tx_ring.pg_vec) {
2460 		memset(&req_u, 0, sizeof(req_u));
2461 		packet_set_ring(sk, &req_u, 1, 1);
2462 	}
2463 
2464 	fanout_release(sk);
2465 
2466 	synchronize_net();
2467 	/*
2468 	 *	Now the socket is dead. No more input will appear.
2469 	 */
2470 	sock_orphan(sk);
2471 	sock->sk = NULL;
2472 
2473 	/* Purge queues */
2474 
2475 	skb_queue_purge(&sk->sk_receive_queue);
2476 	sk_refcnt_debug_release(sk);
2477 
2478 	sock_put(sk);
2479 	return 0;
2480 }
2481 
2482 /*
2483  *	Attach a packet hook.
2484  */
2485 
packet_do_bind(struct sock * sk,struct net_device * dev,__be16 protocol)2486 static int packet_do_bind(struct sock *sk, struct net_device *dev, __be16 protocol)
2487 {
2488 	struct packet_sock *po = pkt_sk(sk);
2489 
2490 	if (po->fanout) {
2491 		if (dev)
2492 			dev_put(dev);
2493 
2494 		return -EINVAL;
2495 	}
2496 
2497 	lock_sock(sk);
2498 
2499 	spin_lock(&po->bind_lock);
2500 	unregister_prot_hook(sk, true);
2501 	po->num = protocol;
2502 	po->prot_hook.type = protocol;
2503 	if (po->prot_hook.dev)
2504 		dev_put(po->prot_hook.dev);
2505 	po->prot_hook.dev = dev;
2506 
2507 	po->ifindex = dev ? dev->ifindex : 0;
2508 
2509 	if (protocol == 0)
2510 		goto out_unlock;
2511 
2512 	if (!dev || (dev->flags & IFF_UP)) {
2513 		register_prot_hook(sk);
2514 	} else {
2515 		sk->sk_err = ENETDOWN;
2516 		if (!sock_flag(sk, SOCK_DEAD))
2517 			sk->sk_error_report(sk);
2518 	}
2519 
2520 out_unlock:
2521 	spin_unlock(&po->bind_lock);
2522 	release_sock(sk);
2523 	return 0;
2524 }
2525 
2526 /*
2527  *	Bind a packet socket to a device
2528  */
2529 
packet_bind_spkt(struct socket * sock,struct sockaddr * uaddr,int addr_len)2530 static int packet_bind_spkt(struct socket *sock, struct sockaddr *uaddr,
2531 			    int addr_len)
2532 {
2533 	struct sock *sk = sock->sk;
2534 	char name[15];
2535 	struct net_device *dev;
2536 	int err = -ENODEV;
2537 
2538 	/*
2539 	 *	Check legality
2540 	 */
2541 
2542 	if (addr_len != sizeof(struct sockaddr))
2543 		return -EINVAL;
2544 	strlcpy(name, uaddr->sa_data, sizeof(name));
2545 
2546 	dev = dev_get_by_name(sock_net(sk), name);
2547 	if (dev)
2548 		err = packet_do_bind(sk, dev, pkt_sk(sk)->num);
2549 	return err;
2550 }
2551 
packet_bind(struct socket * sock,struct sockaddr * uaddr,int addr_len)2552 static int packet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
2553 {
2554 	struct sockaddr_ll *sll = (struct sockaddr_ll *)uaddr;
2555 	struct sock *sk = sock->sk;
2556 	struct net_device *dev = NULL;
2557 	int err;
2558 
2559 
2560 	/*
2561 	 *	Check legality
2562 	 */
2563 
2564 	if (addr_len < sizeof(struct sockaddr_ll))
2565 		return -EINVAL;
2566 	if (sll->sll_family != AF_PACKET)
2567 		return -EINVAL;
2568 
2569 	if (sll->sll_ifindex) {
2570 		err = -ENODEV;
2571 		dev = dev_get_by_index(sock_net(sk), sll->sll_ifindex);
2572 		if (dev == NULL)
2573 			goto out;
2574 	}
2575 	err = packet_do_bind(sk, dev, sll->sll_protocol ? : pkt_sk(sk)->num);
2576 
2577 out:
2578 	return err;
2579 }
2580 
2581 static struct proto packet_proto = {
2582 	.name	  = "PACKET",
2583 	.owner	  = THIS_MODULE,
2584 	.obj_size = sizeof(struct packet_sock),
2585 };
2586 
2587 /*
2588  *	Create a packet of type SOCK_PACKET.
2589  */
2590 
packet_create(struct net * net,struct socket * sock,int protocol,int kern)2591 static int packet_create(struct net *net, struct socket *sock, int protocol,
2592 			 int kern)
2593 {
2594 	struct sock *sk;
2595 	struct packet_sock *po;
2596 	__be16 proto = (__force __be16)protocol; /* weird, but documented */
2597 	int err;
2598 
2599 	if (!ns_capable(net->user_ns, CAP_NET_RAW))
2600 		return -EPERM;
2601 	if (sock->type != SOCK_DGRAM && sock->type != SOCK_RAW &&
2602 	    sock->type != SOCK_PACKET)
2603 		return -ESOCKTNOSUPPORT;
2604 
2605 	sock->state = SS_UNCONNECTED;
2606 
2607 	err = -ENOBUFS;
2608 	sk = sk_alloc(net, PF_PACKET, GFP_KERNEL, &packet_proto);
2609 	if (sk == NULL)
2610 		goto out;
2611 
2612 	sock->ops = &packet_ops;
2613 	if (sock->type == SOCK_PACKET)
2614 		sock->ops = &packet_ops_spkt;
2615 
2616 	sock_init_data(sock, sk);
2617 
2618 	po = pkt_sk(sk);
2619 	sk->sk_family = PF_PACKET;
2620 	po->num = proto;
2621 
2622 	sk->sk_destruct = packet_sock_destruct;
2623 	sk_refcnt_debug_inc(sk);
2624 
2625 	/*
2626 	 *	Attach a protocol block
2627 	 */
2628 
2629 	spin_lock_init(&po->bind_lock);
2630 	mutex_init(&po->pg_vec_lock);
2631 	po->prot_hook.func = packet_rcv;
2632 
2633 	if (sock->type == SOCK_PACKET)
2634 		po->prot_hook.func = packet_rcv_spkt;
2635 
2636 	po->prot_hook.af_packet_priv = sk;
2637 
2638 	if (proto) {
2639 		po->prot_hook.type = proto;
2640 		register_prot_hook(sk);
2641 	}
2642 
2643 	mutex_lock(&net->packet.sklist_lock);
2644 	sk_add_node_rcu(sk, &net->packet.sklist);
2645 	mutex_unlock(&net->packet.sklist_lock);
2646 
2647 	preempt_disable();
2648 	sock_prot_inuse_add(net, &packet_proto, 1);
2649 	preempt_enable();
2650 
2651 	return 0;
2652 out:
2653 	return err;
2654 }
2655 
packet_recv_error(struct sock * sk,struct msghdr * msg,int len)2656 static int packet_recv_error(struct sock *sk, struct msghdr *msg, int len)
2657 {
2658 	struct sock_exterr_skb *serr;
2659 	struct sk_buff *skb, *skb2;
2660 	int copied, err;
2661 
2662 	err = -EAGAIN;
2663 	skb = skb_dequeue(&sk->sk_error_queue);
2664 	if (skb == NULL)
2665 		goto out;
2666 
2667 	copied = skb->len;
2668 	if (copied > len) {
2669 		msg->msg_flags |= MSG_TRUNC;
2670 		copied = len;
2671 	}
2672 	err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
2673 	if (err)
2674 		goto out_free_skb;
2675 
2676 	sock_recv_timestamp(msg, sk, skb);
2677 
2678 	serr = SKB_EXT_ERR(skb);
2679 	put_cmsg(msg, SOL_PACKET, PACKET_TX_TIMESTAMP,
2680 		 sizeof(serr->ee), &serr->ee);
2681 
2682 	msg->msg_flags |= MSG_ERRQUEUE;
2683 	err = copied;
2684 
2685 	/* Reset and regenerate socket error */
2686 	spin_lock_bh(&sk->sk_error_queue.lock);
2687 	sk->sk_err = 0;
2688 	if ((skb2 = skb_peek(&sk->sk_error_queue)) != NULL) {
2689 		sk->sk_err = SKB_EXT_ERR(skb2)->ee.ee_errno;
2690 		spin_unlock_bh(&sk->sk_error_queue.lock);
2691 		sk->sk_error_report(sk);
2692 	} else
2693 		spin_unlock_bh(&sk->sk_error_queue.lock);
2694 
2695 out_free_skb:
2696 	kfree_skb(skb);
2697 out:
2698 	return err;
2699 }
2700 
2701 /*
2702  *	Pull a packet from our receive queue and hand it to the user.
2703  *	If necessary we block.
2704  */
2705 
packet_recvmsg(struct kiocb * iocb,struct socket * sock,struct msghdr * msg,size_t len,int flags)2706 static int packet_recvmsg(struct kiocb *iocb, struct socket *sock,
2707 			  struct msghdr *msg, size_t len, int flags)
2708 {
2709 	struct sock *sk = sock->sk;
2710 	struct sk_buff *skb;
2711 	int copied, err;
2712 	struct sockaddr_ll *sll;
2713 	int vnet_hdr_len = 0;
2714 
2715 	err = -EINVAL;
2716 	if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT|MSG_ERRQUEUE))
2717 		goto out;
2718 
2719 #if 0
2720 	/* What error should we return now? EUNATTACH? */
2721 	if (pkt_sk(sk)->ifindex < 0)
2722 		return -ENODEV;
2723 #endif
2724 
2725 	if (flags & MSG_ERRQUEUE) {
2726 		err = packet_recv_error(sk, msg, len);
2727 		goto out;
2728 	}
2729 
2730 	/*
2731 	 *	Call the generic datagram receiver. This handles all sorts
2732 	 *	of horrible races and re-entrancy so we can forget about it
2733 	 *	in the protocol layers.
2734 	 *
2735 	 *	Now it will return ENETDOWN, if device have just gone down,
2736 	 *	but then it will block.
2737 	 */
2738 
2739 	skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);
2740 
2741 	/*
2742 	 *	An error occurred so return it. Because skb_recv_datagram()
2743 	 *	handles the blocking we don't see and worry about blocking
2744 	 *	retries.
2745 	 */
2746 
2747 	if (skb == NULL)
2748 		goto out;
2749 
2750 	if (pkt_sk(sk)->has_vnet_hdr) {
2751 		struct virtio_net_hdr vnet_hdr = { 0 };
2752 
2753 		err = -EINVAL;
2754 		vnet_hdr_len = sizeof(vnet_hdr);
2755 		if (len < vnet_hdr_len)
2756 			goto out_free;
2757 
2758 		len -= vnet_hdr_len;
2759 
2760 		if (skb_is_gso(skb)) {
2761 			struct skb_shared_info *sinfo = skb_shinfo(skb);
2762 
2763 			/* This is a hint as to how much should be linear. */
2764 			vnet_hdr.hdr_len = skb_headlen(skb);
2765 			vnet_hdr.gso_size = sinfo->gso_size;
2766 			if (sinfo->gso_type & SKB_GSO_TCPV4)
2767 				vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
2768 			else if (sinfo->gso_type & SKB_GSO_TCPV6)
2769 				vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
2770 			else if (sinfo->gso_type & SKB_GSO_UDP)
2771 				vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_UDP;
2772 			else if (sinfo->gso_type & SKB_GSO_FCOE)
2773 				goto out_free;
2774 			else
2775 				BUG();
2776 			if (sinfo->gso_type & SKB_GSO_TCP_ECN)
2777 				vnet_hdr.gso_type |= VIRTIO_NET_HDR_GSO_ECN;
2778 		} else
2779 			vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE;
2780 
2781 		if (skb->ip_summed == CHECKSUM_PARTIAL) {
2782 			vnet_hdr.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
2783 			vnet_hdr.csum_start = skb_checksum_start_offset(skb);
2784 			vnet_hdr.csum_offset = skb->csum_offset;
2785 		} else if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
2786 			vnet_hdr.flags = VIRTIO_NET_HDR_F_DATA_VALID;
2787 		} /* else everything is zero */
2788 
2789 		err = memcpy_toiovec(msg->msg_iov, (void *)&vnet_hdr,
2790 				     vnet_hdr_len);
2791 		if (err < 0)
2792 			goto out_free;
2793 	}
2794 
2795 	/*
2796 	 *	If the address length field is there to be filled in, we fill
2797 	 *	it in now.
2798 	 */
2799 
2800 	sll = &PACKET_SKB_CB(skb)->sa.ll;
2801 	if (sock->type == SOCK_PACKET)
2802 		msg->msg_namelen = sizeof(struct sockaddr_pkt);
2803 	else
2804 		msg->msg_namelen = sll->sll_halen + offsetof(struct sockaddr_ll, sll_addr);
2805 
2806 	/*
2807 	 *	You lose any data beyond the buffer you gave. If it worries a
2808 	 *	user program they can ask the device for its MTU anyway.
2809 	 */
2810 
2811 	copied = skb->len;
2812 	if (copied > len) {
2813 		copied = len;
2814 		msg->msg_flags |= MSG_TRUNC;
2815 	}
2816 
2817 	err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
2818 	if (err)
2819 		goto out_free;
2820 
2821 	sock_recv_ts_and_drops(msg, sk, skb);
2822 
2823 	if (msg->msg_name)
2824 		memcpy(msg->msg_name, &PACKET_SKB_CB(skb)->sa,
2825 		       msg->msg_namelen);
2826 
2827 	if (pkt_sk(sk)->auxdata) {
2828 		struct tpacket_auxdata aux;
2829 
2830 		aux.tp_status = TP_STATUS_USER;
2831 		if (skb->ip_summed == CHECKSUM_PARTIAL)
2832 			aux.tp_status |= TP_STATUS_CSUMNOTREADY;
2833 		aux.tp_len = PACKET_SKB_CB(skb)->origlen;
2834 		aux.tp_snaplen = skb->len;
2835 		aux.tp_mac = 0;
2836 		aux.tp_net = skb_network_offset(skb);
2837 		if (vlan_tx_tag_present(skb)) {
2838 			aux.tp_vlan_tci = vlan_tx_tag_get(skb);
2839 			aux.tp_status |= TP_STATUS_VLAN_VALID;
2840 		} else {
2841 			aux.tp_vlan_tci = 0;
2842 		}
2843 		aux.tp_padding = 0;
2844 		put_cmsg(msg, SOL_PACKET, PACKET_AUXDATA, sizeof(aux), &aux);
2845 	}
2846 
2847 	/*
2848 	 *	Free or return the buffer as appropriate. Again this
2849 	 *	hides all the races and re-entrancy issues from us.
2850 	 */
2851 	err = vnet_hdr_len + ((flags&MSG_TRUNC) ? skb->len : copied);
2852 
2853 out_free:
2854 	skb_free_datagram(sk, skb);
2855 out:
2856 	return err;
2857 }
2858 
packet_getname_spkt(struct socket * sock,struct sockaddr * uaddr,int * uaddr_len,int peer)2859 static int packet_getname_spkt(struct socket *sock, struct sockaddr *uaddr,
2860 			       int *uaddr_len, int peer)
2861 {
2862 	struct net_device *dev;
2863 	struct sock *sk	= sock->sk;
2864 
2865 	if (peer)
2866 		return -EOPNOTSUPP;
2867 
2868 	uaddr->sa_family = AF_PACKET;
2869 	memset(uaddr->sa_data, 0, sizeof(uaddr->sa_data));
2870 	rcu_read_lock();
2871 	dev = dev_get_by_index_rcu(sock_net(sk), pkt_sk(sk)->ifindex);
2872 	if (dev)
2873 		strlcpy(uaddr->sa_data, dev->name, sizeof(uaddr->sa_data));
2874 	rcu_read_unlock();
2875 	*uaddr_len = sizeof(*uaddr);
2876 
2877 	return 0;
2878 }
2879 
packet_getname(struct socket * sock,struct sockaddr * uaddr,int * uaddr_len,int peer)2880 static int packet_getname(struct socket *sock, struct sockaddr *uaddr,
2881 			  int *uaddr_len, int peer)
2882 {
2883 	struct net_device *dev;
2884 	struct sock *sk = sock->sk;
2885 	struct packet_sock *po = pkt_sk(sk);
2886 	DECLARE_SOCKADDR(struct sockaddr_ll *, sll, uaddr);
2887 
2888 	if (peer)
2889 		return -EOPNOTSUPP;
2890 
2891 	sll->sll_family = AF_PACKET;
2892 	sll->sll_ifindex = po->ifindex;
2893 	sll->sll_protocol = po->num;
2894 	sll->sll_pkttype = 0;
2895 	rcu_read_lock();
2896 	dev = dev_get_by_index_rcu(sock_net(sk), po->ifindex);
2897 	if (dev) {
2898 		sll->sll_hatype = dev->type;
2899 		sll->sll_halen = dev->addr_len;
2900 		memcpy(sll->sll_addr, dev->dev_addr, dev->addr_len);
2901 	} else {
2902 		sll->sll_hatype = 0;	/* Bad: we have no ARPHRD_UNSPEC */
2903 		sll->sll_halen = 0;
2904 	}
2905 	rcu_read_unlock();
2906 	*uaddr_len = offsetof(struct sockaddr_ll, sll_addr) + sll->sll_halen;
2907 
2908 	return 0;
2909 }
2910 
packet_dev_mc(struct net_device * dev,struct packet_mclist * i,int what)2911 static int packet_dev_mc(struct net_device *dev, struct packet_mclist *i,
2912 			 int what)
2913 {
2914 	switch (i->type) {
2915 	case PACKET_MR_MULTICAST:
2916 		if (i->alen != dev->addr_len)
2917 			return -EINVAL;
2918 		if (what > 0)
2919 			return dev_mc_add(dev, i->addr);
2920 		else
2921 			return dev_mc_del(dev, i->addr);
2922 		break;
2923 	case PACKET_MR_PROMISC:
2924 		return dev_set_promiscuity(dev, what);
2925 		break;
2926 	case PACKET_MR_ALLMULTI:
2927 		return dev_set_allmulti(dev, what);
2928 		break;
2929 	case PACKET_MR_UNICAST:
2930 		if (i->alen != dev->addr_len)
2931 			return -EINVAL;
2932 		if (what > 0)
2933 			return dev_uc_add(dev, i->addr);
2934 		else
2935 			return dev_uc_del(dev, i->addr);
2936 		break;
2937 	default:
2938 		break;
2939 	}
2940 	return 0;
2941 }
2942 
packet_dev_mclist(struct net_device * dev,struct packet_mclist * i,int what)2943 static void packet_dev_mclist(struct net_device *dev, struct packet_mclist *i, int what)
2944 {
2945 	for ( ; i; i = i->next) {
2946 		if (i->ifindex == dev->ifindex)
2947 			packet_dev_mc(dev, i, what);
2948 	}
2949 }
2950 
packet_mc_add(struct sock * sk,struct packet_mreq_max * mreq)2951 static int packet_mc_add(struct sock *sk, struct packet_mreq_max *mreq)
2952 {
2953 	struct packet_sock *po = pkt_sk(sk);
2954 	struct packet_mclist *ml, *i;
2955 	struct net_device *dev;
2956 	int err;
2957 
2958 	rtnl_lock();
2959 
2960 	err = -ENODEV;
2961 	dev = __dev_get_by_index(sock_net(sk), mreq->mr_ifindex);
2962 	if (!dev)
2963 		goto done;
2964 
2965 	err = -EINVAL;
2966 	if (mreq->mr_alen > dev->addr_len)
2967 		goto done;
2968 
2969 	err = -ENOBUFS;
2970 	i = kmalloc(sizeof(*i), GFP_KERNEL);
2971 	if (i == NULL)
2972 		goto done;
2973 
2974 	err = 0;
2975 	for (ml = po->mclist; ml; ml = ml->next) {
2976 		if (ml->ifindex == mreq->mr_ifindex &&
2977 		    ml->type == mreq->mr_type &&
2978 		    ml->alen == mreq->mr_alen &&
2979 		    memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
2980 			ml->count++;
2981 			/* Free the new element ... */
2982 			kfree(i);
2983 			goto done;
2984 		}
2985 	}
2986 
2987 	i->type = mreq->mr_type;
2988 	i->ifindex = mreq->mr_ifindex;
2989 	i->alen = mreq->mr_alen;
2990 	memcpy(i->addr, mreq->mr_address, i->alen);
2991 	i->count = 1;
2992 	i->next = po->mclist;
2993 	po->mclist = i;
2994 	err = packet_dev_mc(dev, i, 1);
2995 	if (err) {
2996 		po->mclist = i->next;
2997 		kfree(i);
2998 	}
2999 
3000 done:
3001 	rtnl_unlock();
3002 	return err;
3003 }
3004 
packet_mc_drop(struct sock * sk,struct packet_mreq_max * mreq)3005 static int packet_mc_drop(struct sock *sk, struct packet_mreq_max *mreq)
3006 {
3007 	struct packet_mclist *ml, **mlp;
3008 
3009 	rtnl_lock();
3010 
3011 	for (mlp = &pkt_sk(sk)->mclist; (ml = *mlp) != NULL; mlp = &ml->next) {
3012 		if (ml->ifindex == mreq->mr_ifindex &&
3013 		    ml->type == mreq->mr_type &&
3014 		    ml->alen == mreq->mr_alen &&
3015 		    memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
3016 			if (--ml->count == 0) {
3017 				struct net_device *dev;
3018 				*mlp = ml->next;
3019 				dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
3020 				if (dev)
3021 					packet_dev_mc(dev, ml, -1);
3022 				kfree(ml);
3023 			}
3024 			rtnl_unlock();
3025 			return 0;
3026 		}
3027 	}
3028 	rtnl_unlock();
3029 	return -EADDRNOTAVAIL;
3030 }
3031 
packet_flush_mclist(struct sock * sk)3032 static void packet_flush_mclist(struct sock *sk)
3033 {
3034 	struct packet_sock *po = pkt_sk(sk);
3035 	struct packet_mclist *ml;
3036 
3037 	if (!po->mclist)
3038 		return;
3039 
3040 	rtnl_lock();
3041 	while ((ml = po->mclist) != NULL) {
3042 		struct net_device *dev;
3043 
3044 		po->mclist = ml->next;
3045 		dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
3046 		if (dev != NULL)
3047 			packet_dev_mc(dev, ml, -1);
3048 		kfree(ml);
3049 	}
3050 	rtnl_unlock();
3051 }
3052 
3053 static int
packet_setsockopt(struct socket * sock,int level,int optname,char __user * optval,unsigned int optlen)3054 packet_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen)
3055 {
3056 	struct sock *sk = sock->sk;
3057 	struct packet_sock *po = pkt_sk(sk);
3058 	int ret;
3059 
3060 	if (level != SOL_PACKET)
3061 		return -ENOPROTOOPT;
3062 
3063 	switch (optname) {
3064 	case PACKET_ADD_MEMBERSHIP:
3065 	case PACKET_DROP_MEMBERSHIP:
3066 	{
3067 		struct packet_mreq_max mreq;
3068 		int len = optlen;
3069 		memset(&mreq, 0, sizeof(mreq));
3070 		if (len < sizeof(struct packet_mreq))
3071 			return -EINVAL;
3072 		if (len > sizeof(mreq))
3073 			len = sizeof(mreq);
3074 		if (copy_from_user(&mreq, optval, len))
3075 			return -EFAULT;
3076 		if (len < (mreq.mr_alen + offsetof(struct packet_mreq, mr_address)))
3077 			return -EINVAL;
3078 		if (optname == PACKET_ADD_MEMBERSHIP)
3079 			ret = packet_mc_add(sk, &mreq);
3080 		else
3081 			ret = packet_mc_drop(sk, &mreq);
3082 		return ret;
3083 	}
3084 
3085 	case PACKET_RX_RING:
3086 	case PACKET_TX_RING:
3087 	{
3088 		union tpacket_req_u req_u;
3089 		int len;
3090 
3091 		switch (po->tp_version) {
3092 		case TPACKET_V1:
3093 		case TPACKET_V2:
3094 			len = sizeof(req_u.req);
3095 			break;
3096 		case TPACKET_V3:
3097 		default:
3098 			len = sizeof(req_u.req3);
3099 			break;
3100 		}
3101 		if (optlen < len)
3102 			return -EINVAL;
3103 		if (pkt_sk(sk)->has_vnet_hdr)
3104 			return -EINVAL;
3105 		if (copy_from_user(&req_u.req, optval, len))
3106 			return -EFAULT;
3107 		return packet_set_ring(sk, &req_u, 0,
3108 			optname == PACKET_TX_RING);
3109 	}
3110 	case PACKET_COPY_THRESH:
3111 	{
3112 		int val;
3113 
3114 		if (optlen != sizeof(val))
3115 			return -EINVAL;
3116 		if (copy_from_user(&val, optval, sizeof(val)))
3117 			return -EFAULT;
3118 
3119 		pkt_sk(sk)->copy_thresh = val;
3120 		return 0;
3121 	}
3122 	case PACKET_VERSION:
3123 	{
3124 		int val;
3125 
3126 		if (optlen != sizeof(val))
3127 			return -EINVAL;
3128 		if (copy_from_user(&val, optval, sizeof(val)))
3129 			return -EFAULT;
3130 		switch (val) {
3131 		case TPACKET_V1:
3132 		case TPACKET_V2:
3133 		case TPACKET_V3:
3134 			break;
3135 		default:
3136 			return -EINVAL;
3137 		}
3138 		lock_sock(sk);
3139 		if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) {
3140 			ret = -EBUSY;
3141 		} else {
3142 			po->tp_version = val;
3143 			ret = 0;
3144 		}
3145 		release_sock(sk);
3146 		return ret;
3147 	}
3148 	case PACKET_RESERVE:
3149 	{
3150 		unsigned int val;
3151 
3152 		if (optlen != sizeof(val))
3153 			return -EINVAL;
3154 		if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3155 			return -EBUSY;
3156 		if (copy_from_user(&val, optval, sizeof(val)))
3157 			return -EFAULT;
3158 		if (val > INT_MAX)
3159 			return -EINVAL;
3160 		po->tp_reserve = val;
3161 		return 0;
3162 	}
3163 	case PACKET_LOSS:
3164 	{
3165 		unsigned int val;
3166 
3167 		if (optlen != sizeof(val))
3168 			return -EINVAL;
3169 		if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3170 			return -EBUSY;
3171 		if (copy_from_user(&val, optval, sizeof(val)))
3172 			return -EFAULT;
3173 		po->tp_loss = !!val;
3174 		return 0;
3175 	}
3176 	case PACKET_AUXDATA:
3177 	{
3178 		int val;
3179 
3180 		if (optlen < sizeof(val))
3181 			return -EINVAL;
3182 		if (copy_from_user(&val, optval, sizeof(val)))
3183 			return -EFAULT;
3184 
3185 		po->auxdata = !!val;
3186 		return 0;
3187 	}
3188 	case PACKET_ORIGDEV:
3189 	{
3190 		int val;
3191 
3192 		if (optlen < sizeof(val))
3193 			return -EINVAL;
3194 		if (copy_from_user(&val, optval, sizeof(val)))
3195 			return -EFAULT;
3196 
3197 		po->origdev = !!val;
3198 		return 0;
3199 	}
3200 	case PACKET_VNET_HDR:
3201 	{
3202 		int val;
3203 
3204 		if (sock->type != SOCK_RAW)
3205 			return -EINVAL;
3206 		if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3207 			return -EBUSY;
3208 		if (optlen < sizeof(val))
3209 			return -EINVAL;
3210 		if (copy_from_user(&val, optval, sizeof(val)))
3211 			return -EFAULT;
3212 
3213 		po->has_vnet_hdr = !!val;
3214 		return 0;
3215 	}
3216 	case PACKET_TIMESTAMP:
3217 	{
3218 		int val;
3219 
3220 		if (optlen != sizeof(val))
3221 			return -EINVAL;
3222 		if (copy_from_user(&val, optval, sizeof(val)))
3223 			return -EFAULT;
3224 
3225 		po->tp_tstamp = val;
3226 		return 0;
3227 	}
3228 	case PACKET_FANOUT:
3229 	{
3230 		int val;
3231 
3232 		if (optlen != sizeof(val))
3233 			return -EINVAL;
3234 		if (copy_from_user(&val, optval, sizeof(val)))
3235 			return -EFAULT;
3236 
3237 		return fanout_add(sk, val & 0xffff, val >> 16);
3238 	}
3239 	case PACKET_TX_HAS_OFF:
3240 	{
3241 		unsigned int val;
3242 
3243 		if (optlen != sizeof(val))
3244 			return -EINVAL;
3245 		if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3246 			return -EBUSY;
3247 		if (copy_from_user(&val, optval, sizeof(val)))
3248 			return -EFAULT;
3249 		po->tp_tx_has_off = !!val;
3250 		return 0;
3251 	}
3252 	default:
3253 		return -ENOPROTOOPT;
3254 	}
3255 }
3256 
packet_getsockopt(struct socket * sock,int level,int optname,char __user * optval,int __user * optlen)3257 static int packet_getsockopt(struct socket *sock, int level, int optname,
3258 			     char __user *optval, int __user *optlen)
3259 {
3260 	int len;
3261 	int val, lv = sizeof(val);
3262 	struct sock *sk = sock->sk;
3263 	struct packet_sock *po = pkt_sk(sk);
3264 	void *data = &val;
3265 	union tpacket_stats_u st;
3266 
3267 	if (level != SOL_PACKET)
3268 		return -ENOPROTOOPT;
3269 
3270 	if (get_user(len, optlen))
3271 		return -EFAULT;
3272 
3273 	if (len < 0)
3274 		return -EINVAL;
3275 
3276 	switch (optname) {
3277 	case PACKET_STATISTICS:
3278 		spin_lock_bh(&sk->sk_receive_queue.lock);
3279 		memcpy(&st, &po->stats, sizeof(st));
3280 		memset(&po->stats, 0, sizeof(po->stats));
3281 		spin_unlock_bh(&sk->sk_receive_queue.lock);
3282 
3283 		if (po->tp_version == TPACKET_V3) {
3284 			lv = sizeof(struct tpacket_stats_v3);
3285 			data = &st.stats3;
3286 		} else {
3287 			lv = sizeof(struct tpacket_stats);
3288 			data = &st.stats1;
3289 		}
3290 
3291 		break;
3292 	case PACKET_AUXDATA:
3293 		val = po->auxdata;
3294 		break;
3295 	case PACKET_ORIGDEV:
3296 		val = po->origdev;
3297 		break;
3298 	case PACKET_VNET_HDR:
3299 		val = po->has_vnet_hdr;
3300 		break;
3301 	case PACKET_VERSION:
3302 		val = po->tp_version;
3303 		break;
3304 	case PACKET_HDRLEN:
3305 		if (len > sizeof(int))
3306 			len = sizeof(int);
3307 		if (copy_from_user(&val, optval, len))
3308 			return -EFAULT;
3309 		switch (val) {
3310 		case TPACKET_V1:
3311 			val = sizeof(struct tpacket_hdr);
3312 			break;
3313 		case TPACKET_V2:
3314 			val = sizeof(struct tpacket2_hdr);
3315 			break;
3316 		case TPACKET_V3:
3317 			val = sizeof(struct tpacket3_hdr);
3318 			break;
3319 		default:
3320 			return -EINVAL;
3321 		}
3322 		break;
3323 	case PACKET_RESERVE:
3324 		val = po->tp_reserve;
3325 		break;
3326 	case PACKET_LOSS:
3327 		val = po->tp_loss;
3328 		break;
3329 	case PACKET_TIMESTAMP:
3330 		val = po->tp_tstamp;
3331 		break;
3332 	case PACKET_FANOUT:
3333 		val = (po->fanout ?
3334 		       ((u32)po->fanout->id |
3335 			((u32)po->fanout->type << 16) |
3336 			((u32)po->fanout->flags << 24)) :
3337 		       0);
3338 		break;
3339 	case PACKET_TX_HAS_OFF:
3340 		val = po->tp_tx_has_off;
3341 		break;
3342 	default:
3343 		return -ENOPROTOOPT;
3344 	}
3345 
3346 	if (len > lv)
3347 		len = lv;
3348 	if (put_user(len, optlen))
3349 		return -EFAULT;
3350 	if (copy_to_user(optval, data, len))
3351 		return -EFAULT;
3352 	return 0;
3353 }
3354 
3355 
packet_notifier(struct notifier_block * this,unsigned long msg,void * data)3356 static int packet_notifier(struct notifier_block *this, unsigned long msg, void *data)
3357 {
3358 	struct sock *sk;
3359 	struct net_device *dev = data;
3360 	struct net *net = dev_net(dev);
3361 
3362 	rcu_read_lock();
3363 	sk_for_each_rcu(sk, &net->packet.sklist) {
3364 		struct packet_sock *po = pkt_sk(sk);
3365 
3366 		switch (msg) {
3367 		case NETDEV_UNREGISTER:
3368 			if (po->mclist)
3369 				packet_dev_mclist(dev, po->mclist, -1);
3370 			/* fallthrough */
3371 
3372 		case NETDEV_DOWN:
3373 			if (dev->ifindex == po->ifindex) {
3374 				spin_lock(&po->bind_lock);
3375 				if (po->running) {
3376 					__unregister_prot_hook(sk, false);
3377 					sk->sk_err = ENETDOWN;
3378 					if (!sock_flag(sk, SOCK_DEAD))
3379 						sk->sk_error_report(sk);
3380 				}
3381 				if (msg == NETDEV_UNREGISTER) {
3382 					po->ifindex = -1;
3383 					if (po->prot_hook.dev)
3384 						dev_put(po->prot_hook.dev);
3385 					po->prot_hook.dev = NULL;
3386 				}
3387 				spin_unlock(&po->bind_lock);
3388 			}
3389 			break;
3390 		case NETDEV_UP:
3391 			if (dev->ifindex == po->ifindex) {
3392 				spin_lock(&po->bind_lock);
3393 				if (po->num)
3394 					register_prot_hook(sk);
3395 				spin_unlock(&po->bind_lock);
3396 			}
3397 			break;
3398 		}
3399 	}
3400 	rcu_read_unlock();
3401 	return NOTIFY_DONE;
3402 }
3403 
3404 
packet_ioctl(struct socket * sock,unsigned int cmd,unsigned long arg)3405 static int packet_ioctl(struct socket *sock, unsigned int cmd,
3406 			unsigned long arg)
3407 {
3408 	struct sock *sk = sock->sk;
3409 
3410 	switch (cmd) {
3411 	case SIOCOUTQ:
3412 	{
3413 		int amount = sk_wmem_alloc_get(sk);
3414 
3415 		return put_user(amount, (int __user *)arg);
3416 	}
3417 	case SIOCINQ:
3418 	{
3419 		struct sk_buff *skb;
3420 		int amount = 0;
3421 
3422 		spin_lock_bh(&sk->sk_receive_queue.lock);
3423 		skb = skb_peek(&sk->sk_receive_queue);
3424 		if (skb)
3425 			amount = skb->len;
3426 		spin_unlock_bh(&sk->sk_receive_queue.lock);
3427 		return put_user(amount, (int __user *)arg);
3428 	}
3429 	case SIOCGSTAMP:
3430 		return sock_get_timestamp(sk, (struct timeval __user *)arg);
3431 	case SIOCGSTAMPNS:
3432 		return sock_get_timestampns(sk, (struct timespec __user *)arg);
3433 
3434 #ifdef CONFIG_INET
3435 	case SIOCADDRT:
3436 	case SIOCDELRT:
3437 	case SIOCDARP:
3438 	case SIOCGARP:
3439 	case SIOCSARP:
3440 	case SIOCGIFADDR:
3441 	case SIOCSIFADDR:
3442 	case SIOCGIFBRDADDR:
3443 	case SIOCSIFBRDADDR:
3444 	case SIOCGIFNETMASK:
3445 	case SIOCSIFNETMASK:
3446 	case SIOCGIFDSTADDR:
3447 	case SIOCSIFDSTADDR:
3448 	case SIOCSIFFLAGS:
3449 		return inet_dgram_ops.ioctl(sock, cmd, arg);
3450 #endif
3451 
3452 	default:
3453 		return -ENOIOCTLCMD;
3454 	}
3455 	return 0;
3456 }
3457 
packet_poll(struct file * file,struct socket * sock,poll_table * wait)3458 static unsigned int packet_poll(struct file *file, struct socket *sock,
3459 				poll_table *wait)
3460 {
3461 	struct sock *sk = sock->sk;
3462 	struct packet_sock *po = pkt_sk(sk);
3463 	unsigned int mask = datagram_poll(file, sock, wait);
3464 
3465 	spin_lock_bh(&sk->sk_receive_queue.lock);
3466 	if (po->rx_ring.pg_vec) {
3467 		if (!packet_previous_rx_frame(po, &po->rx_ring,
3468 			TP_STATUS_KERNEL))
3469 			mask |= POLLIN | POLLRDNORM;
3470 	}
3471 	spin_unlock_bh(&sk->sk_receive_queue.lock);
3472 	spin_lock_bh(&sk->sk_write_queue.lock);
3473 	if (po->tx_ring.pg_vec) {
3474 		if (packet_current_frame(po, &po->tx_ring, TP_STATUS_AVAILABLE))
3475 			mask |= POLLOUT | POLLWRNORM;
3476 	}
3477 	spin_unlock_bh(&sk->sk_write_queue.lock);
3478 	return mask;
3479 }
3480 
3481 
3482 /* Dirty? Well, I still did not learn better way to account
3483  * for user mmaps.
3484  */
3485 
packet_mm_open(struct vm_area_struct * vma)3486 static void packet_mm_open(struct vm_area_struct *vma)
3487 {
3488 	struct file *file = vma->vm_file;
3489 	struct socket *sock = file->private_data;
3490 	struct sock *sk = sock->sk;
3491 
3492 	if (sk)
3493 		atomic_inc(&pkt_sk(sk)->mapped);
3494 }
3495 
packet_mm_close(struct vm_area_struct * vma)3496 static void packet_mm_close(struct vm_area_struct *vma)
3497 {
3498 	struct file *file = vma->vm_file;
3499 	struct socket *sock = file->private_data;
3500 	struct sock *sk = sock->sk;
3501 
3502 	if (sk)
3503 		atomic_dec(&pkt_sk(sk)->mapped);
3504 }
3505 
3506 static const struct vm_operations_struct packet_mmap_ops = {
3507 	.open	=	packet_mm_open,
3508 	.close	=	packet_mm_close,
3509 };
3510 
free_pg_vec(struct pgv * pg_vec,unsigned int order,unsigned int len)3511 static void free_pg_vec(struct pgv *pg_vec, unsigned int order,
3512 			unsigned int len)
3513 {
3514 	int i;
3515 
3516 	for (i = 0; i < len; i++) {
3517 		if (likely(pg_vec[i].buffer)) {
3518 			if (is_vmalloc_addr(pg_vec[i].buffer))
3519 				vfree(pg_vec[i].buffer);
3520 			else
3521 				free_pages((unsigned long)pg_vec[i].buffer,
3522 					   order);
3523 			pg_vec[i].buffer = NULL;
3524 		}
3525 	}
3526 	kfree(pg_vec);
3527 }
3528 
alloc_one_pg_vec_page(unsigned long order)3529 static char *alloc_one_pg_vec_page(unsigned long order)
3530 {
3531 	char *buffer = NULL;
3532 	gfp_t gfp_flags = GFP_KERNEL | __GFP_COMP |
3533 			  __GFP_ZERO | __GFP_NOWARN | __GFP_NORETRY;
3534 
3535 	buffer = (char *) __get_free_pages(gfp_flags, order);
3536 
3537 	if (buffer)
3538 		return buffer;
3539 
3540 	/*
3541 	 * __get_free_pages failed, fall back to vmalloc
3542 	 */
3543 	buffer = vzalloc((1 << order) * PAGE_SIZE);
3544 
3545 	if (buffer)
3546 		return buffer;
3547 
3548 	/*
3549 	 * vmalloc failed, lets dig into swap here
3550 	 */
3551 	gfp_flags &= ~__GFP_NORETRY;
3552 	buffer = (char *)__get_free_pages(gfp_flags, order);
3553 	if (buffer)
3554 		return buffer;
3555 
3556 	/*
3557 	 * complete and utter failure
3558 	 */
3559 	return NULL;
3560 }
3561 
alloc_pg_vec(struct tpacket_req * req,int order)3562 static struct pgv *alloc_pg_vec(struct tpacket_req *req, int order)
3563 {
3564 	unsigned int block_nr = req->tp_block_nr;
3565 	struct pgv *pg_vec;
3566 	int i;
3567 
3568 	pg_vec = kcalloc(block_nr, sizeof(struct pgv), GFP_KERNEL);
3569 	if (unlikely(!pg_vec))
3570 		goto out;
3571 
3572 	for (i = 0; i < block_nr; i++) {
3573 		pg_vec[i].buffer = alloc_one_pg_vec_page(order);
3574 		if (unlikely(!pg_vec[i].buffer))
3575 			goto out_free_pgvec;
3576 	}
3577 
3578 out:
3579 	return pg_vec;
3580 
3581 out_free_pgvec:
3582 	free_pg_vec(pg_vec, order, block_nr);
3583 	pg_vec = NULL;
3584 	goto out;
3585 }
3586 
packet_set_ring(struct sock * sk,union tpacket_req_u * req_u,int closing,int tx_ring)3587 static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
3588 		int closing, int tx_ring)
3589 {
3590 	struct pgv *pg_vec = NULL;
3591 	struct packet_sock *po = pkt_sk(sk);
3592 	int was_running, order = 0;
3593 	struct packet_ring_buffer *rb;
3594 	struct sk_buff_head *rb_queue;
3595 	__be16 num;
3596 	int err = -EINVAL;
3597 	/* Added to avoid minimal code churn */
3598 	struct tpacket_req *req = &req_u->req;
3599 
3600 	lock_sock(sk);
3601 	/* Opening a Tx-ring is NOT supported in TPACKET_V3 */
3602 	if (!closing && tx_ring && (po->tp_version > TPACKET_V2)) {
3603 		WARN(1, "Tx-ring is not supported.\n");
3604 		goto out;
3605 	}
3606 
3607 	rb = tx_ring ? &po->tx_ring : &po->rx_ring;
3608 	rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue;
3609 
3610 	err = -EBUSY;
3611 	if (!closing) {
3612 		if (atomic_read(&po->mapped))
3613 			goto out;
3614 		if (atomic_read(&rb->pending))
3615 			goto out;
3616 	}
3617 
3618 	if (req->tp_block_nr) {
3619 		/* Sanity tests and some calculations */
3620 		err = -EBUSY;
3621 		if (unlikely(rb->pg_vec))
3622 			goto out;
3623 
3624 		switch (po->tp_version) {
3625 		case TPACKET_V1:
3626 			po->tp_hdrlen = TPACKET_HDRLEN;
3627 			break;
3628 		case TPACKET_V2:
3629 			po->tp_hdrlen = TPACKET2_HDRLEN;
3630 			break;
3631 		case TPACKET_V3:
3632 			po->tp_hdrlen = TPACKET3_HDRLEN;
3633 			break;
3634 		}
3635 
3636 		err = -EINVAL;
3637 		if (unlikely((int)req->tp_block_size <= 0))
3638 			goto out;
3639 		if (unlikely(req->tp_block_size & (PAGE_SIZE - 1)))
3640 			goto out;
3641 		if (po->tp_version >= TPACKET_V3 &&
3642 		    req->tp_block_size <=
3643 			  BLK_PLUS_PRIV((u64)req_u->req3.tp_sizeof_priv))
3644 			goto out;
3645 		if (unlikely(req->tp_frame_size < po->tp_hdrlen +
3646 					po->tp_reserve))
3647 			goto out;
3648 		if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1)))
3649 			goto out;
3650 
3651 		rb->frames_per_block = req->tp_block_size/req->tp_frame_size;
3652 		if (unlikely(rb->frames_per_block <= 0))
3653 			goto out;
3654 		if (unlikely(req->tp_block_size > UINT_MAX / req->tp_block_nr))
3655 			goto out;
3656 		if (unlikely((rb->frames_per_block * req->tp_block_nr) !=
3657 					req->tp_frame_nr))
3658 			goto out;
3659 
3660 		err = -ENOMEM;
3661 		order = get_order(req->tp_block_size);
3662 		pg_vec = alloc_pg_vec(req, order);
3663 		if (unlikely(!pg_vec))
3664 			goto out;
3665 		switch (po->tp_version) {
3666 		case TPACKET_V3:
3667 		/* Transmit path is not supported. We checked
3668 		 * it above but just being paranoid
3669 		 */
3670 			if (!tx_ring)
3671 				init_prb_bdqc(po, rb, pg_vec, req_u, tx_ring);
3672 				break;
3673 		default:
3674 			break;
3675 		}
3676 	}
3677 	/* Done */
3678 	else {
3679 		err = -EINVAL;
3680 		if (unlikely(req->tp_frame_nr))
3681 			goto out;
3682 	}
3683 
3684 
3685 	/* Detach socket from network */
3686 	spin_lock(&po->bind_lock);
3687 	was_running = po->running;
3688 	num = po->num;
3689 	if (was_running) {
3690 		po->num = 0;
3691 		__unregister_prot_hook(sk, false);
3692 	}
3693 	spin_unlock(&po->bind_lock);
3694 
3695 	synchronize_net();
3696 
3697 	err = -EBUSY;
3698 	mutex_lock(&po->pg_vec_lock);
3699 	if (closing || atomic_read(&po->mapped) == 0) {
3700 		err = 0;
3701 		spin_lock_bh(&rb_queue->lock);
3702 		swap(rb->pg_vec, pg_vec);
3703 		rb->frame_max = (req->tp_frame_nr - 1);
3704 		rb->head = 0;
3705 		rb->frame_size = req->tp_frame_size;
3706 		spin_unlock_bh(&rb_queue->lock);
3707 
3708 		swap(rb->pg_vec_order, order);
3709 		swap(rb->pg_vec_len, req->tp_block_nr);
3710 
3711 		rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE;
3712 		po->prot_hook.func = (po->rx_ring.pg_vec) ?
3713 						tpacket_rcv : packet_rcv;
3714 		skb_queue_purge(rb_queue);
3715 		if (atomic_read(&po->mapped))
3716 			pr_err("packet_mmap: vma is busy: %d\n",
3717 			       atomic_read(&po->mapped));
3718 	}
3719 	mutex_unlock(&po->pg_vec_lock);
3720 
3721 	spin_lock(&po->bind_lock);
3722 	if (was_running) {
3723 		po->num = num;
3724 		register_prot_hook(sk);
3725 	}
3726 	spin_unlock(&po->bind_lock);
3727 	if (closing && (po->tp_version > TPACKET_V2)) {
3728 		/* Because we don't support block-based V3 on tx-ring */
3729 		if (!tx_ring)
3730 			prb_shutdown_retire_blk_timer(po, tx_ring, rb_queue);
3731 	}
3732 
3733 	if (pg_vec)
3734 		free_pg_vec(pg_vec, order, req->tp_block_nr);
3735 out:
3736 	release_sock(sk);
3737 	return err;
3738 }
3739 
packet_mmap(struct file * file,struct socket * sock,struct vm_area_struct * vma)3740 static int packet_mmap(struct file *file, struct socket *sock,
3741 		struct vm_area_struct *vma)
3742 {
3743 	struct sock *sk = sock->sk;
3744 	struct packet_sock *po = pkt_sk(sk);
3745 	unsigned long size, expected_size;
3746 	struct packet_ring_buffer *rb;
3747 	unsigned long start;
3748 	int err = -EINVAL;
3749 	int i;
3750 
3751 	if (vma->vm_pgoff)
3752 		return -EINVAL;
3753 
3754 	mutex_lock(&po->pg_vec_lock);
3755 
3756 	expected_size = 0;
3757 	for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
3758 		if (rb->pg_vec) {
3759 			expected_size += rb->pg_vec_len
3760 						* rb->pg_vec_pages
3761 						* PAGE_SIZE;
3762 		}
3763 	}
3764 
3765 	if (expected_size == 0)
3766 		goto out;
3767 
3768 	size = vma->vm_end - vma->vm_start;
3769 	if (size != expected_size)
3770 		goto out;
3771 
3772 	start = vma->vm_start;
3773 	for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
3774 		if (rb->pg_vec == NULL)
3775 			continue;
3776 
3777 		for (i = 0; i < rb->pg_vec_len; i++) {
3778 			struct page *page;
3779 			void *kaddr = rb->pg_vec[i].buffer;
3780 			int pg_num;
3781 
3782 			for (pg_num = 0; pg_num < rb->pg_vec_pages; pg_num++) {
3783 				page = pgv_to_page(kaddr);
3784 				err = vm_insert_page(vma, start, page);
3785 				if (unlikely(err))
3786 					goto out;
3787 				start += PAGE_SIZE;
3788 				kaddr += PAGE_SIZE;
3789 			}
3790 		}
3791 	}
3792 
3793 	atomic_inc(&po->mapped);
3794 	vma->vm_ops = &packet_mmap_ops;
3795 	err = 0;
3796 
3797 out:
3798 	mutex_unlock(&po->pg_vec_lock);
3799 	return err;
3800 }
3801 
3802 static const struct proto_ops packet_ops_spkt = {
3803 	.family =	PF_PACKET,
3804 	.owner =	THIS_MODULE,
3805 	.release =	packet_release,
3806 	.bind =		packet_bind_spkt,
3807 	.connect =	sock_no_connect,
3808 	.socketpair =	sock_no_socketpair,
3809 	.accept =	sock_no_accept,
3810 	.getname =	packet_getname_spkt,
3811 	.poll =		datagram_poll,
3812 	.ioctl =	packet_ioctl,
3813 	.listen =	sock_no_listen,
3814 	.shutdown =	sock_no_shutdown,
3815 	.setsockopt =	sock_no_setsockopt,
3816 	.getsockopt =	sock_no_getsockopt,
3817 	.sendmsg =	packet_sendmsg_spkt,
3818 	.recvmsg =	packet_recvmsg,
3819 	.mmap =		sock_no_mmap,
3820 	.sendpage =	sock_no_sendpage,
3821 };
3822 
3823 static const struct proto_ops packet_ops = {
3824 	.family =	PF_PACKET,
3825 	.owner =	THIS_MODULE,
3826 	.release =	packet_release,
3827 	.bind =		packet_bind,
3828 	.connect =	sock_no_connect,
3829 	.socketpair =	sock_no_socketpair,
3830 	.accept =	sock_no_accept,
3831 	.getname =	packet_getname,
3832 	.poll =		packet_poll,
3833 	.ioctl =	packet_ioctl,
3834 	.listen =	sock_no_listen,
3835 	.shutdown =	sock_no_shutdown,
3836 	.setsockopt =	packet_setsockopt,
3837 	.getsockopt =	packet_getsockopt,
3838 	.sendmsg =	packet_sendmsg,
3839 	.recvmsg =	packet_recvmsg,
3840 	.mmap =		packet_mmap,
3841 	.sendpage =	sock_no_sendpage,
3842 };
3843 
3844 static const struct net_proto_family packet_family_ops = {
3845 	.family =	PF_PACKET,
3846 	.create =	packet_create,
3847 	.owner	=	THIS_MODULE,
3848 };
3849 
3850 static struct notifier_block packet_netdev_notifier = {
3851 	.notifier_call =	packet_notifier,
3852 };
3853 
3854 #ifdef CONFIG_PROC_FS
3855 
packet_seq_start(struct seq_file * seq,loff_t * pos)3856 static void *packet_seq_start(struct seq_file *seq, loff_t *pos)
3857 	__acquires(RCU)
3858 {
3859 	struct net *net = seq_file_net(seq);
3860 
3861 	rcu_read_lock();
3862 	return seq_hlist_start_head_rcu(&net->packet.sklist, *pos);
3863 }
3864 
packet_seq_next(struct seq_file * seq,void * v,loff_t * pos)3865 static void *packet_seq_next(struct seq_file *seq, void *v, loff_t *pos)
3866 {
3867 	struct net *net = seq_file_net(seq);
3868 	return seq_hlist_next_rcu(v, &net->packet.sklist, pos);
3869 }
3870 
packet_seq_stop(struct seq_file * seq,void * v)3871 static void packet_seq_stop(struct seq_file *seq, void *v)
3872 	__releases(RCU)
3873 {
3874 	rcu_read_unlock();
3875 }
3876 
packet_seq_show(struct seq_file * seq,void * v)3877 static int packet_seq_show(struct seq_file *seq, void *v)
3878 {
3879 	if (v == SEQ_START_TOKEN)
3880 		seq_puts(seq, "sk       RefCnt Type Proto  Iface R Rmem   User   Inode\n");
3881 	else {
3882 		struct sock *s = sk_entry(v);
3883 		const struct packet_sock *po = pkt_sk(s);
3884 
3885 		seq_printf(seq,
3886 			   "%pK %-6d %-4d %04x   %-5d %1d %-6u %-6u %-6lu\n",
3887 			   s,
3888 			   atomic_read(&s->sk_refcnt),
3889 			   s->sk_type,
3890 			   ntohs(po->num),
3891 			   po->ifindex,
3892 			   po->running,
3893 			   atomic_read(&s->sk_rmem_alloc),
3894 			   from_kuid_munged(seq_user_ns(seq), sock_i_uid(s)),
3895 			   sock_i_ino(s));
3896 	}
3897 
3898 	return 0;
3899 }
3900 
3901 static const struct seq_operations packet_seq_ops = {
3902 	.start	= packet_seq_start,
3903 	.next	= packet_seq_next,
3904 	.stop	= packet_seq_stop,
3905 	.show	= packet_seq_show,
3906 };
3907 
packet_seq_open(struct inode * inode,struct file * file)3908 static int packet_seq_open(struct inode *inode, struct file *file)
3909 {
3910 	return seq_open_net(inode, file, &packet_seq_ops,
3911 			    sizeof(struct seq_net_private));
3912 }
3913 
3914 static const struct file_operations packet_seq_fops = {
3915 	.owner		= THIS_MODULE,
3916 	.open		= packet_seq_open,
3917 	.read		= seq_read,
3918 	.llseek		= seq_lseek,
3919 	.release	= seq_release_net,
3920 };
3921 
3922 #endif
3923 
packet_net_init(struct net * net)3924 static int __net_init packet_net_init(struct net *net)
3925 {
3926 	mutex_init(&net->packet.sklist_lock);
3927 	INIT_HLIST_HEAD(&net->packet.sklist);
3928 
3929 	if (!proc_create("packet", 0, net->proc_net, &packet_seq_fops))
3930 		return -ENOMEM;
3931 
3932 	return 0;
3933 }
3934 
packet_net_exit(struct net * net)3935 static void __net_exit packet_net_exit(struct net *net)
3936 {
3937 	remove_proc_entry("packet", net->proc_net);
3938 }
3939 
3940 static struct pernet_operations packet_net_ops = {
3941 	.init = packet_net_init,
3942 	.exit = packet_net_exit,
3943 };
3944 
3945 
packet_exit(void)3946 static void __exit packet_exit(void)
3947 {
3948 	unregister_netdevice_notifier(&packet_netdev_notifier);
3949 	unregister_pernet_subsys(&packet_net_ops);
3950 	sock_unregister(PF_PACKET);
3951 	proto_unregister(&packet_proto);
3952 }
3953 
packet_init(void)3954 static int __init packet_init(void)
3955 {
3956 	int rc = proto_register(&packet_proto, 0);
3957 
3958 	if (rc != 0)
3959 		goto out;
3960 
3961 	sock_register(&packet_family_ops);
3962 	register_pernet_subsys(&packet_net_ops);
3963 	register_netdevice_notifier(&packet_netdev_notifier);
3964 out:
3965 	return rc;
3966 }
3967 
3968 module_init(packet_init);
3969 module_exit(packet_exit);
3970 MODULE_LICENSE("GPL");
3971 MODULE_ALIAS_NETPROTO(PF_PACKET);
3972