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