2 * INET An implementation of the TCP/IP protocol suite for the LINUX
3 * operating system. INET is implemented using the BSD Socket
4 * interface as the means of communication with the user level.
6 * PACKET - implements raw packet sockets.
9 * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
10 * Alan Cox, <gw4pts@gw4pts.ampr.org>
13 * Alan Cox : verify_area() now used correctly
14 * Alan Cox : new skbuff lists, look ma no backlogs!
15 * Alan Cox : tidied skbuff lists.
16 * Alan Cox : Now uses generic datagram routines I
17 * added. Also fixed the peek/read crash
18 * from all old Linux datagram code.
19 * Alan Cox : Uses the improved datagram code.
20 * Alan Cox : Added NULL's for socket options.
21 * Alan Cox : Re-commented the code.
22 * Alan Cox : Use new kernel side addressing
23 * Rob Janssen : Correct MTU usage.
24 * Dave Platt : Counter leaks caused by incorrect
25 * interrupt locking and some slightly
26 * dubious gcc output. Can you read
27 * compiler: it said _VOLATILE_
28 * Richard Kooijman : Timestamp fixes.
29 * Alan Cox : New buffers. Use sk->mac.raw.
30 * Alan Cox : sendmsg/recvmsg support.
31 * Alan Cox : Protocol setting support
32 * Alexey Kuznetsov : Untied from IPv4 stack.
33 * Cyrus Durgin : Fixed kerneld for kmod.
34 * Michal Ostrowski : Module initialization cleanup.
35 * Ulises Alonso : Frame number limit removal and
36 * packet_set_ring memory leak.
37 * Eric Biederman : Allow for > 8 byte hardware addresses.
38 * The convention is that longer addresses
39 * will simply extend the hardware address
40 * byte arrays at the end of sockaddr_ll
42 * Johann Baudy : Added TX RING.
43 * Chetan Loke : Implemented TPACKET_V3 block abstraction
45 * Copyright (C) 2011, <lokec@ccs.neu.edu>
48 * This program is free software; you can redistribute it and/or
49 * modify it under the terms of the GNU General Public License
50 * as published by the Free Software Foundation; either version
51 * 2 of the License, or (at your option) any later version.
55 #include <linux/types.h>
57 #include <linux/capability.h>
58 #include <linux/fcntl.h>
59 #include <linux/socket.h>
61 #include <linux/inet.h>
62 #include <linux/netdevice.h>
63 #include <linux/if_packet.h>
64 #include <linux/wireless.h>
65 #include <linux/kernel.h>
66 #include <linux/delay.h>
67 #include <linux/kmod.h>
68 #include <linux/slab.h>
69 #include <linux/vmalloc.h>
70 #include <net/net_namespace.h>
72 #include <net/protocol.h>
73 #include <linux/skbuff.h>
75 #include <linux/errno.h>
76 #include <linux/timer.h>
77 #include <asm/uaccess.h>
78 #include <asm/ioctls.h>
80 #include <asm/cacheflush.h>
82 #include <linux/proc_fs.h>
83 #include <linux/seq_file.h>
84 #include <linux/poll.h>
85 #include <linux/module.h>
86 #include <linux/init.h>
87 #include <linux/mutex.h>
88 #include <linux/if_vlan.h>
89 #include <linux/virtio_net.h>
90 #include <linux/errqueue.h>
91 #include <linux/net_tstamp.h>
92 #include <linux/percpu.h>
94 #include <net/inet_common.h>
96 #include <linux/bpf.h>
102 - if device has no dev->hard_header routine, it adds and removes ll header
103 inside itself. In this case ll header is invisible outside of device,
104 but higher levels still should reserve dev->hard_header_len.
105 Some devices are enough clever to reallocate skb, when header
106 will not fit to reserved space (tunnel), another ones are silly
108 - packet socket receives packets with pulled ll header,
109 so that SOCK_RAW should push it back.
114 Incoming, dev->hard_header!=NULL
115 mac_header -> ll header
118 Outgoing, dev->hard_header!=NULL
119 mac_header -> ll header
122 Incoming, dev->hard_header==NULL
123 mac_header -> UNKNOWN position. It is very likely, that it points to ll
124 header. PPP makes it, that is wrong, because introduce
125 assymetry between rx and tx paths.
128 Outgoing, dev->hard_header==NULL
129 mac_header -> data. ll header is still not built!
133 If dev->hard_header==NULL we are unlikely to restore sensible ll header.
139 dev->hard_header != NULL
140 mac_header -> ll header
143 dev->hard_header == NULL (ll header is added by device, we cannot control it)
147 We should set nh.raw on output to correct posistion,
148 packet classifier depends on it.
151 /* Private packet socket structures. */
153 /* identical to struct packet_mreq except it has
154 * a longer address field.
156 struct packet_mreq_max {
158 unsigned short mr_type;
159 unsigned short mr_alen;
160 unsigned char mr_address[MAX_ADDR_LEN];
164 struct tpacket_hdr *h1;
165 struct tpacket2_hdr *h2;
166 struct tpacket3_hdr *h3;
170 static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
171 int closing, int tx_ring);
173 #define V3_ALIGNMENT (8)
175 #define BLK_HDR_LEN (ALIGN(sizeof(struct tpacket_block_desc), V3_ALIGNMENT))
177 #define BLK_PLUS_PRIV(sz_of_priv) \
178 (BLK_HDR_LEN + ALIGN((sz_of_priv), V3_ALIGNMENT))
180 #define PGV_FROM_VMALLOC 1
182 #define BLOCK_STATUS(x) ((x)->hdr.bh1.block_status)
183 #define BLOCK_NUM_PKTS(x) ((x)->hdr.bh1.num_pkts)
184 #define BLOCK_O2FP(x) ((x)->hdr.bh1.offset_to_first_pkt)
185 #define BLOCK_LEN(x) ((x)->hdr.bh1.blk_len)
186 #define BLOCK_SNUM(x) ((x)->hdr.bh1.seq_num)
187 #define BLOCK_O2PRIV(x) ((x)->offset_to_priv)
188 #define BLOCK_PRIV(x) ((void *)((char *)(x) + BLOCK_O2PRIV(x)))
191 static int tpacket_snd(struct packet_sock *po, struct msghdr *msg);
192 static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
193 struct packet_type *pt, struct net_device *orig_dev);
195 static void *packet_previous_frame(struct packet_sock *po,
196 struct packet_ring_buffer *rb,
198 static void packet_increment_head(struct packet_ring_buffer *buff);
199 static int prb_curr_blk_in_use(struct tpacket_kbdq_core *,
200 struct tpacket_block_desc *);
201 static void *prb_dispatch_next_block(struct tpacket_kbdq_core *,
202 struct packet_sock *);
203 static void prb_retire_current_block(struct tpacket_kbdq_core *,
204 struct packet_sock *, unsigned int status);
205 static int prb_queue_frozen(struct tpacket_kbdq_core *);
206 static void prb_open_block(struct tpacket_kbdq_core *,
207 struct tpacket_block_desc *);
208 static void prb_retire_rx_blk_timer_expired(unsigned long);
209 static void _prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core *);
210 static void prb_init_blk_timer(struct packet_sock *,
211 struct tpacket_kbdq_core *,
212 void (*func) (unsigned long));
213 static void prb_fill_rxhash(struct tpacket_kbdq_core *, struct tpacket3_hdr *);
214 static void prb_clear_rxhash(struct tpacket_kbdq_core *,
215 struct tpacket3_hdr *);
216 static void prb_fill_vlan_info(struct tpacket_kbdq_core *,
217 struct tpacket3_hdr *);
218 static void packet_flush_mclist(struct sock *sk);
220 struct packet_skb_cb {
222 struct sockaddr_pkt pkt;
224 /* Trick: alias skb original length with
225 * ll.sll_family and ll.protocol in order
228 unsigned int origlen;
229 struct sockaddr_ll ll;
234 #define vio_le() virtio_legacy_is_little_endian()
236 #define PACKET_SKB_CB(__skb) ((struct packet_skb_cb *)((__skb)->cb))
238 #define GET_PBDQC_FROM_RB(x) ((struct tpacket_kbdq_core *)(&(x)->prb_bdqc))
239 #define GET_PBLOCK_DESC(x, bid) \
240 ((struct tpacket_block_desc *)((x)->pkbdq[(bid)].buffer))
241 #define GET_CURR_PBLOCK_DESC_FROM_CORE(x) \
242 ((struct tpacket_block_desc *)((x)->pkbdq[(x)->kactive_blk_num].buffer))
243 #define GET_NEXT_PRB_BLK_NUM(x) \
244 (((x)->kactive_blk_num < ((x)->knum_blocks-1)) ? \
245 ((x)->kactive_blk_num+1) : 0)
247 static void __fanout_unlink(struct sock *sk, struct packet_sock *po);
248 static void __fanout_link(struct sock *sk, struct packet_sock *po);
250 static int packet_direct_xmit(struct sk_buff *skb)
252 struct net_device *dev = skb->dev;
253 netdev_features_t features;
254 struct netdev_queue *txq;
255 int ret = NETDEV_TX_BUSY;
257 if (unlikely(!netif_running(dev) ||
258 !netif_carrier_ok(dev)))
261 features = netif_skb_features(skb);
262 if (skb_needs_linearize(skb, features) &&
263 __skb_linearize(skb))
266 txq = skb_get_tx_queue(dev, skb);
270 HARD_TX_LOCK(dev, txq, smp_processor_id());
271 if (!netif_xmit_frozen_or_drv_stopped(txq))
272 ret = netdev_start_xmit(skb, dev, txq, false);
273 HARD_TX_UNLOCK(dev, txq);
277 if (!dev_xmit_complete(ret))
282 atomic_long_inc(&dev->tx_dropped);
284 return NET_XMIT_DROP;
287 static struct net_device *packet_cached_dev_get(struct packet_sock *po)
289 struct net_device *dev;
292 dev = rcu_dereference(po->cached_dev);
300 static void packet_cached_dev_assign(struct packet_sock *po,
301 struct net_device *dev)
303 rcu_assign_pointer(po->cached_dev, dev);
306 static void packet_cached_dev_reset(struct packet_sock *po)
308 RCU_INIT_POINTER(po->cached_dev, NULL);
311 static bool packet_use_direct_xmit(const struct packet_sock *po)
313 return po->xmit == packet_direct_xmit;
316 static u16 __packet_pick_tx_queue(struct net_device *dev, struct sk_buff *skb)
318 return (u16) raw_smp_processor_id() % dev->real_num_tx_queues;
321 static void packet_pick_tx_queue(struct net_device *dev, struct sk_buff *skb)
323 const struct net_device_ops *ops = dev->netdev_ops;
326 if (ops->ndo_select_queue) {
327 queue_index = ops->ndo_select_queue(dev, skb, NULL,
328 __packet_pick_tx_queue);
329 queue_index = netdev_cap_txqueue(dev, queue_index);
331 queue_index = __packet_pick_tx_queue(dev, skb);
334 skb_set_queue_mapping(skb, queue_index);
337 /* register_prot_hook must be invoked with the po->bind_lock held,
338 * or from a context in which asynchronous accesses to the packet
339 * socket is not possible (packet_create()).
341 static void register_prot_hook(struct sock *sk)
343 struct packet_sock *po = pkt_sk(sk);
347 __fanout_link(sk, po);
349 dev_add_pack(&po->prot_hook);
356 /* {,__}unregister_prot_hook() must be invoked with the po->bind_lock
357 * held. If the sync parameter is true, we will temporarily drop
358 * the po->bind_lock and do a synchronize_net to make sure no
359 * asynchronous packet processing paths still refer to the elements
360 * of po->prot_hook. If the sync parameter is false, it is the
361 * callers responsibility to take care of this.
363 static void __unregister_prot_hook(struct sock *sk, bool sync)
365 struct packet_sock *po = pkt_sk(sk);
370 __fanout_unlink(sk, po);
372 __dev_remove_pack(&po->prot_hook);
377 spin_unlock(&po->bind_lock);
379 spin_lock(&po->bind_lock);
383 static void unregister_prot_hook(struct sock *sk, bool sync)
385 struct packet_sock *po = pkt_sk(sk);
388 __unregister_prot_hook(sk, sync);
391 static inline struct page * __pure pgv_to_page(void *addr)
393 if (is_vmalloc_addr(addr))
394 return vmalloc_to_page(addr);
395 return virt_to_page(addr);
398 static void __packet_set_status(struct packet_sock *po, void *frame, int status)
400 union tpacket_uhdr h;
403 switch (po->tp_version) {
405 h.h1->tp_status = status;
406 flush_dcache_page(pgv_to_page(&h.h1->tp_status));
409 h.h2->tp_status = status;
410 flush_dcache_page(pgv_to_page(&h.h2->tp_status));
414 WARN(1, "TPACKET version not supported.\n");
421 static int __packet_get_status(struct packet_sock *po, void *frame)
423 union tpacket_uhdr h;
428 switch (po->tp_version) {
430 flush_dcache_page(pgv_to_page(&h.h1->tp_status));
431 return h.h1->tp_status;
433 flush_dcache_page(pgv_to_page(&h.h2->tp_status));
434 return h.h2->tp_status;
437 WARN(1, "TPACKET version not supported.\n");
443 static __u32 tpacket_get_timestamp(struct sk_buff *skb, struct timespec *ts,
446 struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);
449 (flags & SOF_TIMESTAMPING_RAW_HARDWARE) &&
450 ktime_to_timespec_cond(shhwtstamps->hwtstamp, ts))
451 return TP_STATUS_TS_RAW_HARDWARE;
453 if (ktime_to_timespec_cond(skb->tstamp, ts))
454 return TP_STATUS_TS_SOFTWARE;
459 static __u32 __packet_set_timestamp(struct packet_sock *po, void *frame,
462 union tpacket_uhdr h;
466 if (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp)))
470 switch (po->tp_version) {
472 h.h1->tp_sec = ts.tv_sec;
473 h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
476 h.h2->tp_sec = ts.tv_sec;
477 h.h2->tp_nsec = ts.tv_nsec;
481 WARN(1, "TPACKET version not supported.\n");
485 /* one flush is safe, as both fields always lie on the same cacheline */
486 flush_dcache_page(pgv_to_page(&h.h1->tp_sec));
492 static void *packet_lookup_frame(struct packet_sock *po,
493 struct packet_ring_buffer *rb,
494 unsigned int position,
497 unsigned int pg_vec_pos, frame_offset;
498 union tpacket_uhdr h;
500 pg_vec_pos = position / rb->frames_per_block;
501 frame_offset = position % rb->frames_per_block;
503 h.raw = rb->pg_vec[pg_vec_pos].buffer +
504 (frame_offset * rb->frame_size);
506 if (status != __packet_get_status(po, h.raw))
512 static void *packet_current_frame(struct packet_sock *po,
513 struct packet_ring_buffer *rb,
516 return packet_lookup_frame(po, rb, rb->head, status);
519 static void prb_del_retire_blk_timer(struct tpacket_kbdq_core *pkc)
521 del_timer_sync(&pkc->retire_blk_timer);
524 static void prb_shutdown_retire_blk_timer(struct packet_sock *po,
525 struct sk_buff_head *rb_queue)
527 struct tpacket_kbdq_core *pkc;
529 pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
531 spin_lock_bh(&rb_queue->lock);
532 pkc->delete_blk_timer = 1;
533 spin_unlock_bh(&rb_queue->lock);
535 prb_del_retire_blk_timer(pkc);
538 static void prb_init_blk_timer(struct packet_sock *po,
539 struct tpacket_kbdq_core *pkc,
540 void (*func) (unsigned long))
542 init_timer(&pkc->retire_blk_timer);
543 pkc->retire_blk_timer.data = (long)po;
544 pkc->retire_blk_timer.function = func;
545 pkc->retire_blk_timer.expires = jiffies;
548 static void prb_setup_retire_blk_timer(struct packet_sock *po)
550 struct tpacket_kbdq_core *pkc;
552 pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
553 prb_init_blk_timer(po, pkc, prb_retire_rx_blk_timer_expired);
556 static int prb_calc_retire_blk_tmo(struct packet_sock *po,
557 int blk_size_in_bytes)
559 struct net_device *dev;
560 unsigned int mbits = 0, msec = 0, div = 0, tmo = 0;
561 struct ethtool_cmd ecmd;
566 dev = __dev_get_by_index(sock_net(&po->sk), po->ifindex);
567 if (unlikely(!dev)) {
569 return DEFAULT_PRB_RETIRE_TOV;
571 err = __ethtool_get_settings(dev, &ecmd);
572 speed = ethtool_cmd_speed(&ecmd);
576 * If the link speed is so slow you don't really
577 * need to worry about perf anyways
579 if (speed < SPEED_1000 || speed == SPEED_UNKNOWN) {
580 return DEFAULT_PRB_RETIRE_TOV;
587 mbits = (blk_size_in_bytes * 8) / (1024 * 1024);
599 static void prb_init_ft_ops(struct tpacket_kbdq_core *p1,
600 union tpacket_req_u *req_u)
602 p1->feature_req_word = req_u->req3.tp_feature_req_word;
605 static void init_prb_bdqc(struct packet_sock *po,
606 struct packet_ring_buffer *rb,
608 union tpacket_req_u *req_u)
610 struct tpacket_kbdq_core *p1 = GET_PBDQC_FROM_RB(rb);
611 struct tpacket_block_desc *pbd;
613 memset(p1, 0x0, sizeof(*p1));
615 p1->knxt_seq_num = 1;
617 pbd = (struct tpacket_block_desc *)pg_vec[0].buffer;
618 p1->pkblk_start = pg_vec[0].buffer;
619 p1->kblk_size = req_u->req3.tp_block_size;
620 p1->knum_blocks = req_u->req3.tp_block_nr;
621 p1->hdrlen = po->tp_hdrlen;
622 p1->version = po->tp_version;
623 p1->last_kactive_blk_num = 0;
624 po->stats.stats3.tp_freeze_q_cnt = 0;
625 if (req_u->req3.tp_retire_blk_tov)
626 p1->retire_blk_tov = req_u->req3.tp_retire_blk_tov;
628 p1->retire_blk_tov = prb_calc_retire_blk_tmo(po,
629 req_u->req3.tp_block_size);
630 p1->tov_in_jiffies = msecs_to_jiffies(p1->retire_blk_tov);
631 p1->blk_sizeof_priv = req_u->req3.tp_sizeof_priv;
633 p1->max_frame_len = p1->kblk_size - BLK_PLUS_PRIV(p1->blk_sizeof_priv);
634 prb_init_ft_ops(p1, req_u);
635 prb_setup_retire_blk_timer(po);
636 prb_open_block(p1, pbd);
639 /* Do NOT update the last_blk_num first.
640 * Assumes sk_buff_head lock is held.
642 static void _prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core *pkc)
644 mod_timer(&pkc->retire_blk_timer,
645 jiffies + pkc->tov_in_jiffies);
646 pkc->last_kactive_blk_num = pkc->kactive_blk_num;
651 * 1) We refresh the timer only when we open a block.
652 * By doing this we don't waste cycles refreshing the timer
653 * on packet-by-packet basis.
655 * With a 1MB block-size, on a 1Gbps line, it will take
656 * i) ~8 ms to fill a block + ii) memcpy etc.
657 * In this cut we are not accounting for the memcpy time.
659 * So, if the user sets the 'tmo' to 10ms then the timer
660 * will never fire while the block is still getting filled
661 * (which is what we want). However, the user could choose
662 * to close a block early and that's fine.
664 * But when the timer does fire, we check whether or not to refresh it.
665 * Since the tmo granularity is in msecs, it is not too expensive
666 * to refresh the timer, lets say every '8' msecs.
667 * Either the user can set the 'tmo' or we can derive it based on
668 * a) line-speed and b) block-size.
669 * prb_calc_retire_blk_tmo() calculates the tmo.
672 static void prb_retire_rx_blk_timer_expired(unsigned long data)
674 struct packet_sock *po = (struct packet_sock *)data;
675 struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
677 struct tpacket_block_desc *pbd;
679 spin_lock(&po->sk.sk_receive_queue.lock);
681 frozen = prb_queue_frozen(pkc);
682 pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
684 if (unlikely(pkc->delete_blk_timer))
687 /* We only need to plug the race when the block is partially filled.
689 * lock(); increment BLOCK_NUM_PKTS; unlock()
690 * copy_bits() is in progress ...
691 * timer fires on other cpu:
692 * we can't retire the current block because copy_bits
696 if (BLOCK_NUM_PKTS(pbd)) {
697 while (atomic_read(&pkc->blk_fill_in_prog)) {
698 /* Waiting for skb_copy_bits to finish... */
703 if (pkc->last_kactive_blk_num == pkc->kactive_blk_num) {
705 if (!BLOCK_NUM_PKTS(pbd)) {
706 /* An empty block. Just refresh the timer. */
709 prb_retire_current_block(pkc, po, TP_STATUS_BLK_TMO);
710 if (!prb_dispatch_next_block(pkc, po))
715 /* Case 1. Queue was frozen because user-space was
718 if (prb_curr_blk_in_use(pkc, pbd)) {
720 * Ok, user-space is still behind.
721 * So just refresh the timer.
725 /* Case 2. queue was frozen,user-space caught up,
726 * now the link went idle && the timer fired.
727 * We don't have a block to close.So we open this
728 * block and restart the timer.
729 * opening a block thaws the queue,restarts timer
730 * Thawing/timer-refresh is a side effect.
732 prb_open_block(pkc, pbd);
739 _prb_refresh_rx_retire_blk_timer(pkc);
742 spin_unlock(&po->sk.sk_receive_queue.lock);
745 static void prb_flush_block(struct tpacket_kbdq_core *pkc1,
746 struct tpacket_block_desc *pbd1, __u32 status)
748 /* Flush everything minus the block header */
750 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
755 /* Skip the block header(we know header WILL fit in 4K) */
758 end = (u8 *)PAGE_ALIGN((unsigned long)pkc1->pkblk_end);
759 for (; start < end; start += PAGE_SIZE)
760 flush_dcache_page(pgv_to_page(start));
765 /* Now update the block status. */
767 BLOCK_STATUS(pbd1) = status;
769 /* Flush the block header */
771 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
773 flush_dcache_page(pgv_to_page(start));
783 * 2) Increment active_blk_num
785 * Note:We DONT refresh the timer on purpose.
786 * Because almost always the next block will be opened.
788 static void prb_close_block(struct tpacket_kbdq_core *pkc1,
789 struct tpacket_block_desc *pbd1,
790 struct packet_sock *po, unsigned int stat)
792 __u32 status = TP_STATUS_USER | stat;
794 struct tpacket3_hdr *last_pkt;
795 struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
796 struct sock *sk = &po->sk;
798 if (po->stats.stats3.tp_drops)
799 status |= TP_STATUS_LOSING;
801 last_pkt = (struct tpacket3_hdr *)pkc1->prev;
802 last_pkt->tp_next_offset = 0;
804 /* Get the ts of the last pkt */
805 if (BLOCK_NUM_PKTS(pbd1)) {
806 h1->ts_last_pkt.ts_sec = last_pkt->tp_sec;
807 h1->ts_last_pkt.ts_nsec = last_pkt->tp_nsec;
809 /* Ok, we tmo'd - so get the current time.
811 * It shouldn't really happen as we don't close empty
812 * blocks. See prb_retire_rx_blk_timer_expired().
816 h1->ts_last_pkt.ts_sec = ts.tv_sec;
817 h1->ts_last_pkt.ts_nsec = ts.tv_nsec;
822 /* Flush the block */
823 prb_flush_block(pkc1, pbd1, status);
825 sk->sk_data_ready(sk);
827 pkc1->kactive_blk_num = GET_NEXT_PRB_BLK_NUM(pkc1);
830 static void prb_thaw_queue(struct tpacket_kbdq_core *pkc)
832 pkc->reset_pending_on_curr_blk = 0;
836 * Side effect of opening a block:
838 * 1) prb_queue is thawed.
839 * 2) retire_blk_timer is refreshed.
842 static void prb_open_block(struct tpacket_kbdq_core *pkc1,
843 struct tpacket_block_desc *pbd1)
846 struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
850 /* We could have just memset this but we will lose the
851 * flexibility of making the priv area sticky
854 BLOCK_SNUM(pbd1) = pkc1->knxt_seq_num++;
855 BLOCK_NUM_PKTS(pbd1) = 0;
856 BLOCK_LEN(pbd1) = BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
860 h1->ts_first_pkt.ts_sec = ts.tv_sec;
861 h1->ts_first_pkt.ts_nsec = ts.tv_nsec;
863 pkc1->pkblk_start = (char *)pbd1;
864 pkc1->nxt_offset = pkc1->pkblk_start + BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
866 BLOCK_O2FP(pbd1) = (__u32)BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
867 BLOCK_O2PRIV(pbd1) = BLK_HDR_LEN;
869 pbd1->version = pkc1->version;
870 pkc1->prev = pkc1->nxt_offset;
871 pkc1->pkblk_end = pkc1->pkblk_start + pkc1->kblk_size;
873 prb_thaw_queue(pkc1);
874 _prb_refresh_rx_retire_blk_timer(pkc1);
880 * Queue freeze logic:
881 * 1) Assume tp_block_nr = 8 blocks.
882 * 2) At time 't0', user opens Rx ring.
883 * 3) Some time past 't0', kernel starts filling blocks starting from 0 .. 7
884 * 4) user-space is either sleeping or processing block '0'.
885 * 5) tpacket_rcv is currently filling block '7', since there is no space left,
886 * it will close block-7,loop around and try to fill block '0'.
888 * __packet_lookup_frame_in_block
889 * prb_retire_current_block()
890 * prb_dispatch_next_block()
891 * |->(BLOCK_STATUS == USER) evaluates to true
892 * 5.1) Since block-0 is currently in-use, we just freeze the queue.
893 * 6) Now there are two cases:
894 * 6.1) Link goes idle right after the queue is frozen.
895 * But remember, the last open_block() refreshed the timer.
896 * When this timer expires,it will refresh itself so that we can
897 * re-open block-0 in near future.
898 * 6.2) Link is busy and keeps on receiving packets. This is a simple
899 * case and __packet_lookup_frame_in_block will check if block-0
900 * is free and can now be re-used.
902 static void prb_freeze_queue(struct tpacket_kbdq_core *pkc,
903 struct packet_sock *po)
905 pkc->reset_pending_on_curr_blk = 1;
906 po->stats.stats3.tp_freeze_q_cnt++;
909 #define TOTAL_PKT_LEN_INCL_ALIGN(length) (ALIGN((length), V3_ALIGNMENT))
912 * If the next block is free then we will dispatch it
913 * and return a good offset.
914 * Else, we will freeze the queue.
915 * So, caller must check the return value.
917 static void *prb_dispatch_next_block(struct tpacket_kbdq_core *pkc,
918 struct packet_sock *po)
920 struct tpacket_block_desc *pbd;
924 /* 1. Get current block num */
925 pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
927 /* 2. If this block is currently in_use then freeze the queue */
928 if (TP_STATUS_USER & BLOCK_STATUS(pbd)) {
929 prb_freeze_queue(pkc, po);
935 * open this block and return the offset where the first packet
936 * needs to get stored.
938 prb_open_block(pkc, pbd);
939 return (void *)pkc->nxt_offset;
942 static void prb_retire_current_block(struct tpacket_kbdq_core *pkc,
943 struct packet_sock *po, unsigned int status)
945 struct tpacket_block_desc *pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
947 /* retire/close the current block */
948 if (likely(TP_STATUS_KERNEL == BLOCK_STATUS(pbd))) {
950 * Plug the case where copy_bits() is in progress on
951 * cpu-0 and tpacket_rcv() got invoked on cpu-1, didn't
952 * have space to copy the pkt in the current block and
953 * called prb_retire_current_block()
955 * We don't need to worry about the TMO case because
956 * the timer-handler already handled this case.
958 if (!(status & TP_STATUS_BLK_TMO)) {
959 while (atomic_read(&pkc->blk_fill_in_prog)) {
960 /* Waiting for skb_copy_bits to finish... */
964 prb_close_block(pkc, pbd, po, status);
969 static int prb_curr_blk_in_use(struct tpacket_kbdq_core *pkc,
970 struct tpacket_block_desc *pbd)
972 return TP_STATUS_USER & BLOCK_STATUS(pbd);
975 static int prb_queue_frozen(struct tpacket_kbdq_core *pkc)
977 return pkc->reset_pending_on_curr_blk;
980 static void prb_clear_blk_fill_status(struct packet_ring_buffer *rb)
982 struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(rb);
983 atomic_dec(&pkc->blk_fill_in_prog);
986 static void prb_fill_rxhash(struct tpacket_kbdq_core *pkc,
987 struct tpacket3_hdr *ppd)
989 ppd->hv1.tp_rxhash = skb_get_hash(pkc->skb);
992 static void prb_clear_rxhash(struct tpacket_kbdq_core *pkc,
993 struct tpacket3_hdr *ppd)
995 ppd->hv1.tp_rxhash = 0;
998 static void prb_fill_vlan_info(struct tpacket_kbdq_core *pkc,
999 struct tpacket3_hdr *ppd)
1001 if (skb_vlan_tag_present(pkc->skb)) {
1002 ppd->hv1.tp_vlan_tci = skb_vlan_tag_get(pkc->skb);
1003 ppd->hv1.tp_vlan_tpid = ntohs(pkc->skb->vlan_proto);
1004 ppd->tp_status = TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
1006 ppd->hv1.tp_vlan_tci = 0;
1007 ppd->hv1.tp_vlan_tpid = 0;
1008 ppd->tp_status = TP_STATUS_AVAILABLE;
1012 static void prb_run_all_ft_ops(struct tpacket_kbdq_core *pkc,
1013 struct tpacket3_hdr *ppd)
1015 ppd->hv1.tp_padding = 0;
1016 prb_fill_vlan_info(pkc, ppd);
1018 if (pkc->feature_req_word & TP_FT_REQ_FILL_RXHASH)
1019 prb_fill_rxhash(pkc, ppd);
1021 prb_clear_rxhash(pkc, ppd);
1024 static void prb_fill_curr_block(char *curr,
1025 struct tpacket_kbdq_core *pkc,
1026 struct tpacket_block_desc *pbd,
1029 struct tpacket3_hdr *ppd;
1031 ppd = (struct tpacket3_hdr *)curr;
1032 ppd->tp_next_offset = TOTAL_PKT_LEN_INCL_ALIGN(len);
1034 pkc->nxt_offset += TOTAL_PKT_LEN_INCL_ALIGN(len);
1035 BLOCK_LEN(pbd) += TOTAL_PKT_LEN_INCL_ALIGN(len);
1036 BLOCK_NUM_PKTS(pbd) += 1;
1037 atomic_inc(&pkc->blk_fill_in_prog);
1038 prb_run_all_ft_ops(pkc, ppd);
1041 /* Assumes caller has the sk->rx_queue.lock */
1042 static void *__packet_lookup_frame_in_block(struct packet_sock *po,
1043 struct sk_buff *skb,
1048 struct tpacket_kbdq_core *pkc;
1049 struct tpacket_block_desc *pbd;
1052 pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
1053 pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
1055 /* Queue is frozen when user space is lagging behind */
1056 if (prb_queue_frozen(pkc)) {
1058 * Check if that last block which caused the queue to freeze,
1059 * is still in_use by user-space.
1061 if (prb_curr_blk_in_use(pkc, pbd)) {
1062 /* Can't record this packet */
1066 * Ok, the block was released by user-space.
1067 * Now let's open that block.
1068 * opening a block also thaws the queue.
1069 * Thawing is a side effect.
1071 prb_open_block(pkc, pbd);
1076 curr = pkc->nxt_offset;
1078 end = (char *)pbd + pkc->kblk_size;
1080 /* first try the current block */
1081 if (curr+TOTAL_PKT_LEN_INCL_ALIGN(len) < end) {
1082 prb_fill_curr_block(curr, pkc, pbd, len);
1083 return (void *)curr;
1086 /* Ok, close the current block */
1087 prb_retire_current_block(pkc, po, 0);
1089 /* Now, try to dispatch the next block */
1090 curr = (char *)prb_dispatch_next_block(pkc, po);
1092 pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
1093 prb_fill_curr_block(curr, pkc, pbd, len);
1094 return (void *)curr;
1098 * No free blocks are available.user_space hasn't caught up yet.
1099 * Queue was just frozen and now this packet will get dropped.
1104 static void *packet_current_rx_frame(struct packet_sock *po,
1105 struct sk_buff *skb,
1106 int status, unsigned int len)
1109 switch (po->tp_version) {
1112 curr = packet_lookup_frame(po, &po->rx_ring,
1113 po->rx_ring.head, status);
1116 return __packet_lookup_frame_in_block(po, skb, status, len);
1118 WARN(1, "TPACKET version not supported\n");
1124 static void *prb_lookup_block(struct packet_sock *po,
1125 struct packet_ring_buffer *rb,
1129 struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(rb);
1130 struct tpacket_block_desc *pbd = GET_PBLOCK_DESC(pkc, idx);
1132 if (status != BLOCK_STATUS(pbd))
1137 static int prb_previous_blk_num(struct packet_ring_buffer *rb)
1140 if (rb->prb_bdqc.kactive_blk_num)
1141 prev = rb->prb_bdqc.kactive_blk_num-1;
1143 prev = rb->prb_bdqc.knum_blocks-1;
1147 /* Assumes caller has held the rx_queue.lock */
1148 static void *__prb_previous_block(struct packet_sock *po,
1149 struct packet_ring_buffer *rb,
1152 unsigned int previous = prb_previous_blk_num(rb);
1153 return prb_lookup_block(po, rb, previous, status);
1156 static void *packet_previous_rx_frame(struct packet_sock *po,
1157 struct packet_ring_buffer *rb,
1160 if (po->tp_version <= TPACKET_V2)
1161 return packet_previous_frame(po, rb, status);
1163 return __prb_previous_block(po, rb, status);
1166 static void packet_increment_rx_head(struct packet_sock *po,
1167 struct packet_ring_buffer *rb)
1169 switch (po->tp_version) {
1172 return packet_increment_head(rb);
1175 WARN(1, "TPACKET version not supported.\n");
1181 static void *packet_previous_frame(struct packet_sock *po,
1182 struct packet_ring_buffer *rb,
1185 unsigned int previous = rb->head ? rb->head - 1 : rb->frame_max;
1186 return packet_lookup_frame(po, rb, previous, status);
1189 static void packet_increment_head(struct packet_ring_buffer *buff)
1191 buff->head = buff->head != buff->frame_max ? buff->head+1 : 0;
1194 static void packet_inc_pending(struct packet_ring_buffer *rb)
1196 this_cpu_inc(*rb->pending_refcnt);
1199 static void packet_dec_pending(struct packet_ring_buffer *rb)
1201 this_cpu_dec(*rb->pending_refcnt);
1204 static unsigned int packet_read_pending(const struct packet_ring_buffer *rb)
1206 unsigned int refcnt = 0;
1209 /* We don't use pending refcount in rx_ring. */
1210 if (rb->pending_refcnt == NULL)
1213 for_each_possible_cpu(cpu)
1214 refcnt += *per_cpu_ptr(rb->pending_refcnt, cpu);
1219 static int packet_alloc_pending(struct packet_sock *po)
1221 po->rx_ring.pending_refcnt = NULL;
1223 po->tx_ring.pending_refcnt = alloc_percpu(unsigned int);
1224 if (unlikely(po->tx_ring.pending_refcnt == NULL))
1230 static void packet_free_pending(struct packet_sock *po)
1232 free_percpu(po->tx_ring.pending_refcnt);
1235 #define ROOM_POW_OFF 2
1236 #define ROOM_NONE 0x0
1237 #define ROOM_LOW 0x1
1238 #define ROOM_NORMAL 0x2
1240 static bool __tpacket_has_room(struct packet_sock *po, int pow_off)
1244 len = po->rx_ring.frame_max + 1;
1245 idx = po->rx_ring.head;
1247 idx += len >> pow_off;
1250 return packet_lookup_frame(po, &po->rx_ring, idx, TP_STATUS_KERNEL);
1253 static bool __tpacket_v3_has_room(struct packet_sock *po, int pow_off)
1257 len = po->rx_ring.prb_bdqc.knum_blocks;
1258 idx = po->rx_ring.prb_bdqc.kactive_blk_num;
1260 idx += len >> pow_off;
1263 return prb_lookup_block(po, &po->rx_ring, idx, TP_STATUS_KERNEL);
1266 static int __packet_rcv_has_room(struct packet_sock *po, struct sk_buff *skb)
1268 struct sock *sk = &po->sk;
1269 int ret = ROOM_NONE;
1271 if (po->prot_hook.func != tpacket_rcv) {
1272 int avail = sk->sk_rcvbuf - atomic_read(&sk->sk_rmem_alloc)
1273 - (skb ? skb->truesize : 0);
1274 if (avail > (sk->sk_rcvbuf >> ROOM_POW_OFF))
1282 if (po->tp_version == TPACKET_V3) {
1283 if (__tpacket_v3_has_room(po, ROOM_POW_OFF))
1285 else if (__tpacket_v3_has_room(po, 0))
1288 if (__tpacket_has_room(po, ROOM_POW_OFF))
1290 else if (__tpacket_has_room(po, 0))
1297 static int packet_rcv_has_room(struct packet_sock *po, struct sk_buff *skb)
1302 spin_lock_bh(&po->sk.sk_receive_queue.lock);
1303 ret = __packet_rcv_has_room(po, skb);
1304 has_room = ret == ROOM_NORMAL;
1305 if (po->pressure == has_room)
1306 po->pressure = !has_room;
1307 spin_unlock_bh(&po->sk.sk_receive_queue.lock);
1312 static void packet_sock_destruct(struct sock *sk)
1314 skb_queue_purge(&sk->sk_error_queue);
1316 WARN_ON(atomic_read(&sk->sk_rmem_alloc));
1317 WARN_ON(atomic_read(&sk->sk_wmem_alloc));
1319 if (!sock_flag(sk, SOCK_DEAD)) {
1320 pr_err("Attempt to release alive packet socket: %p\n", sk);
1324 sk_refcnt_debug_dec(sk);
1327 static bool fanout_flow_is_huge(struct packet_sock *po, struct sk_buff *skb)
1332 rxhash = skb_get_hash(skb);
1333 for (i = 0; i < ROLLOVER_HLEN; i++)
1334 if (po->rollover->history[i] == rxhash)
1337 po->rollover->history[prandom_u32() % ROLLOVER_HLEN] = rxhash;
1338 return count > (ROLLOVER_HLEN >> 1);
1341 static unsigned int fanout_demux_hash(struct packet_fanout *f,
1342 struct sk_buff *skb,
1345 return reciprocal_scale(skb_get_hash(skb), num);
1348 static unsigned int fanout_demux_lb(struct packet_fanout *f,
1349 struct sk_buff *skb,
1352 unsigned int val = atomic_inc_return(&f->rr_cur);
1357 static unsigned int fanout_demux_cpu(struct packet_fanout *f,
1358 struct sk_buff *skb,
1361 return smp_processor_id() % num;
1364 static unsigned int fanout_demux_rnd(struct packet_fanout *f,
1365 struct sk_buff *skb,
1368 return prandom_u32_max(num);
1371 static unsigned int fanout_demux_rollover(struct packet_fanout *f,
1372 struct sk_buff *skb,
1373 unsigned int idx, bool try_self,
1376 struct packet_sock *po, *po_next, *po_skip = NULL;
1377 unsigned int i, j, room = ROOM_NONE;
1379 po = pkt_sk(f->arr[idx]);
1382 room = packet_rcv_has_room(po, skb);
1383 if (room == ROOM_NORMAL ||
1384 (room == ROOM_LOW && !fanout_flow_is_huge(po, skb)))
1389 i = j = min_t(int, po->rollover->sock, num - 1);
1391 po_next = pkt_sk(f->arr[i]);
1392 if (po_next != po_skip && !po_next->pressure &&
1393 packet_rcv_has_room(po_next, skb) == ROOM_NORMAL) {
1395 po->rollover->sock = i;
1396 atomic_long_inc(&po->rollover->num);
1397 if (room == ROOM_LOW)
1398 atomic_long_inc(&po->rollover->num_huge);
1406 atomic_long_inc(&po->rollover->num_failed);
1410 static unsigned int fanout_demux_qm(struct packet_fanout *f,
1411 struct sk_buff *skb,
1414 return skb_get_queue_mapping(skb) % num;
1417 static unsigned int fanout_demux_bpf(struct packet_fanout *f,
1418 struct sk_buff *skb,
1421 struct bpf_prog *prog;
1422 unsigned int ret = 0;
1425 prog = rcu_dereference(f->bpf_prog);
1427 ret = bpf_prog_run_clear_cb(prog, skb) % num;
1433 static bool fanout_has_flag(struct packet_fanout *f, u16 flag)
1435 return f->flags & (flag >> 8);
1438 static int packet_rcv_fanout(struct sk_buff *skb, struct net_device *dev,
1439 struct packet_type *pt, struct net_device *orig_dev)
1441 struct packet_fanout *f = pt->af_packet_priv;
1442 unsigned int num = READ_ONCE(f->num_members);
1443 struct net *net = read_pnet(&f->net);
1444 struct packet_sock *po;
1447 if (!net_eq(dev_net(dev), net) || !num) {
1452 if (fanout_has_flag(f, PACKET_FANOUT_FLAG_DEFRAG)) {
1453 skb = ip_check_defrag(net, skb, IP_DEFRAG_AF_PACKET);
1458 case PACKET_FANOUT_HASH:
1460 idx = fanout_demux_hash(f, skb, num);
1462 case PACKET_FANOUT_LB:
1463 idx = fanout_demux_lb(f, skb, num);
1465 case PACKET_FANOUT_CPU:
1466 idx = fanout_demux_cpu(f, skb, num);
1468 case PACKET_FANOUT_RND:
1469 idx = fanout_demux_rnd(f, skb, num);
1471 case PACKET_FANOUT_QM:
1472 idx = fanout_demux_qm(f, skb, num);
1474 case PACKET_FANOUT_ROLLOVER:
1475 idx = fanout_demux_rollover(f, skb, 0, false, num);
1477 case PACKET_FANOUT_CBPF:
1478 case PACKET_FANOUT_EBPF:
1479 idx = fanout_demux_bpf(f, skb, num);
1483 if (fanout_has_flag(f, PACKET_FANOUT_FLAG_ROLLOVER))
1484 idx = fanout_demux_rollover(f, skb, idx, true, num);
1486 po = pkt_sk(f->arr[idx]);
1487 return po->prot_hook.func(skb, dev, &po->prot_hook, orig_dev);
1490 DEFINE_MUTEX(fanout_mutex);
1491 EXPORT_SYMBOL_GPL(fanout_mutex);
1492 static LIST_HEAD(fanout_list);
1494 static void __fanout_link(struct sock *sk, struct packet_sock *po)
1496 struct packet_fanout *f = po->fanout;
1498 spin_lock(&f->lock);
1499 f->arr[f->num_members] = sk;
1502 spin_unlock(&f->lock);
1505 static void __fanout_unlink(struct sock *sk, struct packet_sock *po)
1507 struct packet_fanout *f = po->fanout;
1510 spin_lock(&f->lock);
1511 for (i = 0; i < f->num_members; i++) {
1512 if (f->arr[i] == sk)
1515 BUG_ON(i >= f->num_members);
1516 f->arr[i] = f->arr[f->num_members - 1];
1518 spin_unlock(&f->lock);
1521 static bool match_fanout_group(struct packet_type *ptype, struct sock *sk)
1523 if (sk->sk_family != PF_PACKET)
1526 return ptype->af_packet_priv == pkt_sk(sk)->fanout;
1529 static void fanout_init_data(struct packet_fanout *f)
1532 case PACKET_FANOUT_LB:
1533 atomic_set(&f->rr_cur, 0);
1535 case PACKET_FANOUT_CBPF:
1536 case PACKET_FANOUT_EBPF:
1537 RCU_INIT_POINTER(f->bpf_prog, NULL);
1542 static void __fanout_set_data_bpf(struct packet_fanout *f, struct bpf_prog *new)
1544 struct bpf_prog *old;
1546 spin_lock(&f->lock);
1547 old = rcu_dereference_protected(f->bpf_prog, lockdep_is_held(&f->lock));
1548 rcu_assign_pointer(f->bpf_prog, new);
1549 spin_unlock(&f->lock);
1553 bpf_prog_destroy(old);
1557 static int fanout_set_data_cbpf(struct packet_sock *po, char __user *data,
1560 struct bpf_prog *new;
1561 struct sock_fprog fprog;
1564 if (sock_flag(&po->sk, SOCK_FILTER_LOCKED))
1566 if (len != sizeof(fprog))
1568 if (copy_from_user(&fprog, data, len))
1571 ret = bpf_prog_create_from_user(&new, &fprog, NULL, false);
1575 __fanout_set_data_bpf(po->fanout, new);
1579 static int fanout_set_data_ebpf(struct packet_sock *po, char __user *data,
1582 struct bpf_prog *new;
1585 if (sock_flag(&po->sk, SOCK_FILTER_LOCKED))
1587 if (len != sizeof(fd))
1589 if (copy_from_user(&fd, data, len))
1592 new = bpf_prog_get(fd);
1594 return PTR_ERR(new);
1595 if (new->type != BPF_PROG_TYPE_SOCKET_FILTER) {
1600 __fanout_set_data_bpf(po->fanout, new);
1604 static int fanout_set_data(struct packet_sock *po, char __user *data,
1607 switch (po->fanout->type) {
1608 case PACKET_FANOUT_CBPF:
1609 return fanout_set_data_cbpf(po, data, len);
1610 case PACKET_FANOUT_EBPF:
1611 return fanout_set_data_ebpf(po, data, len);
1617 static void fanout_release_data(struct packet_fanout *f)
1620 case PACKET_FANOUT_CBPF:
1621 case PACKET_FANOUT_EBPF:
1622 __fanout_set_data_bpf(f, NULL);
1626 static int fanout_add(struct sock *sk, u16 id, u16 type_flags)
1628 struct packet_sock *po = pkt_sk(sk);
1629 struct packet_fanout *f, *match;
1630 u8 type = type_flags & 0xff;
1631 u8 flags = type_flags >> 8;
1635 case PACKET_FANOUT_ROLLOVER:
1636 if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)
1638 case PACKET_FANOUT_HASH:
1639 case PACKET_FANOUT_LB:
1640 case PACKET_FANOUT_CPU:
1641 case PACKET_FANOUT_RND:
1642 case PACKET_FANOUT_QM:
1643 case PACKET_FANOUT_CBPF:
1644 case PACKET_FANOUT_EBPF:
1656 if (type == PACKET_FANOUT_ROLLOVER ||
1657 (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)) {
1658 po->rollover = kzalloc(sizeof(*po->rollover), GFP_KERNEL);
1661 atomic_long_set(&po->rollover->num, 0);
1662 atomic_long_set(&po->rollover->num_huge, 0);
1663 atomic_long_set(&po->rollover->num_failed, 0);
1666 mutex_lock(&fanout_mutex);
1668 list_for_each_entry(f, &fanout_list, list) {
1670 read_pnet(&f->net) == sock_net(sk)) {
1676 if (match && match->flags != flags)
1680 match = kzalloc(sizeof(*match), GFP_KERNEL);
1683 write_pnet(&match->net, sock_net(sk));
1686 match->flags = flags;
1687 INIT_LIST_HEAD(&match->list);
1688 spin_lock_init(&match->lock);
1689 atomic_set(&match->sk_ref, 0);
1690 fanout_init_data(match);
1691 match->prot_hook.type = po->prot_hook.type;
1692 match->prot_hook.dev = po->prot_hook.dev;
1693 match->prot_hook.func = packet_rcv_fanout;
1694 match->prot_hook.af_packet_priv = match;
1695 match->prot_hook.id_match = match_fanout_group;
1696 dev_add_pack(&match->prot_hook);
1697 list_add(&match->list, &fanout_list);
1700 if (match->type == type &&
1701 match->prot_hook.type == po->prot_hook.type &&
1702 match->prot_hook.dev == po->prot_hook.dev) {
1704 if (atomic_read(&match->sk_ref) < PACKET_FANOUT_MAX) {
1705 __dev_remove_pack(&po->prot_hook);
1707 atomic_inc(&match->sk_ref);
1708 __fanout_link(sk, po);
1713 mutex_unlock(&fanout_mutex);
1715 kfree(po->rollover);
1716 po->rollover = NULL;
1721 static void fanout_release(struct sock *sk)
1723 struct packet_sock *po = pkt_sk(sk);
1724 struct packet_fanout *f;
1730 mutex_lock(&fanout_mutex);
1733 if (atomic_dec_and_test(&f->sk_ref)) {
1735 dev_remove_pack(&f->prot_hook);
1736 fanout_release_data(f);
1739 mutex_unlock(&fanout_mutex);
1742 kfree_rcu(po->rollover, rcu);
1745 static bool packet_extra_vlan_len_allowed(const struct net_device *dev,
1746 struct sk_buff *skb)
1748 /* Earlier code assumed this would be a VLAN pkt, double-check
1749 * this now that we have the actual packet in hand. We can only
1750 * do this check on Ethernet devices.
1752 if (unlikely(dev->type != ARPHRD_ETHER))
1755 skb_reset_mac_header(skb);
1756 return likely(eth_hdr(skb)->h_proto == htons(ETH_P_8021Q));
1759 static const struct proto_ops packet_ops;
1761 static const struct proto_ops packet_ops_spkt;
1763 static int packet_rcv_spkt(struct sk_buff *skb, struct net_device *dev,
1764 struct packet_type *pt, struct net_device *orig_dev)
1767 struct sockaddr_pkt *spkt;
1770 * When we registered the protocol we saved the socket in the data
1771 * field for just this event.
1774 sk = pt->af_packet_priv;
1777 * Yank back the headers [hope the device set this
1778 * right or kerboom...]
1780 * Incoming packets have ll header pulled,
1783 * For outgoing ones skb->data == skb_mac_header(skb)
1784 * so that this procedure is noop.
1787 if (skb->pkt_type == PACKET_LOOPBACK)
1790 if (!net_eq(dev_net(dev), sock_net(sk)))
1793 skb = skb_share_check(skb, GFP_ATOMIC);
1797 /* drop any routing info */
1800 /* drop conntrack reference */
1803 spkt = &PACKET_SKB_CB(skb)->sa.pkt;
1805 skb_push(skb, skb->data - skb_mac_header(skb));
1808 * The SOCK_PACKET socket receives _all_ frames.
1811 spkt->spkt_family = dev->type;
1812 strlcpy(spkt->spkt_device, dev->name, sizeof(spkt->spkt_device));
1813 spkt->spkt_protocol = skb->protocol;
1816 * Charge the memory to the socket. This is done specifically
1817 * to prevent sockets using all the memory up.
1820 if (sock_queue_rcv_skb(sk, skb) == 0)
1831 * Output a raw packet to a device layer. This bypasses all the other
1832 * protocol layers and you must therefore supply it with a complete frame
1835 static int packet_sendmsg_spkt(struct socket *sock, struct msghdr *msg,
1838 struct sock *sk = sock->sk;
1839 DECLARE_SOCKADDR(struct sockaddr_pkt *, saddr, msg->msg_name);
1840 struct sk_buff *skb = NULL;
1841 struct net_device *dev;
1847 * Get and verify the address.
1851 if (msg->msg_namelen < sizeof(struct sockaddr))
1853 if (msg->msg_namelen == sizeof(struct sockaddr_pkt))
1854 proto = saddr->spkt_protocol;
1856 return -ENOTCONN; /* SOCK_PACKET must be sent giving an address */
1859 * Find the device first to size check it
1862 saddr->spkt_device[sizeof(saddr->spkt_device) - 1] = 0;
1865 dev = dev_get_by_name_rcu(sock_net(sk), saddr->spkt_device);
1871 if (!(dev->flags & IFF_UP))
1875 * You may not queue a frame bigger than the mtu. This is the lowest level
1876 * raw protocol and you must do your own fragmentation at this level.
1879 if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
1880 if (!netif_supports_nofcs(dev)) {
1881 err = -EPROTONOSUPPORT;
1884 extra_len = 4; /* We're doing our own CRC */
1888 if (len > dev->mtu + dev->hard_header_len + VLAN_HLEN + extra_len)
1892 size_t reserved = LL_RESERVED_SPACE(dev);
1893 int tlen = dev->needed_tailroom;
1894 unsigned int hhlen = dev->header_ops ? dev->hard_header_len : 0;
1897 skb = sock_wmalloc(sk, len + reserved + tlen, 0, GFP_KERNEL);
1900 /* FIXME: Save some space for broken drivers that write a hard
1901 * header at transmission time by themselves. PPP is the notable
1902 * one here. This should really be fixed at the driver level.
1904 skb_reserve(skb, reserved);
1905 skb_reset_network_header(skb);
1907 /* Try to align data part correctly */
1912 skb_reset_network_header(skb);
1914 err = memcpy_from_msg(skb_put(skb, len), msg, len);
1920 if (len > (dev->mtu + dev->hard_header_len + extra_len) &&
1921 !packet_extra_vlan_len_allowed(dev, skb)) {
1926 skb->protocol = proto;
1928 skb->priority = sk->sk_priority;
1929 skb->mark = sk->sk_mark;
1931 sock_tx_timestamp(sk, &skb_shinfo(skb)->tx_flags);
1933 if (unlikely(extra_len == 4))
1936 skb_probe_transport_header(skb, 0);
1938 dev_queue_xmit(skb);
1949 static unsigned int run_filter(struct sk_buff *skb,
1950 const struct sock *sk,
1953 struct sk_filter *filter;
1956 filter = rcu_dereference(sk->sk_filter);
1958 res = bpf_prog_run_clear_cb(filter->prog, skb);
1965 * This function makes lazy skb cloning in hope that most of packets
1966 * are discarded by BPF.
1968 * Note tricky part: we DO mangle shared skb! skb->data, skb->len
1969 * and skb->cb are mangled. It works because (and until) packets
1970 * falling here are owned by current CPU. Output packets are cloned
1971 * by dev_queue_xmit_nit(), input packets are processed by net_bh
1972 * sequencially, so that if we return skb to original state on exit,
1973 * we will not harm anyone.
1976 static int packet_rcv(struct sk_buff *skb, struct net_device *dev,
1977 struct packet_type *pt, struct net_device *orig_dev)
1980 struct sockaddr_ll *sll;
1981 struct packet_sock *po;
1982 u8 *skb_head = skb->data;
1983 int skb_len = skb->len;
1984 unsigned int snaplen, res;
1986 if (skb->pkt_type == PACKET_LOOPBACK)
1989 sk = pt->af_packet_priv;
1992 if (!net_eq(dev_net(dev), sock_net(sk)))
1997 if (dev->header_ops) {
1998 /* The device has an explicit notion of ll header,
1999 * exported to higher levels.
2001 * Otherwise, the device hides details of its frame
2002 * structure, so that corresponding packet head is
2003 * never delivered to user.
2005 if (sk->sk_type != SOCK_DGRAM)
2006 skb_push(skb, skb->data - skb_mac_header(skb));
2007 else if (skb->pkt_type == PACKET_OUTGOING) {
2008 /* Special case: outgoing packets have ll header at head */
2009 skb_pull(skb, skb_network_offset(skb));
2015 res = run_filter(skb, sk, snaplen);
2017 goto drop_n_restore;
2021 if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
2024 if (skb_shared(skb)) {
2025 struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
2029 if (skb_head != skb->data) {
2030 skb->data = skb_head;
2037 sock_skb_cb_check_size(sizeof(*PACKET_SKB_CB(skb)) + MAX_ADDR_LEN - 8);
2039 sll = &PACKET_SKB_CB(skb)->sa.ll;
2040 sll->sll_hatype = dev->type;
2041 sll->sll_pkttype = skb->pkt_type;
2042 if (unlikely(po->origdev))
2043 sll->sll_ifindex = orig_dev->ifindex;
2045 sll->sll_ifindex = dev->ifindex;
2047 sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
2049 /* sll->sll_family and sll->sll_protocol are set in packet_recvmsg().
2050 * Use their space for storing the original skb length.
2052 PACKET_SKB_CB(skb)->sa.origlen = skb->len;
2054 if (pskb_trim(skb, snaplen))
2057 skb_set_owner_r(skb, sk);
2061 /* drop conntrack reference */
2064 spin_lock(&sk->sk_receive_queue.lock);
2065 po->stats.stats1.tp_packets++;
2066 sock_skb_set_dropcount(sk, skb);
2067 __skb_queue_tail(&sk->sk_receive_queue, skb);
2068 spin_unlock(&sk->sk_receive_queue.lock);
2069 sk->sk_data_ready(sk);
2073 spin_lock(&sk->sk_receive_queue.lock);
2074 po->stats.stats1.tp_drops++;
2075 atomic_inc(&sk->sk_drops);
2076 spin_unlock(&sk->sk_receive_queue.lock);
2079 if (skb_head != skb->data && skb_shared(skb)) {
2080 skb->data = skb_head;
2088 static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
2089 struct packet_type *pt, struct net_device *orig_dev)
2092 struct packet_sock *po;
2093 struct sockaddr_ll *sll;
2094 union tpacket_uhdr h;
2095 u8 *skb_head = skb->data;
2096 int skb_len = skb->len;
2097 unsigned int snaplen, res;
2098 unsigned long status = TP_STATUS_USER;
2099 unsigned short macoff, netoff, hdrlen;
2100 struct sk_buff *copy_skb = NULL;
2104 /* struct tpacket{2,3}_hdr is aligned to a multiple of TPACKET_ALIGNMENT.
2105 * We may add members to them until current aligned size without forcing
2106 * userspace to call getsockopt(..., PACKET_HDRLEN, ...).
2108 BUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h2)) != 32);
2109 BUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h3)) != 48);
2111 if (skb->pkt_type == PACKET_LOOPBACK)
2114 sk = pt->af_packet_priv;
2117 if (!net_eq(dev_net(dev), sock_net(sk)))
2120 if (dev->header_ops) {
2121 if (sk->sk_type != SOCK_DGRAM)
2122 skb_push(skb, skb->data - skb_mac_header(skb));
2123 else if (skb->pkt_type == PACKET_OUTGOING) {
2124 /* Special case: outgoing packets have ll header at head */
2125 skb_pull(skb, skb_network_offset(skb));
2131 res = run_filter(skb, sk, snaplen);
2133 goto drop_n_restore;
2135 if (skb->ip_summed == CHECKSUM_PARTIAL)
2136 status |= TP_STATUS_CSUMNOTREADY;
2137 else if (skb->pkt_type != PACKET_OUTGOING &&
2138 (skb->ip_summed == CHECKSUM_COMPLETE ||
2139 skb_csum_unnecessary(skb)))
2140 status |= TP_STATUS_CSUM_VALID;
2145 if (sk->sk_type == SOCK_DGRAM) {
2146 macoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +
2149 unsigned int maclen = skb_network_offset(skb);
2150 netoff = TPACKET_ALIGN(po->tp_hdrlen +
2151 (maclen < 16 ? 16 : maclen)) +
2153 macoff = netoff - maclen;
2155 if (po->tp_version <= TPACKET_V2) {
2156 if (macoff + snaplen > po->rx_ring.frame_size) {
2157 if (po->copy_thresh &&
2158 atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) {
2159 if (skb_shared(skb)) {
2160 copy_skb = skb_clone(skb, GFP_ATOMIC);
2162 copy_skb = skb_get(skb);
2163 skb_head = skb->data;
2166 skb_set_owner_r(copy_skb, sk);
2168 snaplen = po->rx_ring.frame_size - macoff;
2169 if ((int)snaplen < 0)
2172 } else if (unlikely(macoff + snaplen >
2173 GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len)) {
2176 nval = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len - macoff;
2177 pr_err_once("tpacket_rcv: packet too big, clamped from %u to %u. macoff=%u\n",
2178 snaplen, nval, macoff);
2180 if (unlikely((int)snaplen < 0)) {
2182 macoff = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len;
2185 spin_lock(&sk->sk_receive_queue.lock);
2186 h.raw = packet_current_rx_frame(po, skb,
2187 TP_STATUS_KERNEL, (macoff+snaplen));
2190 if (po->tp_version <= TPACKET_V2) {
2191 packet_increment_rx_head(po, &po->rx_ring);
2193 * LOSING will be reported till you read the stats,
2194 * because it's COR - Clear On Read.
2195 * Anyways, moving it for V1/V2 only as V3 doesn't need this
2198 if (po->stats.stats1.tp_drops)
2199 status |= TP_STATUS_LOSING;
2201 po->stats.stats1.tp_packets++;
2203 status |= TP_STATUS_COPY;
2204 __skb_queue_tail(&sk->sk_receive_queue, copy_skb);
2206 spin_unlock(&sk->sk_receive_queue.lock);
2208 skb_copy_bits(skb, 0, h.raw + macoff, snaplen);
2210 if (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp)))
2211 getnstimeofday(&ts);
2213 status |= ts_status;
2215 switch (po->tp_version) {
2217 h.h1->tp_len = skb->len;
2218 h.h1->tp_snaplen = snaplen;
2219 h.h1->tp_mac = macoff;
2220 h.h1->tp_net = netoff;
2221 h.h1->tp_sec = ts.tv_sec;
2222 h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
2223 hdrlen = sizeof(*h.h1);
2226 h.h2->tp_len = skb->len;
2227 h.h2->tp_snaplen = snaplen;
2228 h.h2->tp_mac = macoff;
2229 h.h2->tp_net = netoff;
2230 h.h2->tp_sec = ts.tv_sec;
2231 h.h2->tp_nsec = ts.tv_nsec;
2232 if (skb_vlan_tag_present(skb)) {
2233 h.h2->tp_vlan_tci = skb_vlan_tag_get(skb);
2234 h.h2->tp_vlan_tpid = ntohs(skb->vlan_proto);
2235 status |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
2237 h.h2->tp_vlan_tci = 0;
2238 h.h2->tp_vlan_tpid = 0;
2240 memset(h.h2->tp_padding, 0, sizeof(h.h2->tp_padding));
2241 hdrlen = sizeof(*h.h2);
2244 /* tp_nxt_offset,vlan are already populated above.
2245 * So DONT clear those fields here
2247 h.h3->tp_status |= status;
2248 h.h3->tp_len = skb->len;
2249 h.h3->tp_snaplen = snaplen;
2250 h.h3->tp_mac = macoff;
2251 h.h3->tp_net = netoff;
2252 h.h3->tp_sec = ts.tv_sec;
2253 h.h3->tp_nsec = ts.tv_nsec;
2254 memset(h.h3->tp_padding, 0, sizeof(h.h3->tp_padding));
2255 hdrlen = sizeof(*h.h3);
2261 sll = h.raw + TPACKET_ALIGN(hdrlen);
2262 sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
2263 sll->sll_family = AF_PACKET;
2264 sll->sll_hatype = dev->type;
2265 sll->sll_protocol = skb->protocol;
2266 sll->sll_pkttype = skb->pkt_type;
2267 if (unlikely(po->origdev))
2268 sll->sll_ifindex = orig_dev->ifindex;
2270 sll->sll_ifindex = dev->ifindex;
2274 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
2275 if (po->tp_version <= TPACKET_V2) {
2278 end = (u8 *) PAGE_ALIGN((unsigned long) h.raw +
2281 for (start = h.raw; start < end; start += PAGE_SIZE)
2282 flush_dcache_page(pgv_to_page(start));
2287 if (po->tp_version <= TPACKET_V2) {
2288 __packet_set_status(po, h.raw, status);
2289 sk->sk_data_ready(sk);
2291 prb_clear_blk_fill_status(&po->rx_ring);
2295 if (skb_head != skb->data && skb_shared(skb)) {
2296 skb->data = skb_head;
2304 po->stats.stats1.tp_drops++;
2305 spin_unlock(&sk->sk_receive_queue.lock);
2307 sk->sk_data_ready(sk);
2308 kfree_skb(copy_skb);
2309 goto drop_n_restore;
2312 static void tpacket_destruct_skb(struct sk_buff *skb)
2314 struct packet_sock *po = pkt_sk(skb->sk);
2316 if (likely(po->tx_ring.pg_vec)) {
2320 ph = skb_shinfo(skb)->destructor_arg;
2321 packet_dec_pending(&po->tx_ring);
2323 ts = __packet_set_timestamp(po, ph, skb);
2324 __packet_set_status(po, ph, TP_STATUS_AVAILABLE | ts);
2330 static bool ll_header_truncated(const struct net_device *dev, int len)
2332 /* net device doesn't like empty head */
2333 if (unlikely(len < dev->hard_header_len)) {
2334 net_warn_ratelimited("%s: packet size is too short (%d < %d)\n",
2335 current->comm, len, dev->hard_header_len);
2342 static void tpacket_set_protocol(const struct net_device *dev,
2343 struct sk_buff *skb)
2345 if (dev->type == ARPHRD_ETHER) {
2346 skb_reset_mac_header(skb);
2347 skb->protocol = eth_hdr(skb)->h_proto;
2351 static int tpacket_fill_skb(struct packet_sock *po, struct sk_buff *skb,
2352 void *frame, struct net_device *dev, int size_max,
2353 __be16 proto, unsigned char *addr, int hlen)
2355 union tpacket_uhdr ph;
2356 int to_write, offset, len, tp_len, nr_frags, len_max;
2357 struct socket *sock = po->sk.sk_socket;
2364 skb->protocol = proto;
2366 skb->priority = po->sk.sk_priority;
2367 skb->mark = po->sk.sk_mark;
2368 sock_tx_timestamp(&po->sk, &skb_shinfo(skb)->tx_flags);
2369 skb_shinfo(skb)->destructor_arg = ph.raw;
2371 switch (po->tp_version) {
2373 tp_len = ph.h2->tp_len;
2376 tp_len = ph.h1->tp_len;
2379 if (unlikely(tp_len > size_max)) {
2380 pr_err("packet size is too long (%d > %d)\n", tp_len, size_max);
2384 skb_reserve(skb, hlen);
2385 skb_reset_network_header(skb);
2387 if (unlikely(po->tp_tx_has_off)) {
2388 int off_min, off_max, off;
2389 off_min = po->tp_hdrlen - sizeof(struct sockaddr_ll);
2390 off_max = po->tx_ring.frame_size - tp_len;
2391 if (sock->type == SOCK_DGRAM) {
2392 switch (po->tp_version) {
2394 off = ph.h2->tp_net;
2397 off = ph.h1->tp_net;
2401 switch (po->tp_version) {
2403 off = ph.h2->tp_mac;
2406 off = ph.h1->tp_mac;
2410 if (unlikely((off < off_min) || (off_max < off)))
2412 data = ph.raw + off;
2414 data = ph.raw + po->tp_hdrlen - sizeof(struct sockaddr_ll);
2418 if (sock->type == SOCK_DGRAM) {
2419 err = dev_hard_header(skb, dev, ntohs(proto), addr,
2421 if (unlikely(err < 0))
2423 } else if (dev->hard_header_len) {
2424 if (ll_header_truncated(dev, tp_len))
2427 skb_push(skb, dev->hard_header_len);
2428 err = skb_store_bits(skb, 0, data,
2429 dev->hard_header_len);
2433 tpacket_set_protocol(dev, skb);
2435 data += dev->hard_header_len;
2436 to_write -= dev->hard_header_len;
2439 offset = offset_in_page(data);
2440 len_max = PAGE_SIZE - offset;
2441 len = ((to_write > len_max) ? len_max : to_write);
2443 skb->data_len = to_write;
2444 skb->len += to_write;
2445 skb->truesize += to_write;
2446 atomic_add(to_write, &po->sk.sk_wmem_alloc);
2448 while (likely(to_write)) {
2449 nr_frags = skb_shinfo(skb)->nr_frags;
2451 if (unlikely(nr_frags >= MAX_SKB_FRAGS)) {
2452 pr_err("Packet exceed the number of skb frags(%lu)\n",
2457 page = pgv_to_page(data);
2459 flush_dcache_page(page);
2461 skb_fill_page_desc(skb, nr_frags, page, offset, len);
2464 len_max = PAGE_SIZE;
2465 len = ((to_write > len_max) ? len_max : to_write);
2468 skb_probe_transport_header(skb, 0);
2473 static int tpacket_snd(struct packet_sock *po, struct msghdr *msg)
2475 struct sk_buff *skb;
2476 struct net_device *dev;
2478 int err, reserve = 0;
2480 DECLARE_SOCKADDR(struct sockaddr_ll *, saddr, msg->msg_name);
2481 bool need_wait = !(msg->msg_flags & MSG_DONTWAIT);
2482 int tp_len, size_max;
2483 unsigned char *addr;
2485 int status = TP_STATUS_AVAILABLE;
2488 mutex_lock(&po->pg_vec_lock);
2490 if (likely(saddr == NULL)) {
2491 dev = packet_cached_dev_get(po);
2496 if (msg->msg_namelen < sizeof(struct sockaddr_ll))
2498 if (msg->msg_namelen < (saddr->sll_halen
2499 + offsetof(struct sockaddr_ll,
2502 proto = saddr->sll_protocol;
2503 addr = saddr->sll_addr;
2504 dev = dev_get_by_index(sock_net(&po->sk), saddr->sll_ifindex);
2508 if (unlikely(dev == NULL))
2511 if (unlikely(!(dev->flags & IFF_UP)))
2514 if (po->sk.sk_socket->type == SOCK_RAW)
2515 reserve = dev->hard_header_len;
2516 size_max = po->tx_ring.frame_size
2517 - (po->tp_hdrlen - sizeof(struct sockaddr_ll));
2519 if (size_max > dev->mtu + reserve + VLAN_HLEN)
2520 size_max = dev->mtu + reserve + VLAN_HLEN;
2523 ph = packet_current_frame(po, &po->tx_ring,
2524 TP_STATUS_SEND_REQUEST);
2525 if (unlikely(ph == NULL)) {
2526 if (need_wait && need_resched())
2531 status = TP_STATUS_SEND_REQUEST;
2532 hlen = LL_RESERVED_SPACE(dev);
2533 tlen = dev->needed_tailroom;
2534 skb = sock_alloc_send_skb(&po->sk,
2535 hlen + tlen + sizeof(struct sockaddr_ll),
2538 if (unlikely(skb == NULL)) {
2539 /* we assume the socket was initially writeable ... */
2540 if (likely(len_sum > 0))
2544 tp_len = tpacket_fill_skb(po, skb, ph, dev, size_max, proto,
2546 if (likely(tp_len >= 0) &&
2547 tp_len > dev->mtu + reserve &&
2548 !packet_extra_vlan_len_allowed(dev, skb))
2551 if (unlikely(tp_len < 0)) {
2553 __packet_set_status(po, ph,
2554 TP_STATUS_AVAILABLE);
2555 packet_increment_head(&po->tx_ring);
2559 status = TP_STATUS_WRONG_FORMAT;
2565 packet_pick_tx_queue(dev, skb);
2567 skb->destructor = tpacket_destruct_skb;
2568 __packet_set_status(po, ph, TP_STATUS_SENDING);
2569 packet_inc_pending(&po->tx_ring);
2571 status = TP_STATUS_SEND_REQUEST;
2572 err = po->xmit(skb);
2573 if (unlikely(err > 0)) {
2574 err = net_xmit_errno(err);
2575 if (err && __packet_get_status(po, ph) ==
2576 TP_STATUS_AVAILABLE) {
2577 /* skb was destructed already */
2582 * skb was dropped but not destructed yet;
2583 * let's treat it like congestion or err < 0
2587 packet_increment_head(&po->tx_ring);
2589 } while (likely((ph != NULL) ||
2590 /* Note: packet_read_pending() might be slow if we have
2591 * to call it as it's per_cpu variable, but in fast-path
2592 * we already short-circuit the loop with the first
2593 * condition, and luckily don't have to go that path
2596 (need_wait && packet_read_pending(&po->tx_ring))));
2602 __packet_set_status(po, ph, status);
2607 mutex_unlock(&po->pg_vec_lock);
2611 static struct sk_buff *packet_alloc_skb(struct sock *sk, size_t prepad,
2612 size_t reserve, size_t len,
2613 size_t linear, int noblock,
2616 struct sk_buff *skb;
2618 /* Under a page? Don't bother with paged skb. */
2619 if (prepad + len < PAGE_SIZE || !linear)
2622 skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
2627 skb_reserve(skb, reserve);
2628 skb_put(skb, linear);
2629 skb->data_len = len - linear;
2630 skb->len += len - linear;
2635 static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len)
2637 struct sock *sk = sock->sk;
2638 DECLARE_SOCKADDR(struct sockaddr_ll *, saddr, msg->msg_name);
2639 struct sk_buff *skb;
2640 struct net_device *dev;
2642 unsigned char *addr;
2643 int err, reserve = 0;
2644 struct sockcm_cookie sockc;
2645 struct virtio_net_hdr vnet_hdr = { 0 };
2648 struct packet_sock *po = pkt_sk(sk);
2649 unsigned short gso_type = 0;
2655 * Get and verify the address.
2658 if (likely(saddr == NULL)) {
2659 dev = packet_cached_dev_get(po);
2664 if (msg->msg_namelen < sizeof(struct sockaddr_ll))
2666 if (msg->msg_namelen < (saddr->sll_halen + offsetof(struct sockaddr_ll, sll_addr)))
2668 proto = saddr->sll_protocol;
2669 addr = saddr->sll_addr;
2670 dev = dev_get_by_index(sock_net(sk), saddr->sll_ifindex);
2674 if (unlikely(dev == NULL))
2677 if (unlikely(!(dev->flags & IFF_UP)))
2680 sockc.mark = sk->sk_mark;
2681 if (msg->msg_controllen) {
2682 err = sock_cmsg_send(sk, msg, &sockc);
2687 if (sock->type == SOCK_RAW)
2688 reserve = dev->hard_header_len;
2689 if (po->has_vnet_hdr) {
2690 vnet_hdr_len = sizeof(vnet_hdr);
2693 if (len < vnet_hdr_len)
2696 len -= vnet_hdr_len;
2699 n = copy_from_iter(&vnet_hdr, vnet_hdr_len, &msg->msg_iter);
2700 if (n != vnet_hdr_len)
2703 if ((vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
2704 (__virtio16_to_cpu(vio_le(), vnet_hdr.csum_start) +
2705 __virtio16_to_cpu(vio_le(), vnet_hdr.csum_offset) + 2 >
2706 __virtio16_to_cpu(vio_le(), vnet_hdr.hdr_len)))
2707 vnet_hdr.hdr_len = __cpu_to_virtio16(vio_le(),
2708 __virtio16_to_cpu(vio_le(), vnet_hdr.csum_start) +
2709 __virtio16_to_cpu(vio_le(), vnet_hdr.csum_offset) + 2);
2712 if (__virtio16_to_cpu(vio_le(), vnet_hdr.hdr_len) > len)
2715 if (vnet_hdr.gso_type != VIRTIO_NET_HDR_GSO_NONE) {
2716 switch (vnet_hdr.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
2717 case VIRTIO_NET_HDR_GSO_TCPV4:
2718 gso_type = SKB_GSO_TCPV4;
2720 case VIRTIO_NET_HDR_GSO_TCPV6:
2721 gso_type = SKB_GSO_TCPV6;
2723 case VIRTIO_NET_HDR_GSO_UDP:
2724 gso_type = SKB_GSO_UDP;
2730 if (vnet_hdr.gso_type & VIRTIO_NET_HDR_GSO_ECN)
2731 gso_type |= SKB_GSO_TCP_ECN;
2733 if (vnet_hdr.gso_size == 0)
2739 if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
2740 if (!netif_supports_nofcs(dev)) {
2741 err = -EPROTONOSUPPORT;
2744 extra_len = 4; /* We're doing our own CRC */
2748 if (!gso_type && (len > dev->mtu + reserve + VLAN_HLEN + extra_len))
2752 hlen = LL_RESERVED_SPACE(dev);
2753 tlen = dev->needed_tailroom;
2754 skb = packet_alloc_skb(sk, hlen + tlen, hlen, len,
2755 __virtio16_to_cpu(vio_le(), vnet_hdr.hdr_len),
2756 msg->msg_flags & MSG_DONTWAIT, &err);
2760 skb_set_network_header(skb, reserve);
2763 if (sock->type == SOCK_DGRAM) {
2764 offset = dev_hard_header(skb, dev, ntohs(proto), addr, NULL, len);
2765 if (unlikely(offset < 0))
2768 if (ll_header_truncated(dev, len))
2772 /* Returns -EFAULT on error */
2773 err = skb_copy_datagram_from_iter(skb, offset, &msg->msg_iter, len);
2777 sock_tx_timestamp(sk, &skb_shinfo(skb)->tx_flags);
2779 if (!gso_type && (len > dev->mtu + reserve + extra_len) &&
2780 !packet_extra_vlan_len_allowed(dev, skb)) {
2785 skb->protocol = proto;
2787 skb->priority = sk->sk_priority;
2788 skb->mark = sockc.mark;
2790 packet_pick_tx_queue(dev, skb);
2792 if (po->has_vnet_hdr) {
2793 if (vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
2794 u16 s = __virtio16_to_cpu(vio_le(), vnet_hdr.csum_start);
2795 u16 o = __virtio16_to_cpu(vio_le(), vnet_hdr.csum_offset);
2796 if (!skb_partial_csum_set(skb, s, o)) {
2802 skb_shinfo(skb)->gso_size =
2803 __virtio16_to_cpu(vio_le(), vnet_hdr.gso_size);
2804 skb_shinfo(skb)->gso_type = gso_type;
2806 /* Header must be checked, and gso_segs computed. */
2807 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
2808 skb_shinfo(skb)->gso_segs = 0;
2810 len += vnet_hdr_len;
2813 skb_probe_transport_header(skb, reserve);
2815 if (unlikely(extra_len == 4))
2818 err = po->xmit(skb);
2819 if (err > 0 && (err = net_xmit_errno(err)) != 0)
2835 static int packet_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
2837 struct sock *sk = sock->sk;
2838 struct packet_sock *po = pkt_sk(sk);
2840 if (po->tx_ring.pg_vec)
2841 return tpacket_snd(po, msg);
2843 return packet_snd(sock, msg, len);
2847 * Close a PACKET socket. This is fairly simple. We immediately go
2848 * to 'closed' state and remove our protocol entry in the device list.
2851 static int packet_release(struct socket *sock)
2853 struct sock *sk = sock->sk;
2854 struct packet_sock *po;
2856 union tpacket_req_u req_u;
2864 mutex_lock(&net->packet.sklist_lock);
2865 sk_del_node_init_rcu(sk);
2866 mutex_unlock(&net->packet.sklist_lock);
2869 sock_prot_inuse_add(net, sk->sk_prot, -1);
2872 spin_lock(&po->bind_lock);
2873 unregister_prot_hook(sk, false);
2874 packet_cached_dev_reset(po);
2876 if (po->prot_hook.dev) {
2877 dev_put(po->prot_hook.dev);
2878 po->prot_hook.dev = NULL;
2880 spin_unlock(&po->bind_lock);
2882 packet_flush_mclist(sk);
2884 if (po->rx_ring.pg_vec) {
2885 memset(&req_u, 0, sizeof(req_u));
2886 packet_set_ring(sk, &req_u, 1, 0);
2889 if (po->tx_ring.pg_vec) {
2890 memset(&req_u, 0, sizeof(req_u));
2891 packet_set_ring(sk, &req_u, 1, 1);
2898 * Now the socket is dead. No more input will appear.
2905 skb_queue_purge(&sk->sk_receive_queue);
2906 packet_free_pending(po);
2907 sk_refcnt_debug_release(sk);
2914 * Attach a packet hook.
2917 static int packet_do_bind(struct sock *sk, const char *name, int ifindex,
2920 struct packet_sock *po = pkt_sk(sk);
2921 struct net_device *dev_curr;
2924 struct net_device *dev = NULL;
2926 bool unlisted = false;
2932 spin_lock(&po->bind_lock);
2936 dev = dev_get_by_name_rcu(sock_net(sk), name);
2941 } else if (ifindex) {
2942 dev = dev_get_by_index_rcu(sock_net(sk), ifindex);
2952 proto_curr = po->prot_hook.type;
2953 dev_curr = po->prot_hook.dev;
2955 need_rehook = proto_curr != proto || dev_curr != dev;
2960 __unregister_prot_hook(sk, true);
2962 dev_curr = po->prot_hook.dev;
2964 unlisted = !dev_get_by_index_rcu(sock_net(sk),
2969 po->prot_hook.type = proto;
2971 if (unlikely(unlisted)) {
2973 po->prot_hook.dev = NULL;
2975 packet_cached_dev_reset(po);
2977 po->prot_hook.dev = dev;
2978 po->ifindex = dev ? dev->ifindex : 0;
2979 packet_cached_dev_assign(po, dev);
2985 if (proto == 0 || !need_rehook)
2988 if (!unlisted && (!dev || (dev->flags & IFF_UP))) {
2989 register_prot_hook(sk);
2991 sk->sk_err = ENETDOWN;
2992 if (!sock_flag(sk, SOCK_DEAD))
2993 sk->sk_error_report(sk);
2998 spin_unlock(&po->bind_lock);
3004 * Bind a packet socket to a device
3007 static int packet_bind_spkt(struct socket *sock, struct sockaddr *uaddr,
3010 struct sock *sk = sock->sk;
3017 if (addr_len != sizeof(struct sockaddr))
3019 strlcpy(name, uaddr->sa_data, sizeof(name));
3021 return packet_do_bind(sk, name, 0, pkt_sk(sk)->num);
3024 static int packet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
3026 struct sockaddr_ll *sll = (struct sockaddr_ll *)uaddr;
3027 struct sock *sk = sock->sk;
3033 if (addr_len < sizeof(struct sockaddr_ll))
3035 if (sll->sll_family != AF_PACKET)
3038 return packet_do_bind(sk, NULL, sll->sll_ifindex,
3039 sll->sll_protocol ? : pkt_sk(sk)->num);
3042 static struct proto packet_proto = {
3044 .owner = THIS_MODULE,
3045 .obj_size = sizeof(struct packet_sock),
3049 * Create a packet of type SOCK_PACKET.
3052 static int packet_create(struct net *net, struct socket *sock, int protocol,
3056 struct packet_sock *po;
3057 __be16 proto = (__force __be16)protocol; /* weird, but documented */
3060 if (!ns_capable(net->user_ns, CAP_NET_RAW))
3062 if (sock->type != SOCK_DGRAM && sock->type != SOCK_RAW &&
3063 sock->type != SOCK_PACKET)
3064 return -ESOCKTNOSUPPORT;
3066 sock->state = SS_UNCONNECTED;
3069 sk = sk_alloc(net, PF_PACKET, GFP_KERNEL, &packet_proto, kern);
3073 sock->ops = &packet_ops;
3074 if (sock->type == SOCK_PACKET)
3075 sock->ops = &packet_ops_spkt;
3077 sock_init_data(sock, sk);
3080 sk->sk_family = PF_PACKET;
3082 po->xmit = dev_queue_xmit;
3084 err = packet_alloc_pending(po);
3088 packet_cached_dev_reset(po);
3090 sk->sk_destruct = packet_sock_destruct;
3091 sk_refcnt_debug_inc(sk);
3094 * Attach a protocol block
3097 spin_lock_init(&po->bind_lock);
3098 mutex_init(&po->pg_vec_lock);
3099 po->rollover = NULL;
3100 po->prot_hook.func = packet_rcv;
3102 if (sock->type == SOCK_PACKET)
3103 po->prot_hook.func = packet_rcv_spkt;
3105 po->prot_hook.af_packet_priv = sk;
3108 po->prot_hook.type = proto;
3109 register_prot_hook(sk);
3112 mutex_lock(&net->packet.sklist_lock);
3113 sk_add_node_rcu(sk, &net->packet.sklist);
3114 mutex_unlock(&net->packet.sklist_lock);
3117 sock_prot_inuse_add(net, &packet_proto, 1);
3128 * Pull a packet from our receive queue and hand it to the user.
3129 * If necessary we block.
3132 static int packet_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
3135 struct sock *sk = sock->sk;
3136 struct sk_buff *skb;
3138 int vnet_hdr_len = 0;
3139 unsigned int origlen = 0;
3142 if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT|MSG_ERRQUEUE))
3146 /* What error should we return now? EUNATTACH? */
3147 if (pkt_sk(sk)->ifindex < 0)
3151 if (flags & MSG_ERRQUEUE) {
3152 err = sock_recv_errqueue(sk, msg, len,
3153 SOL_PACKET, PACKET_TX_TIMESTAMP);
3158 * Call the generic datagram receiver. This handles all sorts
3159 * of horrible races and re-entrancy so we can forget about it
3160 * in the protocol layers.
3162 * Now it will return ENETDOWN, if device have just gone down,
3163 * but then it will block.
3166 skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);
3169 * An error occurred so return it. Because skb_recv_datagram()
3170 * handles the blocking we don't see and worry about blocking
3177 if (pkt_sk(sk)->pressure)
3178 packet_rcv_has_room(pkt_sk(sk), NULL);
3180 if (pkt_sk(sk)->has_vnet_hdr) {
3181 struct virtio_net_hdr vnet_hdr = { 0 };
3184 vnet_hdr_len = sizeof(vnet_hdr);
3185 if (len < vnet_hdr_len)
3188 len -= vnet_hdr_len;
3190 if (skb_is_gso(skb)) {
3191 struct skb_shared_info *sinfo = skb_shinfo(skb);
3193 /* This is a hint as to how much should be linear. */
3195 __cpu_to_virtio16(vio_le(), skb_headlen(skb));
3197 __cpu_to_virtio16(vio_le(), sinfo->gso_size);
3198 if (sinfo->gso_type & SKB_GSO_TCPV4)
3199 vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
3200 else if (sinfo->gso_type & SKB_GSO_TCPV6)
3201 vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
3202 else if (sinfo->gso_type & SKB_GSO_UDP)
3203 vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_UDP;
3204 else if (sinfo->gso_type & SKB_GSO_FCOE)
3208 if (sinfo->gso_type & SKB_GSO_TCP_ECN)
3209 vnet_hdr.gso_type |= VIRTIO_NET_HDR_GSO_ECN;
3211 vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE;
3213 if (skb->ip_summed == CHECKSUM_PARTIAL) {
3214 vnet_hdr.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
3215 vnet_hdr.csum_start = __cpu_to_virtio16(vio_le(),
3216 skb_checksum_start_offset(skb));
3217 vnet_hdr.csum_offset = __cpu_to_virtio16(vio_le(),
3219 } else if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
3220 vnet_hdr.flags = VIRTIO_NET_HDR_F_DATA_VALID;
3221 } /* else everything is zero */
3223 err = memcpy_to_msg(msg, (void *)&vnet_hdr, vnet_hdr_len);
3228 /* You lose any data beyond the buffer you gave. If it worries
3229 * a user program they can ask the device for its MTU
3235 msg->msg_flags |= MSG_TRUNC;
3238 err = skb_copy_datagram_msg(skb, 0, msg, copied);
3242 if (sock->type != SOCK_PACKET) {
3243 struct sockaddr_ll *sll = &PACKET_SKB_CB(skb)->sa.ll;
3245 /* Original length was stored in sockaddr_ll fields */
3246 origlen = PACKET_SKB_CB(skb)->sa.origlen;
3247 sll->sll_family = AF_PACKET;
3248 sll->sll_protocol = skb->protocol;
3251 sock_recv_ts_and_drops(msg, sk, skb);
3253 if (msg->msg_name) {
3254 /* If the address length field is there to be filled
3255 * in, we fill it in now.
3257 if (sock->type == SOCK_PACKET) {
3258 __sockaddr_check_size(sizeof(struct sockaddr_pkt));
3259 msg->msg_namelen = sizeof(struct sockaddr_pkt);
3261 struct sockaddr_ll *sll = &PACKET_SKB_CB(skb)->sa.ll;
3263 msg->msg_namelen = sll->sll_halen +
3264 offsetof(struct sockaddr_ll, sll_addr);
3266 memcpy(msg->msg_name, &PACKET_SKB_CB(skb)->sa,
3270 if (pkt_sk(sk)->auxdata) {
3271 struct tpacket_auxdata aux;
3273 aux.tp_status = TP_STATUS_USER;
3274 if (skb->ip_summed == CHECKSUM_PARTIAL)
3275 aux.tp_status |= TP_STATUS_CSUMNOTREADY;
3276 else if (skb->pkt_type != PACKET_OUTGOING &&
3277 (skb->ip_summed == CHECKSUM_COMPLETE ||
3278 skb_csum_unnecessary(skb)))
3279 aux.tp_status |= TP_STATUS_CSUM_VALID;
3281 aux.tp_len = origlen;
3282 aux.tp_snaplen = skb->len;
3284 aux.tp_net = skb_network_offset(skb);
3285 if (skb_vlan_tag_present(skb)) {
3286 aux.tp_vlan_tci = skb_vlan_tag_get(skb);
3287 aux.tp_vlan_tpid = ntohs(skb->vlan_proto);
3288 aux.tp_status |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
3290 aux.tp_vlan_tci = 0;
3291 aux.tp_vlan_tpid = 0;
3293 put_cmsg(msg, SOL_PACKET, PACKET_AUXDATA, sizeof(aux), &aux);
3297 * Free or return the buffer as appropriate. Again this
3298 * hides all the races and re-entrancy issues from us.
3300 err = vnet_hdr_len + ((flags&MSG_TRUNC) ? skb->len : copied);
3303 skb_free_datagram(sk, skb);
3308 static int packet_getname_spkt(struct socket *sock, struct sockaddr *uaddr,
3309 int *uaddr_len, int peer)
3311 struct net_device *dev;
3312 struct sock *sk = sock->sk;
3317 uaddr->sa_family = AF_PACKET;
3318 memset(uaddr->sa_data, 0, sizeof(uaddr->sa_data));
3320 dev = dev_get_by_index_rcu(sock_net(sk), pkt_sk(sk)->ifindex);
3322 strlcpy(uaddr->sa_data, dev->name, sizeof(uaddr->sa_data));
3324 *uaddr_len = sizeof(*uaddr);
3329 static int packet_getname(struct socket *sock, struct sockaddr *uaddr,
3330 int *uaddr_len, int peer)
3332 struct net_device *dev;
3333 struct sock *sk = sock->sk;
3334 struct packet_sock *po = pkt_sk(sk);
3335 DECLARE_SOCKADDR(struct sockaddr_ll *, sll, uaddr);
3340 sll->sll_family = AF_PACKET;
3341 sll->sll_ifindex = po->ifindex;
3342 sll->sll_protocol = po->num;
3343 sll->sll_pkttype = 0;
3345 dev = dev_get_by_index_rcu(sock_net(sk), po->ifindex);
3347 sll->sll_hatype = dev->type;
3348 sll->sll_halen = dev->addr_len;
3349 memcpy(sll->sll_addr, dev->dev_addr, dev->addr_len);
3351 sll->sll_hatype = 0; /* Bad: we have no ARPHRD_UNSPEC */
3355 *uaddr_len = offsetof(struct sockaddr_ll, sll_addr) + sll->sll_halen;
3360 static int packet_dev_mc(struct net_device *dev, struct packet_mclist *i,
3364 case PACKET_MR_MULTICAST:
3365 if (i->alen != dev->addr_len)
3368 return dev_mc_add(dev, i->addr);
3370 return dev_mc_del(dev, i->addr);
3372 case PACKET_MR_PROMISC:
3373 return dev_set_promiscuity(dev, what);
3374 case PACKET_MR_ALLMULTI:
3375 return dev_set_allmulti(dev, what);
3376 case PACKET_MR_UNICAST:
3377 if (i->alen != dev->addr_len)
3380 return dev_uc_add(dev, i->addr);
3382 return dev_uc_del(dev, i->addr);
3390 static void packet_dev_mclist_delete(struct net_device *dev,
3391 struct packet_mclist **mlp)
3393 struct packet_mclist *ml;
3395 while ((ml = *mlp) != NULL) {
3396 if (ml->ifindex == dev->ifindex) {
3397 packet_dev_mc(dev, ml, -1);
3405 static int packet_mc_add(struct sock *sk, struct packet_mreq_max *mreq)
3407 struct packet_sock *po = pkt_sk(sk);
3408 struct packet_mclist *ml, *i;
3409 struct net_device *dev;
3415 dev = __dev_get_by_index(sock_net(sk), mreq->mr_ifindex);
3420 if (mreq->mr_alen > dev->addr_len)
3424 i = kmalloc(sizeof(*i), GFP_KERNEL);
3429 for (ml = po->mclist; ml; ml = ml->next) {
3430 if (ml->ifindex == mreq->mr_ifindex &&
3431 ml->type == mreq->mr_type &&
3432 ml->alen == mreq->mr_alen &&
3433 memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
3435 /* Free the new element ... */
3441 i->type = mreq->mr_type;
3442 i->ifindex = mreq->mr_ifindex;
3443 i->alen = mreq->mr_alen;
3444 memcpy(i->addr, mreq->mr_address, i->alen);
3446 i->next = po->mclist;
3448 err = packet_dev_mc(dev, i, 1);
3450 po->mclist = i->next;
3459 static int packet_mc_drop(struct sock *sk, struct packet_mreq_max *mreq)
3461 struct packet_mclist *ml, **mlp;
3465 for (mlp = &pkt_sk(sk)->mclist; (ml = *mlp) != NULL; mlp = &ml->next) {
3466 if (ml->ifindex == mreq->mr_ifindex &&
3467 ml->type == mreq->mr_type &&
3468 ml->alen == mreq->mr_alen &&
3469 memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
3470 if (--ml->count == 0) {
3471 struct net_device *dev;
3473 dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
3475 packet_dev_mc(dev, ml, -1);
3485 static void packet_flush_mclist(struct sock *sk)
3487 struct packet_sock *po = pkt_sk(sk);
3488 struct packet_mclist *ml;
3494 while ((ml = po->mclist) != NULL) {
3495 struct net_device *dev;
3497 po->mclist = ml->next;
3498 dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
3500 packet_dev_mc(dev, ml, -1);
3507 packet_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen)
3509 struct sock *sk = sock->sk;
3510 struct packet_sock *po = pkt_sk(sk);
3513 if (level != SOL_PACKET)
3514 return -ENOPROTOOPT;
3517 case PACKET_ADD_MEMBERSHIP:
3518 case PACKET_DROP_MEMBERSHIP:
3520 struct packet_mreq_max mreq;
3522 memset(&mreq, 0, sizeof(mreq));
3523 if (len < sizeof(struct packet_mreq))
3525 if (len > sizeof(mreq))
3527 if (copy_from_user(&mreq, optval, len))
3529 if (len < (mreq.mr_alen + offsetof(struct packet_mreq, mr_address)))
3531 if (optname == PACKET_ADD_MEMBERSHIP)
3532 ret = packet_mc_add(sk, &mreq);
3534 ret = packet_mc_drop(sk, &mreq);
3538 case PACKET_RX_RING:
3539 case PACKET_TX_RING:
3541 union tpacket_req_u req_u;
3544 switch (po->tp_version) {
3547 len = sizeof(req_u.req);
3551 len = sizeof(req_u.req3);
3556 if (pkt_sk(sk)->has_vnet_hdr)
3558 if (copy_from_user(&req_u.req, optval, len))
3560 return packet_set_ring(sk, &req_u, 0,
3561 optname == PACKET_TX_RING);
3563 case PACKET_COPY_THRESH:
3567 if (optlen != sizeof(val))
3569 if (copy_from_user(&val, optval, sizeof(val)))
3572 pkt_sk(sk)->copy_thresh = val;
3575 case PACKET_VERSION:
3579 if (optlen != sizeof(val))
3581 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3583 if (copy_from_user(&val, optval, sizeof(val)))
3589 po->tp_version = val;
3595 case PACKET_RESERVE:
3599 if (optlen != sizeof(val))
3601 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3603 if (copy_from_user(&val, optval, sizeof(val)))
3605 po->tp_reserve = val;
3612 if (optlen != sizeof(val))
3614 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3616 if (copy_from_user(&val, optval, sizeof(val)))
3618 po->tp_loss = !!val;
3621 case PACKET_AUXDATA:
3625 if (optlen < sizeof(val))
3627 if (copy_from_user(&val, optval, sizeof(val)))
3630 po->auxdata = !!val;
3633 case PACKET_ORIGDEV:
3637 if (optlen < sizeof(val))
3639 if (copy_from_user(&val, optval, sizeof(val)))
3642 po->origdev = !!val;
3645 case PACKET_VNET_HDR:
3649 if (sock->type != SOCK_RAW)
3651 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3653 if (optlen < sizeof(val))
3655 if (copy_from_user(&val, optval, sizeof(val)))
3658 po->has_vnet_hdr = !!val;
3661 case PACKET_TIMESTAMP:
3665 if (optlen != sizeof(val))
3667 if (copy_from_user(&val, optval, sizeof(val)))
3670 po->tp_tstamp = val;
3677 if (optlen != sizeof(val))
3679 if (copy_from_user(&val, optval, sizeof(val)))
3682 return fanout_add(sk, val & 0xffff, val >> 16);
3684 case PACKET_FANOUT_DATA:
3689 return fanout_set_data(po, optval, optlen);
3691 case PACKET_TX_HAS_OFF:
3695 if (optlen != sizeof(val))
3697 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3699 if (copy_from_user(&val, optval, sizeof(val)))
3701 po->tp_tx_has_off = !!val;
3704 case PACKET_QDISC_BYPASS:
3708 if (optlen != sizeof(val))
3710 if (copy_from_user(&val, optval, sizeof(val)))
3713 po->xmit = val ? packet_direct_xmit : dev_queue_xmit;
3717 return -ENOPROTOOPT;
3721 static int packet_getsockopt(struct socket *sock, int level, int optname,
3722 char __user *optval, int __user *optlen)
3725 int val, lv = sizeof(val);
3726 struct sock *sk = sock->sk;
3727 struct packet_sock *po = pkt_sk(sk);
3729 union tpacket_stats_u st;
3730 struct tpacket_rollover_stats rstats;
3732 if (level != SOL_PACKET)
3733 return -ENOPROTOOPT;
3735 if (get_user(len, optlen))
3742 case PACKET_STATISTICS:
3743 spin_lock_bh(&sk->sk_receive_queue.lock);
3744 memcpy(&st, &po->stats, sizeof(st));
3745 memset(&po->stats, 0, sizeof(po->stats));
3746 spin_unlock_bh(&sk->sk_receive_queue.lock);
3748 if (po->tp_version == TPACKET_V3) {
3749 lv = sizeof(struct tpacket_stats_v3);
3750 st.stats3.tp_packets += st.stats3.tp_drops;
3753 lv = sizeof(struct tpacket_stats);
3754 st.stats1.tp_packets += st.stats1.tp_drops;
3759 case PACKET_AUXDATA:
3762 case PACKET_ORIGDEV:
3765 case PACKET_VNET_HDR:
3766 val = po->has_vnet_hdr;
3768 case PACKET_VERSION:
3769 val = po->tp_version;
3772 if (len > sizeof(int))
3774 if (copy_from_user(&val, optval, len))
3778 val = sizeof(struct tpacket_hdr);
3781 val = sizeof(struct tpacket2_hdr);
3784 val = sizeof(struct tpacket3_hdr);
3790 case PACKET_RESERVE:
3791 val = po->tp_reserve;
3796 case PACKET_TIMESTAMP:
3797 val = po->tp_tstamp;
3801 ((u32)po->fanout->id |
3802 ((u32)po->fanout->type << 16) |
3803 ((u32)po->fanout->flags << 24)) :
3806 case PACKET_ROLLOVER_STATS:
3809 rstats.tp_all = atomic_long_read(&po->rollover->num);
3810 rstats.tp_huge = atomic_long_read(&po->rollover->num_huge);
3811 rstats.tp_failed = atomic_long_read(&po->rollover->num_failed);
3813 lv = sizeof(rstats);
3815 case PACKET_TX_HAS_OFF:
3816 val = po->tp_tx_has_off;
3818 case PACKET_QDISC_BYPASS:
3819 val = packet_use_direct_xmit(po);
3822 return -ENOPROTOOPT;
3827 if (put_user(len, optlen))
3829 if (copy_to_user(optval, data, len))
3835 static int packet_notifier(struct notifier_block *this,
3836 unsigned long msg, void *ptr)
3839 struct net_device *dev = netdev_notifier_info_to_dev(ptr);
3840 struct net *net = dev_net(dev);
3843 sk_for_each_rcu(sk, &net->packet.sklist) {
3844 struct packet_sock *po = pkt_sk(sk);
3847 case NETDEV_UNREGISTER:
3849 packet_dev_mclist_delete(dev, &po->mclist);
3853 if (dev->ifindex == po->ifindex) {
3854 spin_lock(&po->bind_lock);
3856 __unregister_prot_hook(sk, false);
3857 sk->sk_err = ENETDOWN;
3858 if (!sock_flag(sk, SOCK_DEAD))
3859 sk->sk_error_report(sk);
3861 if (msg == NETDEV_UNREGISTER) {
3862 packet_cached_dev_reset(po);
3864 if (po->prot_hook.dev)
3865 dev_put(po->prot_hook.dev);
3866 po->prot_hook.dev = NULL;
3868 spin_unlock(&po->bind_lock);
3872 if (dev->ifindex == po->ifindex) {
3873 spin_lock(&po->bind_lock);
3875 register_prot_hook(sk);
3876 spin_unlock(&po->bind_lock);
3886 static int packet_ioctl(struct socket *sock, unsigned int cmd,
3889 struct sock *sk = sock->sk;
3894 int amount = sk_wmem_alloc_get(sk);
3896 return put_user(amount, (int __user *)arg);
3900 struct sk_buff *skb;
3903 spin_lock_bh(&sk->sk_receive_queue.lock);
3904 skb = skb_peek(&sk->sk_receive_queue);
3907 spin_unlock_bh(&sk->sk_receive_queue.lock);
3908 return put_user(amount, (int __user *)arg);
3911 return sock_get_timestamp(sk, (struct timeval __user *)arg);
3913 return sock_get_timestampns(sk, (struct timespec __user *)arg);
3923 case SIOCGIFBRDADDR:
3924 case SIOCSIFBRDADDR:
3925 case SIOCGIFNETMASK:
3926 case SIOCSIFNETMASK:
3927 case SIOCGIFDSTADDR:
3928 case SIOCSIFDSTADDR:
3930 return inet_dgram_ops.ioctl(sock, cmd, arg);
3934 return -ENOIOCTLCMD;
3939 static unsigned int packet_poll(struct file *file, struct socket *sock,
3942 struct sock *sk = sock->sk;
3943 struct packet_sock *po = pkt_sk(sk);
3944 unsigned int mask = datagram_poll(file, sock, wait);
3946 spin_lock_bh(&sk->sk_receive_queue.lock);
3947 if (po->rx_ring.pg_vec) {
3948 if (!packet_previous_rx_frame(po, &po->rx_ring,
3950 mask |= POLLIN | POLLRDNORM;
3952 if (po->pressure && __packet_rcv_has_room(po, NULL) == ROOM_NORMAL)
3954 spin_unlock_bh(&sk->sk_receive_queue.lock);
3955 spin_lock_bh(&sk->sk_write_queue.lock);
3956 if (po->tx_ring.pg_vec) {
3957 if (packet_current_frame(po, &po->tx_ring, TP_STATUS_AVAILABLE))
3958 mask |= POLLOUT | POLLWRNORM;
3960 spin_unlock_bh(&sk->sk_write_queue.lock);
3965 /* Dirty? Well, I still did not learn better way to account
3969 static void packet_mm_open(struct vm_area_struct *vma)
3971 struct file *file = vma->vm_file;
3972 struct socket *sock = file->private_data;
3973 struct sock *sk = sock->sk;
3976 atomic_inc(&pkt_sk(sk)->mapped);
3979 static void packet_mm_close(struct vm_area_struct *vma)
3981 struct file *file = vma->vm_file;
3982 struct socket *sock = file->private_data;
3983 struct sock *sk = sock->sk;
3986 atomic_dec(&pkt_sk(sk)->mapped);
3989 static const struct vm_operations_struct packet_mmap_ops = {
3990 .open = packet_mm_open,
3991 .close = packet_mm_close,
3994 static void free_pg_vec(struct pgv *pg_vec, unsigned int order,
3999 for (i = 0; i < len; i++) {
4000 if (likely(pg_vec[i].buffer)) {
4001 if (is_vmalloc_addr(pg_vec[i].buffer))
4002 vfree(pg_vec[i].buffer);
4004 free_pages((unsigned long)pg_vec[i].buffer,
4006 pg_vec[i].buffer = NULL;
4012 static char *alloc_one_pg_vec_page(unsigned long order)
4015 gfp_t gfp_flags = GFP_KERNEL | __GFP_COMP |
4016 __GFP_ZERO | __GFP_NOWARN | __GFP_NORETRY;
4018 buffer = (char *) __get_free_pages(gfp_flags, order);
4022 /* __get_free_pages failed, fall back to vmalloc */
4023 buffer = vzalloc((1 << order) * PAGE_SIZE);
4027 /* vmalloc failed, lets dig into swap here */
4028 gfp_flags &= ~__GFP_NORETRY;
4029 buffer = (char *) __get_free_pages(gfp_flags, order);
4033 /* complete and utter failure */
4037 static struct pgv *alloc_pg_vec(struct tpacket_req *req, int order)
4039 unsigned int block_nr = req->tp_block_nr;
4043 pg_vec = kcalloc(block_nr, sizeof(struct pgv), GFP_KERNEL);
4044 if (unlikely(!pg_vec))
4047 for (i = 0; i < block_nr; i++) {
4048 pg_vec[i].buffer = alloc_one_pg_vec_page(order);
4049 if (unlikely(!pg_vec[i].buffer))
4050 goto out_free_pgvec;
4057 free_pg_vec(pg_vec, order, block_nr);
4062 static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
4063 int closing, int tx_ring)
4065 struct pgv *pg_vec = NULL;
4066 struct packet_sock *po = pkt_sk(sk);
4067 int was_running, order = 0;
4068 struct packet_ring_buffer *rb;
4069 struct sk_buff_head *rb_queue;
4072 /* Added to avoid minimal code churn */
4073 struct tpacket_req *req = &req_u->req;
4075 /* Opening a Tx-ring is NOT supported in TPACKET_V3 */
4076 if (!closing && tx_ring && (po->tp_version > TPACKET_V2)) {
4077 WARN(1, "Tx-ring is not supported.\n");
4081 rb = tx_ring ? &po->tx_ring : &po->rx_ring;
4082 rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue;
4086 if (atomic_read(&po->mapped))
4088 if (packet_read_pending(rb))
4092 if (req->tp_block_nr) {
4093 /* Sanity tests and some calculations */
4095 if (unlikely(rb->pg_vec))
4098 switch (po->tp_version) {
4100 po->tp_hdrlen = TPACKET_HDRLEN;
4103 po->tp_hdrlen = TPACKET2_HDRLEN;
4106 po->tp_hdrlen = TPACKET3_HDRLEN;
4111 if (unlikely((int)req->tp_block_size <= 0))
4113 if (unlikely(!PAGE_ALIGNED(req->tp_block_size)))
4115 if (po->tp_version >= TPACKET_V3 &&
4116 (int)(req->tp_block_size -
4117 BLK_PLUS_PRIV(req_u->req3.tp_sizeof_priv)) <= 0)
4119 if (unlikely(req->tp_frame_size < po->tp_hdrlen +
4122 if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1)))
4125 rb->frames_per_block = req->tp_block_size / req->tp_frame_size;
4126 if (unlikely(rb->frames_per_block == 0))
4128 if (unlikely((rb->frames_per_block * req->tp_block_nr) !=
4133 order = get_order(req->tp_block_size);
4134 pg_vec = alloc_pg_vec(req, order);
4135 if (unlikely(!pg_vec))
4137 switch (po->tp_version) {
4139 /* Transmit path is not supported. We checked
4140 * it above but just being paranoid
4143 init_prb_bdqc(po, rb, pg_vec, req_u);
4152 if (unlikely(req->tp_frame_nr))
4158 /* Detach socket from network */
4159 spin_lock(&po->bind_lock);
4160 was_running = po->running;
4164 __unregister_prot_hook(sk, false);
4166 spin_unlock(&po->bind_lock);
4171 mutex_lock(&po->pg_vec_lock);
4172 if (closing || atomic_read(&po->mapped) == 0) {
4174 spin_lock_bh(&rb_queue->lock);
4175 swap(rb->pg_vec, pg_vec);
4176 rb->frame_max = (req->tp_frame_nr - 1);
4178 rb->frame_size = req->tp_frame_size;
4179 spin_unlock_bh(&rb_queue->lock);
4181 swap(rb->pg_vec_order, order);
4182 swap(rb->pg_vec_len, req->tp_block_nr);
4184 rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE;
4185 po->prot_hook.func = (po->rx_ring.pg_vec) ?
4186 tpacket_rcv : packet_rcv;
4187 skb_queue_purge(rb_queue);
4188 if (atomic_read(&po->mapped))
4189 pr_err("packet_mmap: vma is busy: %d\n",
4190 atomic_read(&po->mapped));
4192 mutex_unlock(&po->pg_vec_lock);
4194 spin_lock(&po->bind_lock);
4197 register_prot_hook(sk);
4199 spin_unlock(&po->bind_lock);
4200 if (closing && (po->tp_version > TPACKET_V2)) {
4201 /* Because we don't support block-based V3 on tx-ring */
4203 prb_shutdown_retire_blk_timer(po, rb_queue);
4208 free_pg_vec(pg_vec, order, req->tp_block_nr);
4213 static int packet_mmap(struct file *file, struct socket *sock,
4214 struct vm_area_struct *vma)
4216 struct sock *sk = sock->sk;
4217 struct packet_sock *po = pkt_sk(sk);
4218 unsigned long size, expected_size;
4219 struct packet_ring_buffer *rb;
4220 unsigned long start;
4227 mutex_lock(&po->pg_vec_lock);
4230 for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
4232 expected_size += rb->pg_vec_len
4238 if (expected_size == 0)
4241 size = vma->vm_end - vma->vm_start;
4242 if (size != expected_size)
4245 start = vma->vm_start;
4246 for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
4247 if (rb->pg_vec == NULL)
4250 for (i = 0; i < rb->pg_vec_len; i++) {
4252 void *kaddr = rb->pg_vec[i].buffer;
4255 for (pg_num = 0; pg_num < rb->pg_vec_pages; pg_num++) {
4256 page = pgv_to_page(kaddr);
4257 err = vm_insert_page(vma, start, page);
4266 atomic_inc(&po->mapped);
4267 vma->vm_ops = &packet_mmap_ops;
4271 mutex_unlock(&po->pg_vec_lock);
4275 static const struct proto_ops packet_ops_spkt = {
4276 .family = PF_PACKET,
4277 .owner = THIS_MODULE,
4278 .release = packet_release,
4279 .bind = packet_bind_spkt,
4280 .connect = sock_no_connect,
4281 .socketpair = sock_no_socketpair,
4282 .accept = sock_no_accept,
4283 .getname = packet_getname_spkt,
4284 .poll = datagram_poll,
4285 .ioctl = packet_ioctl,
4286 .listen = sock_no_listen,
4287 .shutdown = sock_no_shutdown,
4288 .setsockopt = sock_no_setsockopt,
4289 .getsockopt = sock_no_getsockopt,
4290 .sendmsg = packet_sendmsg_spkt,
4291 .recvmsg = packet_recvmsg,
4292 .mmap = sock_no_mmap,
4293 .sendpage = sock_no_sendpage,
4296 static const struct proto_ops packet_ops = {
4297 .family = PF_PACKET,
4298 .owner = THIS_MODULE,
4299 .release = packet_release,
4300 .bind = packet_bind,
4301 .connect = sock_no_connect,
4302 .socketpair = sock_no_socketpair,
4303 .accept = sock_no_accept,
4304 .getname = packet_getname,
4305 .poll = packet_poll,
4306 .ioctl = packet_ioctl,
4307 .listen = sock_no_listen,
4308 .shutdown = sock_no_shutdown,
4309 .setsockopt = packet_setsockopt,
4310 .getsockopt = packet_getsockopt,
4311 .sendmsg = packet_sendmsg,
4312 .recvmsg = packet_recvmsg,
4313 .mmap = packet_mmap,
4314 .sendpage = sock_no_sendpage,
4317 static const struct net_proto_family packet_family_ops = {
4318 .family = PF_PACKET,
4319 .create = packet_create,
4320 .owner = THIS_MODULE,
4323 static struct notifier_block packet_netdev_notifier = {
4324 .notifier_call = packet_notifier,
4327 #ifdef CONFIG_PROC_FS
4329 static void *packet_seq_start(struct seq_file *seq, loff_t *pos)
4332 struct net *net = seq_file_net(seq);
4335 return seq_hlist_start_head_rcu(&net->packet.sklist, *pos);
4338 static void *packet_seq_next(struct seq_file *seq, void *v, loff_t *pos)
4340 struct net *net = seq_file_net(seq);
4341 return seq_hlist_next_rcu(v, &net->packet.sklist, pos);
4344 static void packet_seq_stop(struct seq_file *seq, void *v)
4350 static int packet_seq_show(struct seq_file *seq, void *v)
4352 if (v == SEQ_START_TOKEN)
4353 seq_puts(seq, "sk RefCnt Type Proto Iface R Rmem User Inode\n");
4355 struct sock *s = sk_entry(v);
4356 const struct packet_sock *po = pkt_sk(s);
4359 "%pK %-6d %-4d %04x %-5d %1d %-6u %-6u %-6lu\n",
4361 atomic_read(&s->sk_refcnt),
4366 atomic_read(&s->sk_rmem_alloc),
4367 from_kuid_munged(seq_user_ns(seq), sock_i_uid(s)),
4374 static const struct seq_operations packet_seq_ops = {
4375 .start = packet_seq_start,
4376 .next = packet_seq_next,
4377 .stop = packet_seq_stop,
4378 .show = packet_seq_show,
4381 static int packet_seq_open(struct inode *inode, struct file *file)
4383 return seq_open_net(inode, file, &packet_seq_ops,
4384 sizeof(struct seq_net_private));
4387 static const struct file_operations packet_seq_fops = {
4388 .owner = THIS_MODULE,
4389 .open = packet_seq_open,
4391 .llseek = seq_lseek,
4392 .release = seq_release_net,
4397 static int __net_init packet_net_init(struct net *net)
4399 mutex_init(&net->packet.sklist_lock);
4400 INIT_HLIST_HEAD(&net->packet.sklist);
4402 if (!proc_create("packet", 0, net->proc_net, &packet_seq_fops))
4408 static void __net_exit packet_net_exit(struct net *net)
4410 remove_proc_entry("packet", net->proc_net);
4413 static struct pernet_operations packet_net_ops = {
4414 .init = packet_net_init,
4415 .exit = packet_net_exit,
4419 static void __exit packet_exit(void)
4421 unregister_netdevice_notifier(&packet_netdev_notifier);
4422 unregister_pernet_subsys(&packet_net_ops);
4423 sock_unregister(PF_PACKET);
4424 proto_unregister(&packet_proto);
4427 static int __init packet_init(void)
4429 int rc = proto_register(&packet_proto, 0);
4434 sock_register(&packet_family_ops);
4435 register_pernet_subsys(&packet_net_ops);
4436 register_netdevice_notifier(&packet_netdev_notifier);
4441 module_init(packet_init);
4442 module_exit(packet_exit);
4443 MODULE_LICENSE("GPL");
4444 MODULE_ALIAS_NETPROTO(PF_PACKET);