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