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>
93 #include <net/inet_common.h>
100 - if device has no dev->hard_header routine, it adds and removes ll header
101 inside itself. In this case ll header is invisible outside of device,
102 but higher levels still should reserve dev->hard_header_len.
103 Some devices are enough clever to reallocate skb, when header
104 will not fit to reserved space (tunnel), another ones are silly
106 - packet socket receives packets with pulled ll header,
107 so that SOCK_RAW should push it back.
112 Incoming, dev->hard_header!=NULL
113 mac_header -> ll header
116 Outgoing, dev->hard_header!=NULL
117 mac_header -> ll header
120 Incoming, dev->hard_header==NULL
121 mac_header -> UNKNOWN position. It is very likely, that it points to ll
122 header. PPP makes it, that is wrong, because introduce
123 assymetry between rx and tx paths.
126 Outgoing, dev->hard_header==NULL
127 mac_header -> data. ll header is still not built!
131 If dev->hard_header==NULL we are unlikely to restore sensible ll header.
137 dev->hard_header != NULL
138 mac_header -> ll header
141 dev->hard_header == NULL (ll header is added by device, we cannot control it)
145 We should set nh.raw on output to correct posistion,
146 packet classifier depends on it.
149 /* Private packet socket structures. */
151 /* identical to struct packet_mreq except it has
152 * a longer address field.
154 struct packet_mreq_max {
156 unsigned short mr_type;
157 unsigned short mr_alen;
158 unsigned char mr_address[MAX_ADDR_LEN];
162 struct tpacket_hdr *h1;
163 struct tpacket2_hdr *h2;
164 struct tpacket3_hdr *h3;
168 static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
169 int closing, int tx_ring);
171 #define V3_ALIGNMENT (8)
173 #define BLK_HDR_LEN (ALIGN(sizeof(struct tpacket_block_desc), V3_ALIGNMENT))
175 #define BLK_PLUS_PRIV(sz_of_priv) \
176 (BLK_HDR_LEN + ALIGN((sz_of_priv), V3_ALIGNMENT))
178 #define PGV_FROM_VMALLOC 1
180 #define BLOCK_STATUS(x) ((x)->hdr.bh1.block_status)
181 #define BLOCK_NUM_PKTS(x) ((x)->hdr.bh1.num_pkts)
182 #define BLOCK_O2FP(x) ((x)->hdr.bh1.offset_to_first_pkt)
183 #define BLOCK_LEN(x) ((x)->hdr.bh1.blk_len)
184 #define BLOCK_SNUM(x) ((x)->hdr.bh1.seq_num)
185 #define BLOCK_O2PRIV(x) ((x)->offset_to_priv)
186 #define BLOCK_PRIV(x) ((void *)((char *)(x) + BLOCK_O2PRIV(x)))
189 static int tpacket_snd(struct packet_sock *po, struct msghdr *msg);
190 static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
191 struct packet_type *pt, struct net_device *orig_dev);
193 static void *packet_previous_frame(struct packet_sock *po,
194 struct packet_ring_buffer *rb,
196 static void packet_increment_head(struct packet_ring_buffer *buff);
197 static int prb_curr_blk_in_use(struct tpacket_kbdq_core *,
198 struct tpacket_block_desc *);
199 static void *prb_dispatch_next_block(struct tpacket_kbdq_core *,
200 struct packet_sock *);
201 static void prb_retire_current_block(struct tpacket_kbdq_core *,
202 struct packet_sock *, unsigned int status);
203 static int prb_queue_frozen(struct tpacket_kbdq_core *);
204 static void prb_open_block(struct tpacket_kbdq_core *,
205 struct tpacket_block_desc *);
206 static void prb_retire_rx_blk_timer_expired(unsigned long);
207 static void _prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core *);
208 static void prb_init_blk_timer(struct packet_sock *,
209 struct tpacket_kbdq_core *,
210 void (*func) (unsigned long));
211 static void prb_fill_rxhash(struct tpacket_kbdq_core *, struct tpacket3_hdr *);
212 static void prb_clear_rxhash(struct tpacket_kbdq_core *,
213 struct tpacket3_hdr *);
214 static void prb_fill_vlan_info(struct tpacket_kbdq_core *,
215 struct tpacket3_hdr *);
216 static void packet_flush_mclist(struct sock *sk);
218 struct packet_skb_cb {
219 unsigned int origlen;
221 struct sockaddr_pkt pkt;
222 struct sockaddr_ll ll;
226 #define PACKET_SKB_CB(__skb) ((struct packet_skb_cb *)((__skb)->cb))
228 #define GET_PBDQC_FROM_RB(x) ((struct tpacket_kbdq_core *)(&(x)->prb_bdqc))
229 #define GET_PBLOCK_DESC(x, bid) \
230 ((struct tpacket_block_desc *)((x)->pkbdq[(bid)].buffer))
231 #define GET_CURR_PBLOCK_DESC_FROM_CORE(x) \
232 ((struct tpacket_block_desc *)((x)->pkbdq[(x)->kactive_blk_num].buffer))
233 #define GET_NEXT_PRB_BLK_NUM(x) \
234 (((x)->kactive_blk_num < ((x)->knum_blocks-1)) ? \
235 ((x)->kactive_blk_num+1) : 0)
237 static void __fanout_unlink(struct sock *sk, struct packet_sock *po);
238 static void __fanout_link(struct sock *sk, struct packet_sock *po);
240 /* register_prot_hook must be invoked with the po->bind_lock held,
241 * or from a context in which asynchronous accesses to the packet
242 * socket is not possible (packet_create()).
244 static void register_prot_hook(struct sock *sk)
246 struct packet_sock *po = pkt_sk(sk);
249 __fanout_link(sk, po);
251 dev_add_pack(&po->prot_hook);
257 /* {,__}unregister_prot_hook() must be invoked with the po->bind_lock
258 * held. If the sync parameter is true, we will temporarily drop
259 * the po->bind_lock and do a synchronize_net to make sure no
260 * asynchronous packet processing paths still refer to the elements
261 * of po->prot_hook. If the sync parameter is false, it is the
262 * callers responsibility to take care of this.
264 static void __unregister_prot_hook(struct sock *sk, bool sync)
266 struct packet_sock *po = pkt_sk(sk);
270 __fanout_unlink(sk, po);
272 __dev_remove_pack(&po->prot_hook);
276 spin_unlock(&po->bind_lock);
278 spin_lock(&po->bind_lock);
282 static void unregister_prot_hook(struct sock *sk, bool sync)
284 struct packet_sock *po = pkt_sk(sk);
287 __unregister_prot_hook(sk, sync);
290 static inline __pure struct page *pgv_to_page(void *addr)
292 if (is_vmalloc_addr(addr))
293 return vmalloc_to_page(addr);
294 return virt_to_page(addr);
297 static void __packet_set_status(struct packet_sock *po, void *frame, int status)
299 union tpacket_uhdr h;
302 switch (po->tp_version) {
304 h.h1->tp_status = status;
305 flush_dcache_page(pgv_to_page(&h.h1->tp_status));
308 h.h2->tp_status = status;
309 flush_dcache_page(pgv_to_page(&h.h2->tp_status));
313 WARN(1, "TPACKET version not supported.\n");
320 static int __packet_get_status(struct packet_sock *po, void *frame)
322 union tpacket_uhdr h;
327 switch (po->tp_version) {
329 flush_dcache_page(pgv_to_page(&h.h1->tp_status));
330 return h.h1->tp_status;
332 flush_dcache_page(pgv_to_page(&h.h2->tp_status));
333 return h.h2->tp_status;
336 WARN(1, "TPACKET version not supported.\n");
342 static void __packet_set_timestamp(struct packet_sock *po, void *frame,
345 union tpacket_uhdr h;
348 if (!ktime_to_timespec_cond(tstamp, &ts) ||
349 !sock_flag(&po->sk, SOCK_TIMESTAMPING_SOFTWARE))
353 switch (po->tp_version) {
355 h.h1->tp_sec = ts.tv_sec;
356 h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
359 h.h2->tp_sec = ts.tv_sec;
360 h.h2->tp_nsec = ts.tv_nsec;
364 WARN(1, "TPACKET version not supported.\n");
368 /* one flush is safe, as both fields always lie on the same cacheline */
369 flush_dcache_page(pgv_to_page(&h.h1->tp_sec));
373 static void *packet_lookup_frame(struct packet_sock *po,
374 struct packet_ring_buffer *rb,
375 unsigned int position,
378 unsigned int pg_vec_pos, frame_offset;
379 union tpacket_uhdr h;
381 pg_vec_pos = position / rb->frames_per_block;
382 frame_offset = position % rb->frames_per_block;
384 h.raw = rb->pg_vec[pg_vec_pos].buffer +
385 (frame_offset * rb->frame_size);
387 if (status != __packet_get_status(po, h.raw))
393 static void *packet_current_frame(struct packet_sock *po,
394 struct packet_ring_buffer *rb,
397 return packet_lookup_frame(po, rb, rb->head, status);
400 static void prb_del_retire_blk_timer(struct tpacket_kbdq_core *pkc)
402 del_timer_sync(&pkc->retire_blk_timer);
405 static void prb_shutdown_retire_blk_timer(struct packet_sock *po,
407 struct sk_buff_head *rb_queue)
409 struct tpacket_kbdq_core *pkc;
411 pkc = tx_ring ? &po->tx_ring.prb_bdqc : &po->rx_ring.prb_bdqc;
413 spin_lock(&rb_queue->lock);
414 pkc->delete_blk_timer = 1;
415 spin_unlock(&rb_queue->lock);
417 prb_del_retire_blk_timer(pkc);
420 static void prb_init_blk_timer(struct packet_sock *po,
421 struct tpacket_kbdq_core *pkc,
422 void (*func) (unsigned long))
424 init_timer(&pkc->retire_blk_timer);
425 pkc->retire_blk_timer.data = (long)po;
426 pkc->retire_blk_timer.function = func;
427 pkc->retire_blk_timer.expires = jiffies;
430 static void prb_setup_retire_blk_timer(struct packet_sock *po, int tx_ring)
432 struct tpacket_kbdq_core *pkc;
437 pkc = tx_ring ? &po->tx_ring.prb_bdqc : &po->rx_ring.prb_bdqc;
438 prb_init_blk_timer(po, pkc, prb_retire_rx_blk_timer_expired);
441 static int prb_calc_retire_blk_tmo(struct packet_sock *po,
442 int blk_size_in_bytes)
444 struct net_device *dev;
445 unsigned int mbits = 0, msec = 0, div = 0, tmo = 0;
446 struct ethtool_cmd ecmd;
451 dev = __dev_get_by_index(sock_net(&po->sk), po->ifindex);
452 if (unlikely(!dev)) {
454 return DEFAULT_PRB_RETIRE_TOV;
456 err = __ethtool_get_settings(dev, &ecmd);
457 speed = ethtool_cmd_speed(&ecmd);
461 * If the link speed is so slow you don't really
462 * need to worry about perf anyways
464 if (speed < SPEED_1000 || speed == SPEED_UNKNOWN) {
465 return DEFAULT_PRB_RETIRE_TOV;
472 mbits = (blk_size_in_bytes * 8) / (1024 * 1024);
484 static void prb_init_ft_ops(struct tpacket_kbdq_core *p1,
485 union tpacket_req_u *req_u)
487 p1->feature_req_word = req_u->req3.tp_feature_req_word;
490 static void init_prb_bdqc(struct packet_sock *po,
491 struct packet_ring_buffer *rb,
493 union tpacket_req_u *req_u, int tx_ring)
495 struct tpacket_kbdq_core *p1 = &rb->prb_bdqc;
496 struct tpacket_block_desc *pbd;
498 memset(p1, 0x0, sizeof(*p1));
500 p1->knxt_seq_num = 1;
502 pbd = (struct tpacket_block_desc *)pg_vec[0].buffer;
503 p1->pkblk_start = pg_vec[0].buffer;
504 p1->kblk_size = req_u->req3.tp_block_size;
505 p1->knum_blocks = req_u->req3.tp_block_nr;
506 p1->hdrlen = po->tp_hdrlen;
507 p1->version = po->tp_version;
508 p1->last_kactive_blk_num = 0;
509 po->stats_u.stats3.tp_freeze_q_cnt = 0;
510 if (req_u->req3.tp_retire_blk_tov)
511 p1->retire_blk_tov = req_u->req3.tp_retire_blk_tov;
513 p1->retire_blk_tov = prb_calc_retire_blk_tmo(po,
514 req_u->req3.tp_block_size);
515 p1->tov_in_jiffies = msecs_to_jiffies(p1->retire_blk_tov);
516 p1->blk_sizeof_priv = req_u->req3.tp_sizeof_priv;
518 prb_init_ft_ops(p1, req_u);
519 prb_setup_retire_blk_timer(po, tx_ring);
520 prb_open_block(p1, pbd);
523 /* Do NOT update the last_blk_num first.
524 * Assumes sk_buff_head lock is held.
526 static void _prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core *pkc)
528 mod_timer(&pkc->retire_blk_timer,
529 jiffies + pkc->tov_in_jiffies);
530 pkc->last_kactive_blk_num = pkc->kactive_blk_num;
535 * 1) We refresh the timer only when we open a block.
536 * By doing this we don't waste cycles refreshing the timer
537 * on packet-by-packet basis.
539 * With a 1MB block-size, on a 1Gbps line, it will take
540 * i) ~8 ms to fill a block + ii) memcpy etc.
541 * In this cut we are not accounting for the memcpy time.
543 * So, if the user sets the 'tmo' to 10ms then the timer
544 * will never fire while the block is still getting filled
545 * (which is what we want). However, the user could choose
546 * to close a block early and that's fine.
548 * But when the timer does fire, we check whether or not to refresh it.
549 * Since the tmo granularity is in msecs, it is not too expensive
550 * to refresh the timer, lets say every '8' msecs.
551 * Either the user can set the 'tmo' or we can derive it based on
552 * a) line-speed and b) block-size.
553 * prb_calc_retire_blk_tmo() calculates the tmo.
556 static void prb_retire_rx_blk_timer_expired(unsigned long data)
558 struct packet_sock *po = (struct packet_sock *)data;
559 struct tpacket_kbdq_core *pkc = &po->rx_ring.prb_bdqc;
561 struct tpacket_block_desc *pbd;
563 spin_lock(&po->sk.sk_receive_queue.lock);
565 frozen = prb_queue_frozen(pkc);
566 pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
568 if (unlikely(pkc->delete_blk_timer))
571 /* We only need to plug the race when the block is partially filled.
573 * lock(); increment BLOCK_NUM_PKTS; unlock()
574 * copy_bits() is in progress ...
575 * timer fires on other cpu:
576 * we can't retire the current block because copy_bits
580 if (BLOCK_NUM_PKTS(pbd)) {
581 while (atomic_read(&pkc->blk_fill_in_prog)) {
582 /* Waiting for skb_copy_bits to finish... */
587 if (pkc->last_kactive_blk_num == pkc->kactive_blk_num) {
589 prb_retire_current_block(pkc, po, TP_STATUS_BLK_TMO);
590 if (!prb_dispatch_next_block(pkc, po))
595 /* Case 1. Queue was frozen because user-space was
598 if (prb_curr_blk_in_use(pkc, pbd)) {
600 * Ok, user-space is still behind.
601 * So just refresh the timer.
605 /* Case 2. queue was frozen,user-space caught up,
606 * now the link went idle && the timer fired.
607 * We don't have a block to close.So we open this
608 * block and restart the timer.
609 * opening a block thaws the queue,restarts timer
610 * Thawing/timer-refresh is a side effect.
612 prb_open_block(pkc, pbd);
619 _prb_refresh_rx_retire_blk_timer(pkc);
622 spin_unlock(&po->sk.sk_receive_queue.lock);
625 static void prb_flush_block(struct tpacket_kbdq_core *pkc1,
626 struct tpacket_block_desc *pbd1, __u32 status)
628 /* Flush everything minus the block header */
630 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
635 /* Skip the block header(we know header WILL fit in 4K) */
638 end = (u8 *)PAGE_ALIGN((unsigned long)pkc1->pkblk_end);
639 for (; start < end; start += PAGE_SIZE)
640 flush_dcache_page(pgv_to_page(start));
645 /* Now update the block status. */
647 BLOCK_STATUS(pbd1) = status;
649 /* Flush the block header */
651 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
653 flush_dcache_page(pgv_to_page(start));
663 * 2) Increment active_blk_num
665 * Note:We DONT refresh the timer on purpose.
666 * Because almost always the next block will be opened.
668 static void prb_close_block(struct tpacket_kbdq_core *pkc1,
669 struct tpacket_block_desc *pbd1,
670 struct packet_sock *po, unsigned int stat)
672 __u32 status = TP_STATUS_USER | stat;
674 struct tpacket3_hdr *last_pkt;
675 struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
677 if (po->stats.tp_drops)
678 status |= TP_STATUS_LOSING;
680 last_pkt = (struct tpacket3_hdr *)pkc1->prev;
681 last_pkt->tp_next_offset = 0;
683 /* Get the ts of the last pkt */
684 if (BLOCK_NUM_PKTS(pbd1)) {
685 h1->ts_last_pkt.ts_sec = last_pkt->tp_sec;
686 h1->ts_last_pkt.ts_nsec = last_pkt->tp_nsec;
688 /* Ok, we tmo'd - so get the current time */
691 h1->ts_last_pkt.ts_sec = ts.tv_sec;
692 h1->ts_last_pkt.ts_nsec = ts.tv_nsec;
697 /* Flush the block */
698 prb_flush_block(pkc1, pbd1, status);
700 pkc1->kactive_blk_num = GET_NEXT_PRB_BLK_NUM(pkc1);
703 static void prb_thaw_queue(struct tpacket_kbdq_core *pkc)
705 pkc->reset_pending_on_curr_blk = 0;
709 * Side effect of opening a block:
711 * 1) prb_queue is thawed.
712 * 2) retire_blk_timer is refreshed.
715 static void prb_open_block(struct tpacket_kbdq_core *pkc1,
716 struct tpacket_block_desc *pbd1)
719 struct tpacket_hdr_v1 *h1 = &pbd1->hdr.bh1;
723 if (likely(TP_STATUS_KERNEL == BLOCK_STATUS(pbd1))) {
725 /* We could have just memset this but we will lose the
726 * flexibility of making the priv area sticky
728 BLOCK_SNUM(pbd1) = pkc1->knxt_seq_num++;
729 BLOCK_NUM_PKTS(pbd1) = 0;
730 BLOCK_LEN(pbd1) = BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
732 h1->ts_first_pkt.ts_sec = ts.tv_sec;
733 h1->ts_first_pkt.ts_nsec = ts.tv_nsec;
734 pkc1->pkblk_start = (char *)pbd1;
735 pkc1->nxt_offset = pkc1->pkblk_start + BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
736 BLOCK_O2FP(pbd1) = (__u32)BLK_PLUS_PRIV(pkc1->blk_sizeof_priv);
737 BLOCK_O2PRIV(pbd1) = BLK_HDR_LEN;
738 pbd1->version = pkc1->version;
739 pkc1->prev = pkc1->nxt_offset;
740 pkc1->pkblk_end = pkc1->pkblk_start + pkc1->kblk_size;
741 prb_thaw_queue(pkc1);
742 _prb_refresh_rx_retire_blk_timer(pkc1);
749 WARN(1, "ERROR block:%p is NOT FREE status:%d kactive_blk_num:%d\n",
750 pbd1, BLOCK_STATUS(pbd1), pkc1->kactive_blk_num);
756 * Queue freeze logic:
757 * 1) Assume tp_block_nr = 8 blocks.
758 * 2) At time 't0', user opens Rx ring.
759 * 3) Some time past 't0', kernel starts filling blocks starting from 0 .. 7
760 * 4) user-space is either sleeping or processing block '0'.
761 * 5) tpacket_rcv is currently filling block '7', since there is no space left,
762 * it will close block-7,loop around and try to fill block '0'.
764 * __packet_lookup_frame_in_block
765 * prb_retire_current_block()
766 * prb_dispatch_next_block()
767 * |->(BLOCK_STATUS == USER) evaluates to true
768 * 5.1) Since block-0 is currently in-use, we just freeze the queue.
769 * 6) Now there are two cases:
770 * 6.1) Link goes idle right after the queue is frozen.
771 * But remember, the last open_block() refreshed the timer.
772 * When this timer expires,it will refresh itself so that we can
773 * re-open block-0 in near future.
774 * 6.2) Link is busy and keeps on receiving packets. This is a simple
775 * case and __packet_lookup_frame_in_block will check if block-0
776 * is free and can now be re-used.
778 static void prb_freeze_queue(struct tpacket_kbdq_core *pkc,
779 struct packet_sock *po)
781 pkc->reset_pending_on_curr_blk = 1;
782 po->stats_u.stats3.tp_freeze_q_cnt++;
785 #define TOTAL_PKT_LEN_INCL_ALIGN(length) (ALIGN((length), V3_ALIGNMENT))
788 * If the next block is free then we will dispatch it
789 * and return a good offset.
790 * Else, we will freeze the queue.
791 * So, caller must check the return value.
793 static void *prb_dispatch_next_block(struct tpacket_kbdq_core *pkc,
794 struct packet_sock *po)
796 struct tpacket_block_desc *pbd;
800 /* 1. Get current block num */
801 pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
803 /* 2. If this block is currently in_use then freeze the queue */
804 if (TP_STATUS_USER & BLOCK_STATUS(pbd)) {
805 prb_freeze_queue(pkc, po);
811 * open this block and return the offset where the first packet
812 * needs to get stored.
814 prb_open_block(pkc, pbd);
815 return (void *)pkc->nxt_offset;
818 static void prb_retire_current_block(struct tpacket_kbdq_core *pkc,
819 struct packet_sock *po, unsigned int status)
821 struct tpacket_block_desc *pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
823 /* retire/close the current block */
824 if (likely(TP_STATUS_KERNEL == BLOCK_STATUS(pbd))) {
826 * Plug the case where copy_bits() is in progress on
827 * cpu-0 and tpacket_rcv() got invoked on cpu-1, didn't
828 * have space to copy the pkt in the current block and
829 * called prb_retire_current_block()
831 * We don't need to worry about the TMO case because
832 * the timer-handler already handled this case.
834 if (!(status & TP_STATUS_BLK_TMO)) {
835 while (atomic_read(&pkc->blk_fill_in_prog)) {
836 /* Waiting for skb_copy_bits to finish... */
840 prb_close_block(pkc, pbd, po, status);
844 WARN(1, "ERROR-pbd[%d]:%p\n", pkc->kactive_blk_num, pbd);
849 static int prb_curr_blk_in_use(struct tpacket_kbdq_core *pkc,
850 struct tpacket_block_desc *pbd)
852 return TP_STATUS_USER & BLOCK_STATUS(pbd);
855 static int prb_queue_frozen(struct tpacket_kbdq_core *pkc)
857 return pkc->reset_pending_on_curr_blk;
860 static void prb_clear_blk_fill_status(struct packet_ring_buffer *rb)
862 struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(rb);
863 atomic_dec(&pkc->blk_fill_in_prog);
866 static void prb_fill_rxhash(struct tpacket_kbdq_core *pkc,
867 struct tpacket3_hdr *ppd)
869 ppd->hv1.tp_rxhash = skb_get_rxhash(pkc->skb);
872 static void prb_clear_rxhash(struct tpacket_kbdq_core *pkc,
873 struct tpacket3_hdr *ppd)
875 ppd->hv1.tp_rxhash = 0;
878 static void prb_fill_vlan_info(struct tpacket_kbdq_core *pkc,
879 struct tpacket3_hdr *ppd)
881 if (vlan_tx_tag_present(pkc->skb)) {
882 ppd->hv1.tp_vlan_tci = vlan_tx_tag_get(pkc->skb);
883 ppd->tp_status = TP_STATUS_VLAN_VALID;
885 ppd->hv1.tp_vlan_tci = 0;
886 ppd->tp_status = TP_STATUS_AVAILABLE;
890 static void prb_run_all_ft_ops(struct tpacket_kbdq_core *pkc,
891 struct tpacket3_hdr *ppd)
893 prb_fill_vlan_info(pkc, ppd);
895 if (pkc->feature_req_word & TP_FT_REQ_FILL_RXHASH)
896 prb_fill_rxhash(pkc, ppd);
898 prb_clear_rxhash(pkc, ppd);
901 static void prb_fill_curr_block(char *curr,
902 struct tpacket_kbdq_core *pkc,
903 struct tpacket_block_desc *pbd,
906 struct tpacket3_hdr *ppd;
908 ppd = (struct tpacket3_hdr *)curr;
909 ppd->tp_next_offset = TOTAL_PKT_LEN_INCL_ALIGN(len);
911 pkc->nxt_offset += TOTAL_PKT_LEN_INCL_ALIGN(len);
912 BLOCK_LEN(pbd) += TOTAL_PKT_LEN_INCL_ALIGN(len);
913 BLOCK_NUM_PKTS(pbd) += 1;
914 atomic_inc(&pkc->blk_fill_in_prog);
915 prb_run_all_ft_ops(pkc, ppd);
918 /* Assumes caller has the sk->rx_queue.lock */
919 static void *__packet_lookup_frame_in_block(struct packet_sock *po,
925 struct tpacket_kbdq_core *pkc;
926 struct tpacket_block_desc *pbd;
929 pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
930 pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
932 /* Queue is frozen when user space is lagging behind */
933 if (prb_queue_frozen(pkc)) {
935 * Check if that last block which caused the queue to freeze,
936 * is still in_use by user-space.
938 if (prb_curr_blk_in_use(pkc, pbd)) {
939 /* Can't record this packet */
943 * Ok, the block was released by user-space.
944 * Now let's open that block.
945 * opening a block also thaws the queue.
946 * Thawing is a side effect.
948 prb_open_block(pkc, pbd);
953 curr = pkc->nxt_offset;
955 end = (char *)pbd + pkc->kblk_size;
957 /* first try the current block */
958 if (curr+TOTAL_PKT_LEN_INCL_ALIGN(len) < end) {
959 prb_fill_curr_block(curr, pkc, pbd, len);
963 /* Ok, close the current block */
964 prb_retire_current_block(pkc, po, 0);
966 /* Now, try to dispatch the next block */
967 curr = (char *)prb_dispatch_next_block(pkc, po);
969 pbd = GET_CURR_PBLOCK_DESC_FROM_CORE(pkc);
970 prb_fill_curr_block(curr, pkc, pbd, len);
975 * No free blocks are available.user_space hasn't caught up yet.
976 * Queue was just frozen and now this packet will get dropped.
981 static void *packet_current_rx_frame(struct packet_sock *po,
983 int status, unsigned int len)
986 switch (po->tp_version) {
989 curr = packet_lookup_frame(po, &po->rx_ring,
990 po->rx_ring.head, status);
993 return __packet_lookup_frame_in_block(po, skb, status, len);
995 WARN(1, "TPACKET version not supported\n");
1001 static void *prb_lookup_block(struct packet_sock *po,
1002 struct packet_ring_buffer *rb,
1006 struct tpacket_kbdq_core *pkc = GET_PBDQC_FROM_RB(rb);
1007 struct tpacket_block_desc *pbd = GET_PBLOCK_DESC(pkc, idx);
1009 if (status != BLOCK_STATUS(pbd))
1014 static int prb_previous_blk_num(struct packet_ring_buffer *rb)
1017 if (rb->prb_bdqc.kactive_blk_num)
1018 prev = rb->prb_bdqc.kactive_blk_num-1;
1020 prev = rb->prb_bdqc.knum_blocks-1;
1024 /* Assumes caller has held the rx_queue.lock */
1025 static void *__prb_previous_block(struct packet_sock *po,
1026 struct packet_ring_buffer *rb,
1029 unsigned int previous = prb_previous_blk_num(rb);
1030 return prb_lookup_block(po, rb, previous, status);
1033 static void *packet_previous_rx_frame(struct packet_sock *po,
1034 struct packet_ring_buffer *rb,
1037 if (po->tp_version <= TPACKET_V2)
1038 return packet_previous_frame(po, rb, status);
1040 return __prb_previous_block(po, rb, status);
1043 static void packet_increment_rx_head(struct packet_sock *po,
1044 struct packet_ring_buffer *rb)
1046 switch (po->tp_version) {
1049 return packet_increment_head(rb);
1052 WARN(1, "TPACKET version not supported.\n");
1058 static void *packet_previous_frame(struct packet_sock *po,
1059 struct packet_ring_buffer *rb,
1062 unsigned int previous = rb->head ? rb->head - 1 : rb->frame_max;
1063 return packet_lookup_frame(po, rb, previous, status);
1066 static void packet_increment_head(struct packet_ring_buffer *buff)
1068 buff->head = buff->head != buff->frame_max ? buff->head+1 : 0;
1071 static bool packet_rcv_has_room(struct packet_sock *po, struct sk_buff *skb)
1073 struct sock *sk = &po->sk;
1076 if (po->prot_hook.func != tpacket_rcv)
1077 return (atomic_read(&sk->sk_rmem_alloc) + skb->truesize)
1080 spin_lock(&sk->sk_receive_queue.lock);
1081 if (po->tp_version == TPACKET_V3)
1082 has_room = prb_lookup_block(po, &po->rx_ring,
1083 po->rx_ring.prb_bdqc.kactive_blk_num,
1086 has_room = packet_lookup_frame(po, &po->rx_ring,
1089 spin_unlock(&sk->sk_receive_queue.lock);
1094 static void packet_sock_destruct(struct sock *sk)
1096 skb_queue_purge(&sk->sk_error_queue);
1098 WARN_ON(atomic_read(&sk->sk_rmem_alloc));
1099 WARN_ON(atomic_read(&sk->sk_wmem_alloc));
1101 if (!sock_flag(sk, SOCK_DEAD)) {
1102 pr_err("Attempt to release alive packet socket: %p\n", sk);
1106 sk_refcnt_debug_dec(sk);
1109 static int fanout_rr_next(struct packet_fanout *f, unsigned int num)
1111 int x = atomic_read(&f->rr_cur) + 1;
1119 static unsigned int fanout_demux_hash(struct packet_fanout *f,
1120 struct sk_buff *skb,
1123 return (((u64)skb->rxhash) * num) >> 32;
1126 static unsigned int fanout_demux_lb(struct packet_fanout *f,
1127 struct sk_buff *skb,
1132 cur = atomic_read(&f->rr_cur);
1133 while ((old = atomic_cmpxchg(&f->rr_cur, cur,
1134 fanout_rr_next(f, num))) != cur)
1139 static unsigned int fanout_demux_cpu(struct packet_fanout *f,
1140 struct sk_buff *skb,
1143 return smp_processor_id() % num;
1146 static unsigned int fanout_demux_rollover(struct packet_fanout *f,
1147 struct sk_buff *skb,
1148 unsigned int idx, unsigned int skip,
1153 i = j = min_t(int, f->next[idx], num - 1);
1155 if (i != skip && packet_rcv_has_room(pkt_sk(f->arr[i]), skb)) {
1167 static bool fanout_has_flag(struct packet_fanout *f, u16 flag)
1169 return f->flags & (flag >> 8);
1172 static int packet_rcv_fanout(struct sk_buff *skb, struct net_device *dev,
1173 struct packet_type *pt, struct net_device *orig_dev)
1175 struct packet_fanout *f = pt->af_packet_priv;
1176 unsigned int num = f->num_members;
1177 struct packet_sock *po;
1180 if (!net_eq(dev_net(dev), read_pnet(&f->net)) ||
1187 case PACKET_FANOUT_HASH:
1189 if (fanout_has_flag(f, PACKET_FANOUT_FLAG_DEFRAG)) {
1190 skb = ip_check_defrag(skb, IP_DEFRAG_AF_PACKET);
1194 skb_get_rxhash(skb);
1195 idx = fanout_demux_hash(f, skb, num);
1197 case PACKET_FANOUT_LB:
1198 idx = fanout_demux_lb(f, skb, num);
1200 case PACKET_FANOUT_CPU:
1201 idx = fanout_demux_cpu(f, skb, num);
1203 case PACKET_FANOUT_ROLLOVER:
1204 idx = fanout_demux_rollover(f, skb, 0, (unsigned int) -1, num);
1208 po = pkt_sk(f->arr[idx]);
1209 if (fanout_has_flag(f, PACKET_FANOUT_FLAG_ROLLOVER) &&
1210 unlikely(!packet_rcv_has_room(po, skb))) {
1211 idx = fanout_demux_rollover(f, skb, idx, idx, num);
1212 po = pkt_sk(f->arr[idx]);
1215 return po->prot_hook.func(skb, dev, &po->prot_hook, orig_dev);
1218 DEFINE_MUTEX(fanout_mutex);
1219 EXPORT_SYMBOL_GPL(fanout_mutex);
1220 static LIST_HEAD(fanout_list);
1222 static void __fanout_link(struct sock *sk, struct packet_sock *po)
1224 struct packet_fanout *f = po->fanout;
1226 spin_lock(&f->lock);
1227 f->arr[f->num_members] = sk;
1230 spin_unlock(&f->lock);
1233 static void __fanout_unlink(struct sock *sk, struct packet_sock *po)
1235 struct packet_fanout *f = po->fanout;
1238 spin_lock(&f->lock);
1239 for (i = 0; i < f->num_members; i++) {
1240 if (f->arr[i] == sk)
1243 BUG_ON(i >= f->num_members);
1244 f->arr[i] = f->arr[f->num_members - 1];
1246 spin_unlock(&f->lock);
1249 static bool match_fanout_group(struct packet_type *ptype, struct sock * sk)
1251 if (ptype->af_packet_priv == (void*)((struct packet_sock *)sk)->fanout)
1257 static int fanout_add(struct sock *sk, u16 id, u16 type_flags)
1259 struct packet_sock *po = pkt_sk(sk);
1260 struct packet_fanout *f, *match;
1261 u8 type = type_flags & 0xff;
1262 u8 flags = type_flags >> 8;
1266 case PACKET_FANOUT_ROLLOVER:
1267 if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)
1269 case PACKET_FANOUT_HASH:
1270 case PACKET_FANOUT_LB:
1271 case PACKET_FANOUT_CPU:
1283 mutex_lock(&fanout_mutex);
1285 list_for_each_entry(f, &fanout_list, list) {
1287 read_pnet(&f->net) == sock_net(sk)) {
1293 if (match && match->flags != flags)
1297 match = kzalloc(sizeof(*match), GFP_KERNEL);
1300 write_pnet(&match->net, sock_net(sk));
1303 match->flags = flags;
1304 atomic_set(&match->rr_cur, 0);
1305 INIT_LIST_HEAD(&match->list);
1306 spin_lock_init(&match->lock);
1307 atomic_set(&match->sk_ref, 0);
1308 match->prot_hook.type = po->prot_hook.type;
1309 match->prot_hook.dev = po->prot_hook.dev;
1310 match->prot_hook.func = packet_rcv_fanout;
1311 match->prot_hook.af_packet_priv = match;
1312 match->prot_hook.id_match = match_fanout_group;
1313 dev_add_pack(&match->prot_hook);
1314 list_add(&match->list, &fanout_list);
1317 if (match->type == type &&
1318 match->prot_hook.type == po->prot_hook.type &&
1319 match->prot_hook.dev == po->prot_hook.dev) {
1321 if (atomic_read(&match->sk_ref) < PACKET_FANOUT_MAX) {
1322 __dev_remove_pack(&po->prot_hook);
1324 atomic_inc(&match->sk_ref);
1325 __fanout_link(sk, po);
1330 mutex_unlock(&fanout_mutex);
1334 static void fanout_release(struct sock *sk)
1336 struct packet_sock *po = pkt_sk(sk);
1337 struct packet_fanout *f;
1343 mutex_lock(&fanout_mutex);
1346 if (atomic_dec_and_test(&f->sk_ref)) {
1348 dev_remove_pack(&f->prot_hook);
1351 mutex_unlock(&fanout_mutex);
1354 static const struct proto_ops packet_ops;
1356 static const struct proto_ops packet_ops_spkt;
1358 static int packet_rcv_spkt(struct sk_buff *skb, struct net_device *dev,
1359 struct packet_type *pt, struct net_device *orig_dev)
1362 struct sockaddr_pkt *spkt;
1365 * When we registered the protocol we saved the socket in the data
1366 * field for just this event.
1369 sk = pt->af_packet_priv;
1372 * Yank back the headers [hope the device set this
1373 * right or kerboom...]
1375 * Incoming packets have ll header pulled,
1378 * For outgoing ones skb->data == skb_mac_header(skb)
1379 * so that this procedure is noop.
1382 if (skb->pkt_type == PACKET_LOOPBACK)
1385 if (!net_eq(dev_net(dev), sock_net(sk)))
1388 skb = skb_share_check(skb, GFP_ATOMIC);
1392 /* drop any routing info */
1395 /* drop conntrack reference */
1398 spkt = &PACKET_SKB_CB(skb)->sa.pkt;
1400 skb_push(skb, skb->data - skb_mac_header(skb));
1403 * The SOCK_PACKET socket receives _all_ frames.
1406 spkt->spkt_family = dev->type;
1407 strlcpy(spkt->spkt_device, dev->name, sizeof(spkt->spkt_device));
1408 spkt->spkt_protocol = skb->protocol;
1411 * Charge the memory to the socket. This is done specifically
1412 * to prevent sockets using all the memory up.
1415 if (sock_queue_rcv_skb(sk, skb) == 0)
1426 * Output a raw packet to a device layer. This bypasses all the other
1427 * protocol layers and you must therefore supply it with a complete frame
1430 static int packet_sendmsg_spkt(struct kiocb *iocb, struct socket *sock,
1431 struct msghdr *msg, size_t len)
1433 struct sock *sk = sock->sk;
1434 struct sockaddr_pkt *saddr = (struct sockaddr_pkt *)msg->msg_name;
1435 struct sk_buff *skb = NULL;
1436 struct net_device *dev;
1442 * Get and verify the address.
1446 if (msg->msg_namelen < sizeof(struct sockaddr))
1448 if (msg->msg_namelen == sizeof(struct sockaddr_pkt))
1449 proto = saddr->spkt_protocol;
1451 return -ENOTCONN; /* SOCK_PACKET must be sent giving an address */
1454 * Find the device first to size check it
1457 saddr->spkt_device[sizeof(saddr->spkt_device) - 1] = 0;
1460 dev = dev_get_by_name_rcu(sock_net(sk), saddr->spkt_device);
1466 if (!(dev->flags & IFF_UP))
1470 * You may not queue a frame bigger than the mtu. This is the lowest level
1471 * raw protocol and you must do your own fragmentation at this level.
1474 if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
1475 if (!netif_supports_nofcs(dev)) {
1476 err = -EPROTONOSUPPORT;
1479 extra_len = 4; /* We're doing our own CRC */
1483 if (len > dev->mtu + dev->hard_header_len + VLAN_HLEN + extra_len)
1487 size_t reserved = LL_RESERVED_SPACE(dev);
1488 int tlen = dev->needed_tailroom;
1489 unsigned int hhlen = dev->header_ops ? dev->hard_header_len : 0;
1492 skb = sock_wmalloc(sk, len + reserved + tlen, 0, GFP_KERNEL);
1495 /* FIXME: Save some space for broken drivers that write a hard
1496 * header at transmission time by themselves. PPP is the notable
1497 * one here. This should really be fixed at the driver level.
1499 skb_reserve(skb, reserved);
1500 skb_reset_network_header(skb);
1502 /* Try to align data part correctly */
1507 skb_reset_network_header(skb);
1509 err = memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len);
1515 if (len > (dev->mtu + dev->hard_header_len + extra_len)) {
1516 /* Earlier code assumed this would be a VLAN pkt,
1517 * double-check this now that we have the actual
1520 struct ethhdr *ehdr;
1521 skb_reset_mac_header(skb);
1522 ehdr = eth_hdr(skb);
1523 if (ehdr->h_proto != htons(ETH_P_8021Q)) {
1529 skb->protocol = proto;
1531 skb->priority = sk->sk_priority;
1532 skb->mark = sk->sk_mark;
1534 sock_tx_timestamp(sk, &skb_shinfo(skb)->tx_flags);
1536 if (unlikely(extra_len == 4))
1539 skb_probe_transport_header(skb, 0);
1541 dev_queue_xmit(skb);
1552 static unsigned int run_filter(const struct sk_buff *skb,
1553 const struct sock *sk,
1556 struct sk_filter *filter;
1559 filter = rcu_dereference(sk->sk_filter);
1561 res = SK_RUN_FILTER(filter, skb);
1568 * This function makes lazy skb cloning in hope that most of packets
1569 * are discarded by BPF.
1571 * Note tricky part: we DO mangle shared skb! skb->data, skb->len
1572 * and skb->cb are mangled. It works because (and until) packets
1573 * falling here are owned by current CPU. Output packets are cloned
1574 * by dev_queue_xmit_nit(), input packets are processed by net_bh
1575 * sequencially, so that if we return skb to original state on exit,
1576 * we will not harm anyone.
1579 static int packet_rcv(struct sk_buff *skb, struct net_device *dev,
1580 struct packet_type *pt, struct net_device *orig_dev)
1583 struct sockaddr_ll *sll;
1584 struct packet_sock *po;
1585 u8 *skb_head = skb->data;
1586 int skb_len = skb->len;
1587 unsigned int snaplen, res;
1589 if (skb->pkt_type == PACKET_LOOPBACK)
1592 sk = pt->af_packet_priv;
1595 if (!net_eq(dev_net(dev), sock_net(sk)))
1600 if (dev->header_ops) {
1601 /* The device has an explicit notion of ll header,
1602 * exported to higher levels.
1604 * Otherwise, the device hides details of its frame
1605 * structure, so that corresponding packet head is
1606 * never delivered to user.
1608 if (sk->sk_type != SOCK_DGRAM)
1609 skb_push(skb, skb->data - skb_mac_header(skb));
1610 else if (skb->pkt_type == PACKET_OUTGOING) {
1611 /* Special case: outgoing packets have ll header at head */
1612 skb_pull(skb, skb_network_offset(skb));
1618 res = run_filter(skb, sk, snaplen);
1620 goto drop_n_restore;
1624 if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
1627 if (skb_shared(skb)) {
1628 struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
1632 if (skb_head != skb->data) {
1633 skb->data = skb_head;
1640 BUILD_BUG_ON(sizeof(*PACKET_SKB_CB(skb)) + MAX_ADDR_LEN - 8 >
1643 sll = &PACKET_SKB_CB(skb)->sa.ll;
1644 sll->sll_family = AF_PACKET;
1645 sll->sll_hatype = dev->type;
1646 sll->sll_protocol = skb->protocol;
1647 sll->sll_pkttype = skb->pkt_type;
1648 if (unlikely(po->origdev))
1649 sll->sll_ifindex = orig_dev->ifindex;
1651 sll->sll_ifindex = dev->ifindex;
1653 sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
1655 PACKET_SKB_CB(skb)->origlen = skb->len;
1657 if (pskb_trim(skb, snaplen))
1660 skb_set_owner_r(skb, sk);
1664 /* drop conntrack reference */
1667 spin_lock(&sk->sk_receive_queue.lock);
1668 po->stats.tp_packets++;
1669 skb->dropcount = atomic_read(&sk->sk_drops);
1670 __skb_queue_tail(&sk->sk_receive_queue, skb);
1671 spin_unlock(&sk->sk_receive_queue.lock);
1672 sk->sk_data_ready(sk, skb->len);
1676 spin_lock(&sk->sk_receive_queue.lock);
1677 po->stats.tp_drops++;
1678 atomic_inc(&sk->sk_drops);
1679 spin_unlock(&sk->sk_receive_queue.lock);
1682 if (skb_head != skb->data && skb_shared(skb)) {
1683 skb->data = skb_head;
1691 static void tpacket_get_timestamp(struct sk_buff *skb, struct timespec *ts,
1694 struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);
1697 if ((flags & SOF_TIMESTAMPING_SYS_HARDWARE) &&
1698 ktime_to_timespec_cond(shhwtstamps->syststamp, ts))
1700 if ((flags & SOF_TIMESTAMPING_RAW_HARDWARE) &&
1701 ktime_to_timespec_cond(shhwtstamps->hwtstamp, ts))
1705 if (ktime_to_timespec_cond(skb->tstamp, ts))
1711 static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
1712 struct packet_type *pt, struct net_device *orig_dev)
1715 struct packet_sock *po;
1716 struct sockaddr_ll *sll;
1717 union tpacket_uhdr h;
1718 u8 *skb_head = skb->data;
1719 int skb_len = skb->len;
1720 unsigned int snaplen, res;
1721 unsigned long status = TP_STATUS_USER;
1722 unsigned short macoff, netoff, hdrlen;
1723 struct sk_buff *copy_skb = NULL;
1726 if (skb->pkt_type == PACKET_LOOPBACK)
1729 sk = pt->af_packet_priv;
1732 if (!net_eq(dev_net(dev), sock_net(sk)))
1735 if (dev->header_ops) {
1736 if (sk->sk_type != SOCK_DGRAM)
1737 skb_push(skb, skb->data - skb_mac_header(skb));
1738 else if (skb->pkt_type == PACKET_OUTGOING) {
1739 /* Special case: outgoing packets have ll header at head */
1740 skb_pull(skb, skb_network_offset(skb));
1744 if (skb->ip_summed == CHECKSUM_PARTIAL)
1745 status |= TP_STATUS_CSUMNOTREADY;
1749 res = run_filter(skb, sk, snaplen);
1751 goto drop_n_restore;
1755 if (sk->sk_type == SOCK_DGRAM) {
1756 macoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +
1759 unsigned int maclen = skb_network_offset(skb);
1760 netoff = TPACKET_ALIGN(po->tp_hdrlen +
1761 (maclen < 16 ? 16 : maclen)) +
1763 macoff = netoff - maclen;
1765 if (po->tp_version <= TPACKET_V2) {
1766 if (macoff + snaplen > po->rx_ring.frame_size) {
1767 if (po->copy_thresh &&
1768 atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) {
1769 if (skb_shared(skb)) {
1770 copy_skb = skb_clone(skb, GFP_ATOMIC);
1772 copy_skb = skb_get(skb);
1773 skb_head = skb->data;
1776 skb_set_owner_r(copy_skb, sk);
1778 snaplen = po->rx_ring.frame_size - macoff;
1779 if ((int)snaplen < 0)
1783 spin_lock(&sk->sk_receive_queue.lock);
1784 h.raw = packet_current_rx_frame(po, skb,
1785 TP_STATUS_KERNEL, (macoff+snaplen));
1788 if (po->tp_version <= TPACKET_V2) {
1789 packet_increment_rx_head(po, &po->rx_ring);
1791 * LOSING will be reported till you read the stats,
1792 * because it's COR - Clear On Read.
1793 * Anyways, moving it for V1/V2 only as V3 doesn't need this
1796 if (po->stats.tp_drops)
1797 status |= TP_STATUS_LOSING;
1799 po->stats.tp_packets++;
1801 status |= TP_STATUS_COPY;
1802 __skb_queue_tail(&sk->sk_receive_queue, copy_skb);
1804 spin_unlock(&sk->sk_receive_queue.lock);
1806 skb_copy_bits(skb, 0, h.raw + macoff, snaplen);
1807 tpacket_get_timestamp(skb, &ts, po->tp_tstamp);
1809 switch (po->tp_version) {
1811 h.h1->tp_len = skb->len;
1812 h.h1->tp_snaplen = snaplen;
1813 h.h1->tp_mac = macoff;
1814 h.h1->tp_net = netoff;
1815 h.h1->tp_sec = ts.tv_sec;
1816 h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
1817 hdrlen = sizeof(*h.h1);
1820 h.h2->tp_len = skb->len;
1821 h.h2->tp_snaplen = snaplen;
1822 h.h2->tp_mac = macoff;
1823 h.h2->tp_net = netoff;
1824 h.h2->tp_sec = ts.tv_sec;
1825 h.h2->tp_nsec = ts.tv_nsec;
1826 if (vlan_tx_tag_present(skb)) {
1827 h.h2->tp_vlan_tci = vlan_tx_tag_get(skb);
1828 status |= TP_STATUS_VLAN_VALID;
1830 h.h2->tp_vlan_tci = 0;
1832 h.h2->tp_padding = 0;
1833 hdrlen = sizeof(*h.h2);
1836 /* tp_nxt_offset,vlan are already populated above.
1837 * So DONT clear those fields here
1839 h.h3->tp_status |= status;
1840 h.h3->tp_len = skb->len;
1841 h.h3->tp_snaplen = snaplen;
1842 h.h3->tp_mac = macoff;
1843 h.h3->tp_net = netoff;
1844 h.h3->tp_sec = ts.tv_sec;
1845 h.h3->tp_nsec = ts.tv_nsec;
1846 hdrlen = sizeof(*h.h3);
1852 sll = h.raw + TPACKET_ALIGN(hdrlen);
1853 sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
1854 sll->sll_family = AF_PACKET;
1855 sll->sll_hatype = dev->type;
1856 sll->sll_protocol = skb->protocol;
1857 sll->sll_pkttype = skb->pkt_type;
1858 if (unlikely(po->origdev))
1859 sll->sll_ifindex = orig_dev->ifindex;
1861 sll->sll_ifindex = dev->ifindex;
1864 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
1868 if (po->tp_version <= TPACKET_V2) {
1869 end = (u8 *)PAGE_ALIGN((unsigned long)h.raw
1870 + macoff + snaplen);
1871 for (start = h.raw; start < end; start += PAGE_SIZE)
1872 flush_dcache_page(pgv_to_page(start));
1877 if (po->tp_version <= TPACKET_V2)
1878 __packet_set_status(po, h.raw, status);
1880 prb_clear_blk_fill_status(&po->rx_ring);
1882 sk->sk_data_ready(sk, 0);
1885 if (skb_head != skb->data && skb_shared(skb)) {
1886 skb->data = skb_head;
1894 po->stats.tp_drops++;
1895 spin_unlock(&sk->sk_receive_queue.lock);
1897 sk->sk_data_ready(sk, 0);
1898 kfree_skb(copy_skb);
1899 goto drop_n_restore;
1902 static void tpacket_destruct_skb(struct sk_buff *skb)
1904 struct packet_sock *po = pkt_sk(skb->sk);
1907 if (likely(po->tx_ring.pg_vec)) {
1908 ph = skb_shinfo(skb)->destructor_arg;
1909 BUG_ON(atomic_read(&po->tx_ring.pending) == 0);
1910 atomic_dec(&po->tx_ring.pending);
1911 __packet_set_timestamp(po, ph, skb->tstamp);
1912 __packet_set_status(po, ph, TP_STATUS_AVAILABLE);
1918 static int tpacket_fill_skb(struct packet_sock *po, struct sk_buff *skb,
1919 void *frame, struct net_device *dev, int size_max,
1920 __be16 proto, unsigned char *addr, int hlen)
1922 union tpacket_uhdr ph;
1923 int to_write, offset, len, tp_len, nr_frags, len_max;
1924 struct socket *sock = po->sk.sk_socket;
1931 skb->protocol = proto;
1933 skb->priority = po->sk.sk_priority;
1934 skb->mark = po->sk.sk_mark;
1935 sock_tx_timestamp(&po->sk, &skb_shinfo(skb)->tx_flags);
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);
1953 skb_probe_transport_header(skb, 0);
1955 if (po->tp_tx_has_off) {
1956 int off_min, off_max, off;
1957 off_min = po->tp_hdrlen - sizeof(struct sockaddr_ll);
1958 off_max = po->tx_ring.frame_size - tp_len;
1959 if (sock->type == SOCK_DGRAM) {
1960 switch (po->tp_version) {
1962 off = ph.h2->tp_net;
1965 off = ph.h1->tp_net;
1969 switch (po->tp_version) {
1971 off = ph.h2->tp_mac;
1974 off = ph.h1->tp_mac;
1978 if (unlikely((off < off_min) || (off_max < off)))
1980 data = ph.raw + off;
1982 data = ph.raw + po->tp_hdrlen - sizeof(struct sockaddr_ll);
1986 if (sock->type == SOCK_DGRAM) {
1987 err = dev_hard_header(skb, dev, ntohs(proto), addr,
1989 if (unlikely(err < 0))
1991 } else if (dev->hard_header_len) {
1992 /* net device doesn't like empty head */
1993 if (unlikely(tp_len <= dev->hard_header_len)) {
1994 pr_err("packet size is too short (%d < %d)\n",
1995 tp_len, dev->hard_header_len);
1999 skb_push(skb, dev->hard_header_len);
2000 err = skb_store_bits(skb, 0, data,
2001 dev->hard_header_len);
2005 data += dev->hard_header_len;
2006 to_write -= dev->hard_header_len;
2009 offset = offset_in_page(data);
2010 len_max = PAGE_SIZE - offset;
2011 len = ((to_write > len_max) ? len_max : to_write);
2013 skb->data_len = to_write;
2014 skb->len += to_write;
2015 skb->truesize += to_write;
2016 atomic_add(to_write, &po->sk.sk_wmem_alloc);
2018 while (likely(to_write)) {
2019 nr_frags = skb_shinfo(skb)->nr_frags;
2021 if (unlikely(nr_frags >= MAX_SKB_FRAGS)) {
2022 pr_err("Packet exceed the number of skb frags(%lu)\n",
2027 page = pgv_to_page(data);
2029 flush_dcache_page(page);
2031 skb_fill_page_desc(skb, nr_frags, page, offset, len);
2034 len_max = PAGE_SIZE;
2035 len = ((to_write > len_max) ? len_max : to_write);
2041 static int tpacket_snd(struct packet_sock *po, struct msghdr *msg)
2043 struct sk_buff *skb;
2044 struct net_device *dev;
2046 bool need_rls_dev = false;
2047 int err, reserve = 0;
2049 struct sockaddr_ll *saddr = (struct sockaddr_ll *)msg->msg_name;
2050 int tp_len, size_max;
2051 unsigned char *addr;
2053 int status = TP_STATUS_AVAILABLE;
2056 mutex_lock(&po->pg_vec_lock);
2058 if (saddr == NULL) {
2059 dev = po->prot_hook.dev;
2064 if (msg->msg_namelen < sizeof(struct sockaddr_ll))
2066 if (msg->msg_namelen < (saddr->sll_halen
2067 + offsetof(struct sockaddr_ll,
2070 proto = saddr->sll_protocol;
2071 addr = saddr->sll_addr;
2072 dev = dev_get_by_index(sock_net(&po->sk), saddr->sll_ifindex);
2073 need_rls_dev = true;
2077 if (unlikely(dev == NULL))
2080 reserve = dev->hard_header_len;
2083 if (unlikely(!(dev->flags & IFF_UP)))
2086 size_max = po->tx_ring.frame_size
2087 - (po->tp_hdrlen - sizeof(struct sockaddr_ll));
2089 if (size_max > dev->mtu + reserve)
2090 size_max = dev->mtu + reserve;
2093 ph = packet_current_frame(po, &po->tx_ring,
2094 TP_STATUS_SEND_REQUEST);
2096 if (unlikely(ph == NULL)) {
2101 status = TP_STATUS_SEND_REQUEST;
2102 hlen = LL_RESERVED_SPACE(dev);
2103 tlen = dev->needed_tailroom;
2104 skb = sock_alloc_send_skb(&po->sk,
2105 hlen + tlen + sizeof(struct sockaddr_ll),
2108 if (unlikely(skb == NULL))
2111 tp_len = tpacket_fill_skb(po, skb, ph, dev, size_max, proto,
2114 if (unlikely(tp_len < 0)) {
2116 __packet_set_status(po, ph,
2117 TP_STATUS_AVAILABLE);
2118 packet_increment_head(&po->tx_ring);
2122 status = TP_STATUS_WRONG_FORMAT;
2128 skb->destructor = tpacket_destruct_skb;
2129 __packet_set_status(po, ph, TP_STATUS_SENDING);
2130 atomic_inc(&po->tx_ring.pending);
2132 status = TP_STATUS_SEND_REQUEST;
2133 err = dev_queue_xmit(skb);
2134 if (unlikely(err > 0)) {
2135 err = net_xmit_errno(err);
2136 if (err && __packet_get_status(po, ph) ==
2137 TP_STATUS_AVAILABLE) {
2138 /* skb was destructed already */
2143 * skb was dropped but not destructed yet;
2144 * let's treat it like congestion or err < 0
2148 packet_increment_head(&po->tx_ring);
2150 } while (likely((ph != NULL) ||
2151 ((!(msg->msg_flags & MSG_DONTWAIT)) &&
2152 (atomic_read(&po->tx_ring.pending))))
2159 __packet_set_status(po, ph, status);
2165 mutex_unlock(&po->pg_vec_lock);
2169 static struct sk_buff *packet_alloc_skb(struct sock *sk, size_t prepad,
2170 size_t reserve, size_t len,
2171 size_t linear, int noblock,
2174 struct sk_buff *skb;
2176 /* Under a page? Don't bother with paged skb. */
2177 if (prepad + len < PAGE_SIZE || !linear)
2180 skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
2185 skb_reserve(skb, reserve);
2186 skb_put(skb, linear);
2187 skb->data_len = len - linear;
2188 skb->len += len - linear;
2193 static int packet_snd(struct socket *sock,
2194 struct msghdr *msg, size_t len)
2196 struct sock *sk = sock->sk;
2197 struct sockaddr_ll *saddr = (struct sockaddr_ll *)msg->msg_name;
2198 struct sk_buff *skb;
2199 struct net_device *dev;
2201 bool need_rls_dev = false;
2202 unsigned char *addr;
2203 int err, reserve = 0;
2204 struct virtio_net_hdr vnet_hdr = { 0 };
2207 struct packet_sock *po = pkt_sk(sk);
2208 unsigned short gso_type = 0;
2213 * Get and verify the address.
2216 if (saddr == NULL) {
2217 dev = po->prot_hook.dev;
2222 if (msg->msg_namelen < sizeof(struct sockaddr_ll))
2224 if (msg->msg_namelen < (saddr->sll_halen + offsetof(struct sockaddr_ll, sll_addr)))
2226 proto = saddr->sll_protocol;
2227 addr = saddr->sll_addr;
2228 dev = dev_get_by_index(sock_net(sk), saddr->sll_ifindex);
2229 need_rls_dev = true;
2235 if (sock->type == SOCK_RAW)
2236 reserve = dev->hard_header_len;
2239 if (!(dev->flags & IFF_UP))
2242 if (po->has_vnet_hdr) {
2243 vnet_hdr_len = sizeof(vnet_hdr);
2246 if (len < vnet_hdr_len)
2249 len -= vnet_hdr_len;
2251 err = memcpy_fromiovec((void *)&vnet_hdr, msg->msg_iov,
2256 if ((vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
2257 (vnet_hdr.csum_start + vnet_hdr.csum_offset + 2 >
2259 vnet_hdr.hdr_len = vnet_hdr.csum_start +
2260 vnet_hdr.csum_offset + 2;
2263 if (vnet_hdr.hdr_len > len)
2266 if (vnet_hdr.gso_type != VIRTIO_NET_HDR_GSO_NONE) {
2267 switch (vnet_hdr.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
2268 case VIRTIO_NET_HDR_GSO_TCPV4:
2269 gso_type = SKB_GSO_TCPV4;
2271 case VIRTIO_NET_HDR_GSO_TCPV6:
2272 gso_type = SKB_GSO_TCPV6;
2274 case VIRTIO_NET_HDR_GSO_UDP:
2275 gso_type = SKB_GSO_UDP;
2281 if (vnet_hdr.gso_type & VIRTIO_NET_HDR_GSO_ECN)
2282 gso_type |= SKB_GSO_TCP_ECN;
2284 if (vnet_hdr.gso_size == 0)
2290 if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
2291 if (!netif_supports_nofcs(dev)) {
2292 err = -EPROTONOSUPPORT;
2295 extra_len = 4; /* We're doing our own CRC */
2299 if (!gso_type && (len > dev->mtu + reserve + VLAN_HLEN + extra_len))
2303 hlen = LL_RESERVED_SPACE(dev);
2304 tlen = dev->needed_tailroom;
2305 skb = packet_alloc_skb(sk, hlen + tlen, hlen, len, vnet_hdr.hdr_len,
2306 msg->msg_flags & MSG_DONTWAIT, &err);
2310 skb_set_network_header(skb, reserve);
2313 if (sock->type == SOCK_DGRAM &&
2314 (offset = dev_hard_header(skb, dev, ntohs(proto), addr, NULL, len)) < 0)
2317 /* Returns -EFAULT on error */
2318 err = skb_copy_datagram_from_iovec(skb, offset, msg->msg_iov, 0, len);
2322 sock_tx_timestamp(sk, &skb_shinfo(skb)->tx_flags);
2324 if (!gso_type && (len > dev->mtu + reserve + extra_len)) {
2325 /* Earlier code assumed this would be a VLAN pkt,
2326 * double-check this now that we have the actual
2329 struct ethhdr *ehdr;
2330 skb_reset_mac_header(skb);
2331 ehdr = eth_hdr(skb);
2332 if (ehdr->h_proto != htons(ETH_P_8021Q)) {
2338 skb->protocol = proto;
2340 skb->priority = sk->sk_priority;
2341 skb->mark = sk->sk_mark;
2343 if (po->has_vnet_hdr) {
2344 if (vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
2345 if (!skb_partial_csum_set(skb, vnet_hdr.csum_start,
2346 vnet_hdr.csum_offset)) {
2352 skb_shinfo(skb)->gso_size = vnet_hdr.gso_size;
2353 skb_shinfo(skb)->gso_type = gso_type;
2355 /* Header must be checked, and gso_segs computed. */
2356 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
2357 skb_shinfo(skb)->gso_segs = 0;
2359 len += vnet_hdr_len;
2362 skb_probe_transport_header(skb, reserve);
2364 if (unlikely(extra_len == 4))
2371 err = dev_queue_xmit(skb);
2372 if (err > 0 && (err = net_xmit_errno(err)) != 0)
2383 if (dev && need_rls_dev)
2389 static int packet_sendmsg(struct kiocb *iocb, struct socket *sock,
2390 struct msghdr *msg, size_t len)
2392 struct sock *sk = sock->sk;
2393 struct packet_sock *po = pkt_sk(sk);
2394 if (po->tx_ring.pg_vec)
2395 return tpacket_snd(po, msg);
2397 return packet_snd(sock, msg, len);
2401 * Close a PACKET socket. This is fairly simple. We immediately go
2402 * to 'closed' state and remove our protocol entry in the device list.
2405 static int packet_release(struct socket *sock)
2407 struct sock *sk = sock->sk;
2408 struct packet_sock *po;
2410 union tpacket_req_u req_u;
2418 mutex_lock(&net->packet.sklist_lock);
2419 sk_del_node_init_rcu(sk);
2420 mutex_unlock(&net->packet.sklist_lock);
2423 sock_prot_inuse_add(net, sk->sk_prot, -1);
2426 spin_lock(&po->bind_lock);
2427 unregister_prot_hook(sk, false);
2428 if (po->prot_hook.dev) {
2429 dev_put(po->prot_hook.dev);
2430 po->prot_hook.dev = NULL;
2432 spin_unlock(&po->bind_lock);
2434 packet_flush_mclist(sk);
2436 if (po->rx_ring.pg_vec) {
2437 memset(&req_u, 0, sizeof(req_u));
2438 packet_set_ring(sk, &req_u, 1, 0);
2441 if (po->tx_ring.pg_vec) {
2442 memset(&req_u, 0, sizeof(req_u));
2443 packet_set_ring(sk, &req_u, 1, 1);
2450 * Now the socket is dead. No more input will appear.
2457 skb_queue_purge(&sk->sk_receive_queue);
2458 sk_refcnt_debug_release(sk);
2465 * Attach a packet hook.
2468 static int packet_do_bind(struct sock *sk, struct net_device *dev, __be16 protocol)
2470 struct packet_sock *po = pkt_sk(sk);
2481 spin_lock(&po->bind_lock);
2482 unregister_prot_hook(sk, true);
2484 po->prot_hook.type = protocol;
2485 if (po->prot_hook.dev)
2486 dev_put(po->prot_hook.dev);
2487 po->prot_hook.dev = dev;
2489 po->ifindex = dev ? dev->ifindex : 0;
2494 if (!dev || (dev->flags & IFF_UP)) {
2495 register_prot_hook(sk);
2497 sk->sk_err = ENETDOWN;
2498 if (!sock_flag(sk, SOCK_DEAD))
2499 sk->sk_error_report(sk);
2503 spin_unlock(&po->bind_lock);
2509 * Bind a packet socket to a device
2512 static int packet_bind_spkt(struct socket *sock, struct sockaddr *uaddr,
2515 struct sock *sk = sock->sk;
2517 struct net_device *dev;
2524 if (addr_len != sizeof(struct sockaddr))
2526 strlcpy(name, uaddr->sa_data, sizeof(name));
2528 dev = dev_get_by_name(sock_net(sk), name);
2530 err = packet_do_bind(sk, dev, pkt_sk(sk)->num);
2534 static int packet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
2536 struct sockaddr_ll *sll = (struct sockaddr_ll *)uaddr;
2537 struct sock *sk = sock->sk;
2538 struct net_device *dev = NULL;
2546 if (addr_len < sizeof(struct sockaddr_ll))
2548 if (sll->sll_family != AF_PACKET)
2551 if (sll->sll_ifindex) {
2553 dev = dev_get_by_index(sock_net(sk), sll->sll_ifindex);
2557 err = packet_do_bind(sk, dev, sll->sll_protocol ? : pkt_sk(sk)->num);
2563 static struct proto packet_proto = {
2565 .owner = THIS_MODULE,
2566 .obj_size = sizeof(struct packet_sock),
2570 * Create a packet of type SOCK_PACKET.
2573 static int packet_create(struct net *net, struct socket *sock, int protocol,
2577 struct packet_sock *po;
2578 __be16 proto = (__force __be16)protocol; /* weird, but documented */
2581 if (!ns_capable(net->user_ns, CAP_NET_RAW))
2583 if (sock->type != SOCK_DGRAM && sock->type != SOCK_RAW &&
2584 sock->type != SOCK_PACKET)
2585 return -ESOCKTNOSUPPORT;
2587 sock->state = SS_UNCONNECTED;
2590 sk = sk_alloc(net, PF_PACKET, GFP_KERNEL, &packet_proto);
2594 sock->ops = &packet_ops;
2595 if (sock->type == SOCK_PACKET)
2596 sock->ops = &packet_ops_spkt;
2598 sock_init_data(sock, sk);
2601 sk->sk_family = PF_PACKET;
2604 sk->sk_destruct = packet_sock_destruct;
2605 sk_refcnt_debug_inc(sk);
2608 * Attach a protocol block
2611 spin_lock_init(&po->bind_lock);
2612 mutex_init(&po->pg_vec_lock);
2613 po->prot_hook.func = packet_rcv;
2615 if (sock->type == SOCK_PACKET)
2616 po->prot_hook.func = packet_rcv_spkt;
2618 po->prot_hook.af_packet_priv = sk;
2621 po->prot_hook.type = proto;
2622 register_prot_hook(sk);
2625 mutex_lock(&net->packet.sklist_lock);
2626 sk_add_node_rcu(sk, &net->packet.sklist);
2627 mutex_unlock(&net->packet.sklist_lock);
2630 sock_prot_inuse_add(net, &packet_proto, 1);
2638 static int packet_recv_error(struct sock *sk, struct msghdr *msg, int len)
2640 struct sock_exterr_skb *serr;
2641 struct sk_buff *skb, *skb2;
2645 skb = skb_dequeue(&sk->sk_error_queue);
2651 msg->msg_flags |= MSG_TRUNC;
2654 err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
2658 sock_recv_timestamp(msg, sk, skb);
2660 serr = SKB_EXT_ERR(skb);
2661 put_cmsg(msg, SOL_PACKET, PACKET_TX_TIMESTAMP,
2662 sizeof(serr->ee), &serr->ee);
2664 msg->msg_flags |= MSG_ERRQUEUE;
2667 /* Reset and regenerate socket error */
2668 spin_lock_bh(&sk->sk_error_queue.lock);
2670 if ((skb2 = skb_peek(&sk->sk_error_queue)) != NULL) {
2671 sk->sk_err = SKB_EXT_ERR(skb2)->ee.ee_errno;
2672 spin_unlock_bh(&sk->sk_error_queue.lock);
2673 sk->sk_error_report(sk);
2675 spin_unlock_bh(&sk->sk_error_queue.lock);
2684 * Pull a packet from our receive queue and hand it to the user.
2685 * If necessary we block.
2688 static int packet_recvmsg(struct kiocb *iocb, struct socket *sock,
2689 struct msghdr *msg, size_t len, int flags)
2691 struct sock *sk = sock->sk;
2692 struct sk_buff *skb;
2694 struct sockaddr_ll *sll;
2695 int vnet_hdr_len = 0;
2698 if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT|MSG_ERRQUEUE))
2702 /* What error should we return now? EUNATTACH? */
2703 if (pkt_sk(sk)->ifindex < 0)
2707 if (flags & MSG_ERRQUEUE) {
2708 err = packet_recv_error(sk, msg, len);
2713 * Call the generic datagram receiver. This handles all sorts
2714 * of horrible races and re-entrancy so we can forget about it
2715 * in the protocol layers.
2717 * Now it will return ENETDOWN, if device have just gone down,
2718 * but then it will block.
2721 skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);
2724 * An error occurred so return it. Because skb_recv_datagram()
2725 * handles the blocking we don't see and worry about blocking
2732 if (pkt_sk(sk)->has_vnet_hdr) {
2733 struct virtio_net_hdr vnet_hdr = { 0 };
2736 vnet_hdr_len = sizeof(vnet_hdr);
2737 if (len < vnet_hdr_len)
2740 len -= vnet_hdr_len;
2742 if (skb_is_gso(skb)) {
2743 struct skb_shared_info *sinfo = skb_shinfo(skb);
2745 /* This is a hint as to how much should be linear. */
2746 vnet_hdr.hdr_len = skb_headlen(skb);
2747 vnet_hdr.gso_size = sinfo->gso_size;
2748 if (sinfo->gso_type & SKB_GSO_TCPV4)
2749 vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
2750 else if (sinfo->gso_type & SKB_GSO_TCPV6)
2751 vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
2752 else if (sinfo->gso_type & SKB_GSO_UDP)
2753 vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_UDP;
2754 else if (sinfo->gso_type & SKB_GSO_FCOE)
2758 if (sinfo->gso_type & SKB_GSO_TCP_ECN)
2759 vnet_hdr.gso_type |= VIRTIO_NET_HDR_GSO_ECN;
2761 vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE;
2763 if (skb->ip_summed == CHECKSUM_PARTIAL) {
2764 vnet_hdr.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
2765 vnet_hdr.csum_start = skb_checksum_start_offset(skb);
2766 vnet_hdr.csum_offset = skb->csum_offset;
2767 } else if (skb->ip_summed == CHECKSUM_UNNECESSARY) {
2768 vnet_hdr.flags = VIRTIO_NET_HDR_F_DATA_VALID;
2769 } /* else everything is zero */
2771 err = memcpy_toiovec(msg->msg_iov, (void *)&vnet_hdr,
2778 * If the address length field is there to be filled in, we fill
2782 sll = &PACKET_SKB_CB(skb)->sa.ll;
2783 if (sock->type == SOCK_PACKET)
2784 msg->msg_namelen = sizeof(struct sockaddr_pkt);
2786 msg->msg_namelen = sll->sll_halen + offsetof(struct sockaddr_ll, sll_addr);
2789 * You lose any data beyond the buffer you gave. If it worries a
2790 * user program they can ask the device for its MTU anyway.
2796 msg->msg_flags |= MSG_TRUNC;
2799 err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
2803 sock_recv_ts_and_drops(msg, sk, skb);
2806 memcpy(msg->msg_name, &PACKET_SKB_CB(skb)->sa,
2809 if (pkt_sk(sk)->auxdata) {
2810 struct tpacket_auxdata aux;
2812 aux.tp_status = TP_STATUS_USER;
2813 if (skb->ip_summed == CHECKSUM_PARTIAL)
2814 aux.tp_status |= TP_STATUS_CSUMNOTREADY;
2815 aux.tp_len = PACKET_SKB_CB(skb)->origlen;
2816 aux.tp_snaplen = skb->len;
2818 aux.tp_net = skb_network_offset(skb);
2819 if (vlan_tx_tag_present(skb)) {
2820 aux.tp_vlan_tci = vlan_tx_tag_get(skb);
2821 aux.tp_status |= TP_STATUS_VLAN_VALID;
2823 aux.tp_vlan_tci = 0;
2826 put_cmsg(msg, SOL_PACKET, PACKET_AUXDATA, sizeof(aux), &aux);
2830 * Free or return the buffer as appropriate. Again this
2831 * hides all the races and re-entrancy issues from us.
2833 err = vnet_hdr_len + ((flags&MSG_TRUNC) ? skb->len : copied);
2836 skb_free_datagram(sk, skb);
2841 static int packet_getname_spkt(struct socket *sock, struct sockaddr *uaddr,
2842 int *uaddr_len, int peer)
2844 struct net_device *dev;
2845 struct sock *sk = sock->sk;
2850 uaddr->sa_family = AF_PACKET;
2852 dev = dev_get_by_index_rcu(sock_net(sk), pkt_sk(sk)->ifindex);
2854 strncpy(uaddr->sa_data, dev->name, 14);
2856 memset(uaddr->sa_data, 0, 14);
2858 *uaddr_len = sizeof(*uaddr);
2863 static int packet_getname(struct socket *sock, struct sockaddr *uaddr,
2864 int *uaddr_len, int peer)
2866 struct net_device *dev;
2867 struct sock *sk = sock->sk;
2868 struct packet_sock *po = pkt_sk(sk);
2869 DECLARE_SOCKADDR(struct sockaddr_ll *, sll, uaddr);
2874 sll->sll_family = AF_PACKET;
2875 sll->sll_ifindex = po->ifindex;
2876 sll->sll_protocol = po->num;
2877 sll->sll_pkttype = 0;
2879 dev = dev_get_by_index_rcu(sock_net(sk), po->ifindex);
2881 sll->sll_hatype = dev->type;
2882 sll->sll_halen = dev->addr_len;
2883 memcpy(sll->sll_addr, dev->dev_addr, dev->addr_len);
2885 sll->sll_hatype = 0; /* Bad: we have no ARPHRD_UNSPEC */
2889 *uaddr_len = offsetof(struct sockaddr_ll, sll_addr) + sll->sll_halen;
2894 static int packet_dev_mc(struct net_device *dev, struct packet_mclist *i,
2898 case PACKET_MR_MULTICAST:
2899 if (i->alen != dev->addr_len)
2902 return dev_mc_add(dev, i->addr);
2904 return dev_mc_del(dev, i->addr);
2906 case PACKET_MR_PROMISC:
2907 return dev_set_promiscuity(dev, what);
2909 case PACKET_MR_ALLMULTI:
2910 return dev_set_allmulti(dev, what);
2912 case PACKET_MR_UNICAST:
2913 if (i->alen != dev->addr_len)
2916 return dev_uc_add(dev, i->addr);
2918 return dev_uc_del(dev, i->addr);
2926 static void packet_dev_mclist(struct net_device *dev, struct packet_mclist *i, int what)
2928 for ( ; i; i = i->next) {
2929 if (i->ifindex == dev->ifindex)
2930 packet_dev_mc(dev, i, what);
2934 static int packet_mc_add(struct sock *sk, struct packet_mreq_max *mreq)
2936 struct packet_sock *po = pkt_sk(sk);
2937 struct packet_mclist *ml, *i;
2938 struct net_device *dev;
2944 dev = __dev_get_by_index(sock_net(sk), mreq->mr_ifindex);
2949 if (mreq->mr_alen > dev->addr_len)
2953 i = kmalloc(sizeof(*i), GFP_KERNEL);
2958 for (ml = po->mclist; ml; ml = ml->next) {
2959 if (ml->ifindex == mreq->mr_ifindex &&
2960 ml->type == mreq->mr_type &&
2961 ml->alen == mreq->mr_alen &&
2962 memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
2964 /* Free the new element ... */
2970 i->type = mreq->mr_type;
2971 i->ifindex = mreq->mr_ifindex;
2972 i->alen = mreq->mr_alen;
2973 memcpy(i->addr, mreq->mr_address, i->alen);
2975 i->next = po->mclist;
2977 err = packet_dev_mc(dev, i, 1);
2979 po->mclist = i->next;
2988 static int packet_mc_drop(struct sock *sk, struct packet_mreq_max *mreq)
2990 struct packet_mclist *ml, **mlp;
2994 for (mlp = &pkt_sk(sk)->mclist; (ml = *mlp) != NULL; mlp = &ml->next) {
2995 if (ml->ifindex == mreq->mr_ifindex &&
2996 ml->type == mreq->mr_type &&
2997 ml->alen == mreq->mr_alen &&
2998 memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
2999 if (--ml->count == 0) {
3000 struct net_device *dev;
3002 dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
3004 packet_dev_mc(dev, ml, -1);
3012 return -EADDRNOTAVAIL;
3015 static void packet_flush_mclist(struct sock *sk)
3017 struct packet_sock *po = pkt_sk(sk);
3018 struct packet_mclist *ml;
3024 while ((ml = po->mclist) != NULL) {
3025 struct net_device *dev;
3027 po->mclist = ml->next;
3028 dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
3030 packet_dev_mc(dev, ml, -1);
3037 packet_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen)
3039 struct sock *sk = sock->sk;
3040 struct packet_sock *po = pkt_sk(sk);
3043 if (level != SOL_PACKET)
3044 return -ENOPROTOOPT;
3047 case PACKET_ADD_MEMBERSHIP:
3048 case PACKET_DROP_MEMBERSHIP:
3050 struct packet_mreq_max mreq;
3052 memset(&mreq, 0, sizeof(mreq));
3053 if (len < sizeof(struct packet_mreq))
3055 if (len > sizeof(mreq))
3057 if (copy_from_user(&mreq, optval, len))
3059 if (len < (mreq.mr_alen + offsetof(struct packet_mreq, mr_address)))
3061 if (optname == PACKET_ADD_MEMBERSHIP)
3062 ret = packet_mc_add(sk, &mreq);
3064 ret = packet_mc_drop(sk, &mreq);
3068 case PACKET_RX_RING:
3069 case PACKET_TX_RING:
3071 union tpacket_req_u req_u;
3074 switch (po->tp_version) {
3077 len = sizeof(req_u.req);
3081 len = sizeof(req_u.req3);
3086 if (pkt_sk(sk)->has_vnet_hdr)
3088 if (copy_from_user(&req_u.req, optval, len))
3090 return packet_set_ring(sk, &req_u, 0,
3091 optname == PACKET_TX_RING);
3093 case PACKET_COPY_THRESH:
3097 if (optlen != sizeof(val))
3099 if (copy_from_user(&val, optval, sizeof(val)))
3102 pkt_sk(sk)->copy_thresh = val;
3105 case PACKET_VERSION:
3109 if (optlen != sizeof(val))
3111 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3113 if (copy_from_user(&val, optval, sizeof(val)))
3119 po->tp_version = val;
3125 case PACKET_RESERVE:
3129 if (optlen != sizeof(val))
3131 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3133 if (copy_from_user(&val, optval, sizeof(val)))
3135 po->tp_reserve = val;
3142 if (optlen != sizeof(val))
3144 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3146 if (copy_from_user(&val, optval, sizeof(val)))
3148 po->tp_loss = !!val;
3151 case PACKET_AUXDATA:
3155 if (optlen < sizeof(val))
3157 if (copy_from_user(&val, optval, sizeof(val)))
3160 po->auxdata = !!val;
3163 case PACKET_ORIGDEV:
3167 if (optlen < sizeof(val))
3169 if (copy_from_user(&val, optval, sizeof(val)))
3172 po->origdev = !!val;
3175 case PACKET_VNET_HDR:
3179 if (sock->type != SOCK_RAW)
3181 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3183 if (optlen < sizeof(val))
3185 if (copy_from_user(&val, optval, sizeof(val)))
3188 po->has_vnet_hdr = !!val;
3191 case PACKET_TIMESTAMP:
3195 if (optlen != sizeof(val))
3197 if (copy_from_user(&val, optval, sizeof(val)))
3200 po->tp_tstamp = val;
3207 if (optlen != sizeof(val))
3209 if (copy_from_user(&val, optval, sizeof(val)))
3212 return fanout_add(sk, val & 0xffff, val >> 16);
3214 case PACKET_TX_HAS_OFF:
3218 if (optlen != sizeof(val))
3220 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3222 if (copy_from_user(&val, optval, sizeof(val)))
3224 po->tp_tx_has_off = !!val;
3228 return -ENOPROTOOPT;
3232 static int packet_getsockopt(struct socket *sock, int level, int optname,
3233 char __user *optval, int __user *optlen)
3236 int val, lv = sizeof(val);
3237 struct sock *sk = sock->sk;
3238 struct packet_sock *po = pkt_sk(sk);
3240 struct tpacket_stats st;
3241 union tpacket_stats_u st_u;
3243 if (level != SOL_PACKET)
3244 return -ENOPROTOOPT;
3246 if (get_user(len, optlen))
3253 case PACKET_STATISTICS:
3254 spin_lock_bh(&sk->sk_receive_queue.lock);
3255 if (po->tp_version == TPACKET_V3) {
3256 lv = sizeof(struct tpacket_stats_v3);
3257 memcpy(&st_u.stats3, &po->stats,
3258 sizeof(struct tpacket_stats));
3259 st_u.stats3.tp_freeze_q_cnt =
3260 po->stats_u.stats3.tp_freeze_q_cnt;
3261 st_u.stats3.tp_packets += po->stats.tp_drops;
3262 data = &st_u.stats3;
3264 lv = sizeof(struct tpacket_stats);
3266 st.tp_packets += st.tp_drops;
3269 memset(&po->stats, 0, sizeof(st));
3270 spin_unlock_bh(&sk->sk_receive_queue.lock);
3272 case PACKET_AUXDATA:
3275 case PACKET_ORIGDEV:
3278 case PACKET_VNET_HDR:
3279 val = po->has_vnet_hdr;
3281 case PACKET_VERSION:
3282 val = po->tp_version;
3285 if (len > sizeof(int))
3287 if (copy_from_user(&val, optval, len))
3291 val = sizeof(struct tpacket_hdr);
3294 val = sizeof(struct tpacket2_hdr);
3297 val = sizeof(struct tpacket3_hdr);
3303 case PACKET_RESERVE:
3304 val = po->tp_reserve;
3309 case PACKET_TIMESTAMP:
3310 val = po->tp_tstamp;
3314 ((u32)po->fanout->id |
3315 ((u32)po->fanout->type << 16) |
3316 ((u32)po->fanout->flags << 24)) :
3319 case PACKET_TX_HAS_OFF:
3320 val = po->tp_tx_has_off;
3323 return -ENOPROTOOPT;
3328 if (put_user(len, optlen))
3330 if (copy_to_user(optval, data, len))
3336 static int packet_notifier(struct notifier_block *this, unsigned long msg, void *data)
3339 struct net_device *dev = data;
3340 struct net *net = dev_net(dev);
3343 sk_for_each_rcu(sk, &net->packet.sklist) {
3344 struct packet_sock *po = pkt_sk(sk);
3347 case NETDEV_UNREGISTER:
3349 packet_dev_mclist(dev, po->mclist, -1);
3353 if (dev->ifindex == po->ifindex) {
3354 spin_lock(&po->bind_lock);
3356 __unregister_prot_hook(sk, false);
3357 sk->sk_err = ENETDOWN;
3358 if (!sock_flag(sk, SOCK_DEAD))
3359 sk->sk_error_report(sk);
3361 if (msg == NETDEV_UNREGISTER) {
3363 if (po->prot_hook.dev)
3364 dev_put(po->prot_hook.dev);
3365 po->prot_hook.dev = NULL;
3367 spin_unlock(&po->bind_lock);
3371 if (dev->ifindex == po->ifindex) {
3372 spin_lock(&po->bind_lock);
3374 register_prot_hook(sk);
3375 spin_unlock(&po->bind_lock);
3385 static int packet_ioctl(struct socket *sock, unsigned int cmd,
3388 struct sock *sk = sock->sk;
3393 int amount = sk_wmem_alloc_get(sk);
3395 return put_user(amount, (int __user *)arg);
3399 struct sk_buff *skb;
3402 spin_lock_bh(&sk->sk_receive_queue.lock);
3403 skb = skb_peek(&sk->sk_receive_queue);
3406 spin_unlock_bh(&sk->sk_receive_queue.lock);
3407 return put_user(amount, (int __user *)arg);
3410 return sock_get_timestamp(sk, (struct timeval __user *)arg);
3412 return sock_get_timestampns(sk, (struct timespec __user *)arg);
3422 case SIOCGIFBRDADDR:
3423 case SIOCSIFBRDADDR:
3424 case SIOCGIFNETMASK:
3425 case SIOCSIFNETMASK:
3426 case SIOCGIFDSTADDR:
3427 case SIOCSIFDSTADDR:
3429 return inet_dgram_ops.ioctl(sock, cmd, arg);
3433 return -ENOIOCTLCMD;
3438 static unsigned int packet_poll(struct file *file, struct socket *sock,
3441 struct sock *sk = sock->sk;
3442 struct packet_sock *po = pkt_sk(sk);
3443 unsigned int mask = datagram_poll(file, sock, wait);
3445 spin_lock_bh(&sk->sk_receive_queue.lock);
3446 if (po->rx_ring.pg_vec) {
3447 if (!packet_previous_rx_frame(po, &po->rx_ring,
3449 mask |= POLLIN | POLLRDNORM;
3451 spin_unlock_bh(&sk->sk_receive_queue.lock);
3452 spin_lock_bh(&sk->sk_write_queue.lock);
3453 if (po->tx_ring.pg_vec) {
3454 if (packet_current_frame(po, &po->tx_ring, TP_STATUS_AVAILABLE))
3455 mask |= POLLOUT | POLLWRNORM;
3457 spin_unlock_bh(&sk->sk_write_queue.lock);
3462 /* Dirty? Well, I still did not learn better way to account
3466 static void packet_mm_open(struct vm_area_struct *vma)
3468 struct file *file = vma->vm_file;
3469 struct socket *sock = file->private_data;
3470 struct sock *sk = sock->sk;
3473 atomic_inc(&pkt_sk(sk)->mapped);
3476 static void packet_mm_close(struct vm_area_struct *vma)
3478 struct file *file = vma->vm_file;
3479 struct socket *sock = file->private_data;
3480 struct sock *sk = sock->sk;
3483 atomic_dec(&pkt_sk(sk)->mapped);
3486 static const struct vm_operations_struct packet_mmap_ops = {
3487 .open = packet_mm_open,
3488 .close = packet_mm_close,
3491 static void free_pg_vec(struct pgv *pg_vec, unsigned int order,
3496 for (i = 0; i < len; i++) {
3497 if (likely(pg_vec[i].buffer)) {
3498 if (is_vmalloc_addr(pg_vec[i].buffer))
3499 vfree(pg_vec[i].buffer);
3501 free_pages((unsigned long)pg_vec[i].buffer,
3503 pg_vec[i].buffer = NULL;
3509 static char *alloc_one_pg_vec_page(unsigned long order)
3511 char *buffer = NULL;
3512 gfp_t gfp_flags = GFP_KERNEL | __GFP_COMP |
3513 __GFP_ZERO | __GFP_NOWARN | __GFP_NORETRY;
3515 buffer = (char *) __get_free_pages(gfp_flags, order);
3521 * __get_free_pages failed, fall back to vmalloc
3523 buffer = vzalloc((1 << order) * PAGE_SIZE);
3529 * vmalloc failed, lets dig into swap here
3531 gfp_flags &= ~__GFP_NORETRY;
3532 buffer = (char *)__get_free_pages(gfp_flags, order);
3537 * complete and utter failure
3542 static struct pgv *alloc_pg_vec(struct tpacket_req *req, int order)
3544 unsigned int block_nr = req->tp_block_nr;
3548 pg_vec = kcalloc(block_nr, sizeof(struct pgv), GFP_KERNEL);
3549 if (unlikely(!pg_vec))
3552 for (i = 0; i < block_nr; i++) {
3553 pg_vec[i].buffer = alloc_one_pg_vec_page(order);
3554 if (unlikely(!pg_vec[i].buffer))
3555 goto out_free_pgvec;
3562 free_pg_vec(pg_vec, order, block_nr);
3567 static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
3568 int closing, int tx_ring)
3570 struct pgv *pg_vec = NULL;
3571 struct packet_sock *po = pkt_sk(sk);
3572 int was_running, order = 0;
3573 struct packet_ring_buffer *rb;
3574 struct sk_buff_head *rb_queue;
3577 /* Added to avoid minimal code churn */
3578 struct tpacket_req *req = &req_u->req;
3580 /* Opening a Tx-ring is NOT supported in TPACKET_V3 */
3581 if (!closing && tx_ring && (po->tp_version > TPACKET_V2)) {
3582 WARN(1, "Tx-ring is not supported.\n");
3586 rb = tx_ring ? &po->tx_ring : &po->rx_ring;
3587 rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue;
3591 if (atomic_read(&po->mapped))
3593 if (atomic_read(&rb->pending))
3597 if (req->tp_block_nr) {
3598 /* Sanity tests and some calculations */
3600 if (unlikely(rb->pg_vec))
3603 switch (po->tp_version) {
3605 po->tp_hdrlen = TPACKET_HDRLEN;
3608 po->tp_hdrlen = TPACKET2_HDRLEN;
3611 po->tp_hdrlen = TPACKET3_HDRLEN;
3616 if (unlikely((int)req->tp_block_size <= 0))
3618 if (unlikely(req->tp_block_size & (PAGE_SIZE - 1)))
3620 if (unlikely(req->tp_frame_size < po->tp_hdrlen +
3623 if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1)))
3626 rb->frames_per_block = req->tp_block_size/req->tp_frame_size;
3627 if (unlikely(rb->frames_per_block <= 0))
3629 if (unlikely((rb->frames_per_block * req->tp_block_nr) !=
3634 order = get_order(req->tp_block_size);
3635 pg_vec = alloc_pg_vec(req, order);
3636 if (unlikely(!pg_vec))
3638 switch (po->tp_version) {
3640 /* Transmit path is not supported. We checked
3641 * it above but just being paranoid
3644 init_prb_bdqc(po, rb, pg_vec, req_u, tx_ring);
3653 if (unlikely(req->tp_frame_nr))
3659 /* Detach socket from network */
3660 spin_lock(&po->bind_lock);
3661 was_running = po->running;
3665 __unregister_prot_hook(sk, false);
3667 spin_unlock(&po->bind_lock);
3672 mutex_lock(&po->pg_vec_lock);
3673 if (closing || atomic_read(&po->mapped) == 0) {
3675 spin_lock_bh(&rb_queue->lock);
3676 swap(rb->pg_vec, pg_vec);
3677 rb->frame_max = (req->tp_frame_nr - 1);
3679 rb->frame_size = req->tp_frame_size;
3680 spin_unlock_bh(&rb_queue->lock);
3682 swap(rb->pg_vec_order, order);
3683 swap(rb->pg_vec_len, req->tp_block_nr);
3685 rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE;
3686 po->prot_hook.func = (po->rx_ring.pg_vec) ?
3687 tpacket_rcv : packet_rcv;
3688 skb_queue_purge(rb_queue);
3689 if (atomic_read(&po->mapped))
3690 pr_err("packet_mmap: vma is busy: %d\n",
3691 atomic_read(&po->mapped));
3693 mutex_unlock(&po->pg_vec_lock);
3695 spin_lock(&po->bind_lock);
3698 register_prot_hook(sk);
3700 spin_unlock(&po->bind_lock);
3701 if (closing && (po->tp_version > TPACKET_V2)) {
3702 /* Because we don't support block-based V3 on tx-ring */
3704 prb_shutdown_retire_blk_timer(po, tx_ring, rb_queue);
3709 free_pg_vec(pg_vec, order, req->tp_block_nr);
3714 static int packet_mmap(struct file *file, struct socket *sock,
3715 struct vm_area_struct *vma)
3717 struct sock *sk = sock->sk;
3718 struct packet_sock *po = pkt_sk(sk);
3719 unsigned long size, expected_size;
3720 struct packet_ring_buffer *rb;
3721 unsigned long start;
3728 mutex_lock(&po->pg_vec_lock);
3731 for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
3733 expected_size += rb->pg_vec_len
3739 if (expected_size == 0)
3742 size = vma->vm_end - vma->vm_start;
3743 if (size != expected_size)
3746 start = vma->vm_start;
3747 for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
3748 if (rb->pg_vec == NULL)
3751 for (i = 0; i < rb->pg_vec_len; i++) {
3753 void *kaddr = rb->pg_vec[i].buffer;
3756 for (pg_num = 0; pg_num < rb->pg_vec_pages; pg_num++) {
3757 page = pgv_to_page(kaddr);
3758 err = vm_insert_page(vma, start, page);
3767 atomic_inc(&po->mapped);
3768 vma->vm_ops = &packet_mmap_ops;
3772 mutex_unlock(&po->pg_vec_lock);
3776 static const struct proto_ops packet_ops_spkt = {
3777 .family = PF_PACKET,
3778 .owner = THIS_MODULE,
3779 .release = packet_release,
3780 .bind = packet_bind_spkt,
3781 .connect = sock_no_connect,
3782 .socketpair = sock_no_socketpair,
3783 .accept = sock_no_accept,
3784 .getname = packet_getname_spkt,
3785 .poll = datagram_poll,
3786 .ioctl = packet_ioctl,
3787 .listen = sock_no_listen,
3788 .shutdown = sock_no_shutdown,
3789 .setsockopt = sock_no_setsockopt,
3790 .getsockopt = sock_no_getsockopt,
3791 .sendmsg = packet_sendmsg_spkt,
3792 .recvmsg = packet_recvmsg,
3793 .mmap = sock_no_mmap,
3794 .sendpage = sock_no_sendpage,
3797 static const struct proto_ops packet_ops = {
3798 .family = PF_PACKET,
3799 .owner = THIS_MODULE,
3800 .release = packet_release,
3801 .bind = packet_bind,
3802 .connect = sock_no_connect,
3803 .socketpair = sock_no_socketpair,
3804 .accept = sock_no_accept,
3805 .getname = packet_getname,
3806 .poll = packet_poll,
3807 .ioctl = packet_ioctl,
3808 .listen = sock_no_listen,
3809 .shutdown = sock_no_shutdown,
3810 .setsockopt = packet_setsockopt,
3811 .getsockopt = packet_getsockopt,
3812 .sendmsg = packet_sendmsg,
3813 .recvmsg = packet_recvmsg,
3814 .mmap = packet_mmap,
3815 .sendpage = sock_no_sendpage,
3818 static const struct net_proto_family packet_family_ops = {
3819 .family = PF_PACKET,
3820 .create = packet_create,
3821 .owner = THIS_MODULE,
3824 static struct notifier_block packet_netdev_notifier = {
3825 .notifier_call = packet_notifier,
3828 #ifdef CONFIG_PROC_FS
3830 static void *packet_seq_start(struct seq_file *seq, loff_t *pos)
3833 struct net *net = seq_file_net(seq);
3836 return seq_hlist_start_head_rcu(&net->packet.sklist, *pos);
3839 static void *packet_seq_next(struct seq_file *seq, void *v, loff_t *pos)
3841 struct net *net = seq_file_net(seq);
3842 return seq_hlist_next_rcu(v, &net->packet.sklist, pos);
3845 static void packet_seq_stop(struct seq_file *seq, void *v)
3851 static int packet_seq_show(struct seq_file *seq, void *v)
3853 if (v == SEQ_START_TOKEN)
3854 seq_puts(seq, "sk RefCnt Type Proto Iface R Rmem User Inode\n");
3856 struct sock *s = sk_entry(v);
3857 const struct packet_sock *po = pkt_sk(s);
3860 "%pK %-6d %-4d %04x %-5d %1d %-6u %-6u %-6lu\n",
3862 atomic_read(&s->sk_refcnt),
3867 atomic_read(&s->sk_rmem_alloc),
3868 from_kuid_munged(seq_user_ns(seq), sock_i_uid(s)),
3875 static const struct seq_operations packet_seq_ops = {
3876 .start = packet_seq_start,
3877 .next = packet_seq_next,
3878 .stop = packet_seq_stop,
3879 .show = packet_seq_show,
3882 static int packet_seq_open(struct inode *inode, struct file *file)
3884 return seq_open_net(inode, file, &packet_seq_ops,
3885 sizeof(struct seq_net_private));
3888 static const struct file_operations packet_seq_fops = {
3889 .owner = THIS_MODULE,
3890 .open = packet_seq_open,
3892 .llseek = seq_lseek,
3893 .release = seq_release_net,
3898 static int __net_init packet_net_init(struct net *net)
3900 mutex_init(&net->packet.sklist_lock);
3901 INIT_HLIST_HEAD(&net->packet.sklist);
3903 if (!proc_create("packet", 0, net->proc_net, &packet_seq_fops))
3909 static void __net_exit packet_net_exit(struct net *net)
3911 remove_proc_entry("packet", net->proc_net);
3914 static struct pernet_operations packet_net_ops = {
3915 .init = packet_net_init,
3916 .exit = packet_net_exit,
3920 static void __exit packet_exit(void)
3922 unregister_netdevice_notifier(&packet_netdev_notifier);
3923 unregister_pernet_subsys(&packet_net_ops);
3924 sock_unregister(PF_PACKET);
3925 proto_unregister(&packet_proto);
3928 static int __init packet_init(void)
3930 int rc = proto_register(&packet_proto, 0);
3935 sock_register(&packet_family_ops);
3936 register_pernet_subsys(&packet_net_ops);
3937 register_netdevice_notifier(&packet_netdev_notifier);
3942 module_init(packet_init);
3943 module_exit(packet_exit);
3944 MODULE_LICENSE("GPL");
3945 MODULE_ALIAS_NETPROTO(PF_PACKET);