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