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/kmod.h>
67 #include <linux/slab.h>
68 #include <linux/vmalloc.h>
69 #include <net/net_namespace.h>
71 #include <net/protocol.h>
72 #include <linux/skbuff.h>
74 #include <linux/errno.h>
75 #include <linux/timer.h>
76 #include <asm/uaccess.h>
77 #include <asm/ioctls.h>
79 #include <asm/cacheflush.h>
81 #include <linux/proc_fs.h>
82 #include <linux/seq_file.h>
83 #include <linux/poll.h>
84 #include <linux/module.h>
85 #include <linux/init.h>
86 #include <linux/mutex.h>
87 #include <linux/if_vlan.h>
88 #include <linux/virtio_net.h>
89 #include <linux/errqueue.h>
90 #include <linux/net_tstamp.h>
91 #include <net/flow_keys.h>
94 #include <net/inet_common.h>
101 - if device has no dev->hard_header routine, it adds and removes ll header
102 inside itself. In this case ll header is invisible outside of device,
103 but higher levels still should reserve dev->hard_header_len.
104 Some devices are enough clever to reallocate skb, when header
105 will not fit to reserved space (tunnel), another ones are silly
107 - packet socket receives packets with pulled ll header,
108 so that SOCK_RAW should push it back.
113 Incoming, dev->hard_header!=NULL
114 mac_header -> ll header
117 Outgoing, dev->hard_header!=NULL
118 mac_header -> ll header
121 Incoming, dev->hard_header==NULL
122 mac_header -> UNKNOWN position. It is very likely, that it points to ll
123 header. PPP makes it, that is wrong, because introduce
124 assymetry between rx and tx paths.
127 Outgoing, dev->hard_header==NULL
128 mac_header -> data. ll header is still not built!
132 If dev->hard_header==NULL we are unlikely to restore sensible ll header.
138 dev->hard_header != NULL
139 mac_header -> ll header
142 dev->hard_header == NULL (ll header is added by device, we cannot control it)
146 We should set nh.raw on output to correct posistion,
147 packet classifier depends on it.
150 /* Private packet socket structures. */
152 /* identical to struct packet_mreq except it has
153 * a longer address field.
155 struct packet_mreq_max {
157 unsigned short mr_type;
158 unsigned short mr_alen;
159 unsigned char mr_address[MAX_ADDR_LEN];
162 static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
163 int closing, int tx_ring);
166 #define V3_ALIGNMENT (8)
168 #define BLK_HDR_LEN (ALIGN(sizeof(struct tpacket_block_desc), V3_ALIGNMENT))
170 #define BLK_PLUS_PRIV(sz_of_priv) \
171 (BLK_HDR_LEN + ALIGN((sz_of_priv), V3_ALIGNMENT))
173 #define PGV_FROM_VMALLOC 1
175 #define BLOCK_STATUS(x) ((x)->hdr.bh1.block_status)
176 #define BLOCK_NUM_PKTS(x) ((x)->hdr.bh1.num_pkts)
177 #define BLOCK_O2FP(x) ((x)->hdr.bh1.offset_to_first_pkt)
178 #define BLOCK_LEN(x) ((x)->hdr.bh1.blk_len)
179 #define BLOCK_SNUM(x) ((x)->hdr.bh1.seq_num)
180 #define BLOCK_O2PRIV(x) ((x)->offset_to_priv)
181 #define BLOCK_PRIV(x) ((void *)((char *)(x) + BLOCK_O2PRIV(x)))
184 static int tpacket_snd(struct packet_sock *po, struct msghdr *msg);
185 static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
186 struct packet_type *pt, struct net_device *orig_dev);
188 static void *packet_previous_frame(struct packet_sock *po,
189 struct packet_ring_buffer *rb,
191 static void packet_increment_head(struct packet_ring_buffer *buff);
192 static int prb_curr_blk_in_use(struct tpacket_kbdq_core *,
193 struct tpacket_block_desc *);
194 static void *prb_dispatch_next_block(struct tpacket_kbdq_core *,
195 struct packet_sock *);
196 static void prb_retire_current_block(struct tpacket_kbdq_core *,
197 struct packet_sock *, unsigned int status);
198 static int prb_queue_frozen(struct tpacket_kbdq_core *);
199 static void prb_open_block(struct tpacket_kbdq_core *,
200 struct tpacket_block_desc *);
201 static void prb_retire_rx_blk_timer_expired(unsigned long);
202 static void _prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core *);
203 static void prb_init_blk_timer(struct packet_sock *,
204 struct tpacket_kbdq_core *,
205 void (*func) (unsigned long));
206 static void prb_fill_rxhash(struct tpacket_kbdq_core *, struct tpacket3_hdr *);
207 static void prb_clear_rxhash(struct tpacket_kbdq_core *,
208 struct tpacket3_hdr *);
209 static void prb_fill_vlan_info(struct tpacket_kbdq_core *,
210 struct tpacket3_hdr *);
211 static void packet_flush_mclist(struct sock *sk);
213 struct packet_skb_cb {
214 unsigned int origlen;
216 struct sockaddr_pkt pkt;
217 struct sockaddr_ll ll;
221 #define PACKET_SKB_CB(__skb) ((struct packet_skb_cb *)((__skb)->cb))
223 #define GET_PBDQC_FROM_RB(x) ((struct tpacket_kbdq_core *)(&(x)->prb_bdqc))
224 #define GET_PBLOCK_DESC(x, bid) \
225 ((struct tpacket_block_desc *)((x)->pkbdq[(bid)].buffer))
226 #define GET_CURR_PBLOCK_DESC_FROM_CORE(x) \
227 ((struct tpacket_block_desc *)((x)->pkbdq[(x)->kactive_blk_num].buffer))
228 #define GET_NEXT_PRB_BLK_NUM(x) \
229 (((x)->kactive_blk_num < ((x)->knum_blocks-1)) ? \
230 ((x)->kactive_blk_num+1) : 0)
232 static void __fanout_unlink(struct sock *sk, struct packet_sock *po);
233 static void __fanout_link(struct sock *sk, struct packet_sock *po);
235 /* register_prot_hook must be invoked with the po->bind_lock held,
236 * or from a context in which asynchronous accesses to the packet
237 * socket is not possible (packet_create()).
239 static void register_prot_hook(struct sock *sk)
241 struct packet_sock *po = pkt_sk(sk);
244 __fanout_link(sk, po);
246 dev_add_pack(&po->prot_hook);
252 /* {,__}unregister_prot_hook() must be invoked with the po->bind_lock
253 * held. If the sync parameter is true, we will temporarily drop
254 * the po->bind_lock and do a synchronize_net to make sure no
255 * asynchronous packet processing paths still refer to the elements
256 * of po->prot_hook. If the sync parameter is false, it is the
257 * callers responsibility to take care of this.
259 static void __unregister_prot_hook(struct sock *sk, bool sync)
261 struct packet_sock *po = pkt_sk(sk);
265 __fanout_unlink(sk, po);
267 __dev_remove_pack(&po->prot_hook);
271 spin_unlock(&po->bind_lock);
273 spin_lock(&po->bind_lock);
277 static void unregister_prot_hook(struct sock *sk, bool sync)
279 struct packet_sock *po = pkt_sk(sk);
282 __unregister_prot_hook(sk, sync);
285 static inline __pure struct page *pgv_to_page(void *addr)
287 if (is_vmalloc_addr(addr))
288 return vmalloc_to_page(addr);
289 return virt_to_page(addr);
292 static void __packet_set_status(struct packet_sock *po, void *frame, int status)
295 struct tpacket_hdr *h1;
296 struct tpacket2_hdr *h2;
301 switch (po->tp_version) {
303 h.h1->tp_status = status;
304 flush_dcache_page(pgv_to_page(&h.h1->tp_status));
307 h.h2->tp_status = status;
308 flush_dcache_page(pgv_to_page(&h.h2->tp_status));
312 WARN(1, "TPACKET version not supported.\n");
319 static int __packet_get_status(struct packet_sock *po, void *frame)
322 struct tpacket_hdr *h1;
323 struct tpacket2_hdr *h2;
330 switch (po->tp_version) {
332 flush_dcache_page(pgv_to_page(&h.h1->tp_status));
333 return h.h1->tp_status;
335 flush_dcache_page(pgv_to_page(&h.h2->tp_status));
336 return h.h2->tp_status;
339 WARN(1, "TPACKET version not supported.\n");
345 static void *packet_lookup_frame(struct packet_sock *po,
346 struct packet_ring_buffer *rb,
347 unsigned int position,
350 unsigned int pg_vec_pos, frame_offset;
352 struct tpacket_hdr *h1;
353 struct tpacket2_hdr *h2;
357 pg_vec_pos = position / rb->frames_per_block;
358 frame_offset = position % rb->frames_per_block;
360 h.raw = rb->pg_vec[pg_vec_pos].buffer +
361 (frame_offset * rb->frame_size);
363 if (status != __packet_get_status(po, h.raw))
369 static void *packet_current_frame(struct packet_sock *po,
370 struct packet_ring_buffer *rb,
373 return packet_lookup_frame(po, rb, rb->head, status);
376 static void prb_del_retire_blk_timer(struct tpacket_kbdq_core *pkc)
378 del_timer_sync(&pkc->retire_blk_timer);
381 static void prb_shutdown_retire_blk_timer(struct packet_sock *po,
383 struct sk_buff_head *rb_queue)
385 struct tpacket_kbdq_core *pkc;
387 pkc = tx_ring ? &po->tx_ring.prb_bdqc : &po->rx_ring.prb_bdqc;
389 spin_lock(&rb_queue->lock);
390 pkc->delete_blk_timer = 1;
391 spin_unlock(&rb_queue->lock);
393 prb_del_retire_blk_timer(pkc);
396 static void prb_init_blk_timer(struct packet_sock *po,
397 struct tpacket_kbdq_core *pkc,
398 void (*func) (unsigned long))
400 init_timer(&pkc->retire_blk_timer);
401 pkc->retire_blk_timer.data = (long)po;
402 pkc->retire_blk_timer.function = func;
403 pkc->retire_blk_timer.expires = jiffies;
406 static void prb_setup_retire_blk_timer(struct packet_sock *po, int tx_ring)
408 struct tpacket_kbdq_core *pkc;
413 pkc = tx_ring ? &po->tx_ring.prb_bdqc : &po->rx_ring.prb_bdqc;
414 prb_init_blk_timer(po, pkc, prb_retire_rx_blk_timer_expired);
417 static int prb_calc_retire_blk_tmo(struct packet_sock *po,
418 int blk_size_in_bytes)
420 struct net_device *dev;
421 unsigned int mbits = 0, msec = 0, div = 0, tmo = 0;
422 struct ethtool_cmd ecmd;
427 dev = __dev_get_by_index(sock_net(&po->sk), po->ifindex);
428 if (unlikely(!dev)) {
430 return DEFAULT_PRB_RETIRE_TOV;
432 err = __ethtool_get_settings(dev, &ecmd);
433 speed = ethtool_cmd_speed(&ecmd);
437 * If the link speed is so slow you don't really
438 * need to worry about perf anyways
440 if (speed < SPEED_1000 || speed == SPEED_UNKNOWN) {
441 return DEFAULT_PRB_RETIRE_TOV;
448 mbits = (blk_size_in_bytes * 8) / (1024 * 1024);
460 static void prb_init_ft_ops(struct tpacket_kbdq_core *p1,
461 union tpacket_req_u *req_u)
463 p1->feature_req_word = req_u->req3.tp_feature_req_word;
466 static void init_prb_bdqc(struct packet_sock *po,
467 struct packet_ring_buffer *rb,
469 union tpacket_req_u *req_u, int tx_ring)
471 struct tpacket_kbdq_core *p1 = &rb->prb_bdqc;
472 struct tpacket_block_desc *pbd;
474 memset(p1, 0x0, sizeof(*p1));
476 p1->knxt_seq_num = 1;
478 pbd = (struct tpacket_block_desc *)pg_vec[0].buffer;
479 p1->pkblk_start = pg_vec[0].buffer;
480 p1->kblk_size = req_u->req3.tp_block_size;
481 p1->knum_blocks = req_u->req3.tp_block_nr;
482 p1->hdrlen = po->tp_hdrlen;
483 p1->version = po->tp_version;
484 p1->last_kactive_blk_num = 0;
485 po->stats_u.stats3.tp_freeze_q_cnt = 0;
486 if (req_u->req3.tp_retire_blk_tov)
487 p1->retire_blk_tov = req_u->req3.tp_retire_blk_tov;
489 p1->retire_blk_tov = prb_calc_retire_blk_tmo(po,
490 req_u->req3.tp_block_size);
491 p1->tov_in_jiffies = msecs_to_jiffies(p1->retire_blk_tov);
492 p1->blk_sizeof_priv = req_u->req3.tp_sizeof_priv;
494 prb_init_ft_ops(p1, req_u);
495 prb_setup_retire_blk_timer(po, tx_ring);
496 prb_open_block(p1, pbd);
499 /* Do NOT update the last_blk_num first.
500 * Assumes sk_buff_head lock is held.
502 static void _prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core *pkc)
504 mod_timer(&pkc->retire_blk_timer,
505 jiffies + pkc->tov_in_jiffies);
506 pkc->last_kactive_blk_num = pkc->kactive_blk_num;
511 * 1) We refresh the timer only when we open a block.
512 * By doing this we don't waste cycles refreshing the timer
513 * on packet-by-packet basis.
515 * With a 1MB block-size, on a 1Gbps line, it will take
516 * i) ~8 ms to fill a block + ii) memcpy etc.
517 * In this cut we are not accounting for the memcpy time.
519 * So, if the user sets the 'tmo' to 10ms then the timer
520 * will never fire while the block is still getting filled
521 * (which is what we want). However, the user could choose
522 * to close a block early and that's fine.
524 * But when the timer does fire, we check whether or not to refresh it.
525 * Since the tmo granularity is in msecs, it is not too expensive
526 * to refresh the timer, lets say every '8' msecs.
527 * Either the user can set the 'tmo' or we can derive it based on
528 * a) line-speed and b) block-size.
529 * prb_calc_retire_blk_tmo() calculates the tmo.
532 static void prb_retire_rx_blk_timer_expired(unsigned long data)
534 struct packet_sock *po = (struct packet_sock *)data;
535 struct tpacket_kbdq_core *pkc = &po->rx_ring.prb_bdqc;
537 struct tpacket_block_desc *pbd;
539 spin_lock(&po->sk.sk_receive_queue.lock);
541 frozen = prb_queue_frozen(pkc);
542 pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
544 if (unlikely(pkc->delete_blk_timer))
547 /* We only need to plug the race when the block is partially filled.
549 * lock(); increment BLOCK_NUM_PKTS; unlock()
550 * copy_bits() is in progress ...
551 * timer fires on other cpu:
552 * we can't retire the current block because copy_bits
556 if (BLOCK_NUM_PKTS(pbd)) {
557 while (atomic_read(&pkc->blk_fill_in_prog)) {
558 /* Waiting for skb_copy_bits to finish... */
563 if (pkc->last_kactive_blk_num == pkc->kactive_blk_num) {
565 prb_retire_current_block(pkc, po, TP_STATUS_BLK_TMO);
566 if (!prb_dispatch_next_block(pkc, po))
571 /* Case 1. Queue was frozen because user-space was
574 if (prb_curr_blk_in_use(pkc, pbd)) {
576 * Ok, user-space is still behind.
577 * So just refresh the timer.
581 /* Case 2. queue was frozen,user-space caught up,
582 * now the link went idle && the timer fired.
583 * We don't have a block to close.So we open this
584 * block and restart the timer.
585 * opening a block thaws the queue,restarts timer
586 * Thawing/timer-refresh is a side effect.
588 prb_open_block(pkc, pbd);
595 _prb_refresh_rx_retire_blk_timer(pkc);
598 spin_unlock(&po->sk.sk_receive_queue.lock);
601 static void prb_flush_block(struct tpacket_kbdq_core *pkc1,
602 struct tpacket_block_desc *pbd1, __u32 status)
604 /* Flush everything minus the block header */
606 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
611 /* Skip the block header(we know header WILL fit in 4K) */
614 end = (u8 *)PAGE_ALIGN((unsigned long)pkc1->pkblk_end);
615 for (; start < end; start += PAGE_SIZE)
616 flush_dcache_page(pgv_to_page(start));
621 /* Now update the block status. */
623 BLOCK_STATUS(pbd1) = status;
625 /* Flush the block header */
627 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
629 flush_dcache_page(pgv_to_page(start));
639 * 2) Increment active_blk_num
641 * Note:We DONT refresh the timer on purpose.
642 * Because almost always the next block will be opened.
644 static void prb_close_block(struct tpacket_kbdq_core *pkc1,
645 struct tpacket_block_desc *pbd1,
646 struct packet_sock *po, unsigned int stat)
648 __u32 status = TP_STATUS_USER | stat;
650 struct tpacket3_hdr *last_pkt;
651 struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
653 if (po->stats.tp_drops)
654 status |= TP_STATUS_LOSING;
656 last_pkt = (struct tpacket3_hdr *)pkc1->prev;
657 last_pkt->tp_next_offset = 0;
659 /* Get the ts of the last pkt */
660 if (BLOCK_NUM_PKTS(pbd1)) {
661 h1->ts_last_pkt.ts_sec = last_pkt->tp_sec;
662 h1->ts_last_pkt.ts_nsec = last_pkt->tp_nsec;
664 /* Ok, we tmo'd - so get the current time */
667 h1->ts_last_pkt.ts_sec = ts.tv_sec;
668 h1->ts_last_pkt.ts_nsec = ts.tv_nsec;
673 /* Flush the block */
674 prb_flush_block(pkc1, pbd1, status);
676 pkc1->kactive_blk_num = GET_NEXT_PRB_BLK_NUM(pkc1);
679 static void prb_thaw_queue(struct tpacket_kbdq_core *pkc)
681 pkc->reset_pending_on_curr_blk = 0;
685 * Side effect of opening a block:
687 * 1) prb_queue is thawed.
688 * 2) retire_blk_timer is refreshed.
691 static void prb_open_block(struct tpacket_kbdq_core *pkc1,
692 struct tpacket_block_desc *pbd1)
695 struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
699 if (likely(TP_STATUS_KERNEL == BLOCK_STATUS(pbd1))) {
701 /* We could have just memset this but we will lose the
702 * flexibility of making the priv area sticky
704 BLOCK_SNUM(pbd1) = pkc1->knxt_seq_num++;
705 BLOCK_NUM_PKTS(pbd1) = 0;
706 BLOCK_LEN(pbd1) = BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
708 h1->ts_first_pkt.ts_sec = ts.tv_sec;
709 h1->ts_first_pkt.ts_nsec = ts.tv_nsec;
710 pkc1->pkblk_start = (char *)pbd1;
711 pkc1->nxt_offset = pkc1->pkblk_start + BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
712 BLOCK_O2FP(pbd1) = (__u32)BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
713 BLOCK_O2PRIV(pbd1) = BLK_HDR_LEN;
714 pbd1->version = pkc1->version;
715 pkc1->prev = pkc1->nxt_offset;
716 pkc1->pkblk_end = pkc1->pkblk_start + pkc1->kblk_size;
717 prb_thaw_queue(pkc1);
718 _prb_refresh_rx_retire_blk_timer(pkc1);
725 WARN(1, "ERROR block:%p is NOT FREE status:%d kactive_blk_num:%d\n",
726 pbd1, BLOCK_STATUS(pbd1), pkc1->kactive_blk_num);
732 * Queue freeze logic:
733 * 1) Assume tp_block_nr = 8 blocks.
734 * 2) At time 't0', user opens Rx ring.
735 * 3) Some time past 't0', kernel starts filling blocks starting from 0 .. 7
736 * 4) user-space is either sleeping or processing block '0'.
737 * 5) tpacket_rcv is currently filling block '7', since there is no space left,
738 * it will close block-7,loop around and try to fill block '0'.
740 * __packet_lookup_frame_in_block
741 * prb_retire_current_block()
742 * prb_dispatch_next_block()
743 * |->(BLOCK_STATUS == USER) evaluates to true
744 * 5.1) Since block-0 is currently in-use, we just freeze the queue.
745 * 6) Now there are two cases:
746 * 6.1) Link goes idle right after the queue is frozen.
747 * But remember, the last open_block() refreshed the timer.
748 * When this timer expires,it will refresh itself so that we can
749 * re-open block-0 in near future.
750 * 6.2) Link is busy and keeps on receiving packets. This is a simple
751 * case and __packet_lookup_frame_in_block will check if block-0
752 * is free and can now be re-used.
754 static void prb_freeze_queue(struct tpacket_kbdq_core *pkc,
755 struct packet_sock *po)
757 pkc->reset_pending_on_curr_blk = 1;
758 po->stats_u.stats3.tp_freeze_q_cnt++;
761 #define TOTAL_PKT_LEN_INCL_ALIGN(length) (ALIGN((length), V3_ALIGNMENT))
764 * If the next block is free then we will dispatch it
765 * and return a good offset.
766 * Else, we will freeze the queue.
767 * So, caller must check the return value.
769 static void *prb_dispatch_next_block(struct tpacket_kbdq_core *pkc,
770 struct packet_sock *po)
772 struct tpacket_block_desc *pbd;
776 /* 1. Get current block num */
777 pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
779 /* 2. If this block is currently in_use then freeze the queue */
780 if (TP_STATUS_USER & BLOCK_STATUS(pbd)) {
781 prb_freeze_queue(pkc, po);
787 * open this block and return the offset where the first packet
788 * needs to get stored.
790 prb_open_block(pkc, pbd);
791 return (void *)pkc->nxt_offset;
794 static void prb_retire_current_block(struct tpacket_kbdq_core *pkc,
795 struct packet_sock *po, unsigned int status)
797 struct tpacket_block_desc *pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
799 /* retire/close the current block */
800 if (likely(TP_STATUS_KERNEL == BLOCK_STATUS(pbd))) {
802 * Plug the case where copy_bits() is in progress on
803 * cpu-0 and tpacket_rcv() got invoked on cpu-1, didn't
804 * have space to copy the pkt in the current block and
805 * called prb_retire_current_block()
807 * We don't need to worry about the TMO case because
808 * the timer-handler already handled this case.
810 if (!(status & TP_STATUS_BLK_TMO)) {
811 while (atomic_read(&pkc->blk_fill_in_prog)) {
812 /* Waiting for skb_copy_bits to finish... */
816 prb_close_block(pkc, pbd, po, status);
820 WARN(1, "ERROR-pbd[%d]:%p\n", pkc->kactive_blk_num, pbd);
825 static int prb_curr_blk_in_use(struct tpacket_kbdq_core *pkc,
826 struct tpacket_block_desc *pbd)
828 return TP_STATUS_USER & BLOCK_STATUS(pbd);
831 static int prb_queue_frozen(struct tpacket_kbdq_core *pkc)
833 return pkc->reset_pending_on_curr_blk;
836 static void prb_clear_blk_fill_status(struct packet_ring_buffer *rb)
838 struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(rb);
839 atomic_dec(&pkc->blk_fill_in_prog);
842 static void prb_fill_rxhash(struct tpacket_kbdq_core *pkc,
843 struct tpacket3_hdr *ppd)
845 ppd->hv1.tp_rxhash = skb_get_rxhash(pkc->skb);
848 static void prb_clear_rxhash(struct tpacket_kbdq_core *pkc,
849 struct tpacket3_hdr *ppd)
851 ppd->hv1.tp_rxhash = 0;
854 static void prb_fill_vlan_info(struct tpacket_kbdq_core *pkc,
855 struct tpacket3_hdr *ppd)
857 if (vlan_tx_tag_present(pkc->skb)) {
858 ppd->hv1.tp_vlan_tci = vlan_tx_tag_get(pkc->skb);
859 ppd->tp_status = TP_STATUS_VLAN_VALID;
861 ppd->hv1.tp_vlan_tci = 0;
862 ppd->tp_status = TP_STATUS_AVAILABLE;
866 static void prb_run_all_ft_ops(struct tpacket_kbdq_core *pkc,
867 struct tpacket3_hdr *ppd)
869 prb_fill_vlan_info(pkc, ppd);
871 if (pkc->feature_req_word & TP_FT_REQ_FILL_RXHASH)
872 prb_fill_rxhash(pkc, ppd);
874 prb_clear_rxhash(pkc, ppd);
877 static void prb_fill_curr_block(char *curr,
878 struct tpacket_kbdq_core *pkc,
879 struct tpacket_block_desc *pbd,
882 struct tpacket3_hdr *ppd;
884 ppd = (struct tpacket3_hdr *)curr;
885 ppd->tp_next_offset = TOTAL_PKT_LEN_INCL_ALIGN(len);
887 pkc->nxt_offset += TOTAL_PKT_LEN_INCL_ALIGN(len);
888 BLOCK_LEN(pbd) += TOTAL_PKT_LEN_INCL_ALIGN(len);
889 BLOCK_NUM_PKTS(pbd) += 1;
890 atomic_inc(&pkc->blk_fill_in_prog);
891 prb_run_all_ft_ops(pkc, ppd);
894 /* Assumes caller has the sk->rx_queue.lock */
895 static void *__packet_lookup_frame_in_block(struct packet_sock *po,
901 struct tpacket_kbdq_core *pkc;
902 struct tpacket_block_desc *pbd;
905 pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
906 pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
908 /* Queue is frozen when user space is lagging behind */
909 if (prb_queue_frozen(pkc)) {
911 * Check if that last block which caused the queue to freeze,
912 * is still in_use by user-space.
914 if (prb_curr_blk_in_use(pkc, pbd)) {
915 /* Can't record this packet */
919 * Ok, the block was released by user-space.
920 * Now let's open that block.
921 * opening a block also thaws the queue.
922 * Thawing is a side effect.
924 prb_open_block(pkc, pbd);
929 curr = pkc->nxt_offset;
931 end = (char *)pbd + pkc->kblk_size;
933 /* first try the current block */
934 if (curr+TOTAL_PKT_LEN_INCL_ALIGN(len) < end) {
935 prb_fill_curr_block(curr, pkc, pbd, len);
939 /* Ok, close the current block */
940 prb_retire_current_block(pkc, po, 0);
942 /* Now, try to dispatch the next block */
943 curr = (char *)prb_dispatch_next_block(pkc, po);
945 pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
946 prb_fill_curr_block(curr, pkc, pbd, len);
951 * No free blocks are available.user_space hasn't caught up yet.
952 * Queue was just frozen and now this packet will get dropped.
957 static void *packet_current_rx_frame(struct packet_sock *po,
959 int status, unsigned int len)
962 switch (po->tp_version) {
965 curr = packet_lookup_frame(po, &po->rx_ring,
966 po->rx_ring.head, status);
969 return __packet_lookup_frame_in_block(po, skb, status, len);
971 WARN(1, "TPACKET version not supported\n");
977 static void *prb_lookup_block(struct packet_sock *po,
978 struct packet_ring_buffer *rb,
982 struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(rb);
983 struct tpacket_block_desc *pbd = GET_PBLOCK_DESC(pkc, idx);
985 if (status != BLOCK_STATUS(pbd))
990 static int prb_previous_blk_num(struct packet_ring_buffer *rb)
993 if (rb->prb_bdqc.kactive_blk_num)
994 prev = rb->prb_bdqc.kactive_blk_num-1;
996 prev = rb->prb_bdqc.knum_blocks-1;
1000 /* Assumes caller has held the rx_queue.lock */
1001 static void *__prb_previous_block(struct packet_sock *po,
1002 struct packet_ring_buffer *rb,
1005 unsigned int previous = prb_previous_blk_num(rb);
1006 return prb_lookup_block(po, rb, previous, status);
1009 static void *packet_previous_rx_frame(struct packet_sock *po,
1010 struct packet_ring_buffer *rb,
1013 if (po->tp_version <= TPACKET_V2)
1014 return packet_previous_frame(po, rb, status);
1016 return __prb_previous_block(po, rb, status);
1019 static void packet_increment_rx_head(struct packet_sock *po,
1020 struct packet_ring_buffer *rb)
1022 switch (po->tp_version) {
1025 return packet_increment_head(rb);
1028 WARN(1, "TPACKET version not supported.\n");
1034 static void *packet_previous_frame(struct packet_sock *po,
1035 struct packet_ring_buffer *rb,
1038 unsigned int previous = rb->head ? rb->head - 1 : rb->frame_max;
1039 return packet_lookup_frame(po, rb, previous, status);
1042 static void packet_increment_head(struct packet_ring_buffer *buff)
1044 buff->head = buff->head != buff->frame_max ? buff->head+1 : 0;
1047 static bool packet_rcv_has_room(struct packet_sock *po, struct sk_buff *skb)
1049 struct sock *sk = &po->sk;
1052 if (po->prot_hook.func != tpacket_rcv)
1053 return (atomic_read(&sk->sk_rmem_alloc) + skb->truesize)
1056 spin_lock(&sk->sk_receive_queue.lock);
1057 if (po->tp_version == TPACKET_V3)
1058 has_room = prb_lookup_block(po, &po->rx_ring,
1059 po->rx_ring.prb_bdqc.kactive_blk_num,
1062 has_room = packet_lookup_frame(po, &po->rx_ring,
1065 spin_unlock(&sk->sk_receive_queue.lock);
1070 static void packet_sock_destruct(struct sock *sk)
1072 skb_queue_purge(&sk->sk_error_queue);
1074 WARN_ON(atomic_read(&sk->sk_rmem_alloc));
1075 WARN_ON(atomic_read(&sk->sk_wmem_alloc));
1077 if (!sock_flag(sk, SOCK_DEAD)) {
1078 pr_err("Attempt to release alive packet socket: %p\n", sk);
1082 sk_refcnt_debug_dec(sk);
1085 static int fanout_rr_next(struct packet_fanout *f, unsigned int num)
1087 int x = atomic_read(&f->rr_cur) + 1;
1095 static unsigned int fanout_demux_hash(struct packet_fanout *f,
1096 struct sk_buff *skb,
1099 return (((u64)skb->rxhash) * num) >> 32;
1102 static unsigned int fanout_demux_lb(struct packet_fanout *f,
1103 struct sk_buff *skb,
1108 cur = atomic_read(&f->rr_cur);
1109 while ((old = atomic_cmpxchg(&f->rr_cur, cur,
1110 fanout_rr_next(f, num))) != cur)
1115 static unsigned int fanout_demux_cpu(struct packet_fanout *f,
1116 struct sk_buff *skb,
1119 return smp_processor_id() % num;
1122 static unsigned int fanout_demux_rollover(struct packet_fanout *f,
1123 struct sk_buff *skb,
1124 unsigned int idx, unsigned int skip,
1129 i = j = min_t(int, f->next[idx], num - 1);
1131 if (i != skip && packet_rcv_has_room(pkt_sk(f->arr[i]), skb)) {
1143 static bool fanout_has_flag(struct packet_fanout *f, u16 flag)
1145 return f->flags & (flag >> 8);
1148 static int packet_rcv_fanout(struct sk_buff *skb, struct net_device *dev,
1149 struct packet_type *pt, struct net_device *orig_dev)
1151 struct packet_fanout *f = pt->af_packet_priv;
1152 unsigned int num = f->num_members;
1153 struct packet_sock *po;
1156 if (!net_eq(dev_net(dev), read_pnet(&f->net)) ||
1163 case PACKET_FANOUT_HASH:
1165 if (fanout_has_flag(f, PACKET_FANOUT_FLAG_DEFRAG)) {
1166 skb = ip_check_defrag(skb, IP_DEFRAG_AF_PACKET);
1170 skb_get_rxhash(skb);
1171 idx = fanout_demux_hash(f, skb, num);
1173 case PACKET_FANOUT_LB:
1174 idx = fanout_demux_lb(f, skb, num);
1176 case PACKET_FANOUT_CPU:
1177 idx = fanout_demux_cpu(f, skb, num);
1179 case PACKET_FANOUT_ROLLOVER:
1180 idx = fanout_demux_rollover(f, skb, 0, (unsigned int) -1, num);
1184 po = pkt_sk(f->arr[idx]);
1185 if (fanout_has_flag(f, PACKET_FANOUT_FLAG_ROLLOVER) &&
1186 unlikely(!packet_rcv_has_room(po, skb))) {
1187 idx = fanout_demux_rollover(f, skb, idx, idx, num);
1188 po = pkt_sk(f->arr[idx]);
1191 return po->prot_hook.func(skb, dev, &po->prot_hook, orig_dev);
1194 DEFINE_MUTEX(fanout_mutex);
1195 EXPORT_SYMBOL_GPL(fanout_mutex);
1196 static LIST_HEAD(fanout_list);
1198 static void __fanout_link(struct sock *sk, struct packet_sock *po)
1200 struct packet_fanout *f = po->fanout;
1202 spin_lock(&f->lock);
1203 f->arr[f->num_members] = sk;
1206 spin_unlock(&f->lock);
1209 static void __fanout_unlink(struct sock *sk, struct packet_sock *po)
1211 struct packet_fanout *f = po->fanout;
1214 spin_lock(&f->lock);
1215 for (i = 0; i < f->num_members; i++) {
1216 if (f->arr[i] == sk)
1219 BUG_ON(i >= f->num_members);
1220 f->arr[i] = f->arr[f->num_members - 1];
1222 spin_unlock(&f->lock);
1225 static bool match_fanout_group(struct packet_type *ptype, struct sock * sk)
1227 if (ptype->af_packet_priv == (void*)((struct packet_sock *)sk)->fanout)
1233 static int fanout_add(struct sock *sk, u16 id, u16 type_flags)
1235 struct packet_sock *po = pkt_sk(sk);
1236 struct packet_fanout *f, *match;
1237 u8 type = type_flags & 0xff;
1238 u8 flags = type_flags >> 8;
1242 case PACKET_FANOUT_ROLLOVER:
1243 if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)
1245 case PACKET_FANOUT_HASH:
1246 case PACKET_FANOUT_LB:
1247 case PACKET_FANOUT_CPU:
1259 mutex_lock(&fanout_mutex);
1261 list_for_each_entry(f, &fanout_list, list) {
1263 read_pnet(&f->net) == sock_net(sk)) {
1269 if (match && match->flags != flags)
1273 match = kzalloc(sizeof(*match), GFP_KERNEL);
1276 write_pnet(&match->net, sock_net(sk));
1279 match->flags = flags;
1280 atomic_set(&match->rr_cur, 0);
1281 INIT_LIST_HEAD(&match->list);
1282 spin_lock_init(&match->lock);
1283 atomic_set(&match->sk_ref, 0);
1284 match->prot_hook.type = po->prot_hook.type;
1285 match->prot_hook.dev = po->prot_hook.dev;
1286 match->prot_hook.func = packet_rcv_fanout;
1287 match->prot_hook.af_packet_priv = match;
1288 match->prot_hook.id_match = match_fanout_group;
1289 dev_add_pack(&match->prot_hook);
1290 list_add(&match->list, &fanout_list);
1293 if (match->type == type &&
1294 match->prot_hook.type == po->prot_hook.type &&
1295 match->prot_hook.dev == po->prot_hook.dev) {
1297 if (atomic_read(&match->sk_ref) < PACKET_FANOUT_MAX) {
1298 __dev_remove_pack(&po->prot_hook);
1300 atomic_inc(&match->sk_ref);
1301 __fanout_link(sk, po);
1306 mutex_unlock(&fanout_mutex);
1310 static void fanout_release(struct sock *sk)
1312 struct packet_sock *po = pkt_sk(sk);
1313 struct packet_fanout *f;
1319 mutex_lock(&fanout_mutex);
1322 if (atomic_dec_and_test(&f->sk_ref)) {
1324 dev_remove_pack(&f->prot_hook);
1327 mutex_unlock(&fanout_mutex);
1330 static const struct proto_ops packet_ops;
1332 static const struct proto_ops packet_ops_spkt;
1334 static int packet_rcv_spkt(struct sk_buff *skb, struct net_device *dev,
1335 struct packet_type *pt, struct net_device *orig_dev)
1338 struct sockaddr_pkt *spkt;
1341 * When we registered the protocol we saved the socket in the data
1342 * field for just this event.
1345 sk = pt->af_packet_priv;
1348 * Yank back the headers [hope the device set this
1349 * right or kerboom...]
1351 * Incoming packets have ll header pulled,
1354 * For outgoing ones skb->data == skb_mac_header(skb)
1355 * so that this procedure is noop.
1358 if (skb->pkt_type == PACKET_LOOPBACK)
1361 if (!net_eq(dev_net(dev), sock_net(sk)))
1364 skb = skb_share_check(skb, GFP_ATOMIC);
1368 /* drop any routing info */
1371 /* drop conntrack reference */
1374 spkt = &PACKET_SKB_CB(skb)->sa.pkt;
1376 skb_push(skb, skb->data - skb_mac_header(skb));
1379 * The SOCK_PACKET socket receives _all_ frames.
1382 spkt->spkt_family = dev->type;
1383 strlcpy(spkt->spkt_device, dev->name, sizeof(spkt->spkt_device));
1384 spkt->spkt_protocol = skb->protocol;
1387 * Charge the memory to the socket. This is done specifically
1388 * to prevent sockets using all the memory up.
1391 if (sock_queue_rcv_skb(sk, skb) == 0)
1402 * Output a raw packet to a device layer. This bypasses all the other
1403 * protocol layers and you must therefore supply it with a complete frame
1406 static int packet_sendmsg_spkt(struct kiocb *iocb, struct socket *sock,
1407 struct msghdr *msg, size_t len)
1409 struct sock *sk = sock->sk;
1410 struct sockaddr_pkt *saddr = (struct sockaddr_pkt *)msg->msg_name;
1411 struct sk_buff *skb = NULL;
1412 struct net_device *dev;
1416 struct flow_keys keys;
1419 * Get and verify the address.
1423 if (msg->msg_namelen < sizeof(struct sockaddr))
1425 if (msg->msg_namelen == sizeof(struct sockaddr_pkt))
1426 proto = saddr->spkt_protocol;
1428 return -ENOTCONN; /* SOCK_PACKET must be sent giving an address */
1431 * Find the device first to size check it
1434 saddr->spkt_device[sizeof(saddr->spkt_device) - 1] = 0;
1437 dev = dev_get_by_name_rcu(sock_net(sk), saddr->spkt_device);
1443 if (!(dev->flags & IFF_UP))
1447 * You may not queue a frame bigger than the mtu. This is the lowest level
1448 * raw protocol and you must do your own fragmentation at this level.
1451 if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
1452 if (!netif_supports_nofcs(dev)) {
1453 err = -EPROTONOSUPPORT;
1456 extra_len = 4; /* We're doing our own CRC */
1460 if (len > dev->mtu + dev->hard_header_len + VLAN_HLEN + extra_len)
1464 size_t reserved = LL_RESERVED_SPACE(dev);
1465 int tlen = dev->needed_tailroom;
1466 unsigned int hhlen = dev->header_ops ? dev->hard_header_len : 0;
1469 skb = sock_wmalloc(sk, len + reserved + tlen, 0, GFP_KERNEL);
1472 /* FIXME: Save some space for broken drivers that write a hard
1473 * header at transmission time by themselves. PPP is the notable
1474 * one here. This should really be fixed at the driver level.
1476 skb_reserve(skb, reserved);
1477 skb_reset_network_header(skb);
1479 /* Try to align data part correctly */
1484 skb_reset_network_header(skb);
1486 err = memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len);
1492 if (len > (dev->mtu + dev->hard_header_len + extra_len)) {
1493 /* Earlier code assumed this would be a VLAN pkt,
1494 * double-check this now that we have the actual
1497 struct ethhdr *ehdr;
1498 skb_reset_mac_header(skb);
1499 ehdr = eth_hdr(skb);
1500 if (ehdr->h_proto != htons(ETH_P_8021Q)) {
1506 skb->protocol = proto;
1508 skb->priority = sk->sk_priority;
1509 skb->mark = sk->sk_mark;
1510 err = sock_tx_timestamp(sk, &skb_shinfo(skb)->tx_flags);
1514 if (unlikely(extra_len == 4))
1517 if (skb_flow_dissect(skb, &keys))
1518 skb_set_transport_header(skb, keys.thoff);
1520 skb_reset_transport_header(skb);
1522 dev_queue_xmit(skb);
1533 static unsigned int run_filter(const struct sk_buff *skb,
1534 const struct sock *sk,
1537 struct sk_filter *filter;
1540 filter = rcu_dereference(sk->sk_filter);
1542 res = SK_RUN_FILTER(filter, skb);
1549 * This function makes lazy skb cloning in hope that most of packets
1550 * are discarded by BPF.
1552 * Note tricky part: we DO mangle shared skb! skb->data, skb->len
1553 * and skb->cb are mangled. It works because (and until) packets
1554 * falling here are owned by current CPU. Output packets are cloned
1555 * by dev_queue_xmit_nit(), input packets are processed by net_bh
1556 * sequencially, so that if we return skb to original state on exit,
1557 * we will not harm anyone.
1560 static int packet_rcv(struct sk_buff *skb, struct net_device *dev,
1561 struct packet_type *pt, struct net_device *orig_dev)
1564 struct sockaddr_ll *sll;
1565 struct packet_sock *po;
1566 u8 *skb_head = skb->data;
1567 int skb_len = skb->len;
1568 unsigned int snaplen, res;
1570 if (skb->pkt_type == PACKET_LOOPBACK)
1573 sk = pt->af_packet_priv;
1576 if (!net_eq(dev_net(dev), sock_net(sk)))
1581 if (dev->header_ops) {
1582 /* The device has an explicit notion of ll header,
1583 * exported to higher levels.
1585 * Otherwise, the device hides details of its frame
1586 * structure, so that corresponding packet head is
1587 * never delivered to user.
1589 if (sk->sk_type != SOCK_DGRAM)
1590 skb_push(skb, skb->data - skb_mac_header(skb));
1591 else if (skb->pkt_type == PACKET_OUTGOING) {
1592 /* Special case: outgoing packets have ll header at head */
1593 skb_pull(skb, skb_network_offset(skb));
1599 res = run_filter(skb, sk, snaplen);
1601 goto drop_n_restore;
1605 if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
1608 if (skb_shared(skb)) {
1609 struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
1613 if (skb_head != skb->data) {
1614 skb->data = skb_head;
1621 BUILD_BUG_ON(sizeof(*PACKET_SKB_CB(skb)) + MAX_ADDR_LEN - 8 >
1624 sll = &PACKET_SKB_CB(skb)->sa.ll;
1625 sll->sll_family = AF_PACKET;
1626 sll->sll_hatype = dev->type;
1627 sll->sll_protocol = skb->protocol;
1628 sll->sll_pkttype = skb->pkt_type;
1629 if (unlikely(po->origdev))
1630 sll->sll_ifindex = orig_dev->ifindex;
1632 sll->sll_ifindex = dev->ifindex;
1634 sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
1636 PACKET_SKB_CB(skb)->origlen = skb->len;
1638 if (pskb_trim(skb, snaplen))
1641 skb_set_owner_r(skb, sk);
1645 /* drop conntrack reference */
1648 spin_lock(&sk->sk_receive_queue.lock);
1649 po->stats.tp_packets++;
1650 skb->dropcount = atomic_read(&sk->sk_drops);
1651 __skb_queue_tail(&sk->sk_receive_queue, skb);
1652 spin_unlock(&sk->sk_receive_queue.lock);
1653 sk->sk_data_ready(sk, skb->len);
1657 spin_lock(&sk->sk_receive_queue.lock);
1658 po->stats.tp_drops++;
1659 atomic_inc(&sk->sk_drops);
1660 spin_unlock(&sk->sk_receive_queue.lock);
1663 if (skb_head != skb->data && skb_shared(skb)) {
1664 skb->data = skb_head;
1672 static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
1673 struct packet_type *pt, struct net_device *orig_dev)
1676 struct packet_sock *po;
1677 struct sockaddr_ll *sll;
1679 struct tpacket_hdr *h1;
1680 struct tpacket2_hdr *h2;
1681 struct tpacket3_hdr *h3;
1684 u8 *skb_head = skb->data;
1685 int skb_len = skb->len;
1686 unsigned int snaplen, res;
1687 unsigned long status = TP_STATUS_USER;
1688 unsigned short macoff, netoff, hdrlen;
1689 struct sk_buff *copy_skb = NULL;
1692 struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);
1694 if (skb->pkt_type == PACKET_LOOPBACK)
1697 sk = pt->af_packet_priv;
1700 if (!net_eq(dev_net(dev), sock_net(sk)))
1703 if (dev->header_ops) {
1704 if (sk->sk_type != SOCK_DGRAM)
1705 skb_push(skb, skb->data - skb_mac_header(skb));
1706 else if (skb->pkt_type == PACKET_OUTGOING) {
1707 /* Special case: outgoing packets have ll header at head */
1708 skb_pull(skb, skb_network_offset(skb));
1712 if (skb->ip_summed == CHECKSUM_PARTIAL)
1713 status |= TP_STATUS_CSUMNOTREADY;
1717 res = run_filter(skb, sk, snaplen);
1719 goto drop_n_restore;
1723 if (sk->sk_type == SOCK_DGRAM) {
1724 macoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +
1727 unsigned int maclen = skb_network_offset(skb);
1728 netoff = TPACKET_ALIGN(po->tp_hdrlen +
1729 (maclen < 16 ? 16 : maclen)) +
1731 macoff = netoff - maclen;
1733 if (po->tp_version <= TPACKET_V2) {
1734 if (macoff + snaplen > po->rx_ring.frame_size) {
1735 if (po->copy_thresh &&
1736 atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) {
1737 if (skb_shared(skb)) {
1738 copy_skb = skb_clone(skb, GFP_ATOMIC);
1740 copy_skb = skb_get(skb);
1741 skb_head = skb->data;
1744 skb_set_owner_r(copy_skb, sk);
1746 snaplen = po->rx_ring.frame_size - macoff;
1747 if ((int)snaplen < 0)
1751 spin_lock(&sk->sk_receive_queue.lock);
1752 h.raw = packet_current_rx_frame(po, skb,
1753 TP_STATUS_KERNEL, (macoff+snaplen));
1756 if (po->tp_version <= TPACKET_V2) {
1757 packet_increment_rx_head(po, &po->rx_ring);
1759 * LOSING will be reported till you read the stats,
1760 * because it's COR - Clear On Read.
1761 * Anyways, moving it for V1/V2 only as V3 doesn't need this
1764 if (po->stats.tp_drops)
1765 status |= TP_STATUS_LOSING;
1767 po->stats.tp_packets++;
1769 status |= TP_STATUS_COPY;
1770 __skb_queue_tail(&sk->sk_receive_queue, copy_skb);
1772 spin_unlock(&sk->sk_receive_queue.lock);
1774 skb_copy_bits(skb, 0, h.raw + macoff, snaplen);
1776 switch (po->tp_version) {
1778 h.h1->tp_len = skb->len;
1779 h.h1->tp_snaplen = snaplen;
1780 h.h1->tp_mac = macoff;
1781 h.h1->tp_net = netoff;
1782 if ((po->tp_tstamp & SOF_TIMESTAMPING_SYS_HARDWARE)
1783 && shhwtstamps->syststamp.tv64)
1784 tv = ktime_to_timeval(shhwtstamps->syststamp);
1785 else if ((po->tp_tstamp & SOF_TIMESTAMPING_RAW_HARDWARE)
1786 && shhwtstamps->hwtstamp.tv64)
1787 tv = ktime_to_timeval(shhwtstamps->hwtstamp);
1788 else if (skb->tstamp.tv64)
1789 tv = ktime_to_timeval(skb->tstamp);
1791 do_gettimeofday(&tv);
1792 h.h1->tp_sec = tv.tv_sec;
1793 h.h1->tp_usec = tv.tv_usec;
1794 hdrlen = sizeof(*h.h1);
1797 h.h2->tp_len = skb->len;
1798 h.h2->tp_snaplen = snaplen;
1799 h.h2->tp_mac = macoff;
1800 h.h2->tp_net = netoff;
1801 if ((po->tp_tstamp & SOF_TIMESTAMPING_SYS_HARDWARE)
1802 && shhwtstamps->syststamp.tv64)
1803 ts = ktime_to_timespec(shhwtstamps->syststamp);
1804 else if ((po->tp_tstamp & SOF_TIMESTAMPING_RAW_HARDWARE)
1805 && shhwtstamps->hwtstamp.tv64)
1806 ts = ktime_to_timespec(shhwtstamps->hwtstamp);
1807 else if (skb->tstamp.tv64)
1808 ts = ktime_to_timespec(skb->tstamp);
1810 getnstimeofday(&ts);
1811 h.h2->tp_sec = ts.tv_sec;
1812 h.h2->tp_nsec = ts.tv_nsec;
1813 if (vlan_tx_tag_present(skb)) {
1814 h.h2->tp_vlan_tci = vlan_tx_tag_get(skb);
1815 status |= TP_STATUS_VLAN_VALID;
1817 h.h2->tp_vlan_tci = 0;
1819 h.h2->tp_padding = 0;
1820 hdrlen = sizeof(*h.h2);
1823 /* tp_nxt_offset,vlan are already populated above.
1824 * So DONT clear those fields here
1826 h.h3->tp_status |= status;
1827 h.h3->tp_len = skb->len;
1828 h.h3->tp_snaplen = snaplen;
1829 h.h3->tp_mac = macoff;
1830 h.h3->tp_net = netoff;
1831 if ((po->tp_tstamp & SOF_TIMESTAMPING_SYS_HARDWARE)
1832 && shhwtstamps->syststamp.tv64)
1833 ts = ktime_to_timespec(shhwtstamps->syststamp);
1834 else if ((po->tp_tstamp & SOF_TIMESTAMPING_RAW_HARDWARE)
1835 && shhwtstamps->hwtstamp.tv64)
1836 ts = ktime_to_timespec(shhwtstamps->hwtstamp);
1837 else if (skb->tstamp.tv64)
1838 ts = ktime_to_timespec(skb->tstamp);
1840 getnstimeofday(&ts);
1841 h.h3->tp_sec = ts.tv_sec;
1842 h.h3->tp_nsec = ts.tv_nsec;
1843 hdrlen = sizeof(*h.h3);
1849 sll = h.raw + TPACKET_ALIGN(hdrlen);
1850 sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
1851 sll->sll_family = AF_PACKET;
1852 sll->sll_hatype = dev->type;
1853 sll->sll_protocol = skb->protocol;
1854 sll->sll_pkttype = skb->pkt_type;
1855 if (unlikely(po->origdev))
1856 sll->sll_ifindex = orig_dev->ifindex;
1858 sll->sll_ifindex = dev->ifindex;
1861 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
1865 if (po->tp_version <= TPACKET_V2) {
1866 end = (u8 *)PAGE_ALIGN((unsigned long)h.raw
1867 + macoff + snaplen);
1868 for (start = h.raw; start < end; start += PAGE_SIZE)
1869 flush_dcache_page(pgv_to_page(start));
1874 if (po->tp_version <= TPACKET_V2)
1875 __packet_set_status(po, h.raw, status);
1877 prb_clear_blk_fill_status(&po->rx_ring);
1879 sk->sk_data_ready(sk, 0);
1882 if (skb_head != skb->data && skb_shared(skb)) {
1883 skb->data = skb_head;
1891 po->stats.tp_drops++;
1892 spin_unlock(&sk->sk_receive_queue.lock);
1894 sk->sk_data_ready(sk, 0);
1895 kfree_skb(copy_skb);
1896 goto drop_n_restore;
1899 static void tpacket_destruct_skb(struct sk_buff *skb)
1901 struct packet_sock *po = pkt_sk(skb->sk);
1904 if (likely(po->tx_ring.pg_vec)) {
1905 ph = skb_shinfo(skb)->destructor_arg;
1906 BUG_ON(atomic_read(&po->tx_ring.pending) == 0);
1907 atomic_dec(&po->tx_ring.pending);
1908 __packet_set_status(po, ph, TP_STATUS_AVAILABLE);
1914 static int tpacket_fill_skb(struct packet_sock *po, struct sk_buff *skb,
1915 void *frame, struct net_device *dev, int size_max,
1916 __be16 proto, unsigned char *addr, int hlen)
1919 struct tpacket_hdr *h1;
1920 struct tpacket2_hdr *h2;
1923 int to_write, offset, len, tp_len, nr_frags, len_max;
1924 struct socket *sock = po->sk.sk_socket;
1928 struct flow_keys keys;
1932 skb->protocol = proto;
1934 skb->priority = po->sk.sk_priority;
1935 skb->mark = po->sk.sk_mark;
1936 skb_shinfo(skb)->destructor_arg = ph.raw;
1938 switch (po->tp_version) {
1940 tp_len = ph.h2->tp_len;
1943 tp_len = ph.h1->tp_len;
1946 if (unlikely(tp_len > size_max)) {
1947 pr_err("packet size is too long (%d > %d)\n", tp_len, size_max);
1951 skb_reserve(skb, hlen);
1952 skb_reset_network_header(skb);
1954 if (skb_flow_dissect(skb, &keys))
1955 skb_set_transport_header(skb, keys.thoff);
1957 skb_reset_transport_header(skb);
1959 if (po->tp_tx_has_off) {
1960 int off_min, off_max, off;
1961 off_min = po->tp_hdrlen - sizeof(struct sockaddr_ll);
1962 off_max = po->tx_ring.frame_size - tp_len;
1963 if (sock->type == SOCK_DGRAM) {
1964 switch (po->tp_version) {
1966 off = ph.h2->tp_net;
1969 off = ph.h1->tp_net;
1973 switch (po->tp_version) {
1975 off = ph.h2->tp_mac;
1978 off = ph.h1->tp_mac;
1982 if (unlikely((off < off_min) || (off_max < off)))
1984 data = ph.raw + off;
1986 data = ph.raw + po->tp_hdrlen - sizeof(struct sockaddr_ll);
1990 if (sock->type == SOCK_DGRAM) {
1991 err = dev_hard_header(skb, dev, ntohs(proto), addr,
1993 if (unlikely(err < 0))
1995 } else if (dev->hard_header_len) {
1996 /* net device doesn't like empty head */
1997 if (unlikely(tp_len <= dev->hard_header_len)) {
1998 pr_err("packet size is too short (%d < %d)\n",
1999 tp_len, dev->hard_header_len);
2003 skb_push(skb, dev->hard_header_len);
2004 err = skb_store_bits(skb, 0, data,
2005 dev->hard_header_len);
2009 data += dev->hard_header_len;
2010 to_write -= dev->hard_header_len;
2013 offset = offset_in_page(data);
2014 len_max = PAGE_SIZE - offset;
2015 len = ((to_write > len_max) ? len_max : to_write);
2017 skb->data_len = to_write;
2018 skb->len += to_write;
2019 skb->truesize += to_write;
2020 atomic_add(to_write, &po->sk.sk_wmem_alloc);
2022 while (likely(to_write)) {
2023 nr_frags = skb_shinfo(skb)->nr_frags;
2025 if (unlikely(nr_frags >= MAX_SKB_FRAGS)) {
2026 pr_err("Packet exceed the number of skb frags(%lu)\n",
2031 page = pgv_to_page(data);
2033 flush_dcache_page(page);
2035 skb_fill_page_desc(skb, nr_frags, page, offset, len);
2038 len_max = PAGE_SIZE;
2039 len = ((to_write > len_max) ? len_max : to_write);
2045 static int tpacket_snd(struct packet_sock *po, struct msghdr *msg)
2047 struct sk_buff *skb;
2048 struct net_device *dev;
2050 bool need_rls_dev = false;
2051 int err, reserve = 0;
2053 struct sockaddr_ll *saddr = (struct sockaddr_ll *)msg->msg_name;
2054 int tp_len, size_max;
2055 unsigned char *addr;
2057 int status = TP_STATUS_AVAILABLE;
2060 mutex_lock(&po->pg_vec_lock);
2062 if (saddr == NULL) {
2063 dev = po->prot_hook.dev;
2068 if (msg->msg_namelen < sizeof(struct sockaddr_ll))
2070 if (msg->msg_namelen < (saddr->sll_halen
2071 + offsetof(struct sockaddr_ll,
2074 proto = saddr->sll_protocol;
2075 addr = saddr->sll_addr;
2076 dev = dev_get_by_index(sock_net(&po->sk), saddr->sll_ifindex);
2077 need_rls_dev = true;
2081 if (unlikely(dev == NULL))
2084 reserve = dev->hard_header_len;
2087 if (unlikely(!(dev->flags & IFF_UP)))
2090 size_max = po->tx_ring.frame_size
2091 - (po->tp_hdrlen - sizeof(struct sockaddr_ll));
2093 if (size_max > dev->mtu + reserve)
2094 size_max = dev->mtu + reserve;
2097 ph = packet_current_frame(po, &po->tx_ring,
2098 TP_STATUS_SEND_REQUEST);
2100 if (unlikely(ph == NULL)) {
2105 status = TP_STATUS_SEND_REQUEST;
2106 hlen = LL_RESERVED_SPACE(dev);
2107 tlen = dev->needed_tailroom;
2108 skb = sock_alloc_send_skb(&po->sk,
2109 hlen + tlen + sizeof(struct sockaddr_ll),
2112 if (unlikely(skb == NULL))
2115 tp_len = tpacket_fill_skb(po, skb, ph, dev, size_max, proto,
2118 if (unlikely(tp_len < 0)) {
2120 __packet_set_status(po, ph,
2121 TP_STATUS_AVAILABLE);
2122 packet_increment_head(&po->tx_ring);
2126 status = TP_STATUS_WRONG_FORMAT;
2132 skb->destructor = tpacket_destruct_skb;
2133 __packet_set_status(po, ph, TP_STATUS_SENDING);
2134 atomic_inc(&po->tx_ring.pending);
2136 status = TP_STATUS_SEND_REQUEST;
2137 err = dev_queue_xmit(skb);
2138 if (unlikely(err > 0)) {
2139 err = net_xmit_errno(err);
2140 if (err && __packet_get_status(po, ph) ==
2141 TP_STATUS_AVAILABLE) {
2142 /* skb was destructed already */
2147 * skb was dropped but not destructed yet;
2148 * let's treat it like congestion or err < 0
2152 packet_increment_head(&po->tx_ring);
2154 } while (likely((ph != NULL) ||
2155 ((!(msg->msg_flags & MSG_DONTWAIT)) &&
2156 (atomic_read(&po->tx_ring.pending))))
2163 __packet_set_status(po, ph, status);
2169 mutex_unlock(&po->pg_vec_lock);
2173 static struct sk_buff *packet_alloc_skb(struct sock *sk, size_t prepad,
2174 size_t reserve, size_t len,
2175 size_t linear, int noblock,
2178 struct sk_buff *skb;
2180 /* Under a page? Don't bother with paged skb. */
2181 if (prepad + len < PAGE_SIZE || !linear)
2184 skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
2189 skb_reserve(skb, reserve);
2190 skb_put(skb, linear);
2191 skb->data_len = len - linear;
2192 skb->len += len - linear;
2197 static int packet_snd(struct socket *sock,
2198 struct msghdr *msg, size_t len)
2200 struct sock *sk = sock->sk;
2201 struct sockaddr_ll *saddr = (struct sockaddr_ll *)msg->msg_name;
2202 struct sk_buff *skb;
2203 struct net_device *dev;
2205 bool need_rls_dev = false;
2206 unsigned char *addr;
2207 int err, reserve = 0;
2208 struct virtio_net_hdr vnet_hdr = { 0 };
2211 struct packet_sock *po = pkt_sk(sk);
2212 unsigned short gso_type = 0;
2215 struct flow_keys keys;
2218 * Get and verify the address.
2221 if (saddr == NULL) {
2222 dev = po->prot_hook.dev;
2227 if (msg->msg_namelen < sizeof(struct sockaddr_ll))
2229 if (msg->msg_namelen < (saddr->sll_halen + offsetof(struct sockaddr_ll, sll_addr)))
2231 proto = saddr->sll_protocol;
2232 addr = saddr->sll_addr;
2233 dev = dev_get_by_index(sock_net(sk), saddr->sll_ifindex);
2234 need_rls_dev = true;
2240 if (sock->type == SOCK_RAW)
2241 reserve = dev->hard_header_len;
2244 if (!(dev->flags & IFF_UP))
2247 if (po->has_vnet_hdr) {
2248 vnet_hdr_len = sizeof(vnet_hdr);
2251 if (len < vnet_hdr_len)
2254 len -= vnet_hdr_len;
2256 err = memcpy_fromiovec((void *)&vnet_hdr, msg->msg_iov,
2261 if ((vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
2262 (vnet_hdr.csum_start + vnet_hdr.csum_offset + 2 >
2264 vnet_hdr.hdr_len = vnet_hdr.csum_start +
2265 vnet_hdr.csum_offset + 2;
2268 if (vnet_hdr.hdr_len > len)
2271 if (vnet_hdr.gso_type != VIRTIO_NET_HDR_GSO_NONE) {
2272 switch (vnet_hdr.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
2273 case VIRTIO_NET_HDR_GSO_TCPV4:
2274 gso_type = SKB_GSO_TCPV4;
2276 case VIRTIO_NET_HDR_GSO_TCPV6:
2277 gso_type = SKB_GSO_TCPV6;
2279 case VIRTIO_NET_HDR_GSO_UDP:
2280 gso_type = SKB_GSO_UDP;
2286 if (vnet_hdr.gso_type & VIRTIO_NET_HDR_GSO_ECN)
2287 gso_type |= SKB_GSO_TCP_ECN;
2289 if (vnet_hdr.gso_size == 0)
2295 if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
2296 if (!netif_supports_nofcs(dev)) {
2297 err = -EPROTONOSUPPORT;
2300 extra_len = 4; /* We're doing our own CRC */
2304 if (!gso_type && (len > dev->mtu + reserve + VLAN_HLEN + extra_len))
2308 hlen = LL_RESERVED_SPACE(dev);
2309 tlen = dev->needed_tailroom;
2310 skb = packet_alloc_skb(sk, hlen + tlen, hlen, len, vnet_hdr.hdr_len,
2311 msg->msg_flags & MSG_DONTWAIT, &err);
2315 skb_set_network_header(skb, reserve);
2318 if (sock->type == SOCK_DGRAM &&
2319 (offset = dev_hard_header(skb, dev, ntohs(proto), addr, NULL, len)) < 0)
2322 /* Returns -EFAULT on error */
2323 err = skb_copy_datagram_from_iovec(skb, offset, msg->msg_iov, 0, len);
2326 err = sock_tx_timestamp(sk, &skb_shinfo(skb)->tx_flags);
2330 if (!gso_type && (len > dev->mtu + reserve + extra_len)) {
2331 /* Earlier code assumed this would be a VLAN pkt,
2332 * double-check this now that we have the actual
2335 struct ethhdr *ehdr;
2336 skb_reset_mac_header(skb);
2337 ehdr = eth_hdr(skb);
2338 if (ehdr->h_proto != htons(ETH_P_8021Q)) {
2344 skb->protocol = proto;
2346 skb->priority = sk->sk_priority;
2347 skb->mark = sk->sk_mark;
2349 if (po->has_vnet_hdr) {
2350 if (vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
2351 if (!skb_partial_csum_set(skb, vnet_hdr.csum_start,
2352 vnet_hdr.csum_offset)) {
2358 skb_shinfo(skb)->gso_size = vnet_hdr.gso_size;
2359 skb_shinfo(skb)->gso_type = gso_type;
2361 /* Header must be checked, and gso_segs computed. */
2362 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
2363 skb_shinfo(skb)->gso_segs = 0;
2365 len += vnet_hdr_len;
2368 if (skb->ip_summed == CHECKSUM_PARTIAL)
2369 skb_set_transport_header(skb, skb_checksum_start_offset(skb));
2370 else if (skb_flow_dissect(skb, &keys))
2371 skb_set_transport_header(skb, keys.thoff);
2373 skb_set_transport_header(skb, reserve);
2375 if (unlikely(extra_len == 4))
2382 err = dev_queue_xmit(skb);
2383 if (err > 0 && (err = net_xmit_errno(err)) != 0)
2394 if (dev && need_rls_dev)
2400 static int packet_sendmsg(struct kiocb *iocb, struct socket *sock,
2401 struct msghdr *msg, size_t len)
2403 struct sock *sk = sock->sk;
2404 struct packet_sock *po = pkt_sk(sk);
2405 if (po->tx_ring.pg_vec)
2406 return tpacket_snd(po, msg);
2408 return packet_snd(sock, msg, len);
2412 * Close a PACKET socket. This is fairly simple. We immediately go
2413 * to 'closed' state and remove our protocol entry in the device list.
2416 static int packet_release(struct socket *sock)
2418 struct sock *sk = sock->sk;
2419 struct packet_sock *po;
2421 union tpacket_req_u req_u;
2429 mutex_lock(&net->packet.sklist_lock);
2430 sk_del_node_init_rcu(sk);
2431 mutex_unlock(&net->packet.sklist_lock);
2434 sock_prot_inuse_add(net, sk->sk_prot, -1);
2437 spin_lock(&po->bind_lock);
2438 unregister_prot_hook(sk, false);
2439 if (po->prot_hook.dev) {
2440 dev_put(po->prot_hook.dev);
2441 po->prot_hook.dev = NULL;
2443 spin_unlock(&po->bind_lock);
2445 packet_flush_mclist(sk);
2447 if (po->rx_ring.pg_vec) {
2448 memset(&req_u, 0, sizeof(req_u));
2449 packet_set_ring(sk, &req_u, 1, 0);
2452 if (po->tx_ring.pg_vec) {
2453 memset(&req_u, 0, sizeof(req_u));
2454 packet_set_ring(sk, &req_u, 1, 1);
2461 * Now the socket is dead. No more input will appear.
2468 skb_queue_purge(&sk->sk_receive_queue);
2469 sk_refcnt_debug_release(sk);
2476 * Attach a packet hook.
2479 static int packet_do_bind(struct sock *sk, struct net_device *dev, __be16 protocol)
2481 struct packet_sock *po = pkt_sk(sk);
2492 spin_lock(&po->bind_lock);
2493 unregister_prot_hook(sk, true);
2495 po->prot_hook.type = protocol;
2496 if (po->prot_hook.dev)
2497 dev_put(po->prot_hook.dev);
2498 po->prot_hook.dev = dev;
2500 po->ifindex = dev ? dev->ifindex : 0;
2505 if (!dev || (dev->flags & IFF_UP)) {
2506 register_prot_hook(sk);
2508 sk->sk_err = ENETDOWN;
2509 if (!sock_flag(sk, SOCK_DEAD))
2510 sk->sk_error_report(sk);
2514 spin_unlock(&po->bind_lock);
2520 * Bind a packet socket to a device
2523 static int packet_bind_spkt(struct socket *sock, struct sockaddr *uaddr,
2526 struct sock *sk = sock->sk;
2528 struct net_device *dev;
2535 if (addr_len != sizeof(struct sockaddr))
2537 strlcpy(name, uaddr->sa_data, sizeof(name));
2539 dev = dev_get_by_name(sock_net(sk), name);
2541 err = packet_do_bind(sk, dev, pkt_sk(sk)->num);
2545 static int packet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
2547 struct sockaddr_ll *sll = (struct sockaddr_ll *)uaddr;
2548 struct sock *sk = sock->sk;
2549 struct net_device *dev = NULL;
2557 if (addr_len < sizeof(struct sockaddr_ll))
2559 if (sll->sll_family != AF_PACKET)
2562 if (sll->sll_ifindex) {
2564 dev = dev_get_by_index(sock_net(sk), sll->sll_ifindex);
2568 err = packet_do_bind(sk, dev, sll->sll_protocol ? : pkt_sk(sk)->num);
2574 static struct proto packet_proto = {
2576 .owner = THIS_MODULE,
2577 .obj_size = sizeof(struct packet_sock),
2581 * Create a packet of type SOCK_PACKET.
2584 static int packet_create(struct net *net, struct socket *sock, int protocol,
2588 struct packet_sock *po;
2589 __be16 proto = (__force __be16)protocol; /* weird, but documented */
2592 if (!ns_capable(net->user_ns, CAP_NET_RAW))
2594 if (sock->type != SOCK_DGRAM && sock->type != SOCK_RAW &&
2595 sock->type != SOCK_PACKET)
2596 return -ESOCKTNOSUPPORT;
2598 sock->state = SS_UNCONNECTED;
2601 sk = sk_alloc(net, PF_PACKET, GFP_KERNEL, &packet_proto);
2605 sock->ops = &packet_ops;
2606 if (sock->type == SOCK_PACKET)
2607 sock->ops = &packet_ops_spkt;
2609 sock_init_data(sock, sk);
2612 sk->sk_family = PF_PACKET;
2615 sk->sk_destruct = packet_sock_destruct;
2616 sk_refcnt_debug_inc(sk);
2619 * Attach a protocol block
2622 spin_lock_init(&po->bind_lock);
2623 mutex_init(&po->pg_vec_lock);
2624 po->prot_hook.func = packet_rcv;
2626 if (sock->type == SOCK_PACKET)
2627 po->prot_hook.func = packet_rcv_spkt;
2629 po->prot_hook.af_packet_priv = sk;
2632 po->prot_hook.type = proto;
2633 register_prot_hook(sk);
2636 mutex_lock(&net->packet.sklist_lock);
2637 sk_add_node_rcu(sk, &net->packet.sklist);
2638 mutex_unlock(&net->packet.sklist_lock);
2641 sock_prot_inuse_add(net, &packet_proto, 1);
2649 static int packet_recv_error(struct sock *sk, struct msghdr *msg, int len)
2651 struct sock_exterr_skb *serr;
2652 struct sk_buff *skb, *skb2;
2656 skb = skb_dequeue(&sk->sk_error_queue);
2662 msg->msg_flags |= MSG_TRUNC;
2665 err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
2669 sock_recv_timestamp(msg, sk, skb);
2671 serr = SKB_EXT_ERR(skb);
2672 put_cmsg(msg, SOL_PACKET, PACKET_TX_TIMESTAMP,
2673 sizeof(serr->ee), &serr->ee);
2675 msg->msg_flags |= MSG_ERRQUEUE;
2678 /* Reset and regenerate socket error */
2679 spin_lock_bh(&sk->sk_error_queue.lock);
2681 if ((skb2 = skb_peek(&sk->sk_error_queue)) != NULL) {
2682 sk->sk_err = SKB_EXT_ERR(skb2)->ee.ee_errno;
2683 spin_unlock_bh(&sk->sk_error_queue.lock);
2684 sk->sk_error_report(sk);
2686 spin_unlock_bh(&sk->sk_error_queue.lock);
2695 * Pull a packet from our receive queue and hand it to the user.
2696 * If necessary we block.
2699 static int packet_recvmsg(struct kiocb *iocb, struct socket *sock,
2700 struct msghdr *msg, size_t len, int flags)
2702 struct sock *sk = sock->sk;
2703 struct sk_buff *skb;
2705 struct sockaddr_ll *sll;
2706 int vnet_hdr_len = 0;
2709 if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT|MSG_ERRQUEUE))
2713 /* What error should we return now? EUNATTACH? */
2714 if (pkt_sk(sk)->ifindex < 0)
2718 if (flags & MSG_ERRQUEUE) {
2719 err = packet_recv_error(sk, msg, len);
2724 * Call the generic datagram receiver. This handles all sorts
2725 * of horrible races and re-entrancy so we can forget about it
2726 * in the protocol layers.
2728 * Now it will return ENETDOWN, if device have just gone down,
2729 * but then it will block.
2732 skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);
2735 * An error occurred so return it. Because skb_recv_datagram()
2736 * handles the blocking we don't see and worry about blocking
2743 if (pkt_sk(sk)->has_vnet_hdr) {
2744 struct virtio_net_hdr vnet_hdr = { 0 };
2747 vnet_hdr_len = sizeof(vnet_hdr);
2748 if (len < vnet_hdr_len)
2751 len -= vnet_hdr_len;
2753 if (skb_is_gso(skb)) {
2754 struct skb_shared_info *sinfo = skb_shinfo(skb);
2756 /* This is a hint as to how much should be linear. */
2757 vnet_hdr.hdr_len = skb_headlen(skb);
2758 vnet_hdr.gso_size = sinfo->gso_size;
2759 if (sinfo->gso_type & SKB_GSO_TCPV4)
2760 vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
2761 else if (sinfo->gso_type & SKB_GSO_TCPV6)
2762 vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
2763 else if (sinfo->gso_type & SKB_GSO_UDP)
2764 vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_UDP;
2765 else if (sinfo->gso_type & SKB_GSO_FCOE)
2769 if (sinfo->gso_type & SKB_GSO_TCP_ECN)
2770 vnet_hdr.gso_type |= VIRTIO_NET_HDR_GSO_ECN;
2772 vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE;
2774 if (skb->ip_summed == CHECKSUM_PARTIAL) {
2775 vnet_hdr.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
2776 vnet_hdr.csum_start = skb_checksum_start_offset(skb);
2777 vnet_hdr.csum_offset = skb->csum_offset;
2778 } else if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
2779 vnet_hdr.flags = VIRTIO_NET_HDR_F_DATA_VALID;
2780 } /* else everything is zero */
2782 err = memcpy_toiovec(msg->msg_iov, (void *)&vnet_hdr,
2789 * If the address length field is there to be filled in, we fill
2793 sll = &PACKET_SKB_CB(skb)->sa.ll;
2794 if (sock->type == SOCK_PACKET)
2795 msg->msg_namelen = sizeof(struct sockaddr_pkt);
2797 msg->msg_namelen = sll->sll_halen + offsetof(struct sockaddr_ll, sll_addr);
2800 * You lose any data beyond the buffer you gave. If it worries a
2801 * user program they can ask the device for its MTU anyway.
2807 msg->msg_flags |= MSG_TRUNC;
2810 err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
2814 sock_recv_ts_and_drops(msg, sk, skb);
2817 memcpy(msg->msg_name, &PACKET_SKB_CB(skb)->sa,
2820 if (pkt_sk(sk)->auxdata) {
2821 struct tpacket_auxdata aux;
2823 aux.tp_status = TP_STATUS_USER;
2824 if (skb->ip_summed == CHECKSUM_PARTIAL)
2825 aux.tp_status |= TP_STATUS_CSUMNOTREADY;
2826 aux.tp_len = PACKET_SKB_CB(skb)->origlen;
2827 aux.tp_snaplen = skb->len;
2829 aux.tp_net = skb_network_offset(skb);
2830 if (vlan_tx_tag_present(skb)) {
2831 aux.tp_vlan_tci = vlan_tx_tag_get(skb);
2832 aux.tp_status |= TP_STATUS_VLAN_VALID;
2834 aux.tp_vlan_tci = 0;
2837 put_cmsg(msg, SOL_PACKET, PACKET_AUXDATA, sizeof(aux), &aux);
2841 * Free or return the buffer as appropriate. Again this
2842 * hides all the races and re-entrancy issues from us.
2844 err = vnet_hdr_len + ((flags&MSG_TRUNC) ? skb->len : copied);
2847 skb_free_datagram(sk, skb);
2852 static int packet_getname_spkt(struct socket *sock, struct sockaddr *uaddr,
2853 int *uaddr_len, int peer)
2855 struct net_device *dev;
2856 struct sock *sk = sock->sk;
2861 uaddr->sa_family = AF_PACKET;
2863 dev = dev_get_by_index_rcu(sock_net(sk), pkt_sk(sk)->ifindex);
2865 strncpy(uaddr->sa_data, dev->name, 14);
2867 memset(uaddr->sa_data, 0, 14);
2869 *uaddr_len = sizeof(*uaddr);
2874 static int packet_getname(struct socket *sock, struct sockaddr *uaddr,
2875 int *uaddr_len, int peer)
2877 struct net_device *dev;
2878 struct sock *sk = sock->sk;
2879 struct packet_sock *po = pkt_sk(sk);
2880 DECLARE_SOCKADDR(struct sockaddr_ll *, sll, uaddr);
2885 sll->sll_family = AF_PACKET;
2886 sll->sll_ifindex = po->ifindex;
2887 sll->sll_protocol = po->num;
2888 sll->sll_pkttype = 0;
2890 dev = dev_get_by_index_rcu(sock_net(sk), po->ifindex);
2892 sll->sll_hatype = dev->type;
2893 sll->sll_halen = dev->addr_len;
2894 memcpy(sll->sll_addr, dev->dev_addr, dev->addr_len);
2896 sll->sll_hatype = 0; /* Bad: we have no ARPHRD_UNSPEC */
2900 *uaddr_len = offsetof(struct sockaddr_ll, sll_addr) + sll->sll_halen;
2905 static int packet_dev_mc(struct net_device *dev, struct packet_mclist *i,
2909 case PACKET_MR_MULTICAST:
2910 if (i->alen != dev->addr_len)
2913 return dev_mc_add(dev, i->addr);
2915 return dev_mc_del(dev, i->addr);
2917 case PACKET_MR_PROMISC:
2918 return dev_set_promiscuity(dev, what);
2920 case PACKET_MR_ALLMULTI:
2921 return dev_set_allmulti(dev, what);
2923 case PACKET_MR_UNICAST:
2924 if (i->alen != dev->addr_len)
2927 return dev_uc_add(dev, i->addr);
2929 return dev_uc_del(dev, i->addr);
2937 static void packet_dev_mclist(struct net_device *dev, struct packet_mclist *i, int what)
2939 for ( ; i; i = i->next) {
2940 if (i->ifindex == dev->ifindex)
2941 packet_dev_mc(dev, i, what);
2945 static int packet_mc_add(struct sock *sk, struct packet_mreq_max *mreq)
2947 struct packet_sock *po = pkt_sk(sk);
2948 struct packet_mclist *ml, *i;
2949 struct net_device *dev;
2955 dev = __dev_get_by_index(sock_net(sk), mreq->mr_ifindex);
2960 if (mreq->mr_alen > dev->addr_len)
2964 i = kmalloc(sizeof(*i), GFP_KERNEL);
2969 for (ml = po->mclist; ml; ml = ml->next) {
2970 if (ml->ifindex == mreq->mr_ifindex &&
2971 ml->type == mreq->mr_type &&
2972 ml->alen == mreq->mr_alen &&
2973 memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
2975 /* Free the new element ... */
2981 i->type = mreq->mr_type;
2982 i->ifindex = mreq->mr_ifindex;
2983 i->alen = mreq->mr_alen;
2984 memcpy(i->addr, mreq->mr_address, i->alen);
2986 i->next = po->mclist;
2988 err = packet_dev_mc(dev, i, 1);
2990 po->mclist = i->next;
2999 static int packet_mc_drop(struct sock *sk, struct packet_mreq_max *mreq)
3001 struct packet_mclist *ml, **mlp;
3005 for (mlp = &pkt_sk(sk)->mclist; (ml = *mlp) != NULL; mlp = &ml->next) {
3006 if (ml->ifindex == mreq->mr_ifindex &&
3007 ml->type == mreq->mr_type &&
3008 ml->alen == mreq->mr_alen &&
3009 memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
3010 if (--ml->count == 0) {
3011 struct net_device *dev;
3013 dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
3015 packet_dev_mc(dev, ml, -1);
3023 return -EADDRNOTAVAIL;
3026 static void packet_flush_mclist(struct sock *sk)
3028 struct packet_sock *po = pkt_sk(sk);
3029 struct packet_mclist *ml;
3035 while ((ml = po->mclist) != NULL) {
3036 struct net_device *dev;
3038 po->mclist = ml->next;
3039 dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
3041 packet_dev_mc(dev, ml, -1);
3048 packet_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen)
3050 struct sock *sk = sock->sk;
3051 struct packet_sock *po = pkt_sk(sk);
3054 if (level != SOL_PACKET)
3055 return -ENOPROTOOPT;
3058 case PACKET_ADD_MEMBERSHIP:
3059 case PACKET_DROP_MEMBERSHIP:
3061 struct packet_mreq_max mreq;
3063 memset(&mreq, 0, sizeof(mreq));
3064 if (len < sizeof(struct packet_mreq))
3066 if (len > sizeof(mreq))
3068 if (copy_from_user(&mreq, optval, len))
3070 if (len < (mreq.mr_alen + offsetof(struct packet_mreq, mr_address)))
3072 if (optname == PACKET_ADD_MEMBERSHIP)
3073 ret = packet_mc_add(sk, &mreq);
3075 ret = packet_mc_drop(sk, &mreq);
3079 case PACKET_RX_RING:
3080 case PACKET_TX_RING:
3082 union tpacket_req_u req_u;
3085 switch (po->tp_version) {
3088 len = sizeof(req_u.req);
3092 len = sizeof(req_u.req3);
3097 if (pkt_sk(sk)->has_vnet_hdr)
3099 if (copy_from_user(&req_u.req, optval, len))
3101 return packet_set_ring(sk, &req_u, 0,
3102 optname == PACKET_TX_RING);
3104 case PACKET_COPY_THRESH:
3108 if (optlen != sizeof(val))
3110 if (copy_from_user(&val, optval, sizeof(val)))
3113 pkt_sk(sk)->copy_thresh = val;
3116 case PACKET_VERSION:
3120 if (optlen != sizeof(val))
3122 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3124 if (copy_from_user(&val, optval, sizeof(val)))
3130 po->tp_version = val;
3136 case PACKET_RESERVE:
3140 if (optlen != sizeof(val))
3142 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3144 if (copy_from_user(&val, optval, sizeof(val)))
3146 po->tp_reserve = val;
3153 if (optlen != sizeof(val))
3155 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3157 if (copy_from_user(&val, optval, sizeof(val)))
3159 po->tp_loss = !!val;
3162 case PACKET_AUXDATA:
3166 if (optlen < sizeof(val))
3168 if (copy_from_user(&val, optval, sizeof(val)))
3171 po->auxdata = !!val;
3174 case PACKET_ORIGDEV:
3178 if (optlen < sizeof(val))
3180 if (copy_from_user(&val, optval, sizeof(val)))
3183 po->origdev = !!val;
3186 case PACKET_VNET_HDR:
3190 if (sock->type != SOCK_RAW)
3192 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3194 if (optlen < sizeof(val))
3196 if (copy_from_user(&val, optval, sizeof(val)))
3199 po->has_vnet_hdr = !!val;
3202 case PACKET_TIMESTAMP:
3206 if (optlen != sizeof(val))
3208 if (copy_from_user(&val, optval, sizeof(val)))
3211 po->tp_tstamp = val;
3218 if (optlen != sizeof(val))
3220 if (copy_from_user(&val, optval, sizeof(val)))
3223 return fanout_add(sk, val & 0xffff, val >> 16);
3225 case PACKET_TX_HAS_OFF:
3229 if (optlen != sizeof(val))
3231 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3233 if (copy_from_user(&val, optval, sizeof(val)))
3235 po->tp_tx_has_off = !!val;
3239 return -ENOPROTOOPT;
3243 static int packet_getsockopt(struct socket *sock, int level, int optname,
3244 char __user *optval, int __user *optlen)
3247 int val, lv = sizeof(val);
3248 struct sock *sk = sock->sk;
3249 struct packet_sock *po = pkt_sk(sk);
3251 struct tpacket_stats st;
3252 union tpacket_stats_u st_u;
3254 if (level != SOL_PACKET)
3255 return -ENOPROTOOPT;
3257 if (get_user(len, optlen))
3264 case PACKET_STATISTICS:
3265 spin_lock_bh(&sk->sk_receive_queue.lock);
3266 if (po->tp_version == TPACKET_V3) {
3267 lv = sizeof(struct tpacket_stats_v3);
3268 memcpy(&st_u.stats3, &po->stats,
3269 sizeof(struct tpacket_stats));
3270 st_u.stats3.tp_freeze_q_cnt =
3271 po->stats_u.stats3.tp_freeze_q_cnt;
3272 st_u.stats3.tp_packets += po->stats.tp_drops;
3273 data = &st_u.stats3;
3275 lv = sizeof(struct tpacket_stats);
3277 st.tp_packets += st.tp_drops;
3280 memset(&po->stats, 0, sizeof(st));
3281 spin_unlock_bh(&sk->sk_receive_queue.lock);
3283 case PACKET_AUXDATA:
3286 case PACKET_ORIGDEV:
3289 case PACKET_VNET_HDR:
3290 val = po->has_vnet_hdr;
3292 case PACKET_VERSION:
3293 val = po->tp_version;
3296 if (len > sizeof(int))
3298 if (copy_from_user(&val, optval, len))
3302 val = sizeof(struct tpacket_hdr);
3305 val = sizeof(struct tpacket2_hdr);
3308 val = sizeof(struct tpacket3_hdr);
3314 case PACKET_RESERVE:
3315 val = po->tp_reserve;
3320 case PACKET_TIMESTAMP:
3321 val = po->tp_tstamp;
3325 ((u32)po->fanout->id |
3326 ((u32)po->fanout->type << 16) |
3327 ((u32)po->fanout->flags << 24)) :
3330 case PACKET_TX_HAS_OFF:
3331 val = po->tp_tx_has_off;
3334 return -ENOPROTOOPT;
3339 if (put_user(len, optlen))
3341 if (copy_to_user(optval, data, len))
3347 static int packet_notifier(struct notifier_block *this, unsigned long msg, void *data)
3350 struct net_device *dev = data;
3351 struct net *net = dev_net(dev);
3354 sk_for_each_rcu(sk, &net->packet.sklist) {
3355 struct packet_sock *po = pkt_sk(sk);
3358 case NETDEV_UNREGISTER:
3360 packet_dev_mclist(dev, po->mclist, -1);
3364 if (dev->ifindex == po->ifindex) {
3365 spin_lock(&po->bind_lock);
3367 __unregister_prot_hook(sk, false);
3368 sk->sk_err = ENETDOWN;
3369 if (!sock_flag(sk, SOCK_DEAD))
3370 sk->sk_error_report(sk);
3372 if (msg == NETDEV_UNREGISTER) {
3374 if (po->prot_hook.dev)
3375 dev_put(po->prot_hook.dev);
3376 po->prot_hook.dev = NULL;
3378 spin_unlock(&po->bind_lock);
3382 if (dev->ifindex == po->ifindex) {
3383 spin_lock(&po->bind_lock);
3385 register_prot_hook(sk);
3386 spin_unlock(&po->bind_lock);
3396 static int packet_ioctl(struct socket *sock, unsigned int cmd,
3399 struct sock *sk = sock->sk;
3404 int amount = sk_wmem_alloc_get(sk);
3406 return put_user(amount, (int __user *)arg);
3410 struct sk_buff *skb;
3413 spin_lock_bh(&sk->sk_receive_queue.lock);
3414 skb = skb_peek(&sk->sk_receive_queue);
3417 spin_unlock_bh(&sk->sk_receive_queue.lock);
3418 return put_user(amount, (int __user *)arg);
3421 return sock_get_timestamp(sk, (struct timeval __user *)arg);
3423 return sock_get_timestampns(sk, (struct timespec __user *)arg);
3433 case SIOCGIFBRDADDR:
3434 case SIOCSIFBRDADDR:
3435 case SIOCGIFNETMASK:
3436 case SIOCSIFNETMASK:
3437 case SIOCGIFDSTADDR:
3438 case SIOCSIFDSTADDR:
3440 return inet_dgram_ops.ioctl(sock, cmd, arg);
3444 return -ENOIOCTLCMD;
3449 static unsigned int packet_poll(struct file *file, struct socket *sock,
3452 struct sock *sk = sock->sk;
3453 struct packet_sock *po = pkt_sk(sk);
3454 unsigned int mask = datagram_poll(file, sock, wait);
3456 spin_lock_bh(&sk->sk_receive_queue.lock);
3457 if (po->rx_ring.pg_vec) {
3458 if (!packet_previous_rx_frame(po, &po->rx_ring,
3460 mask |= POLLIN | POLLRDNORM;
3462 spin_unlock_bh(&sk->sk_receive_queue.lock);
3463 spin_lock_bh(&sk->sk_write_queue.lock);
3464 if (po->tx_ring.pg_vec) {
3465 if (packet_current_frame(po, &po->tx_ring, TP_STATUS_AVAILABLE))
3466 mask |= POLLOUT | POLLWRNORM;
3468 spin_unlock_bh(&sk->sk_write_queue.lock);
3473 /* Dirty? Well, I still did not learn better way to account
3477 static void packet_mm_open(struct vm_area_struct *vma)
3479 struct file *file = vma->vm_file;
3480 struct socket *sock = file->private_data;
3481 struct sock *sk = sock->sk;
3484 atomic_inc(&pkt_sk(sk)->mapped);
3487 static void packet_mm_close(struct vm_area_struct *vma)
3489 struct file *file = vma->vm_file;
3490 struct socket *sock = file->private_data;
3491 struct sock *sk = sock->sk;
3494 atomic_dec(&pkt_sk(sk)->mapped);
3497 static const struct vm_operations_struct packet_mmap_ops = {
3498 .open = packet_mm_open,
3499 .close = packet_mm_close,
3502 static void free_pg_vec(struct pgv *pg_vec, unsigned int order,
3507 for (i = 0; i < len; i++) {
3508 if (likely(pg_vec[i].buffer)) {
3509 if (is_vmalloc_addr(pg_vec[i].buffer))
3510 vfree(pg_vec[i].buffer);
3512 free_pages((unsigned long)pg_vec[i].buffer,
3514 pg_vec[i].buffer = NULL;
3520 static char *alloc_one_pg_vec_page(unsigned long order)
3522 char *buffer = NULL;
3523 gfp_t gfp_flags = GFP_KERNEL | __GFP_COMP |
3524 __GFP_ZERO | __GFP_NOWARN | __GFP_NORETRY;
3526 buffer = (char *) __get_free_pages(gfp_flags, order);
3532 * __get_free_pages failed, fall back to vmalloc
3534 buffer = vzalloc((1 << order) * PAGE_SIZE);
3540 * vmalloc failed, lets dig into swap here
3542 gfp_flags &= ~__GFP_NORETRY;
3543 buffer = (char *)__get_free_pages(gfp_flags, order);
3548 * complete and utter failure
3553 static struct pgv *alloc_pg_vec(struct tpacket_req *req, int order)
3555 unsigned int block_nr = req->tp_block_nr;
3559 pg_vec = kcalloc(block_nr, sizeof(struct pgv), GFP_KERNEL);
3560 if (unlikely(!pg_vec))
3563 for (i = 0; i < block_nr; i++) {
3564 pg_vec[i].buffer = alloc_one_pg_vec_page(order);
3565 if (unlikely(!pg_vec[i].buffer))
3566 goto out_free_pgvec;
3573 free_pg_vec(pg_vec, order, block_nr);
3578 static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
3579 int closing, int tx_ring)
3581 struct pgv *pg_vec = NULL;
3582 struct packet_sock *po = pkt_sk(sk);
3583 int was_running, order = 0;
3584 struct packet_ring_buffer *rb;
3585 struct sk_buff_head *rb_queue;
3588 /* Added to avoid minimal code churn */
3589 struct tpacket_req *req = &req_u->req;
3591 /* Opening a Tx-ring is NOT supported in TPACKET_V3 */
3592 if (!closing && tx_ring && (po->tp_version > TPACKET_V2)) {
3593 WARN(1, "Tx-ring is not supported.\n");
3597 rb = tx_ring ? &po->tx_ring : &po->rx_ring;
3598 rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue;
3602 if (atomic_read(&po->mapped))
3604 if (atomic_read(&rb->pending))
3608 if (req->tp_block_nr) {
3609 /* Sanity tests and some calculations */
3611 if (unlikely(rb->pg_vec))
3614 switch (po->tp_version) {
3616 po->tp_hdrlen = TPACKET_HDRLEN;
3619 po->tp_hdrlen = TPACKET2_HDRLEN;
3622 po->tp_hdrlen = TPACKET3_HDRLEN;
3627 if (unlikely((int)req->tp_block_size <= 0))
3629 if (unlikely(req->tp_block_size & (PAGE_SIZE - 1)))
3631 if (unlikely(req->tp_frame_size < po->tp_hdrlen +
3634 if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1)))
3637 rb->frames_per_block = req->tp_block_size/req->tp_frame_size;
3638 if (unlikely(rb->frames_per_block <= 0))
3640 if (unlikely((rb->frames_per_block * req->tp_block_nr) !=
3645 order = get_order(req->tp_block_size);
3646 pg_vec = alloc_pg_vec(req, order);
3647 if (unlikely(!pg_vec))
3649 switch (po->tp_version) {
3651 /* Transmit path is not supported. We checked
3652 * it above but just being paranoid
3655 init_prb_bdqc(po, rb, pg_vec, req_u, tx_ring);
3664 if (unlikely(req->tp_frame_nr))
3670 /* Detach socket from network */
3671 spin_lock(&po->bind_lock);
3672 was_running = po->running;
3676 __unregister_prot_hook(sk, false);
3678 spin_unlock(&po->bind_lock);
3683 mutex_lock(&po->pg_vec_lock);
3684 if (closing || atomic_read(&po->mapped) == 0) {
3686 spin_lock_bh(&rb_queue->lock);
3687 swap(rb->pg_vec, pg_vec);
3688 rb->frame_max = (req->tp_frame_nr - 1);
3690 rb->frame_size = req->tp_frame_size;
3691 spin_unlock_bh(&rb_queue->lock);
3693 swap(rb->pg_vec_order, order);
3694 swap(rb->pg_vec_len, req->tp_block_nr);
3696 rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE;
3697 po->prot_hook.func = (po->rx_ring.pg_vec) ?
3698 tpacket_rcv : packet_rcv;
3699 skb_queue_purge(rb_queue);
3700 if (atomic_read(&po->mapped))
3701 pr_err("packet_mmap: vma is busy: %d\n",
3702 atomic_read(&po->mapped));
3704 mutex_unlock(&po->pg_vec_lock);
3706 spin_lock(&po->bind_lock);
3709 register_prot_hook(sk);
3711 spin_unlock(&po->bind_lock);
3712 if (closing && (po->tp_version > TPACKET_V2)) {
3713 /* Because we don't support block-based V3 on tx-ring */
3715 prb_shutdown_retire_blk_timer(po, tx_ring, rb_queue);
3720 free_pg_vec(pg_vec, order, req->tp_block_nr);
3725 static int packet_mmap(struct file *file, struct socket *sock,
3726 struct vm_area_struct *vma)
3728 struct sock *sk = sock->sk;
3729 struct packet_sock *po = pkt_sk(sk);
3730 unsigned long size, expected_size;
3731 struct packet_ring_buffer *rb;
3732 unsigned long start;
3739 mutex_lock(&po->pg_vec_lock);
3742 for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
3744 expected_size += rb->pg_vec_len
3750 if (expected_size == 0)
3753 size = vma->vm_end - vma->vm_start;
3754 if (size != expected_size)
3757 start = vma->vm_start;
3758 for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
3759 if (rb->pg_vec == NULL)
3762 for (i = 0; i < rb->pg_vec_len; i++) {
3764 void *kaddr = rb->pg_vec[i].buffer;
3767 for (pg_num = 0; pg_num < rb->pg_vec_pages; pg_num++) {
3768 page = pgv_to_page(kaddr);
3769 err = vm_insert_page(vma, start, page);
3778 atomic_inc(&po->mapped);
3779 vma->vm_ops = &packet_mmap_ops;
3783 mutex_unlock(&po->pg_vec_lock);
3787 static const struct proto_ops packet_ops_spkt = {
3788 .family = PF_PACKET,
3789 .owner = THIS_MODULE,
3790 .release = packet_release,
3791 .bind = packet_bind_spkt,
3792 .connect = sock_no_connect,
3793 .socketpair = sock_no_socketpair,
3794 .accept = sock_no_accept,
3795 .getname = packet_getname_spkt,
3796 .poll = datagram_poll,
3797 .ioctl = packet_ioctl,
3798 .listen = sock_no_listen,
3799 .shutdown = sock_no_shutdown,
3800 .setsockopt = sock_no_setsockopt,
3801 .getsockopt = sock_no_getsockopt,
3802 .sendmsg = packet_sendmsg_spkt,
3803 .recvmsg = packet_recvmsg,
3804 .mmap = sock_no_mmap,
3805 .sendpage = sock_no_sendpage,
3808 static const struct proto_ops packet_ops = {
3809 .family = PF_PACKET,
3810 .owner = THIS_MODULE,
3811 .release = packet_release,
3812 .bind = packet_bind,
3813 .connect = sock_no_connect,
3814 .socketpair = sock_no_socketpair,
3815 .accept = sock_no_accept,
3816 .getname = packet_getname,
3817 .poll = packet_poll,
3818 .ioctl = packet_ioctl,
3819 .listen = sock_no_listen,
3820 .shutdown = sock_no_shutdown,
3821 .setsockopt = packet_setsockopt,
3822 .getsockopt = packet_getsockopt,
3823 .sendmsg = packet_sendmsg,
3824 .recvmsg = packet_recvmsg,
3825 .mmap = packet_mmap,
3826 .sendpage = sock_no_sendpage,
3829 static const struct net_proto_family packet_family_ops = {
3830 .family = PF_PACKET,
3831 .create = packet_create,
3832 .owner = THIS_MODULE,
3835 static struct notifier_block packet_netdev_notifier = {
3836 .notifier_call = packet_notifier,
3839 #ifdef CONFIG_PROC_FS
3841 static void *packet_seq_start(struct seq_file *seq, loff_t *pos)
3844 struct net *net = seq_file_net(seq);
3847 return seq_hlist_start_head_rcu(&net->packet.sklist, *pos);
3850 static void *packet_seq_next(struct seq_file *seq, void *v, loff_t *pos)
3852 struct net *net = seq_file_net(seq);
3853 return seq_hlist_next_rcu(v, &net->packet.sklist, pos);
3856 static void packet_seq_stop(struct seq_file *seq, void *v)
3862 static int packet_seq_show(struct seq_file *seq, void *v)
3864 if (v == SEQ_START_TOKEN)
3865 seq_puts(seq, "sk RefCnt Type Proto Iface R Rmem User Inode\n");
3867 struct sock *s = sk_entry(v);
3868 const struct packet_sock *po = pkt_sk(s);
3871 "%pK %-6d %-4d %04x %-5d %1d %-6u %-6u %-6lu\n",
3873 atomic_read(&s->sk_refcnt),
3878 atomic_read(&s->sk_rmem_alloc),
3879 from_kuid_munged(seq_user_ns(seq), sock_i_uid(s)),
3886 static const struct seq_operations packet_seq_ops = {
3887 .start = packet_seq_start,
3888 .next = packet_seq_next,
3889 .stop = packet_seq_stop,
3890 .show = packet_seq_show,
3893 static int packet_seq_open(struct inode *inode, struct file *file)
3895 return seq_open_net(inode, file, &packet_seq_ops,
3896 sizeof(struct seq_net_private));
3899 static const struct file_operations packet_seq_fops = {
3900 .owner = THIS_MODULE,
3901 .open = packet_seq_open,
3903 .llseek = seq_lseek,
3904 .release = seq_release_net,
3909 static int __net_init packet_net_init(struct net *net)
3911 mutex_init(&net->packet.sklist_lock);
3912 INIT_HLIST_HEAD(&net->packet.sklist);
3914 if (!proc_create("packet", 0, net->proc_net, &packet_seq_fops))
3920 static void __net_exit packet_net_exit(struct net *net)
3922 remove_proc_entry("packet", net->proc_net);
3925 static struct pernet_operations packet_net_ops = {
3926 .init = packet_net_init,
3927 .exit = packet_net_exit,
3931 static void __exit packet_exit(void)
3933 unregister_netdevice_notifier(&packet_netdev_notifier);
3934 unregister_pernet_subsys(&packet_net_ops);
3935 sock_unregister(PF_PACKET);
3936 proto_unregister(&packet_proto);
3939 static int __init packet_init(void)
3941 int rc = proto_register(&packet_proto, 0);
3946 sock_register(&packet_family_ops);
3947 register_pernet_subsys(&packet_net_ops);
3948 register_netdevice_notifier(&packet_netdev_notifier);
3953 module_init(packet_init);
3954 module_exit(packet_exit);
3955 MODULE_LICENSE("GPL");
3956 MODULE_ALIAS_NETPROTO(PF_PACKET);