1 // SPDX-License-Identifier: GPL-2.0-or-later
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.
7 * PACKET - implements raw packet sockets.
10 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
11 * Alan Cox, <gw4pts@gw4pts.ampr.org>
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
43 * Johann Baudy : Added TX RING.
44 * Chetan Loke : Implemented TPACKET_V3 block abstraction
46 * Copyright (C) 2011, <lokec@ccs.neu.edu>
49 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
51 #include <linux/ethtool.h>
52 #include <linux/types.h>
54 #include <linux/capability.h>
55 #include <linux/fcntl.h>
56 #include <linux/socket.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>
68 #include <net/protocol.h>
69 #include <linux/skbuff.h>
71 #include <linux/errno.h>
72 #include <linux/timer.h>
73 #include <linux/uaccess.h>
74 #include <asm/ioctls.h>
76 #include <asm/cacheflush.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>
90 #include <net/inet_common.h>
92 #include <linux/bpf.h>
93 #include <net/compat.h>
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
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
108 - packet socket receives packets with pulled ll header,
109 so that SOCK_RAW should push it back.
114 Incoming, dev_has_header(dev) == true
115 mac_header -> ll header
118 Outgoing, dev_has_header(dev) == true
119 mac_header -> ll header
122 Incoming, dev_has_header(dev) == false
124 However drivers often make it point to the ll header.
125 This is incorrect because the ll header should be invisible to us.
128 Outgoing, dev_has_header(dev) == false
129 mac_header -> data. ll header is invisible to us.
133 If dev_has_header(dev) == false we are unable to restore the ll header,
134 because it is invisible to us.
140 dev_has_header(dev) == true
141 mac_header -> ll header
144 dev_has_header(dev) == false (ll header is invisible to us)
148 We should set network_header on output to the correct position,
149 packet classifier depends on it.
152 /* Private packet socket structures. */
154 /* identical to struct packet_mreq except it has
155 * a longer address field.
157 struct packet_mreq_max {
159 unsigned short mr_type;
160 unsigned short mr_alen;
161 unsigned char mr_address[MAX_ADDR_LEN];
165 struct tpacket_hdr *h1;
166 struct tpacket2_hdr *h2;
167 struct tpacket3_hdr *h3;
171 static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
172 int closing, int tx_ring);
174 #define V3_ALIGNMENT (8)
176 #define BLK_HDR_LEN (ALIGN(sizeof(struct tpacket_block_desc), V3_ALIGNMENT))
178 #define BLK_PLUS_PRIV(sz_of_priv) \
179 (BLK_HDR_LEN + ALIGN((sz_of_priv), V3_ALIGNMENT))
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)
189 static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
190 struct packet_type *pt, struct net_device *orig_dev);
192 static void *packet_previous_frame(struct packet_sock *po,
193 struct packet_ring_buffer *rb,
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);
214 struct packet_skb_cb {
216 struct sockaddr_pkt pkt;
218 /* Trick: alias skb original length with
219 * ll.sll_family and ll.protocol in order
222 unsigned int origlen;
223 struct sockaddr_ll ll;
228 #define vio_le() virtio_legacy_is_little_endian()
230 #define PACKET_SKB_CB(__skb) ((struct packet_skb_cb *)((__skb)->cb))
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)
241 static void __fanout_unlink(struct sock *sk, struct packet_sock *po);
242 static void __fanout_link(struct sock *sk, struct packet_sock *po);
244 static int packet_direct_xmit(struct sk_buff *skb)
246 return dev_direct_xmit(skb, packet_pick_tx_queue(skb));
249 static struct net_device *packet_cached_dev_get(struct packet_sock *po)
251 struct net_device *dev;
254 dev = rcu_dereference(po->cached_dev);
261 static void packet_cached_dev_assign(struct packet_sock *po,
262 struct net_device *dev)
264 rcu_assign_pointer(po->cached_dev, dev);
267 static void packet_cached_dev_reset(struct packet_sock *po)
269 RCU_INIT_POINTER(po->cached_dev, NULL);
272 static bool packet_use_direct_xmit(const struct packet_sock *po)
274 /* Paired with WRITE_ONCE() in packet_setsockopt() */
275 return READ_ONCE(po->xmit) == packet_direct_xmit;
278 static u16 packet_pick_tx_queue(struct sk_buff *skb)
280 struct net_device *dev = skb->dev;
281 const struct net_device_ops *ops = dev->netdev_ops;
282 int cpu = raw_smp_processor_id();
286 skb->sender_cpu = cpu + 1;
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);
293 queue_index = netdev_pick_tx(dev, skb, NULL);
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()).
303 static void __register_prot_hook(struct sock *sk)
305 struct packet_sock *po = pkt_sk(sk);
309 __fanout_link(sk, po);
311 dev_add_pack(&po->prot_hook);
318 static void register_prot_hook(struct sock *sk)
320 lockdep_assert_held_once(&pkt_sk(sk)->bind_lock);
321 __register_prot_hook(sk);
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.
330 static void __unregister_prot_hook(struct sock *sk, bool sync)
332 struct packet_sock *po = pkt_sk(sk);
334 lockdep_assert_held_once(&po->bind_lock);
339 __fanout_unlink(sk, po);
341 __dev_remove_pack(&po->prot_hook);
346 spin_unlock(&po->bind_lock);
348 spin_lock(&po->bind_lock);
352 static void unregister_prot_hook(struct sock *sk, bool sync)
354 struct packet_sock *po = pkt_sk(sk);
357 __unregister_prot_hook(sk, sync);
360 static inline struct page * __pure pgv_to_page(void *addr)
362 if (is_vmalloc_addr(addr))
363 return vmalloc_to_page(addr);
364 return virt_to_page(addr);
367 static void __packet_set_status(struct packet_sock *po, void *frame, int status)
369 union tpacket_uhdr h;
371 /* WRITE_ONCE() are paired with READ_ONCE() in __packet_get_status */
374 switch (po->tp_version) {
376 WRITE_ONCE(h.h1->tp_status, status);
377 flush_dcache_page(pgv_to_page(&h.h1->tp_status));
380 WRITE_ONCE(h.h2->tp_status, status);
381 flush_dcache_page(pgv_to_page(&h.h2->tp_status));
384 WRITE_ONCE(h.h3->tp_status, status);
385 flush_dcache_page(pgv_to_page(&h.h3->tp_status));
388 WARN(1, "TPACKET version not supported.\n");
395 static int __packet_get_status(const struct packet_sock *po, void *frame)
397 union tpacket_uhdr h;
401 /* READ_ONCE() are paired with WRITE_ONCE() in __packet_set_status */
404 switch (po->tp_version) {
406 flush_dcache_page(pgv_to_page(&h.h1->tp_status));
407 return READ_ONCE(h.h1->tp_status);
409 flush_dcache_page(pgv_to_page(&h.h2->tp_status));
410 return READ_ONCE(h.h2->tp_status);
412 flush_dcache_page(pgv_to_page(&h.h3->tp_status));
413 return READ_ONCE(h.h3->tp_status);
415 WARN(1, "TPACKET version not supported.\n");
421 static __u32 tpacket_get_timestamp(struct sk_buff *skb, struct timespec64 *ts,
424 struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);
427 (flags & SOF_TIMESTAMPING_RAW_HARDWARE) &&
428 ktime_to_timespec64_cond(shhwtstamps->hwtstamp, ts))
429 return TP_STATUS_TS_RAW_HARDWARE;
431 if ((flags & SOF_TIMESTAMPING_SOFTWARE) &&
432 ktime_to_timespec64_cond(skb->tstamp, ts))
433 return TP_STATUS_TS_SOFTWARE;
438 static __u32 __packet_set_timestamp(struct packet_sock *po, void *frame,
441 union tpacket_uhdr h;
442 struct timespec64 ts;
445 if (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp)))
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
456 switch (po->tp_version) {
458 h.h1->tp_sec = ts.tv_sec;
459 h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
462 h.h2->tp_sec = ts.tv_sec;
463 h.h2->tp_nsec = ts.tv_nsec;
466 h.h3->tp_sec = ts.tv_sec;
467 h.h3->tp_nsec = ts.tv_nsec;
470 WARN(1, "TPACKET version not supported.\n");
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));
481 static void *packet_lookup_frame(const struct packet_sock *po,
482 const struct packet_ring_buffer *rb,
483 unsigned int position,
486 unsigned int pg_vec_pos, frame_offset;
487 union tpacket_uhdr h;
489 pg_vec_pos = position / rb->frames_per_block;
490 frame_offset = position % rb->frames_per_block;
492 h.raw = rb->pg_vec[pg_vec_pos].buffer +
493 (frame_offset * rb->frame_size);
495 if (status != __packet_get_status(po, h.raw))
501 static void *packet_current_frame(struct packet_sock *po,
502 struct packet_ring_buffer *rb,
505 return packet_lookup_frame(po, rb, rb->head, status);
508 static void prb_del_retire_blk_timer(struct tpacket_kbdq_core *pkc)
510 del_timer_sync(&pkc->retire_blk_timer);
513 static void prb_shutdown_retire_blk_timer(struct packet_sock *po,
514 struct sk_buff_head *rb_queue)
516 struct tpacket_kbdq_core *pkc;
518 pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
520 spin_lock_bh(&rb_queue->lock);
521 pkc->delete_blk_timer = 1;
522 spin_unlock_bh(&rb_queue->lock);
524 prb_del_retire_blk_timer(pkc);
527 static void prb_setup_retire_blk_timer(struct packet_sock *po)
529 struct tpacket_kbdq_core *pkc;
531 pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
532 timer_setup(&pkc->retire_blk_timer, prb_retire_rx_blk_timer_expired,
534 pkc->retire_blk_timer.expires = jiffies;
537 static int prb_calc_retire_blk_tmo(struct packet_sock *po,
538 int blk_size_in_bytes)
540 struct net_device *dev;
541 unsigned int mbits, div;
542 struct ethtool_link_ksettings ecmd;
546 dev = __dev_get_by_index(sock_net(&po->sk), po->ifindex);
547 if (unlikely(!dev)) {
549 return DEFAULT_PRB_RETIRE_TOV;
551 err = __ethtool_get_link_ksettings(dev, &ecmd);
554 return DEFAULT_PRB_RETIRE_TOV;
556 /* If the link speed is so slow you don't really
557 * need to worry about perf anyways
559 if (ecmd.base.speed < SPEED_1000 ||
560 ecmd.base.speed == SPEED_UNKNOWN)
561 return DEFAULT_PRB_RETIRE_TOV;
563 div = ecmd.base.speed / 1000;
564 mbits = (blk_size_in_bytes * 8) / (1024 * 1024);
574 static void prb_init_ft_ops(struct tpacket_kbdq_core *p1,
575 union tpacket_req_u *req_u)
577 p1->feature_req_word = req_u->req3.tp_feature_req_word;
580 static void init_prb_bdqc(struct packet_sock *po,
581 struct packet_ring_buffer *rb,
583 union tpacket_req_u *req_u)
585 struct tpacket_kbdq_core *p1 = GET_PBDQC_FROM_RB(rb);
586 struct tpacket_block_desc *pbd;
588 memset(p1, 0x0, sizeof(*p1));
590 p1->knxt_seq_num = 1;
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;
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);
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);
615 /* Do NOT update the last_blk_num first.
616 * Assumes sk_buff_head lock is held.
618 static void _prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core *pkc)
620 mod_timer(&pkc->retire_blk_timer,
621 jiffies + pkc->tov_in_jiffies);
622 pkc->last_kactive_blk_num = pkc->kactive_blk_num;
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.
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.
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.
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.
648 static void prb_retire_rx_blk_timer_expired(struct timer_list *t)
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);
654 struct tpacket_block_desc *pbd;
656 spin_lock(&po->sk.sk_receive_queue.lock);
658 frozen = prb_queue_frozen(pkc);
659 pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
661 if (unlikely(pkc->delete_blk_timer))
664 /* We only need to plug the race when the block is partially filled.
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
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);
679 if (pkc->last_kactive_blk_num == pkc->kactive_blk_num) {
681 if (!BLOCK_NUM_PKTS(pbd)) {
682 /* An empty block. Just refresh the timer. */
685 prb_retire_current_block(pkc, po, TP_STATUS_BLK_TMO);
686 if (!prb_dispatch_next_block(pkc, po))
691 /* Case 1. Queue was frozen because user-space was
694 if (prb_curr_blk_in_use(pbd)) {
696 * Ok, user-space is still behind.
697 * So just refresh the timer.
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.
708 prb_open_block(pkc, pbd);
715 _prb_refresh_rx_retire_blk_timer(pkc);
718 spin_unlock(&po->sk.sk_receive_queue.lock);
721 static void prb_flush_block(struct tpacket_kbdq_core *pkc1,
722 struct tpacket_block_desc *pbd1, __u32 status)
724 /* Flush everything minus the block header */
726 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
731 /* Skip the block header(we know header WILL fit in 4K) */
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));
741 /* Now update the block status. */
743 BLOCK_STATUS(pbd1) = status;
745 /* Flush the block header */
747 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
749 flush_dcache_page(pgv_to_page(start));
759 * 2) Increment active_blk_num
761 * Note:We DONT refresh the timer on purpose.
762 * Because almost always the next block will be opened.
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)
768 __u32 status = TP_STATUS_USER | stat;
770 struct tpacket3_hdr *last_pkt;
771 struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
772 struct sock *sk = &po->sk;
774 if (atomic_read(&po->tp_drops))
775 status |= TP_STATUS_LOSING;
777 last_pkt = (struct tpacket3_hdr *)pkc1->prev;
778 last_pkt->tp_next_offset = 0;
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;
785 /* Ok, we tmo'd - so get the current time.
787 * It shouldn't really happen as we don't close empty
788 * blocks. See prb_retire_rx_blk_timer_expired().
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;
798 /* Flush the block */
799 prb_flush_block(pkc1, pbd1, status);
801 sk->sk_data_ready(sk);
803 pkc1->kactive_blk_num = GET_NEXT_PRB_BLK_NUM(pkc1);
806 static void prb_thaw_queue(struct tpacket_kbdq_core *pkc)
808 pkc->reset_pending_on_curr_blk = 0;
812 * Side effect of opening a block:
814 * 1) prb_queue is thawed.
815 * 2) retire_blk_timer is refreshed.
818 static void prb_open_block(struct tpacket_kbdq_core *pkc1,
819 struct tpacket_block_desc *pbd1)
821 struct timespec64 ts;
822 struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
826 /* We could have just memset this but we will lose the
827 * flexibility of making the priv area sticky
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);
834 ktime_get_real_ts64(&ts);
836 h1->ts_first_pkt.ts_sec = ts.tv_sec;
837 h1->ts_first_pkt.ts_nsec = ts.tv_nsec;
839 pkc1->pkblk_start = (char *)pbd1;
840 pkc1->nxt_offset = pkc1->pkblk_start + BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
842 BLOCK_O2FP(pbd1) = (__u32)BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
843 BLOCK_O2PRIV(pbd1) = BLK_HDR_LEN;
845 pbd1->version = pkc1->version;
846 pkc1->prev = pkc1->nxt_offset;
847 pkc1->pkblk_end = pkc1->pkblk_start + pkc1->kblk_size;
849 prb_thaw_queue(pkc1);
850 _prb_refresh_rx_retire_blk_timer(pkc1);
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'.
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.
878 static void prb_freeze_queue(struct tpacket_kbdq_core *pkc,
879 struct packet_sock *po)
881 pkc->reset_pending_on_curr_blk = 1;
882 po->stats.stats3.tp_freeze_q_cnt++;
885 #define TOTAL_PKT_LEN_INCL_ALIGN(length) (ALIGN((length), V3_ALIGNMENT))
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.
893 static void *prb_dispatch_next_block(struct tpacket_kbdq_core *pkc,
894 struct packet_sock *po)
896 struct tpacket_block_desc *pbd;
900 /* 1. Get current block num */
901 pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
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);
911 * open this block and return the offset where the first packet
912 * needs to get stored.
914 prb_open_block(pkc, pbd);
915 return (void *)pkc->nxt_offset;
918 static void prb_retire_current_block(struct tpacket_kbdq_core *pkc,
919 struct packet_sock *po, unsigned int status)
921 struct tpacket_block_desc *pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
923 /* retire/close the current block */
924 if (likely(TP_STATUS_KERNEL == BLOCK_STATUS(pbd))) {
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()
931 * We don't need to worry about the TMO case because
932 * the timer-handler already handled this case.
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);
939 prb_close_block(pkc, pbd, po, status);
944 static int prb_curr_blk_in_use(struct tpacket_block_desc *pbd)
946 return TP_STATUS_USER & BLOCK_STATUS(pbd);
949 static int prb_queue_frozen(struct tpacket_kbdq_core *pkc)
951 return pkc->reset_pending_on_curr_blk;
954 static void prb_clear_blk_fill_status(struct packet_ring_buffer *rb)
955 __releases(&pkc->blk_fill_in_prog_lock)
957 struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(rb);
959 read_unlock(&pkc->blk_fill_in_prog_lock);
962 static void prb_fill_rxhash(struct tpacket_kbdq_core *pkc,
963 struct tpacket3_hdr *ppd)
965 ppd->hv1.tp_rxhash = skb_get_hash(pkc->skb);
968 static void prb_clear_rxhash(struct tpacket_kbdq_core *pkc,
969 struct tpacket3_hdr *ppd)
971 ppd->hv1.tp_rxhash = 0;
974 static void prb_fill_vlan_info(struct tpacket_kbdq_core *pkc,
975 struct tpacket3_hdr *ppd)
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;
982 ppd->hv1.tp_vlan_tci = 0;
983 ppd->hv1.tp_vlan_tpid = 0;
984 ppd->tp_status = TP_STATUS_AVAILABLE;
988 static void prb_run_all_ft_ops(struct tpacket_kbdq_core *pkc,
989 struct tpacket3_hdr *ppd)
991 ppd->hv1.tp_padding = 0;
992 prb_fill_vlan_info(pkc, ppd);
994 if (pkc->feature_req_word & TP_FT_REQ_FILL_RXHASH)
995 prb_fill_rxhash(pkc, ppd);
997 prb_clear_rxhash(pkc, ppd);
1000 static void prb_fill_curr_block(char *curr,
1001 struct tpacket_kbdq_core *pkc,
1002 struct tpacket_block_desc *pbd,
1004 __acquires(&pkc->blk_fill_in_prog_lock)
1006 struct tpacket3_hdr *ppd;
1008 ppd = (struct tpacket3_hdr *)curr;
1009 ppd->tp_next_offset = TOTAL_PKT_LEN_INCL_ALIGN(len);
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);
1018 /* Assumes caller has the sk->rx_queue.lock */
1019 static void *__packet_lookup_frame_in_block(struct packet_sock *po,
1020 struct sk_buff *skb,
1024 struct tpacket_kbdq_core *pkc;
1025 struct tpacket_block_desc *pbd;
1028 pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
1029 pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
1031 /* Queue is frozen when user space is lagging behind */
1032 if (prb_queue_frozen(pkc)) {
1034 * Check if that last block which caused the queue to freeze,
1035 * is still in_use by user-space.
1037 if (prb_curr_blk_in_use(pbd)) {
1038 /* Can't record this packet */
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.
1047 prb_open_block(pkc, pbd);
1052 curr = pkc->nxt_offset;
1054 end = (char *)pbd + pkc->kblk_size;
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;
1062 /* Ok, close the current block */
1063 prb_retire_current_block(pkc, po, 0);
1065 /* Now, try to dispatch the next block */
1066 curr = (char *)prb_dispatch_next_block(pkc, po);
1068 pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
1069 prb_fill_curr_block(curr, pkc, pbd, len);
1070 return (void *)curr;
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.
1080 static void *packet_current_rx_frame(struct packet_sock *po,
1081 struct sk_buff *skb,
1082 int status, unsigned int len)
1085 switch (po->tp_version) {
1088 curr = packet_lookup_frame(po, &po->rx_ring,
1089 po->rx_ring.head, status);
1092 return __packet_lookup_frame_in_block(po, skb, len);
1094 WARN(1, "TPACKET version not supported\n");
1100 static void *prb_lookup_block(const struct packet_sock *po,
1101 const struct packet_ring_buffer *rb,
1105 struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(rb);
1106 struct tpacket_block_desc *pbd = GET_PBLOCK_DESC(pkc, idx);
1108 if (status != BLOCK_STATUS(pbd))
1113 static int prb_previous_blk_num(struct packet_ring_buffer *rb)
1116 if (rb->prb_bdqc.kactive_blk_num)
1117 prev = rb->prb_bdqc.kactive_blk_num-1;
1119 prev = rb->prb_bdqc.knum_blocks-1;
1123 /* Assumes caller has held the rx_queue.lock */
1124 static void *__prb_previous_block(struct packet_sock *po,
1125 struct packet_ring_buffer *rb,
1128 unsigned int previous = prb_previous_blk_num(rb);
1129 return prb_lookup_block(po, rb, previous, status);
1132 static void *packet_previous_rx_frame(struct packet_sock *po,
1133 struct packet_ring_buffer *rb,
1136 if (po->tp_version <= TPACKET_V2)
1137 return packet_previous_frame(po, rb, status);
1139 return __prb_previous_block(po, rb, status);
1142 static void packet_increment_rx_head(struct packet_sock *po,
1143 struct packet_ring_buffer *rb)
1145 switch (po->tp_version) {
1148 return packet_increment_head(rb);
1151 WARN(1, "TPACKET version not supported.\n");
1157 static void *packet_previous_frame(struct packet_sock *po,
1158 struct packet_ring_buffer *rb,
1161 unsigned int previous = rb->head ? rb->head - 1 : rb->frame_max;
1162 return packet_lookup_frame(po, rb, previous, status);
1165 static void packet_increment_head(struct packet_ring_buffer *buff)
1167 buff->head = buff->head != buff->frame_max ? buff->head+1 : 0;
1170 static void packet_inc_pending(struct packet_ring_buffer *rb)
1172 this_cpu_inc(*rb->pending_refcnt);
1175 static void packet_dec_pending(struct packet_ring_buffer *rb)
1177 this_cpu_dec(*rb->pending_refcnt);
1180 static unsigned int packet_read_pending(const struct packet_ring_buffer *rb)
1182 unsigned int refcnt = 0;
1185 /* We don't use pending refcount in rx_ring. */
1186 if (rb->pending_refcnt == NULL)
1189 for_each_possible_cpu(cpu)
1190 refcnt += *per_cpu_ptr(rb->pending_refcnt, cpu);
1195 static int packet_alloc_pending(struct packet_sock *po)
1197 po->rx_ring.pending_refcnt = NULL;
1199 po->tx_ring.pending_refcnt = alloc_percpu(unsigned int);
1200 if (unlikely(po->tx_ring.pending_refcnt == NULL))
1206 static void packet_free_pending(struct packet_sock *po)
1208 free_percpu(po->tx_ring.pending_refcnt);
1211 #define ROOM_POW_OFF 2
1212 #define ROOM_NONE 0x0
1213 #define ROOM_LOW 0x1
1214 #define ROOM_NORMAL 0x2
1216 static bool __tpacket_has_room(const struct packet_sock *po, int pow_off)
1220 len = READ_ONCE(po->rx_ring.frame_max) + 1;
1221 idx = READ_ONCE(po->rx_ring.head);
1223 idx += len >> pow_off;
1226 return packet_lookup_frame(po, &po->rx_ring, idx, TP_STATUS_KERNEL);
1229 static bool __tpacket_v3_has_room(const struct packet_sock *po, int pow_off)
1233 len = READ_ONCE(po->rx_ring.prb_bdqc.knum_blocks);
1234 idx = READ_ONCE(po->rx_ring.prb_bdqc.kactive_blk_num);
1236 idx += len >> pow_off;
1239 return prb_lookup_block(po, &po->rx_ring, idx, TP_STATUS_KERNEL);
1242 static int __packet_rcv_has_room(const struct packet_sock *po,
1243 const struct sk_buff *skb)
1245 const struct sock *sk = &po->sk;
1246 int ret = ROOM_NONE;
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);
1253 if (avail > (rcvbuf >> ROOM_POW_OFF))
1261 if (po->tp_version == TPACKET_V3) {
1262 if (__tpacket_v3_has_room(po, ROOM_POW_OFF))
1264 else if (__tpacket_v3_has_room(po, 0))
1267 if (__tpacket_has_room(po, ROOM_POW_OFF))
1269 else if (__tpacket_has_room(po, 0))
1276 static int packet_rcv_has_room(struct packet_sock *po, struct sk_buff *skb)
1280 ret = __packet_rcv_has_room(po, skb);
1281 pressure = ret != ROOM_NORMAL;
1283 if (READ_ONCE(po->pressure) != pressure)
1284 WRITE_ONCE(po->pressure, pressure);
1289 static void packet_rcv_try_clear_pressure(struct packet_sock *po)
1291 if (READ_ONCE(po->pressure) &&
1292 __packet_rcv_has_room(po, NULL) == ROOM_NORMAL)
1293 WRITE_ONCE(po->pressure, 0);
1296 static void packet_sock_destruct(struct sock *sk)
1298 skb_queue_purge(&sk->sk_error_queue);
1300 WARN_ON(atomic_read(&sk->sk_rmem_alloc));
1301 WARN_ON(refcount_read(&sk->sk_wmem_alloc));
1303 if (!sock_flag(sk, SOCK_DEAD)) {
1304 pr_err("Attempt to release alive packet socket: %p\n", sk);
1308 sk_refcnt_debug_dec(sk);
1311 static bool fanout_flow_is_huge(struct packet_sock *po, struct sk_buff *skb)
1313 u32 *history = po->rollover->history;
1317 rxhash = skb_get_hash(skb);
1318 for (i = 0; i < ROLLOVER_HLEN; i++)
1319 if (READ_ONCE(history[i]) == rxhash)
1322 victim = prandom_u32() % ROLLOVER_HLEN;
1324 /* Avoid dirtying the cache line if possible */
1325 if (READ_ONCE(history[victim]) != rxhash)
1326 WRITE_ONCE(history[victim], rxhash);
1328 return count > (ROLLOVER_HLEN >> 1);
1331 static unsigned int fanout_demux_hash(struct packet_fanout *f,
1332 struct sk_buff *skb,
1335 return reciprocal_scale(__skb_get_hash_symmetric(skb), num);
1338 static unsigned int fanout_demux_lb(struct packet_fanout *f,
1339 struct sk_buff *skb,
1342 unsigned int val = atomic_inc_return(&f->rr_cur);
1347 static unsigned int fanout_demux_cpu(struct packet_fanout *f,
1348 struct sk_buff *skb,
1351 return smp_processor_id() % num;
1354 static unsigned int fanout_demux_rnd(struct packet_fanout *f,
1355 struct sk_buff *skb,
1358 return prandom_u32_max(num);
1361 static unsigned int fanout_demux_rollover(struct packet_fanout *f,
1362 struct sk_buff *skb,
1363 unsigned int idx, bool try_self,
1366 struct packet_sock *po, *po_next, *po_skip = NULL;
1367 unsigned int i, j, room = ROOM_NONE;
1369 po = pkt_sk(rcu_dereference(f->arr[idx]));
1372 room = packet_rcv_has_room(po, skb);
1373 if (room == ROOM_NORMAL ||
1374 (room == ROOM_LOW && !fanout_flow_is_huge(po, skb)))
1379 i = j = min_t(int, po->rollover->sock, num - 1);
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) {
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);
1396 atomic_long_inc(&po->rollover->num_failed);
1400 static unsigned int fanout_demux_qm(struct packet_fanout *f,
1401 struct sk_buff *skb,
1404 return skb_get_queue_mapping(skb) % num;
1407 static unsigned int fanout_demux_bpf(struct packet_fanout *f,
1408 struct sk_buff *skb,
1411 struct bpf_prog *prog;
1412 unsigned int ret = 0;
1415 prog = rcu_dereference(f->bpf_prog);
1417 ret = bpf_prog_run_clear_cb(prog, skb) % num;
1423 static bool fanout_has_flag(struct packet_fanout *f, u16 flag)
1425 return f->flags & (flag >> 8);
1428 static int packet_rcv_fanout(struct sk_buff *skb, struct net_device *dev,
1429 struct packet_type *pt, struct net_device *orig_dev)
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;
1437 if (!net_eq(dev_net(dev), net) || !num) {
1442 if (fanout_has_flag(f, PACKET_FANOUT_FLAG_DEFRAG)) {
1443 skb = ip_check_defrag(net, skb, IP_DEFRAG_AF_PACKET);
1448 case PACKET_FANOUT_HASH:
1450 idx = fanout_demux_hash(f, skb, num);
1452 case PACKET_FANOUT_LB:
1453 idx = fanout_demux_lb(f, skb, num);
1455 case PACKET_FANOUT_CPU:
1456 idx = fanout_demux_cpu(f, skb, num);
1458 case PACKET_FANOUT_RND:
1459 idx = fanout_demux_rnd(f, skb, num);
1461 case PACKET_FANOUT_QM:
1462 idx = fanout_demux_qm(f, skb, num);
1464 case PACKET_FANOUT_ROLLOVER:
1465 idx = fanout_demux_rollover(f, skb, 0, false, num);
1467 case PACKET_FANOUT_CBPF:
1468 case PACKET_FANOUT_EBPF:
1469 idx = fanout_demux_bpf(f, skb, num);
1473 if (fanout_has_flag(f, PACKET_FANOUT_FLAG_ROLLOVER))
1474 idx = fanout_demux_rollover(f, skb, idx, true, num);
1476 po = pkt_sk(rcu_dereference(f->arr[idx]));
1477 return po->prot_hook.func(skb, dev, &po->prot_hook, orig_dev);
1480 DEFINE_MUTEX(fanout_mutex);
1481 EXPORT_SYMBOL_GPL(fanout_mutex);
1482 static LIST_HEAD(fanout_list);
1483 static u16 fanout_next_id;
1485 static void __fanout_link(struct sock *sk, struct packet_sock *po)
1487 struct packet_fanout *f = po->fanout;
1489 spin_lock(&f->lock);
1490 rcu_assign_pointer(f->arr[f->num_members], sk);
1493 if (f->num_members == 1)
1494 dev_add_pack(&f->prot_hook);
1495 spin_unlock(&f->lock);
1498 static void __fanout_unlink(struct sock *sk, struct packet_sock *po)
1500 struct packet_fanout *f = po->fanout;
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)
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)));
1514 if (f->num_members == 0)
1515 __dev_remove_pack(&f->prot_hook);
1516 spin_unlock(&f->lock);
1519 static bool match_fanout_group(struct packet_type *ptype, struct sock *sk)
1521 if (sk->sk_family != PF_PACKET)
1524 return ptype->af_packet_priv == pkt_sk(sk)->fanout;
1527 static void fanout_init_data(struct packet_fanout *f)
1530 case PACKET_FANOUT_LB:
1531 atomic_set(&f->rr_cur, 0);
1533 case PACKET_FANOUT_CBPF:
1534 case PACKET_FANOUT_EBPF:
1535 RCU_INIT_POINTER(f->bpf_prog, NULL);
1540 static void __fanout_set_data_bpf(struct packet_fanout *f, struct bpf_prog *new)
1542 struct bpf_prog *old;
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);
1551 bpf_prog_destroy(old);
1555 static int fanout_set_data_cbpf(struct packet_sock *po, sockptr_t data,
1558 struct bpf_prog *new;
1559 struct sock_fprog fprog;
1562 if (sock_flag(&po->sk, SOCK_FILTER_LOCKED))
1565 ret = copy_bpf_fprog_from_user(&fprog, data, len);
1569 ret = bpf_prog_create_from_user(&new, &fprog, NULL, false);
1573 __fanout_set_data_bpf(po->fanout, new);
1577 static int fanout_set_data_ebpf(struct packet_sock *po, sockptr_t data,
1580 struct bpf_prog *new;
1583 if (sock_flag(&po->sk, SOCK_FILTER_LOCKED))
1585 if (len != sizeof(fd))
1587 if (copy_from_sockptr(&fd, data, len))
1590 new = bpf_prog_get_type(fd, BPF_PROG_TYPE_SOCKET_FILTER);
1592 return PTR_ERR(new);
1594 __fanout_set_data_bpf(po->fanout, new);
1598 static int fanout_set_data(struct packet_sock *po, sockptr_t data,
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);
1611 static void fanout_release_data(struct packet_fanout *f)
1614 case PACKET_FANOUT_CBPF:
1615 case PACKET_FANOUT_EBPF:
1616 __fanout_set_data_bpf(f, NULL);
1620 static bool __fanout_id_is_free(struct sock *sk, u16 candidate_id)
1622 struct packet_fanout *f;
1624 list_for_each_entry(f, &fanout_list, list) {
1625 if (f->id == candidate_id &&
1626 read_pnet(&f->net) == sock_net(sk)) {
1633 static bool fanout_find_new_id(struct sock *sk, u16 *new_id)
1635 u16 id = fanout_next_id;
1638 if (__fanout_id_is_free(sk, id)) {
1640 fanout_next_id = id + 1;
1645 } while (id != fanout_next_id);
1650 static int fanout_add(struct sock *sk, struct fanout_args *args)
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;
1662 case PACKET_FANOUT_ROLLOVER:
1663 if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)
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:
1678 mutex_lock(&fanout_mutex);
1684 if (type == PACKET_FANOUT_ROLLOVER ||
1685 (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)) {
1687 rollover = kzalloc(sizeof(*rollover), GFP_KERNEL);
1690 atomic_long_set(&rollover->num, 0);
1691 atomic_long_set(&rollover->num_huge, 0);
1692 atomic_long_set(&rollover->num_failed, 0);
1695 if (type_flags & PACKET_FANOUT_FLAG_UNIQUEID) {
1700 if (!fanout_find_new_id(sk, &id)) {
1704 /* ephemeral flag for the first socket in the group: drop it */
1705 flags &= ~(PACKET_FANOUT_FLAG_UNIQUEID >> 8);
1709 list_for_each_entry(f, &fanout_list, list) {
1711 read_pnet(&f->net) == sock_net(sk)) {
1718 if (match->flags != flags)
1720 if (args->max_num_members &&
1721 args->max_num_members != match->max_num_members)
1724 if (args->max_num_members > PACKET_FANOUT_MAX)
1726 if (!args->max_num_members)
1727 /* legacy PACKET_FANOUT_MAX */
1728 args->max_num_members = 256;
1730 match = kvzalloc(struct_size(match, arr, args->max_num_members),
1734 write_pnet(&match->net, sock_net(sk));
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);
1753 spin_lock(&po->bind_lock);
1755 match->type == type &&
1756 match->prot_hook.type == po->prot_hook.type &&
1757 match->prot_hook.dev == po->prot_hook.dev) {
1759 if (refcount_read(&match->sk_ref) < match->max_num_members) {
1760 __dev_remove_pack(&po->prot_hook);
1762 /* Paired with packet_setsockopt(PACKET_FANOUT_DATA) */
1763 WRITE_ONCE(po->fanout, match);
1765 po->rollover = rollover;
1767 refcount_set(&match->sk_ref, refcount_read(&match->sk_ref) + 1);
1768 __fanout_link(sk, po);
1772 spin_unlock(&po->bind_lock);
1774 if (err && !refcount_read(&match->sk_ref)) {
1775 list_del(&match->list);
1781 mutex_unlock(&fanout_mutex);
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())
1790 static struct packet_fanout *fanout_release(struct sock *sk)
1792 struct packet_sock *po = pkt_sk(sk);
1793 struct packet_fanout *f;
1795 mutex_lock(&fanout_mutex);
1800 if (refcount_dec_and_test(&f->sk_ref))
1805 mutex_unlock(&fanout_mutex);
1810 static bool packet_extra_vlan_len_allowed(const struct net_device *dev,
1811 struct sk_buff *skb)
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.
1817 if (unlikely(dev->type != ARPHRD_ETHER))
1820 skb_reset_mac_header(skb);
1821 return likely(eth_hdr(skb)->h_proto == htons(ETH_P_8021Q));
1824 static const struct proto_ops packet_ops;
1826 static const struct proto_ops packet_ops_spkt;
1828 static int packet_rcv_spkt(struct sk_buff *skb, struct net_device *dev,
1829 struct packet_type *pt, struct net_device *orig_dev)
1832 struct sockaddr_pkt *spkt;
1835 * When we registered the protocol we saved the socket in the data
1836 * field for just this event.
1839 sk = pt->af_packet_priv;
1842 * Yank back the headers [hope the device set this
1843 * right or kerboom...]
1845 * Incoming packets have ll header pulled,
1848 * For outgoing ones skb->data == skb_mac_header(skb)
1849 * so that this procedure is noop.
1852 if (skb->pkt_type == PACKET_LOOPBACK)
1855 if (!net_eq(dev_net(dev), sock_net(sk)))
1858 skb = skb_share_check(skb, GFP_ATOMIC);
1862 /* drop any routing info */
1865 /* drop conntrack reference */
1868 spkt = &PACKET_SKB_CB(skb)->sa.pkt;
1870 skb_push(skb, skb->data - skb_mac_header(skb));
1873 * The SOCK_PACKET socket receives _all_ frames.
1876 spkt->spkt_family = dev->type;
1877 strlcpy(spkt->spkt_device, dev->name, sizeof(spkt->spkt_device));
1878 spkt->spkt_protocol = skb->protocol;
1881 * Charge the memory to the socket. This is done specifically
1882 * to prevent sockets using all the memory up.
1885 if (sock_queue_rcv_skb(sk, skb) == 0)
1894 static void packet_parse_headers(struct sk_buff *skb, struct socket *sock)
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);
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);
1910 skb_probe_transport_header(skb);
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
1918 static int packet_sendmsg_spkt(struct socket *sock, struct msghdr *msg,
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;
1931 * Get and verify the address.
1935 if (msg->msg_namelen < sizeof(struct sockaddr))
1937 if (msg->msg_namelen == sizeof(struct sockaddr_pkt))
1938 proto = saddr->spkt_protocol;
1940 return -ENOTCONN; /* SOCK_PACKET must be sent giving an address */
1943 * Find the device first to size check it
1946 saddr->spkt_device[sizeof(saddr->spkt_device) - 1] = 0;
1949 dev = dev_get_by_name_rcu(sock_net(sk), saddr->spkt_device);
1955 if (!(dev->flags & IFF_UP))
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.
1963 if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
1964 if (!netif_supports_nofcs(dev)) {
1965 err = -EPROTONOSUPPORT;
1968 extra_len = 4; /* We're doing our own CRC */
1972 if (len > dev->mtu + dev->hard_header_len + VLAN_HLEN + extra_len)
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;
1981 skb = sock_wmalloc(sk, len + reserved + tlen, 0, GFP_KERNEL);
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.
1988 skb_reserve(skb, reserved);
1989 skb_reset_network_header(skb);
1991 /* Try to align data part correctly */
1996 skb_reset_network_header(skb);
1998 err = memcpy_from_msg(skb_put(skb, len), msg, len);
2004 if (!dev_validate_header(dev, skb->data, len) || !skb->len) {
2008 if (len > (dev->mtu + dev->hard_header_len + extra_len) &&
2009 !packet_extra_vlan_len_allowed(dev, skb)) {
2014 sockcm_init(&sockc, sk);
2015 if (msg->msg_controllen) {
2016 err = sock_cmsg_send(sk, msg, &sockc);
2021 skb->protocol = proto;
2023 skb->priority = sk->sk_priority;
2024 skb->mark = sk->sk_mark;
2025 skb->tstamp = sockc.transmit_time;
2027 skb_setup_tx_timestamp(skb, sockc.tsflags);
2029 if (unlikely(extra_len == 4))
2032 packet_parse_headers(skb, sock);
2034 dev_queue_xmit(skb);
2045 static unsigned int run_filter(struct sk_buff *skb,
2046 const struct sock *sk,
2049 struct sk_filter *filter;
2052 filter = rcu_dereference(sk->sk_filter);
2054 res = bpf_prog_run_clear_cb(filter->prog, skb);
2060 static int packet_rcv_vnet(struct msghdr *msg, const struct sk_buff *skb,
2063 struct virtio_net_hdr vnet_hdr;
2065 if (*len < sizeof(vnet_hdr))
2067 *len -= sizeof(vnet_hdr);
2069 if (virtio_net_hdr_from_skb(skb, &vnet_hdr, vio_le(), true, 0))
2072 return memcpy_to_msg(msg, (void *)&vnet_hdr, sizeof(vnet_hdr));
2076 * This function makes lazy skb cloning in hope that most of packets
2077 * are discarded by BPF.
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.
2087 static int packet_rcv(struct sk_buff *skb, struct net_device *dev,
2088 struct packet_type *pt, struct net_device *orig_dev)
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;
2098 if (skb->pkt_type == PACKET_LOOPBACK)
2101 sk = pt->af_packet_priv;
2104 if (!net_eq(dev_net(dev), sock_net(sk)))
2109 if (dev_has_header(dev)) {
2110 /* The device has an explicit notion of ll header,
2111 * exported to higher levels.
2113 * Otherwise, the device hides details of its frame
2114 * structure, so that corresponding packet head is
2115 * never delivered to user.
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));
2127 res = run_filter(skb, sk, snaplen);
2129 goto drop_n_restore;
2133 if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
2136 if (skb_shared(skb)) {
2137 struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
2141 if (skb_head != skb->data) {
2142 skb->data = skb_head;
2149 sock_skb_cb_check_size(sizeof(*PACKET_SKB_CB(skb)) + MAX_ADDR_LEN - 8);
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;
2157 sll->sll_ifindex = dev->ifindex;
2159 sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
2161 /* sll->sll_family and sll->sll_protocol are set in packet_recvmsg().
2162 * Use their space for storing the original skb length.
2164 PACKET_SKB_CB(skb)->sa.origlen = skb->len;
2166 if (pskb_trim(skb, snaplen))
2169 skb_set_owner_r(skb, sk);
2173 /* drop conntrack reference */
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);
2185 is_drop_n_account = true;
2186 atomic_inc(&po->tp_drops);
2187 atomic_inc(&sk->sk_drops);
2190 if (skb_head != skb->data && skb_shared(skb)) {
2191 skb->data = skb_head;
2195 if (!is_drop_n_account)
2202 static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
2203 struct packet_type *pt, struct net_device *orig_dev)
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;
2218 bool is_drop_n_account = false;
2219 unsigned int slot_id = 0;
2220 bool do_vnet = false;
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, ...).
2226 BUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h2)) != 32);
2227 BUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h3)) != 48);
2229 if (skb->pkt_type == PACKET_LOOPBACK)
2232 sk = pt->af_packet_priv;
2235 if (!net_eq(dev_net(dev), sock_net(sk)))
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));
2249 res = run_filter(skb, sk, snaplen);
2251 goto drop_n_restore;
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;
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;
2268 if (sk->sk_type == SOCK_DGRAM) {
2269 macoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +
2272 unsigned int maclen = skb_network_offset(skb);
2273 netoff = TPACKET_ALIGN(po->tp_hdrlen +
2274 (maclen < 16 ? 16 : maclen)) +
2276 if (po->has_vnet_hdr) {
2277 netoff += sizeof(struct virtio_net_hdr);
2280 macoff = netoff - maclen;
2282 if (netoff > USHRT_MAX) {
2283 atomic_inc(&po->tp_drops);
2284 goto drop_n_restore;
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);
2293 copy_skb = skb_get(skb);
2294 skb_head = skb->data;
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);
2302 snaplen = po->rx_ring.frame_size - macoff;
2303 if ((int)snaplen < 0) {
2308 } else if (unlikely(macoff + snaplen >
2309 GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len)) {
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);
2316 if (unlikely((int)snaplen < 0)) {
2318 macoff = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len;
2322 spin_lock(&sk->sk_receive_queue.lock);
2323 h.raw = packet_current_rx_frame(po, skb,
2324 TP_STATUS_KERNEL, (macoff+snaplen));
2326 goto drop_n_account;
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);
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;
2344 if (po->tp_version <= TPACKET_V2) {
2345 packet_increment_rx_head(po, &po->rx_ring);
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
2352 if (atomic_read(&po->tp_drops))
2353 status |= TP_STATUS_LOSING;
2356 po->stats.stats1.tp_packets++;
2358 status |= TP_STATUS_COPY;
2359 __skb_queue_tail(&sk->sk_receive_queue, copy_skb);
2361 spin_unlock(&sk->sk_receive_queue.lock);
2363 skb_copy_bits(skb, 0, h.raw + macoff, snaplen);
2365 /* Always timestamp; prefer an existing software timestamp taken
2366 * closer to the time of capture.
2368 ts_status = tpacket_get_timestamp(skb, &ts,
2369 po->tp_tstamp | SOF_TIMESTAMPING_SOFTWARE);
2371 ktime_get_real_ts64(&ts);
2373 status |= ts_status;
2375 switch (po->tp_version) {
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);
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;
2397 h.h2->tp_vlan_tci = 0;
2398 h.h2->tp_vlan_tpid = 0;
2400 memset(h.h2->tp_padding, 0, sizeof(h.h2->tp_padding));
2401 hdrlen = sizeof(*h.h2);
2404 /* tp_nxt_offset,vlan are already populated above.
2405 * So DONT clear those fields here
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);
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;
2430 sll->sll_ifindex = dev->ifindex;
2434 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
2435 if (po->tp_version <= TPACKET_V2) {
2438 end = (u8 *) PAGE_ALIGN((unsigned long) h.raw +
2441 for (start = h.raw; start < end; start += PAGE_SIZE)
2442 flush_dcache_page(pgv_to_page(start));
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);
2458 if (skb_head != skb->data && skb_shared(skb)) {
2459 skb->data = skb_head;
2463 if (!is_drop_n_account)
2470 spin_unlock(&sk->sk_receive_queue.lock);
2471 atomic_inc(&po->tp_drops);
2472 is_drop_n_account = true;
2474 sk->sk_data_ready(sk);
2475 kfree_skb(copy_skb);
2476 goto drop_n_restore;
2479 static void tpacket_destruct_skb(struct sk_buff *skb)
2481 struct packet_sock *po = pkt_sk(skb->sk);
2483 if (likely(po->tx_ring.pg_vec)) {
2487 ph = skb_zcopy_get_nouarg(skb);
2488 packet_dec_pending(&po->tx_ring);
2490 ts = __packet_set_timestamp(po, ph, skb);
2491 __packet_set_status(po, ph, TP_STATUS_AVAILABLE | ts);
2493 if (!packet_read_pending(&po->tx_ring))
2494 complete(&po->skb_completion);
2500 static int __packet_snd_vnet_parse(struct virtio_net_hdr *vnet_hdr, size_t len)
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);
2510 if (__virtio16_to_cpu(vio_le(), vnet_hdr->hdr_len) > len)
2516 static int packet_snd_vnet_parse(struct msghdr *msg, size_t *len,
2517 struct virtio_net_hdr *vnet_hdr)
2519 if (*len < sizeof(*vnet_hdr))
2521 *len -= sizeof(*vnet_hdr);
2523 if (!copy_from_iter_full(vnet_hdr, sizeof(*vnet_hdr), &msg->msg_iter))
2526 return __packet_snd_vnet_parse(vnet_hdr, *len);
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)
2534 union tpacket_uhdr ph;
2535 int to_write, offset, len, nr_frags, len_max;
2536 struct socket *sock = po->sk.sk_socket;
2542 skb->protocol = proto;
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);
2550 skb_reserve(skb, hlen);
2551 skb_reset_network_header(skb);
2555 if (sock->type == SOCK_DGRAM) {
2556 err = dev_hard_header(skb, dev, ntohs(proto), addr,
2558 if (unlikely(err < 0))
2560 } else if (copylen) {
2561 int hdrlen = min_t(int, copylen, tp_len);
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);
2568 if (!dev_validate_header(dev, skb->data, hdrlen))
2575 offset = offset_in_page(data);
2576 len_max = PAGE_SIZE - offset;
2577 len = ((to_write > len_max) ? len_max : to_write);
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);
2584 while (likely(to_write)) {
2585 nr_frags = skb_shinfo(skb)->nr_frags;
2587 if (unlikely(nr_frags >= MAX_SKB_FRAGS)) {
2588 pr_err("Packet exceed the number of skb frags(%lu)\n",
2593 page = pgv_to_page(data);
2595 flush_dcache_page(page);
2597 skb_fill_page_desc(skb, nr_frags, page, offset, len);
2600 len_max = PAGE_SIZE;
2601 len = ((to_write > len_max) ? len_max : to_write);
2604 packet_parse_headers(skb, sock);
2609 static int tpacket_parse_header(struct packet_sock *po, void *frame,
2610 int size_max, void **data)
2612 union tpacket_uhdr ph;
2617 switch (po->tp_version) {
2619 if (ph.h3->tp_next_offset != 0) {
2620 pr_warn_once("variable sized slot not supported");
2623 tp_len = ph.h3->tp_len;
2626 tp_len = ph.h2->tp_len;
2629 tp_len = ph.h1->tp_len;
2632 if (unlikely(tp_len > size_max)) {
2633 pr_err("packet size is too long (%d > %d)\n", tp_len, size_max);
2637 if (unlikely(po->tp_tx_has_off)) {
2638 int off_min, off_max;
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) {
2645 off = ph.h3->tp_net;
2648 off = ph.h2->tp_net;
2651 off = ph.h1->tp_net;
2655 switch (po->tp_version) {
2657 off = ph.h3->tp_mac;
2660 off = ph.h2->tp_mac;
2663 off = ph.h1->tp_mac;
2667 if (unlikely((off < off_min) || (off_max < off)))
2670 off = po->tp_hdrlen - sizeof(struct sockaddr_ll);
2673 *data = frame + off;
2677 static int tpacket_snd(struct packet_sock *po, struct msghdr *msg)
2679 struct sk_buff *skb = NULL;
2680 struct net_device *dev;
2681 struct virtio_net_hdr *vnet_hdr = NULL;
2682 struct sockcm_cookie sockc;
2684 int err, reserve = 0;
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;
2692 int status = TP_STATUS_AVAILABLE;
2693 int hlen, tlen, copylen = 0;
2696 mutex_lock(&po->pg_vec_lock);
2698 /* packet_sendmsg() check on tx_ring.pg_vec was lockless,
2699 * we need to confirm it under protection of pg_vec_lock.
2701 if (unlikely(!po->tx_ring.pg_vec)) {
2705 if (likely(saddr == NULL)) {
2706 dev = packet_cached_dev_get(po);
2707 proto = READ_ONCE(po->num);
2710 if (msg->msg_namelen < sizeof(struct sockaddr_ll))
2712 if (msg->msg_namelen < (saddr->sll_halen
2713 + offsetof(struct sockaddr_ll,
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))
2722 addr = saddr->sll_addr;
2727 if (unlikely(dev == NULL))
2730 if (unlikely(!(dev->flags & IFF_UP)))
2733 sockcm_init(&sockc, &po->sk);
2734 if (msg->msg_controllen) {
2735 err = sock_cmsg_send(&po->sk, msg, &sockc);
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));
2745 if ((size_max > dev->mtu + reserve + VLAN_HLEN) && !po->has_vnet_hdr)
2746 size_max = dev->mtu + reserve + VLAN_HLEN;
2748 reinit_completion(&po->skb_completion);
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);
2758 err = !timeo ? -ETIMEDOUT : -ERESTARTSYS;
2762 /* check for additional frames */
2767 tp_len = tpacket_parse_header(po, ph, size_max, &data);
2771 status = TP_STATUS_SEND_REQUEST;
2772 hlen = LL_RESERVED_SPACE(dev);
2773 tlen = dev->needed_tailroom;
2774 if (po->has_vnet_hdr) {
2776 data += sizeof(*vnet_hdr);
2777 tp_len -= sizeof(*vnet_hdr);
2779 __packet_snd_vnet_parse(vnet_hdr, tp_len)) {
2783 copylen = __virtio16_to_cpu(vio_le(),
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),
2792 if (unlikely(skb == NULL)) {
2793 /* we assume the socket was initially writeable ... */
2794 if (likely(len_sum > 0))
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))
2806 if (unlikely(tp_len < 0)) {
2809 __packet_set_status(po, ph,
2810 TP_STATUS_AVAILABLE);
2811 packet_increment_head(&po->tx_ring);
2815 status = TP_STATUS_WRONG_FORMAT;
2821 if (po->has_vnet_hdr) {
2822 if (virtio_net_hdr_to_skb(skb, vnet_hdr, vio_le())) {
2826 virtio_net_hdr_set_proto(skb, vnet_hdr);
2829 skb->destructor = tpacket_destruct_skb;
2830 __packet_set_status(po, ph, TP_STATUS_SENDING);
2831 packet_inc_pending(&po->tx_ring);
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)) {
2838 err = net_xmit_errno(err);
2839 if (err && __packet_get_status(po, ph) ==
2840 TP_STATUS_AVAILABLE) {
2841 /* skb was destructed already */
2846 * skb was dropped but not destructed yet;
2847 * let's treat it like congestion or err < 0
2851 packet_increment_head(&po->tx_ring);
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
2860 (need_wait && packet_read_pending(&po->tx_ring))));
2866 __packet_set_status(po, ph, status);
2871 mutex_unlock(&po->pg_vec_lock);
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,
2880 struct sk_buff *skb;
2882 /* Under a page? Don't bother with paged skb. */
2883 if (prepad + len < PAGE_SIZE || !linear)
2886 skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
2891 skb_reserve(skb, reserve);
2892 skb_put(skb, linear);
2893 skb->data_len = len - linear;
2894 skb->len += len - linear;
2899 static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len)
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;
2906 unsigned char *addr = NULL;
2907 int err, reserve = 0;
2908 struct sockcm_cookie sockc;
2909 struct virtio_net_hdr vnet_hdr = { 0 };
2911 struct packet_sock *po = pkt_sk(sk);
2912 bool has_vnet_hdr = false;
2913 int hlen, tlen, linear;
2917 * Get and verify the address.
2920 if (likely(saddr == NULL)) {
2921 dev = packet_cached_dev_get(po);
2922 proto = READ_ONCE(po->num);
2925 if (msg->msg_namelen < sizeof(struct sockaddr_ll))
2927 if (msg->msg_namelen < (saddr->sll_halen + offsetof(struct sockaddr_ll, sll_addr)))
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))
2935 addr = saddr->sll_addr;
2940 if (unlikely(dev == NULL))
2943 if (unlikely(!(dev->flags & IFF_UP)))
2946 sockcm_init(&sockc, sk);
2947 sockc.mark = sk->sk_mark;
2948 if (msg->msg_controllen) {
2949 err = sock_cmsg_send(sk, msg, &sockc);
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);
2960 has_vnet_hdr = true;
2963 if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
2964 if (!netif_supports_nofcs(dev)) {
2965 err = -EPROTONOSUPPORT;
2968 extra_len = 4; /* We're doing our own CRC */
2972 if (!vnet_hdr.gso_type &&
2973 (len > dev->mtu + reserve + VLAN_HLEN + extra_len))
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);
2986 skb_reset_network_header(skb);
2989 if (sock->type == SOCK_DGRAM) {
2990 offset = dev_hard_header(skb, dev, ntohs(proto), addr, NULL, len);
2991 if (unlikely(offset < 0))
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);
3000 /* Returns -EFAULT on error */
3001 err = skb_copy_datagram_from_iter(skb, offset, &msg->msg_iter, len);
3005 if ((sock->type == SOCK_RAW &&
3006 !dev_validate_header(dev, skb->data, len)) || !skb->len) {
3011 skb_setup_tx_timestamp(skb, sockc.tsflags);
3013 if (!vnet_hdr.gso_type && (len > dev->mtu + reserve + extra_len) &&
3014 !packet_extra_vlan_len_allowed(dev, skb)) {
3019 skb->protocol = proto;
3021 skb->priority = sk->sk_priority;
3022 skb->mark = sockc.mark;
3023 skb->tstamp = sockc.transmit_time;
3025 if (unlikely(extra_len == 4))
3028 packet_parse_headers(skb, sock);
3031 err = virtio_net_hdr_to_skb(skb, &vnet_hdr, vio_le());
3034 len += sizeof(vnet_hdr);
3035 virtio_net_hdr_set_proto(skb, &vnet_hdr);
3038 /* Paired with WRITE_ONCE() in packet_setsockopt() */
3039 err = READ_ONCE(po->xmit)(skb);
3040 if (unlikely(err != 0)) {
3042 err = net_xmit_errno(err);
3059 static int packet_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
3061 struct sock *sk = sock->sk;
3062 struct packet_sock *po = pkt_sk(sk);
3064 /* Reading tx_ring.pg_vec without holding pg_vec_lock is racy.
3065 * tpacket_snd() will redo the check safely.
3067 if (data_race(po->tx_ring.pg_vec))
3068 return tpacket_snd(po, msg);
3070 return packet_snd(sock, msg, len);
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.
3078 static int packet_release(struct socket *sock)
3080 struct sock *sk = sock->sk;
3081 struct packet_sock *po;
3082 struct packet_fanout *f;
3084 union tpacket_req_u req_u;
3092 mutex_lock(&net->packet.sklist_lock);
3093 sk_del_node_init_rcu(sk);
3094 mutex_unlock(&net->packet.sklist_lock);
3097 sock_prot_inuse_add(net, sk->sk_prot, -1);
3100 spin_lock(&po->bind_lock);
3101 unregister_prot_hook(sk, false);
3102 packet_cached_dev_reset(po);
3104 if (po->prot_hook.dev) {
3105 dev_put(po->prot_hook.dev);
3106 po->prot_hook.dev = NULL;
3108 spin_unlock(&po->bind_lock);
3110 packet_flush_mclist(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);
3118 if (po->tx_ring.pg_vec) {
3119 memset(&req_u, 0, sizeof(req_u));
3120 packet_set_ring(sk, &req_u, 1, 1);
3124 f = fanout_release(sk);
3128 kfree(po->rollover);
3130 fanout_release_data(f);
3134 * Now the socket is dead. No more input will appear.
3141 skb_queue_purge(&sk->sk_receive_queue);
3142 packet_free_pending(po);
3143 sk_refcnt_debug_release(sk);
3150 * Attach a packet hook.
3153 static int packet_do_bind(struct sock *sk, const char *name, int ifindex,
3156 struct packet_sock *po = pkt_sk(sk);
3157 struct net_device *dev_curr;
3160 struct net_device *dev = NULL;
3162 bool unlisted = false;
3165 spin_lock(&po->bind_lock);
3177 dev = dev_get_by_name_rcu(sock_net(sk), name);
3182 } else if (ifindex) {
3183 dev = dev_get_by_index_rcu(sock_net(sk), ifindex);
3192 proto_curr = po->prot_hook.type;
3193 dev_curr = po->prot_hook.dev;
3195 need_rehook = proto_curr != proto || dev_curr != dev;
3200 /* prevents packet_notifier() from calling
3201 * register_prot_hook()
3203 WRITE_ONCE(po->num, 0);
3204 __unregister_prot_hook(sk, true);
3206 dev_curr = po->prot_hook.dev;
3208 unlisted = !dev_get_by_index_rcu(sock_net(sk),
3212 BUG_ON(po->running);
3213 WRITE_ONCE(po->num, proto);
3214 po->prot_hook.type = proto;
3216 if (unlikely(unlisted)) {
3218 po->prot_hook.dev = NULL;
3219 WRITE_ONCE(po->ifindex, -1);
3220 packet_cached_dev_reset(po);
3222 po->prot_hook.dev = dev;
3223 WRITE_ONCE(po->ifindex, dev ? dev->ifindex : 0);
3224 packet_cached_dev_assign(po, dev);
3229 if (proto == 0 || !need_rehook)
3232 if (!unlisted && (!dev || (dev->flags & IFF_UP))) {
3233 register_prot_hook(sk);
3235 sk->sk_err = ENETDOWN;
3236 if (!sock_flag(sk, SOCK_DEAD))
3237 sk_error_report(sk);
3242 spin_unlock(&po->bind_lock);
3248 * Bind a packet socket to a device
3251 static int packet_bind_spkt(struct socket *sock, struct sockaddr *uaddr,
3254 struct sock *sk = sock->sk;
3255 char name[sizeof(uaddr->sa_data) + 1];
3261 if (addr_len != sizeof(struct sockaddr))
3263 /* uaddr->sa_data comes from the userspace, it's not guaranteed to be
3266 memcpy(name, uaddr->sa_data, sizeof(uaddr->sa_data));
3267 name[sizeof(uaddr->sa_data)] = 0;
3269 return packet_do_bind(sk, name, 0, 0);
3272 static int packet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
3274 struct sockaddr_ll *sll = (struct sockaddr_ll *)uaddr;
3275 struct sock *sk = sock->sk;
3281 if (addr_len < sizeof(struct sockaddr_ll))
3283 if (sll->sll_family != AF_PACKET)
3286 return packet_do_bind(sk, NULL, sll->sll_ifindex, sll->sll_protocol);
3289 static struct proto packet_proto = {
3291 .owner = THIS_MODULE,
3292 .obj_size = sizeof(struct packet_sock),
3296 * Create a packet of type SOCK_PACKET.
3299 static int packet_create(struct net *net, struct socket *sock, int protocol,
3303 struct packet_sock *po;
3304 __be16 proto = (__force __be16)protocol; /* weird, but documented */
3307 if (!ns_capable(net->user_ns, CAP_NET_RAW))
3309 if (sock->type != SOCK_DGRAM && sock->type != SOCK_RAW &&
3310 sock->type != SOCK_PACKET)
3311 return -ESOCKTNOSUPPORT;
3313 sock->state = SS_UNCONNECTED;
3316 sk = sk_alloc(net, PF_PACKET, GFP_KERNEL, &packet_proto, kern);
3320 sock->ops = &packet_ops;
3321 if (sock->type == SOCK_PACKET)
3322 sock->ops = &packet_ops_spkt;
3324 sock_init_data(sock, sk);
3327 init_completion(&po->skb_completion);
3328 sk->sk_family = PF_PACKET;
3330 po->xmit = dev_queue_xmit;
3332 err = packet_alloc_pending(po);
3336 packet_cached_dev_reset(po);
3338 sk->sk_destruct = packet_sock_destruct;
3339 sk_refcnt_debug_inc(sk);
3342 * Attach a protocol block
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;
3350 if (sock->type == SOCK_PACKET)
3351 po->prot_hook.func = packet_rcv_spkt;
3353 po->prot_hook.af_packet_priv = sk;
3354 po->prot_hook.af_packet_net = sock_net(sk);
3357 po->prot_hook.type = proto;
3358 __register_prot_hook(sk);
3361 mutex_lock(&net->packet.sklist_lock);
3362 sk_add_node_tail_rcu(sk, &net->packet.sklist);
3363 mutex_unlock(&net->packet.sklist_lock);
3366 sock_prot_inuse_add(net, &packet_proto, 1);
3377 * Pull a packet from our receive queue and hand it to the user.
3378 * If necessary we block.
3381 static int packet_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
3384 struct sock *sk = sock->sk;
3385 struct sk_buff *skb;
3387 int vnet_hdr_len = 0;
3388 unsigned int origlen = 0;
3391 if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT|MSG_ERRQUEUE))
3395 /* What error should we return now? EUNATTACH? */
3396 if (pkt_sk(sk)->ifindex < 0)
3400 if (flags & MSG_ERRQUEUE) {
3401 err = sock_recv_errqueue(sk, msg, len,
3402 SOL_PACKET, PACKET_TX_TIMESTAMP);
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.
3411 * Now it will return ENETDOWN, if device have just gone down,
3412 * but then it will block.
3415 skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);
3418 * An error occurred so return it. Because skb_recv_datagram()
3419 * handles the blocking we don't see and worry about blocking
3426 packet_rcv_try_clear_pressure(pkt_sk(sk));
3428 if (pkt_sk(sk)->has_vnet_hdr) {
3429 err = packet_rcv_vnet(msg, skb, &len);
3432 vnet_hdr_len = sizeof(struct virtio_net_hdr);
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
3442 msg->msg_flags |= MSG_TRUNC;
3445 err = skb_copy_datagram_msg(skb, 0, msg, copied);
3449 if (sock->type != SOCK_PACKET) {
3450 struct sockaddr_ll *sll = &PACKET_SKB_CB(skb)->sa.ll;
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;
3458 sock_recv_ts_and_drops(msg, sk, skb);
3460 if (msg->msg_name) {
3461 const size_t max_len = min(sizeof(skb->cb),
3462 sizeof(struct sockaddr_storage));
3465 /* If the address length field is there to be filled
3466 * in, we fill it in now.
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;
3473 struct sockaddr_ll *sll = &PACKET_SKB_CB(skb)->sa.ll;
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);
3485 if (WARN_ON_ONCE(copy_len > max_len)) {
3487 msg->msg_namelen = copy_len;
3489 memcpy(msg->msg_name, &PACKET_SKB_CB(skb)->sa, copy_len);
3492 if (packet_sock_flag(pkt_sk(sk), PACKET_SOCK_AUXDATA)) {
3493 struct tpacket_auxdata aux;
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;
3502 aux.tp_len = origlen;
3503 aux.tp_snaplen = skb->len;
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;
3511 aux.tp_vlan_tci = 0;
3512 aux.tp_vlan_tpid = 0;
3514 put_cmsg(msg, SOL_PACKET, PACKET_AUXDATA, sizeof(aux), &aux);
3518 * Free or return the buffer as appropriate. Again this
3519 * hides all the races and re-entrancy issues from us.
3521 err = vnet_hdr_len + ((flags&MSG_TRUNC) ? skb->len : copied);
3524 skb_free_datagram(sk, skb);
3529 static int packet_getname_spkt(struct socket *sock, struct sockaddr *uaddr,
3532 struct net_device *dev;
3533 struct sock *sk = sock->sk;
3538 uaddr->sa_family = AF_PACKET;
3539 memset(uaddr->sa_data, 0, sizeof(uaddr->sa_data));
3541 dev = dev_get_by_index_rcu(sock_net(sk), READ_ONCE(pkt_sk(sk)->ifindex));
3543 strlcpy(uaddr->sa_data, dev->name, sizeof(uaddr->sa_data));
3546 return sizeof(*uaddr);
3549 static int packet_getname(struct socket *sock, struct sockaddr *uaddr,
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);
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;
3567 dev = dev_get_by_index_rcu(sock_net(sk), ifindex);
3569 sll->sll_hatype = dev->type;
3570 sll->sll_halen = dev->addr_len;
3571 memcpy(sll->sll_addr, dev->dev_addr, dev->addr_len);
3573 sll->sll_hatype = 0; /* Bad: we have no ARPHRD_UNSPEC */
3578 return offsetof(struct sockaddr_ll, sll_addr) + sll->sll_halen;
3581 static int packet_dev_mc(struct net_device *dev, struct packet_mclist *i,
3585 case PACKET_MR_MULTICAST:
3586 if (i->alen != dev->addr_len)
3589 return dev_mc_add(dev, i->addr);
3591 return dev_mc_del(dev, i->addr);
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)
3601 return dev_uc_add(dev, i->addr);
3603 return dev_uc_del(dev, i->addr);
3611 static void packet_dev_mclist_delete(struct net_device *dev,
3612 struct packet_mclist **mlp)
3614 struct packet_mclist *ml;
3616 while ((ml = *mlp) != NULL) {
3617 if (ml->ifindex == dev->ifindex) {
3618 packet_dev_mc(dev, ml, -1);
3626 static int packet_mc_add(struct sock *sk, struct packet_mreq_max *mreq)
3628 struct packet_sock *po = pkt_sk(sk);
3629 struct packet_mclist *ml, *i;
3630 struct net_device *dev;
3636 dev = __dev_get_by_index(sock_net(sk), mreq->mr_ifindex);
3641 if (mreq->mr_alen > dev->addr_len)
3645 i = kmalloc(sizeof(*i), GFP_KERNEL);
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) {
3656 /* Free the new element ... */
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);
3668 i->next = po->mclist;
3670 err = packet_dev_mc(dev, i, 1);
3672 po->mclist = i->next;
3681 static int packet_mc_drop(struct sock *sk, struct packet_mreq_max *mreq)
3683 struct packet_mclist *ml, **mlp;
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;
3695 dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
3697 packet_dev_mc(dev, ml, -1);
3707 static void packet_flush_mclist(struct sock *sk)
3709 struct packet_sock *po = pkt_sk(sk);
3710 struct packet_mclist *ml;
3716 while ((ml = po->mclist) != NULL) {
3717 struct net_device *dev;
3719 po->mclist = ml->next;
3720 dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
3722 packet_dev_mc(dev, ml, -1);
3729 packet_setsockopt(struct socket *sock, int level, int optname, sockptr_t optval,
3730 unsigned int optlen)
3732 struct sock *sk = sock->sk;
3733 struct packet_sock *po = pkt_sk(sk);
3736 if (level != SOL_PACKET)
3737 return -ENOPROTOOPT;
3740 case PACKET_ADD_MEMBERSHIP:
3741 case PACKET_DROP_MEMBERSHIP:
3743 struct packet_mreq_max mreq;
3745 memset(&mreq, 0, sizeof(mreq));
3746 if (len < sizeof(struct packet_mreq))
3748 if (len > sizeof(mreq))
3750 if (copy_from_sockptr(&mreq, optval, len))
3752 if (len < (mreq.mr_alen + offsetof(struct packet_mreq, mr_address)))
3754 if (optname == PACKET_ADD_MEMBERSHIP)
3755 ret = packet_mc_add(sk, &mreq);
3757 ret = packet_mc_drop(sk, &mreq);
3761 case PACKET_RX_RING:
3762 case PACKET_TX_RING:
3764 union tpacket_req_u req_u;
3768 switch (po->tp_version) {
3771 len = sizeof(req_u.req);
3775 len = sizeof(req_u.req3);
3781 if (copy_from_sockptr(&req_u.req, optval, len))
3784 ret = packet_set_ring(sk, &req_u, 0,
3785 optname == PACKET_TX_RING);
3790 case PACKET_COPY_THRESH:
3794 if (optlen != sizeof(val))
3796 if (copy_from_sockptr(&val, optval, sizeof(val)))
3799 pkt_sk(sk)->copy_thresh = val;
3802 case PACKET_VERSION:
3806 if (optlen != sizeof(val))
3808 if (copy_from_sockptr(&val, optval, sizeof(val)))
3819 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) {
3822 po->tp_version = val;
3828 case PACKET_RESERVE:
3832 if (optlen != sizeof(val))
3834 if (copy_from_sockptr(&val, optval, sizeof(val)))
3839 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) {
3842 po->tp_reserve = val;
3852 if (optlen != sizeof(val))
3854 if (copy_from_sockptr(&val, optval, sizeof(val)))
3858 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) {
3861 po->tp_loss = !!val;
3867 case PACKET_AUXDATA:
3871 if (optlen < sizeof(val))
3873 if (copy_from_sockptr(&val, optval, sizeof(val)))
3876 packet_sock_flag_set(po, PACKET_SOCK_AUXDATA, val);
3879 case PACKET_ORIGDEV:
3883 if (optlen < sizeof(val))
3885 if (copy_from_sockptr(&val, optval, sizeof(val)))
3888 packet_sock_flag_set(po, PACKET_SOCK_ORIGDEV, val);
3891 case PACKET_VNET_HDR:
3895 if (sock->type != SOCK_RAW)
3897 if (optlen < sizeof(val))
3899 if (copy_from_sockptr(&val, optval, sizeof(val)))
3903 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) {
3906 po->has_vnet_hdr = !!val;
3912 case PACKET_TIMESTAMP:
3916 if (optlen != sizeof(val))
3918 if (copy_from_sockptr(&val, optval, sizeof(val)))
3921 po->tp_tstamp = val;
3926 struct fanout_args args = { 0 };
3928 if (optlen != sizeof(int) && optlen != sizeof(args))
3930 if (copy_from_sockptr(&args, optval, optlen))
3933 return fanout_add(sk, &args);
3935 case PACKET_FANOUT_DATA:
3937 /* Paired with the WRITE_ONCE() in fanout_add() */
3938 if (!READ_ONCE(po->fanout))
3941 return fanout_set_data(po, optval, optlen);
3943 case PACKET_IGNORE_OUTGOING:
3947 if (optlen != sizeof(val))
3949 if (copy_from_sockptr(&val, optval, sizeof(val)))
3951 if (val < 0 || val > 1)
3954 po->prot_hook.ignore_outgoing = !!val;
3957 case PACKET_TX_HAS_OFF:
3961 if (optlen != sizeof(val))
3963 if (copy_from_sockptr(&val, optval, sizeof(val)))
3967 if (!po->rx_ring.pg_vec && !po->tx_ring.pg_vec)
3968 po->tp_tx_has_off = !!val;
3973 case PACKET_QDISC_BYPASS:
3977 if (optlen != sizeof(val))
3979 if (copy_from_sockptr(&val, optval, sizeof(val)))
3982 /* Paired with all lockless reads of po->xmit */
3983 WRITE_ONCE(po->xmit, val ? packet_direct_xmit : dev_queue_xmit);
3987 return -ENOPROTOOPT;
3991 static int packet_getsockopt(struct socket *sock, int level, int optname,
3992 char __user *optval, int __user *optlen)
3995 int val, lv = sizeof(val);
3996 struct sock *sk = sock->sk;
3997 struct packet_sock *po = pkt_sk(sk);
3999 union tpacket_stats_u st;
4000 struct tpacket_rollover_stats rstats;
4003 if (level != SOL_PACKET)
4004 return -ENOPROTOOPT;
4006 if (get_user(len, optlen))
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);
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;
4026 lv = sizeof(struct tpacket_stats);
4027 st.stats1.tp_drops = drops;
4028 st.stats1.tp_packets += drops;
4033 case PACKET_AUXDATA:
4034 val = packet_sock_flag(po, PACKET_SOCK_AUXDATA);
4036 case PACKET_ORIGDEV:
4037 val = packet_sock_flag(po, PACKET_SOCK_ORIGDEV);
4039 case PACKET_VNET_HDR:
4040 val = po->has_vnet_hdr;
4042 case PACKET_VERSION:
4043 val = po->tp_version;
4046 if (len > sizeof(int))
4048 if (len < sizeof(int))
4050 if (copy_from_user(&val, optval, len))
4054 val = sizeof(struct tpacket_hdr);
4057 val = sizeof(struct tpacket2_hdr);
4060 val = sizeof(struct tpacket3_hdr);
4066 case PACKET_RESERVE:
4067 val = po->tp_reserve;
4072 case PACKET_TIMESTAMP:
4073 val = po->tp_tstamp;
4077 ((u32)po->fanout->id |
4078 ((u32)po->fanout->type << 16) |
4079 ((u32)po->fanout->flags << 24)) :
4082 case PACKET_IGNORE_OUTGOING:
4083 val = po->prot_hook.ignore_outgoing;
4085 case PACKET_ROLLOVER_STATS:
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);
4092 lv = sizeof(rstats);
4094 case PACKET_TX_HAS_OFF:
4095 val = po->tp_tx_has_off;
4097 case PACKET_QDISC_BYPASS:
4098 val = packet_use_direct_xmit(po);
4101 return -ENOPROTOOPT;
4106 if (put_user(len, optlen))
4108 if (copy_to_user(optval, data, len))
4113 static int packet_notifier(struct notifier_block *this,
4114 unsigned long msg, void *ptr)
4117 struct net_device *dev = netdev_notifier_info_to_dev(ptr);
4118 struct net *net = dev_net(dev);
4121 sk_for_each_rcu(sk, &net->packet.sklist) {
4122 struct packet_sock *po = pkt_sk(sk);
4125 case NETDEV_UNREGISTER:
4127 packet_dev_mclist_delete(dev, &po->mclist);
4131 if (dev->ifindex == po->ifindex) {
4132 spin_lock(&po->bind_lock);
4134 __unregister_prot_hook(sk, false);
4135 sk->sk_err = ENETDOWN;
4136 if (!sock_flag(sk, SOCK_DEAD))
4137 sk_error_report(sk);
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;
4145 spin_unlock(&po->bind_lock);
4149 if (dev->ifindex == po->ifindex) {
4150 spin_lock(&po->bind_lock);
4152 register_prot_hook(sk);
4153 spin_unlock(&po->bind_lock);
4163 static int packet_ioctl(struct socket *sock, unsigned int cmd,
4166 struct sock *sk = sock->sk;
4171 int amount = sk_wmem_alloc_get(sk);
4173 return put_user(amount, (int __user *)arg);
4177 struct sk_buff *skb;
4180 spin_lock_bh(&sk->sk_receive_queue.lock);
4181 skb = skb_peek(&sk->sk_receive_queue);
4184 spin_unlock_bh(&sk->sk_receive_queue.lock);
4185 return put_user(amount, (int __user *)arg);
4195 case SIOCGIFBRDADDR:
4196 case SIOCSIFBRDADDR:
4197 case SIOCGIFNETMASK:
4198 case SIOCSIFNETMASK:
4199 case SIOCGIFDSTADDR:
4200 case SIOCSIFDSTADDR:
4202 return inet_dgram_ops.ioctl(sock, cmd, arg);
4206 return -ENOIOCTLCMD;
4211 static __poll_t packet_poll(struct file *file, struct socket *sock,
4214 struct sock *sk = sock->sk;
4215 struct packet_sock *po = pkt_sk(sk);
4216 __poll_t mask = datagram_poll(file, sock, wait);
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,
4222 mask |= EPOLLIN | EPOLLRDNORM;
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;
4231 spin_unlock_bh(&sk->sk_write_queue.lock);
4236 /* Dirty? Well, I still did not learn better way to account
4240 static void packet_mm_open(struct vm_area_struct *vma)
4242 struct file *file = vma->vm_file;
4243 struct socket *sock = file->private_data;
4244 struct sock *sk = sock->sk;
4247 atomic_inc(&pkt_sk(sk)->mapped);
4250 static void packet_mm_close(struct vm_area_struct *vma)
4252 struct file *file = vma->vm_file;
4253 struct socket *sock = file->private_data;
4254 struct sock *sk = sock->sk;
4257 atomic_dec(&pkt_sk(sk)->mapped);
4260 static const struct vm_operations_struct packet_mmap_ops = {
4261 .open = packet_mm_open,
4262 .close = packet_mm_close,
4265 static void free_pg_vec(struct pgv *pg_vec, unsigned int order,
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);
4275 free_pages((unsigned long)pg_vec[i].buffer,
4277 pg_vec[i].buffer = NULL;
4283 static char *alloc_one_pg_vec_page(unsigned long order)
4286 gfp_t gfp_flags = GFP_KERNEL | __GFP_COMP |
4287 __GFP_ZERO | __GFP_NOWARN | __GFP_NORETRY;
4289 buffer = (char *) __get_free_pages(gfp_flags, order);
4293 /* __get_free_pages failed, fall back to vmalloc */
4294 buffer = vzalloc(array_size((1 << order), PAGE_SIZE));
4298 /* vmalloc failed, lets dig into swap here */
4299 gfp_flags &= ~__GFP_NORETRY;
4300 buffer = (char *) __get_free_pages(gfp_flags, order);
4304 /* complete and utter failure */
4308 static struct pgv *alloc_pg_vec(struct tpacket_req *req, int order)
4310 unsigned int block_nr = req->tp_block_nr;
4314 pg_vec = kcalloc(block_nr, sizeof(struct pgv), GFP_KERNEL | __GFP_NOWARN);
4315 if (unlikely(!pg_vec))
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;
4328 free_pg_vec(pg_vec, order, block_nr);
4333 static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
4334 int closing, int tx_ring)
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;
4344 /* Added to avoid minimal code churn */
4345 struct tpacket_req *req = &req_u->req;
4347 rb = tx_ring ? &po->tx_ring : &po->rx_ring;
4348 rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue;
4352 if (atomic_read(&po->mapped))
4354 if (packet_read_pending(rb))
4358 if (req->tp_block_nr) {
4359 unsigned int min_frame_size;
4361 /* Sanity tests and some calculations */
4363 if (unlikely(rb->pg_vec))
4366 switch (po->tp_version) {
4368 po->tp_hdrlen = TPACKET_HDRLEN;
4371 po->tp_hdrlen = TPACKET2_HDRLEN;
4374 po->tp_hdrlen = TPACKET3_HDRLEN;
4379 if (unlikely((int)req->tp_block_size <= 0))
4381 if (unlikely(!PAGE_ALIGNED(req->tp_block_size)))
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)
4388 if (unlikely(req->tp_frame_size < min_frame_size))
4390 if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1)))
4393 rb->frames_per_block = req->tp_block_size / req->tp_frame_size;
4394 if (unlikely(rb->frames_per_block == 0))
4396 if (unlikely(rb->frames_per_block > UINT_MAX / req->tp_block_nr))
4398 if (unlikely((rb->frames_per_block * req->tp_block_nr) !=
4403 order = get_order(req->tp_block_size);
4404 pg_vec = alloc_pg_vec(req, order);
4405 if (unlikely(!pg_vec))
4407 switch (po->tp_version) {
4409 /* Block transmit is not supported yet */
4411 init_prb_bdqc(po, rb, pg_vec, req_u);
4413 struct tpacket_req3 *req3 = &req_u->req3;
4415 if (req3->tp_retire_blk_tov ||
4416 req3->tp_sizeof_priv ||
4417 req3->tp_feature_req_word) {
4419 goto out_free_pg_vec;
4425 rx_owner_map = bitmap_alloc(req->tp_frame_nr,
4426 GFP_KERNEL | __GFP_NOWARN | __GFP_ZERO);
4428 goto out_free_pg_vec;
4436 if (unlikely(req->tp_frame_nr))
4441 /* Detach socket from network */
4442 spin_lock(&po->bind_lock);
4443 was_running = po->running;
4446 WRITE_ONCE(po->num, 0);
4447 __unregister_prot_hook(sk, false);
4449 spin_unlock(&po->bind_lock);
4454 mutex_lock(&po->pg_vec_lock);
4455 if (closing || atomic_read(&po->mapped) == 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);
4463 rb->frame_size = req->tp_frame_size;
4464 spin_unlock_bh(&rb_queue->lock);
4466 swap(rb->pg_vec_order, order);
4467 swap(rb->pg_vec_len, req->tp_block_nr);
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_read(&po->mapped))
4474 pr_err("packet_mmap: vma is busy: %d\n",
4475 atomic_read(&po->mapped));
4477 mutex_unlock(&po->pg_vec_lock);
4479 spin_lock(&po->bind_lock);
4481 WRITE_ONCE(po->num, num);
4482 register_prot_hook(sk);
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 */
4488 prb_shutdown_retire_blk_timer(po, rb_queue);
4493 bitmap_free(rx_owner_map);
4494 free_pg_vec(pg_vec, order, req->tp_block_nr);
4500 static int packet_mmap(struct file *file, struct socket *sock,
4501 struct vm_area_struct *vma)
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;
4514 mutex_lock(&po->pg_vec_lock);
4517 for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
4519 expected_size += rb->pg_vec_len
4525 if (expected_size == 0)
4528 size = vma->vm_end - vma->vm_start;
4529 if (size != expected_size)
4532 start = vma->vm_start;
4533 for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
4534 if (rb->pg_vec == NULL)
4537 for (i = 0; i < rb->pg_vec_len; i++) {
4539 void *kaddr = rb->pg_vec[i].buffer;
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);
4553 atomic_inc(&po->mapped);
4554 vma->vm_ops = &packet_mmap_ops;
4558 mutex_unlock(&po->pg_vec_lock);
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,
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,
4604 static const struct net_proto_family packet_family_ops = {
4605 .family = PF_PACKET,
4606 .create = packet_create,
4607 .owner = THIS_MODULE,
4610 static struct notifier_block packet_netdev_notifier = {
4611 .notifier_call = packet_notifier,
4614 #ifdef CONFIG_PROC_FS
4616 static void *packet_seq_start(struct seq_file *seq, loff_t *pos)
4619 struct net *net = seq_file_net(seq);
4622 return seq_hlist_start_head_rcu(&net->packet.sklist, *pos);
4625 static void *packet_seq_next(struct seq_file *seq, void *v, loff_t *pos)
4627 struct net *net = seq_file_net(seq);
4628 return seq_hlist_next_rcu(v, &net->packet.sklist, pos);
4631 static void packet_seq_stop(struct seq_file *seq, void *v)
4637 static int packet_seq_show(struct seq_file *seq, void *v)
4639 if (v == SEQ_START_TOKEN)
4641 "%*sRefCnt Type Proto Iface R Rmem User Inode\n",
4642 IS_ENABLED(CONFIG_64BIT) ? -17 : -9, "sk");
4644 struct sock *s = sk_entry(v);
4645 const struct packet_sock *po = pkt_sk(s);
4648 "%pK %-6d %-4d %04x %-5d %1d %-6u %-6u %-6lu\n",
4650 refcount_read(&s->sk_refcnt),
4652 ntohs(READ_ONCE(po->num)),
4653 READ_ONCE(po->ifindex),
4655 atomic_read(&s->sk_rmem_alloc),
4656 from_kuid_munged(seq_user_ns(seq), sock_i_uid(s)),
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,
4671 static int __net_init packet_net_init(struct net *net)
4673 mutex_init(&net->packet.sklist_lock);
4674 INIT_HLIST_HEAD(&net->packet.sklist);
4676 #ifdef CONFIG_PROC_FS
4677 if (!proc_create_net("packet", 0, net->proc_net, &packet_seq_ops,
4678 sizeof(struct seq_net_private)))
4680 #endif /* CONFIG_PROC_FS */
4685 static void __net_exit packet_net_exit(struct net *net)
4687 remove_proc_entry("packet", net->proc_net);
4688 WARN_ON_ONCE(!hlist_empty(&net->packet.sklist));
4691 static struct pernet_operations packet_net_ops = {
4692 .init = packet_net_init,
4693 .exit = packet_net_exit,
4697 static void __exit packet_exit(void)
4699 unregister_netdevice_notifier(&packet_netdev_notifier);
4700 unregister_pernet_subsys(&packet_net_ops);
4701 sock_unregister(PF_PACKET);
4702 proto_unregister(&packet_proto);
4705 static int __init packet_init(void)
4709 rc = proto_register(&packet_proto, 0);
4712 rc = sock_register(&packet_family_ops);
4715 rc = register_pernet_subsys(&packet_net_ops);
4718 rc = register_netdevice_notifier(&packet_netdev_notifier);
4725 unregister_pernet_subsys(&packet_net_ops);
4727 sock_unregister(PF_PACKET);
4729 proto_unregister(&packet_proto);
4734 module_init(packet_init);
4735 module_exit(packet_exit);
4736 MODULE_LICENSE("GPL");
4737 MODULE_ALIAS_NETPROTO(PF_PACKET);