]> git.karo-electronics.de Git - linux-beck.git/blob - net/packet/af_packet.c
packet: fix races in fanout_add()
[linux-beck.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 #include <linux/bpf.h>
96 #include <net/compat.h>
97
98 #include "internal.h"
99
100 /*
101    Assumptions:
102    - if device has no dev->hard_header routine, it adds and removes ll header
103      inside itself. In this case ll header is invisible outside of device,
104      but higher levels still should reserve dev->hard_header_len.
105      Some devices are enough clever to reallocate skb, when header
106      will not fit to reserved space (tunnel), another ones are silly
107      (PPP).
108    - packet socket receives packets with pulled ll header,
109      so that SOCK_RAW should push it back.
110
111 On receive:
112 -----------
113
114 Incoming, dev->hard_header!=NULL
115    mac_header -> ll header
116    data       -> data
117
118 Outgoing, dev->hard_header!=NULL
119    mac_header -> ll header
120    data       -> ll header
121
122 Incoming, dev->hard_header==NULL
123    mac_header -> UNKNOWN position. It is very likely, that it points to ll
124                  header.  PPP makes it, that is wrong, because introduce
125                  assymetry between rx and tx paths.
126    data       -> data
127
128 Outgoing, dev->hard_header==NULL
129    mac_header -> data. ll header is still not built!
130    data       -> data
131
132 Resume
133   If dev->hard_header==NULL we are unlikely to restore sensible ll header.
134
135
136 On transmit:
137 ------------
138
139 dev->hard_header != NULL
140    mac_header -> ll header
141    data       -> ll header
142
143 dev->hard_header == NULL (ll header is added by device, we cannot control it)
144    mac_header -> data
145    data       -> data
146
147    We should set nh.raw on output to correct posistion,
148    packet classifier depends on it.
149  */
150
151 /* Private packet socket structures. */
152
153 /* identical to struct packet_mreq except it has
154  * a longer address field.
155  */
156 struct packet_mreq_max {
157         int             mr_ifindex;
158         unsigned short  mr_type;
159         unsigned short  mr_alen;
160         unsigned char   mr_address[MAX_ADDR_LEN];
161 };
162
163 union tpacket_uhdr {
164         struct tpacket_hdr  *h1;
165         struct tpacket2_hdr *h2;
166         struct tpacket3_hdr *h3;
167         void *raw;
168 };
169
170 static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
171                 int closing, int tx_ring);
172
173 #define V3_ALIGNMENT    (8)
174
175 #define BLK_HDR_LEN     (ALIGN(sizeof(struct tpacket_block_desc), V3_ALIGNMENT))
176
177 #define BLK_PLUS_PRIV(sz_of_priv) \
178         (BLK_HDR_LEN + ALIGN((sz_of_priv), V3_ALIGNMENT))
179
180 #define PGV_FROM_VMALLOC 1
181
182 #define BLOCK_STATUS(x) ((x)->hdr.bh1.block_status)
183 #define BLOCK_NUM_PKTS(x)       ((x)->hdr.bh1.num_pkts)
184 #define BLOCK_O2FP(x)           ((x)->hdr.bh1.offset_to_first_pkt)
185 #define BLOCK_LEN(x)            ((x)->hdr.bh1.blk_len)
186 #define BLOCK_SNUM(x)           ((x)->hdr.bh1.seq_num)
187 #define BLOCK_O2PRIV(x) ((x)->offset_to_priv)
188 #define BLOCK_PRIV(x)           ((void *)((char *)(x) + BLOCK_O2PRIV(x)))
189
190 struct packet_sock;
191 static int tpacket_snd(struct packet_sock *po, struct msghdr *msg);
192 static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
193                        struct packet_type *pt, struct net_device *orig_dev);
194
195 static void *packet_previous_frame(struct packet_sock *po,
196                 struct packet_ring_buffer *rb,
197                 int status);
198 static void packet_increment_head(struct packet_ring_buffer *buff);
199 static int prb_curr_blk_in_use(struct tpacket_kbdq_core *,
200                         struct tpacket_block_desc *);
201 static void *prb_dispatch_next_block(struct tpacket_kbdq_core *,
202                         struct packet_sock *);
203 static void prb_retire_current_block(struct tpacket_kbdq_core *,
204                 struct packet_sock *, unsigned int status);
205 static int prb_queue_frozen(struct tpacket_kbdq_core *);
206 static void prb_open_block(struct tpacket_kbdq_core *,
207                 struct tpacket_block_desc *);
208 static void prb_retire_rx_blk_timer_expired(unsigned long);
209 static void _prb_refresh_rx_retire_blk_timer(struct tpacket_kbdq_core *);
210 static void prb_init_blk_timer(struct packet_sock *,
211                 struct tpacket_kbdq_core *,
212                 void (*func) (unsigned long));
213 static void prb_fill_rxhash(struct tpacket_kbdq_core *, struct tpacket3_hdr *);
214 static void prb_clear_rxhash(struct tpacket_kbdq_core *,
215                 struct tpacket3_hdr *);
216 static void prb_fill_vlan_info(struct tpacket_kbdq_core *,
217                 struct tpacket3_hdr *);
218 static void packet_flush_mclist(struct sock *sk);
219
220 struct packet_skb_cb {
221         union {
222                 struct sockaddr_pkt pkt;
223                 union {
224                         /* Trick: alias skb original length with
225                          * ll.sll_family and ll.protocol in order
226                          * to save room.
227                          */
228                         unsigned int origlen;
229                         struct sockaddr_ll ll;
230                 };
231         } sa;
232 };
233
234 #define vio_le() virtio_legacy_is_little_endian()
235
236 #define PACKET_SKB_CB(__skb)    ((struct packet_skb_cb *)((__skb)->cb))
237
238 #define GET_PBDQC_FROM_RB(x)    ((struct tpacket_kbdq_core *)(&(x)->prb_bdqc))
239 #define GET_PBLOCK_DESC(x, bid) \
240         ((struct tpacket_block_desc *)((x)->pkbdq[(bid)].buffer))
241 #define GET_CURR_PBLOCK_DESC_FROM_CORE(x)       \
242         ((struct tpacket_block_desc *)((x)->pkbdq[(x)->kactive_blk_num].buffer))
243 #define GET_NEXT_PRB_BLK_NUM(x) \
244         (((x)->kactive_blk_num < ((x)->knum_blocks-1)) ? \
245         ((x)->kactive_blk_num+1) : 0)
246
247 static void __fanout_unlink(struct sock *sk, struct packet_sock *po);
248 static void __fanout_link(struct sock *sk, struct packet_sock *po);
249
250 static int packet_direct_xmit(struct sk_buff *skb)
251 {
252         struct net_device *dev = skb->dev;
253         struct sk_buff *orig_skb = skb;
254         struct netdev_queue *txq;
255         int ret = NETDEV_TX_BUSY;
256
257         if (unlikely(!netif_running(dev) ||
258                      !netif_carrier_ok(dev)))
259                 goto drop;
260
261         skb = validate_xmit_skb_list(skb, dev);
262         if (skb != orig_skb)
263                 goto drop;
264
265         txq = skb_get_tx_queue(dev, skb);
266
267         local_bh_disable();
268
269         HARD_TX_LOCK(dev, txq, smp_processor_id());
270         if (!netif_xmit_frozen_or_drv_stopped(txq))
271                 ret = netdev_start_xmit(skb, dev, txq, false);
272         HARD_TX_UNLOCK(dev, txq);
273
274         local_bh_enable();
275
276         if (!dev_xmit_complete(ret))
277                 kfree_skb(skb);
278
279         return ret;
280 drop:
281         atomic_long_inc(&dev->tx_dropped);
282         kfree_skb_list(skb);
283         return NET_XMIT_DROP;
284 }
285
286 static struct net_device *packet_cached_dev_get(struct packet_sock *po)
287 {
288         struct net_device *dev;
289
290         rcu_read_lock();
291         dev = rcu_dereference(po->cached_dev);
292         if (likely(dev))
293                 dev_hold(dev);
294         rcu_read_unlock();
295
296         return dev;
297 }
298
299 static void packet_cached_dev_assign(struct packet_sock *po,
300                                      struct net_device *dev)
301 {
302         rcu_assign_pointer(po->cached_dev, dev);
303 }
304
305 static void packet_cached_dev_reset(struct packet_sock *po)
306 {
307         RCU_INIT_POINTER(po->cached_dev, NULL);
308 }
309
310 static bool packet_use_direct_xmit(const struct packet_sock *po)
311 {
312         return po->xmit == packet_direct_xmit;
313 }
314
315 static u16 __packet_pick_tx_queue(struct net_device *dev, struct sk_buff *skb)
316 {
317         return (u16) raw_smp_processor_id() % dev->real_num_tx_queues;
318 }
319
320 static void packet_pick_tx_queue(struct net_device *dev, struct sk_buff *skb)
321 {
322         const struct net_device_ops *ops = dev->netdev_ops;
323         u16 queue_index;
324
325         if (ops->ndo_select_queue) {
326                 queue_index = ops->ndo_select_queue(dev, skb, NULL,
327                                                     __packet_pick_tx_queue);
328                 queue_index = netdev_cap_txqueue(dev, queue_index);
329         } else {
330                 queue_index = __packet_pick_tx_queue(dev, skb);
331         }
332
333         skb_set_queue_mapping(skb, queue_index);
334 }
335
336 /* register_prot_hook must be invoked with the po->bind_lock held,
337  * or from a context in which asynchronous accesses to the packet
338  * socket is not possible (packet_create()).
339  */
340 static void register_prot_hook(struct sock *sk)
341 {
342         struct packet_sock *po = pkt_sk(sk);
343
344         if (!po->running) {
345                 if (po->fanout)
346                         __fanout_link(sk, po);
347                 else
348                         dev_add_pack(&po->prot_hook);
349
350                 sock_hold(sk);
351                 po->running = 1;
352         }
353 }
354
355 /* {,__}unregister_prot_hook() must be invoked with the po->bind_lock
356  * held.   If the sync parameter is true, we will temporarily drop
357  * the po->bind_lock and do a synchronize_net to make sure no
358  * asynchronous packet processing paths still refer to the elements
359  * of po->prot_hook.  If the sync parameter is false, it is the
360  * callers responsibility to take care of this.
361  */
362 static void __unregister_prot_hook(struct sock *sk, bool sync)
363 {
364         struct packet_sock *po = pkt_sk(sk);
365
366         po->running = 0;
367
368         if (po->fanout)
369                 __fanout_unlink(sk, po);
370         else
371                 __dev_remove_pack(&po->prot_hook);
372
373         __sock_put(sk);
374
375         if (sync) {
376                 spin_unlock(&po->bind_lock);
377                 synchronize_net();
378                 spin_lock(&po->bind_lock);
379         }
380 }
381
382 static void unregister_prot_hook(struct sock *sk, bool sync)
383 {
384         struct packet_sock *po = pkt_sk(sk);
385
386         if (po->running)
387                 __unregister_prot_hook(sk, sync);
388 }
389
390 static inline struct page * __pure pgv_to_page(void *addr)
391 {
392         if (is_vmalloc_addr(addr))
393                 return vmalloc_to_page(addr);
394         return virt_to_page(addr);
395 }
396
397 static void __packet_set_status(struct packet_sock *po, void *frame, int status)
398 {
399         union tpacket_uhdr h;
400
401         h.raw = frame;
402         switch (po->tp_version) {
403         case TPACKET_V1:
404                 h.h1->tp_status = status;
405                 flush_dcache_page(pgv_to_page(&h.h1->tp_status));
406                 break;
407         case TPACKET_V2:
408                 h.h2->tp_status = status;
409                 flush_dcache_page(pgv_to_page(&h.h2->tp_status));
410                 break;
411         case TPACKET_V3:
412         default:
413                 WARN(1, "TPACKET version not supported.\n");
414                 BUG();
415         }
416
417         smp_wmb();
418 }
419
420 static int __packet_get_status(struct packet_sock *po, void *frame)
421 {
422         union tpacket_uhdr h;
423
424         smp_rmb();
425
426         h.raw = frame;
427         switch (po->tp_version) {
428         case TPACKET_V1:
429                 flush_dcache_page(pgv_to_page(&h.h1->tp_status));
430                 return h.h1->tp_status;
431         case TPACKET_V2:
432                 flush_dcache_page(pgv_to_page(&h.h2->tp_status));
433                 return h.h2->tp_status;
434         case TPACKET_V3:
435         default:
436                 WARN(1, "TPACKET version not supported.\n");
437                 BUG();
438                 return 0;
439         }
440 }
441
442 static __u32 tpacket_get_timestamp(struct sk_buff *skb, struct timespec *ts,
443                                    unsigned int flags)
444 {
445         struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);
446
447         if (shhwtstamps &&
448             (flags & SOF_TIMESTAMPING_RAW_HARDWARE) &&
449             ktime_to_timespec_cond(shhwtstamps->hwtstamp, ts))
450                 return TP_STATUS_TS_RAW_HARDWARE;
451
452         if (ktime_to_timespec_cond(skb->tstamp, ts))
453                 return TP_STATUS_TS_SOFTWARE;
454
455         return 0;
456 }
457
458 static __u32 __packet_set_timestamp(struct packet_sock *po, void *frame,
459                                     struct sk_buff *skb)
460 {
461         union tpacket_uhdr h;
462         struct timespec ts;
463         __u32 ts_status;
464
465         if (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp)))
466                 return 0;
467
468         h.raw = frame;
469         switch (po->tp_version) {
470         case TPACKET_V1:
471                 h.h1->tp_sec = ts.tv_sec;
472                 h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
473                 break;
474         case TPACKET_V2:
475                 h.h2->tp_sec = ts.tv_sec;
476                 h.h2->tp_nsec = ts.tv_nsec;
477                 break;
478         case TPACKET_V3:
479         default:
480                 WARN(1, "TPACKET version not supported.\n");
481                 BUG();
482         }
483
484         /* one flush is safe, as both fields always lie on the same cacheline */
485         flush_dcache_page(pgv_to_page(&h.h1->tp_sec));
486         smp_wmb();
487
488         return ts_status;
489 }
490
491 static void *packet_lookup_frame(struct packet_sock *po,
492                 struct packet_ring_buffer *rb,
493                 unsigned int position,
494                 int status)
495 {
496         unsigned int pg_vec_pos, frame_offset;
497         union tpacket_uhdr h;
498
499         pg_vec_pos = position / rb->frames_per_block;
500         frame_offset = position % rb->frames_per_block;
501
502         h.raw = rb->pg_vec[pg_vec_pos].buffer +
503                 (frame_offset * rb->frame_size);
504
505         if (status != __packet_get_status(po, h.raw))
506                 return NULL;
507
508         return h.raw;
509 }
510
511 static void *packet_current_frame(struct packet_sock *po,
512                 struct packet_ring_buffer *rb,
513                 int status)
514 {
515         return packet_lookup_frame(po, rb, rb->head, status);
516 }
517
518 static void prb_del_retire_blk_timer(struct tpacket_kbdq_core *pkc)
519 {
520         del_timer_sync(&pkc->retire_blk_timer);
521 }
522
523 static void prb_shutdown_retire_blk_timer(struct packet_sock *po,
524                 struct sk_buff_head *rb_queue)
525 {
526         struct tpacket_kbdq_core *pkc;
527
528         pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
529
530         spin_lock_bh(&rb_queue->lock);
531         pkc->delete_blk_timer = 1;
532         spin_unlock_bh(&rb_queue->lock);
533
534         prb_del_retire_blk_timer(pkc);
535 }
536
537 static void prb_init_blk_timer(struct packet_sock *po,
538                 struct tpacket_kbdq_core *pkc,
539                 void (*func) (unsigned long))
540 {
541         init_timer(&pkc->retire_blk_timer);
542         pkc->retire_blk_timer.data = (long)po;
543         pkc->retire_blk_timer.function = func;
544         pkc->retire_blk_timer.expires = jiffies;
545 }
546
547 static void prb_setup_retire_blk_timer(struct packet_sock *po)
548 {
549         struct tpacket_kbdq_core *pkc;
550
551         pkc = GET_PBDQC_FROM_RB(&po->rx_ring);
552         prb_init_blk_timer(po, pkc, prb_retire_rx_blk_timer_expired);
553 }
554
555 static int prb_calc_retire_blk_tmo(struct packet_sock *po,
556                                 int blk_size_in_bytes)
557 {
558         struct net_device *dev;
559         unsigned int mbits = 0, msec = 0, div = 0, tmo = 0;
560         struct ethtool_link_ksettings ecmd;
561         int err;
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_link_ksettings(dev, &ecmd);
570         rtnl_unlock();
571         if (!err) {
572                 /*
573                  * If the link speed is so slow you don't really
574                  * need to worry about perf anyways
575                  */
576                 if (ecmd.base.speed < SPEED_1000 ||
577                     ecmd.base.speed == SPEED_UNKNOWN) {
578                         return DEFAULT_PRB_RETIRE_TOV;
579                 } else {
580                         msec = 1;
581                         div = ecmd.base.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 bool fanout_flow_is_huge(struct packet_sock *po, struct sk_buff *skb)
1326 {
1327         u32 rxhash;
1328         int i, count = 0;
1329
1330         rxhash = skb_get_hash(skb);
1331         for (i = 0; i < ROLLOVER_HLEN; i++)
1332                 if (po->rollover->history[i] == rxhash)
1333                         count++;
1334
1335         po->rollover->history[prandom_u32() % ROLLOVER_HLEN] = rxhash;
1336         return count > (ROLLOVER_HLEN >> 1);
1337 }
1338
1339 static unsigned int fanout_demux_hash(struct packet_fanout *f,
1340                                       struct sk_buff *skb,
1341                                       unsigned int num)
1342 {
1343         return reciprocal_scale(__skb_get_hash_symmetric(skb), num);
1344 }
1345
1346 static unsigned int fanout_demux_lb(struct packet_fanout *f,
1347                                     struct sk_buff *skb,
1348                                     unsigned int num)
1349 {
1350         unsigned int val = atomic_inc_return(&f->rr_cur);
1351
1352         return val % num;
1353 }
1354
1355 static unsigned int fanout_demux_cpu(struct packet_fanout *f,
1356                                      struct sk_buff *skb,
1357                                      unsigned int num)
1358 {
1359         return smp_processor_id() % num;
1360 }
1361
1362 static unsigned int fanout_demux_rnd(struct packet_fanout *f,
1363                                      struct sk_buff *skb,
1364                                      unsigned int num)
1365 {
1366         return prandom_u32_max(num);
1367 }
1368
1369 static unsigned int fanout_demux_rollover(struct packet_fanout *f,
1370                                           struct sk_buff *skb,
1371                                           unsigned int idx, bool try_self,
1372                                           unsigned int num)
1373 {
1374         struct packet_sock *po, *po_next, *po_skip = NULL;
1375         unsigned int i, j, room = ROOM_NONE;
1376
1377         po = pkt_sk(f->arr[idx]);
1378
1379         if (try_self) {
1380                 room = packet_rcv_has_room(po, skb);
1381                 if (room == ROOM_NORMAL ||
1382                     (room == ROOM_LOW && !fanout_flow_is_huge(po, skb)))
1383                         return idx;
1384                 po_skip = po;
1385         }
1386
1387         i = j = min_t(int, po->rollover->sock, num - 1);
1388         do {
1389                 po_next = pkt_sk(f->arr[i]);
1390                 if (po_next != po_skip && !po_next->pressure &&
1391                     packet_rcv_has_room(po_next, skb) == ROOM_NORMAL) {
1392                         if (i != j)
1393                                 po->rollover->sock = i;
1394                         atomic_long_inc(&po->rollover->num);
1395                         if (room == ROOM_LOW)
1396                                 atomic_long_inc(&po->rollover->num_huge);
1397                         return i;
1398                 }
1399
1400                 if (++i == num)
1401                         i = 0;
1402         } while (i != j);
1403
1404         atomic_long_inc(&po->rollover->num_failed);
1405         return idx;
1406 }
1407
1408 static unsigned int fanout_demux_qm(struct packet_fanout *f,
1409                                     struct sk_buff *skb,
1410                                     unsigned int num)
1411 {
1412         return skb_get_queue_mapping(skb) % num;
1413 }
1414
1415 static unsigned int fanout_demux_bpf(struct packet_fanout *f,
1416                                      struct sk_buff *skb,
1417                                      unsigned int num)
1418 {
1419         struct bpf_prog *prog;
1420         unsigned int ret = 0;
1421
1422         rcu_read_lock();
1423         prog = rcu_dereference(f->bpf_prog);
1424         if (prog)
1425                 ret = bpf_prog_run_clear_cb(prog, skb) % num;
1426         rcu_read_unlock();
1427
1428         return ret;
1429 }
1430
1431 static bool fanout_has_flag(struct packet_fanout *f, u16 flag)
1432 {
1433         return f->flags & (flag >> 8);
1434 }
1435
1436 static int packet_rcv_fanout(struct sk_buff *skb, struct net_device *dev,
1437                              struct packet_type *pt, struct net_device *orig_dev)
1438 {
1439         struct packet_fanout *f = pt->af_packet_priv;
1440         unsigned int num = READ_ONCE(f->num_members);
1441         struct net *net = read_pnet(&f->net);
1442         struct packet_sock *po;
1443         unsigned int idx;
1444
1445         if (!net_eq(dev_net(dev), net) || !num) {
1446                 kfree_skb(skb);
1447                 return 0;
1448         }
1449
1450         if (fanout_has_flag(f, PACKET_FANOUT_FLAG_DEFRAG)) {
1451                 skb = ip_check_defrag(net, skb, IP_DEFRAG_AF_PACKET);
1452                 if (!skb)
1453                         return 0;
1454         }
1455         switch (f->type) {
1456         case PACKET_FANOUT_HASH:
1457         default:
1458                 idx = fanout_demux_hash(f, skb, num);
1459                 break;
1460         case PACKET_FANOUT_LB:
1461                 idx = fanout_demux_lb(f, skb, num);
1462                 break;
1463         case PACKET_FANOUT_CPU:
1464                 idx = fanout_demux_cpu(f, skb, num);
1465                 break;
1466         case PACKET_FANOUT_RND:
1467                 idx = fanout_demux_rnd(f, skb, num);
1468                 break;
1469         case PACKET_FANOUT_QM:
1470                 idx = fanout_demux_qm(f, skb, num);
1471                 break;
1472         case PACKET_FANOUT_ROLLOVER:
1473                 idx = fanout_demux_rollover(f, skb, 0, false, num);
1474                 break;
1475         case PACKET_FANOUT_CBPF:
1476         case PACKET_FANOUT_EBPF:
1477                 idx = fanout_demux_bpf(f, skb, num);
1478                 break;
1479         }
1480
1481         if (fanout_has_flag(f, PACKET_FANOUT_FLAG_ROLLOVER))
1482                 idx = fanout_demux_rollover(f, skb, idx, true, num);
1483
1484         po = pkt_sk(f->arr[idx]);
1485         return po->prot_hook.func(skb, dev, &po->prot_hook, orig_dev);
1486 }
1487
1488 DEFINE_MUTEX(fanout_mutex);
1489 EXPORT_SYMBOL_GPL(fanout_mutex);
1490 static LIST_HEAD(fanout_list);
1491
1492 static void __fanout_link(struct sock *sk, struct packet_sock *po)
1493 {
1494         struct packet_fanout *f = po->fanout;
1495
1496         spin_lock(&f->lock);
1497         f->arr[f->num_members] = sk;
1498         smp_wmb();
1499         f->num_members++;
1500         spin_unlock(&f->lock);
1501 }
1502
1503 static void __fanout_unlink(struct sock *sk, struct packet_sock *po)
1504 {
1505         struct packet_fanout *f = po->fanout;
1506         int i;
1507
1508         spin_lock(&f->lock);
1509         for (i = 0; i < f->num_members; i++) {
1510                 if (f->arr[i] == sk)
1511                         break;
1512         }
1513         BUG_ON(i >= f->num_members);
1514         f->arr[i] = f->arr[f->num_members - 1];
1515         f->num_members--;
1516         spin_unlock(&f->lock);
1517 }
1518
1519 static bool match_fanout_group(struct packet_type *ptype, struct sock *sk)
1520 {
1521         if (sk->sk_family != PF_PACKET)
1522                 return false;
1523
1524         return ptype->af_packet_priv == pkt_sk(sk)->fanout;
1525 }
1526
1527 static void fanout_init_data(struct packet_fanout *f)
1528 {
1529         switch (f->type) {
1530         case PACKET_FANOUT_LB:
1531                 atomic_set(&f->rr_cur, 0);
1532                 break;
1533         case PACKET_FANOUT_CBPF:
1534         case PACKET_FANOUT_EBPF:
1535                 RCU_INIT_POINTER(f->bpf_prog, NULL);
1536                 break;
1537         }
1538 }
1539
1540 static void __fanout_set_data_bpf(struct packet_fanout *f, struct bpf_prog *new)
1541 {
1542         struct bpf_prog *old;
1543
1544         spin_lock(&f->lock);
1545         old = rcu_dereference_protected(f->bpf_prog, lockdep_is_held(&f->lock));
1546         rcu_assign_pointer(f->bpf_prog, new);
1547         spin_unlock(&f->lock);
1548
1549         if (old) {
1550                 synchronize_net();
1551                 bpf_prog_destroy(old);
1552         }
1553 }
1554
1555 static int fanout_set_data_cbpf(struct packet_sock *po, char __user *data,
1556                                 unsigned int len)
1557 {
1558         struct bpf_prog *new;
1559         struct sock_fprog fprog;
1560         int ret;
1561
1562         if (sock_flag(&po->sk, SOCK_FILTER_LOCKED))
1563                 return -EPERM;
1564         if (len != sizeof(fprog))
1565                 return -EINVAL;
1566         if (copy_from_user(&fprog, data, len))
1567                 return -EFAULT;
1568
1569         ret = bpf_prog_create_from_user(&new, &fprog, NULL, false);
1570         if (ret)
1571                 return ret;
1572
1573         __fanout_set_data_bpf(po->fanout, new);
1574         return 0;
1575 }
1576
1577 static int fanout_set_data_ebpf(struct packet_sock *po, char __user *data,
1578                                 unsigned int len)
1579 {
1580         struct bpf_prog *new;
1581         u32 fd;
1582
1583         if (sock_flag(&po->sk, SOCK_FILTER_LOCKED))
1584                 return -EPERM;
1585         if (len != sizeof(fd))
1586                 return -EINVAL;
1587         if (copy_from_user(&fd, data, len))
1588                 return -EFAULT;
1589
1590         new = bpf_prog_get_type(fd, BPF_PROG_TYPE_SOCKET_FILTER);
1591         if (IS_ERR(new))
1592                 return PTR_ERR(new);
1593
1594         __fanout_set_data_bpf(po->fanout, new);
1595         return 0;
1596 }
1597
1598 static int fanout_set_data(struct packet_sock *po, char __user *data,
1599                            unsigned int len)
1600 {
1601         switch (po->fanout->type) {
1602         case PACKET_FANOUT_CBPF:
1603                 return fanout_set_data_cbpf(po, data, len);
1604         case PACKET_FANOUT_EBPF:
1605                 return fanout_set_data_ebpf(po, data, len);
1606         default:
1607                 return -EINVAL;
1608         };
1609 }
1610
1611 static void fanout_release_data(struct packet_fanout *f)
1612 {
1613         switch (f->type) {
1614         case PACKET_FANOUT_CBPF:
1615         case PACKET_FANOUT_EBPF:
1616                 __fanout_set_data_bpf(f, NULL);
1617         };
1618 }
1619
1620 static int fanout_add(struct sock *sk, u16 id, u16 type_flags)
1621 {
1622         struct packet_rollover *rollover = NULL;
1623         struct packet_sock *po = pkt_sk(sk);
1624         struct packet_fanout *f, *match;
1625         u8 type = type_flags & 0xff;
1626         u8 flags = type_flags >> 8;
1627         int err;
1628
1629         switch (type) {
1630         case PACKET_FANOUT_ROLLOVER:
1631                 if (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)
1632                         return -EINVAL;
1633         case PACKET_FANOUT_HASH:
1634         case PACKET_FANOUT_LB:
1635         case PACKET_FANOUT_CPU:
1636         case PACKET_FANOUT_RND:
1637         case PACKET_FANOUT_QM:
1638         case PACKET_FANOUT_CBPF:
1639         case PACKET_FANOUT_EBPF:
1640                 break;
1641         default:
1642                 return -EINVAL;
1643         }
1644
1645         mutex_lock(&fanout_mutex);
1646
1647         err = -EINVAL;
1648         if (!po->running)
1649                 goto out;
1650
1651         err = -EALREADY;
1652         if (po->fanout)
1653                 goto out;
1654
1655         if (type == PACKET_FANOUT_ROLLOVER ||
1656             (type_flags & PACKET_FANOUT_FLAG_ROLLOVER)) {
1657                 err = -ENOMEM;
1658                 rollover = kzalloc(sizeof(*rollover), GFP_KERNEL);
1659                 if (!rollover)
1660                         goto out;
1661                 atomic_long_set(&rollover->num, 0);
1662                 atomic_long_set(&rollover->num_huge, 0);
1663                 atomic_long_set(&rollover->num_failed, 0);
1664                 po->rollover = rollover;
1665         }
1666
1667         match = NULL;
1668         list_for_each_entry(f, &fanout_list, list) {
1669                 if (f->id == id &&
1670                     read_pnet(&f->net) == sock_net(sk)) {
1671                         match = f;
1672                         break;
1673                 }
1674         }
1675         err = -EINVAL;
1676         if (match && match->flags != flags)
1677                 goto out;
1678         if (!match) {
1679                 err = -ENOMEM;
1680                 match = kzalloc(sizeof(*match), GFP_KERNEL);
1681                 if (!match)
1682                         goto out;
1683                 write_pnet(&match->net, sock_net(sk));
1684                 match->id = id;
1685                 match->type = type;
1686                 match->flags = flags;
1687                 INIT_LIST_HEAD(&match->list);
1688                 spin_lock_init(&match->lock);
1689                 atomic_set(&match->sk_ref, 0);
1690                 fanout_init_data(match);
1691                 match->prot_hook.type = po->prot_hook.type;
1692                 match->prot_hook.dev = po->prot_hook.dev;
1693                 match->prot_hook.func = packet_rcv_fanout;
1694                 match->prot_hook.af_packet_priv = match;
1695                 match->prot_hook.id_match = match_fanout_group;
1696                 dev_add_pack(&match->prot_hook);
1697                 list_add(&match->list, &fanout_list);
1698         }
1699         err = -EINVAL;
1700         if (match->type == type &&
1701             match->prot_hook.type == po->prot_hook.type &&
1702             match->prot_hook.dev == po->prot_hook.dev) {
1703                 err = -ENOSPC;
1704                 if (atomic_read(&match->sk_ref) < PACKET_FANOUT_MAX) {
1705                         __dev_remove_pack(&po->prot_hook);
1706                         po->fanout = match;
1707                         atomic_inc(&match->sk_ref);
1708                         __fanout_link(sk, po);
1709                         err = 0;
1710                 }
1711         }
1712 out:
1713         if (err && rollover) {
1714                 kfree(rollover);
1715                 po->rollover = NULL;
1716         }
1717         mutex_unlock(&fanout_mutex);
1718         return err;
1719 }
1720
1721 static void fanout_release(struct sock *sk)
1722 {
1723         struct packet_sock *po = pkt_sk(sk);
1724         struct packet_fanout *f;
1725
1726         mutex_lock(&fanout_mutex);
1727         f = po->fanout;
1728         if (f) {
1729                 po->fanout = NULL;
1730
1731                 if (atomic_dec_and_test(&f->sk_ref)) {
1732                         list_del(&f->list);
1733                         dev_remove_pack(&f->prot_hook);
1734                         fanout_release_data(f);
1735                         kfree(f);
1736                 }
1737
1738                 if (po->rollover)
1739                         kfree_rcu(po->rollover, rcu);
1740         }
1741         mutex_unlock(&fanout_mutex);
1742 }
1743
1744 static bool packet_extra_vlan_len_allowed(const struct net_device *dev,
1745                                           struct sk_buff *skb)
1746 {
1747         /* Earlier code assumed this would be a VLAN pkt, double-check
1748          * this now that we have the actual packet in hand. We can only
1749          * do this check on Ethernet devices.
1750          */
1751         if (unlikely(dev->type != ARPHRD_ETHER))
1752                 return false;
1753
1754         skb_reset_mac_header(skb);
1755         return likely(eth_hdr(skb)->h_proto == htons(ETH_P_8021Q));
1756 }
1757
1758 static const struct proto_ops packet_ops;
1759
1760 static const struct proto_ops packet_ops_spkt;
1761
1762 static int packet_rcv_spkt(struct sk_buff *skb, struct net_device *dev,
1763                            struct packet_type *pt, struct net_device *orig_dev)
1764 {
1765         struct sock *sk;
1766         struct sockaddr_pkt *spkt;
1767
1768         /*
1769          *      When we registered the protocol we saved the socket in the data
1770          *      field for just this event.
1771          */
1772
1773         sk = pt->af_packet_priv;
1774
1775         /*
1776          *      Yank back the headers [hope the device set this
1777          *      right or kerboom...]
1778          *
1779          *      Incoming packets have ll header pulled,
1780          *      push it back.
1781          *
1782          *      For outgoing ones skb->data == skb_mac_header(skb)
1783          *      so that this procedure is noop.
1784          */
1785
1786         if (skb->pkt_type == PACKET_LOOPBACK)
1787                 goto out;
1788
1789         if (!net_eq(dev_net(dev), sock_net(sk)))
1790                 goto out;
1791
1792         skb = skb_share_check(skb, GFP_ATOMIC);
1793         if (skb == NULL)
1794                 goto oom;
1795
1796         /* drop any routing info */
1797         skb_dst_drop(skb);
1798
1799         /* drop conntrack reference */
1800         nf_reset(skb);
1801
1802         spkt = &PACKET_SKB_CB(skb)->sa.pkt;
1803
1804         skb_push(skb, skb->data - skb_mac_header(skb));
1805
1806         /*
1807          *      The SOCK_PACKET socket receives _all_ frames.
1808          */
1809
1810         spkt->spkt_family = dev->type;
1811         strlcpy(spkt->spkt_device, dev->name, sizeof(spkt->spkt_device));
1812         spkt->spkt_protocol = skb->protocol;
1813
1814         /*
1815          *      Charge the memory to the socket. This is done specifically
1816          *      to prevent sockets using all the memory up.
1817          */
1818
1819         if (sock_queue_rcv_skb(sk, skb) == 0)
1820                 return 0;
1821
1822 out:
1823         kfree_skb(skb);
1824 oom:
1825         return 0;
1826 }
1827
1828
1829 /*
1830  *      Output a raw packet to a device layer. This bypasses all the other
1831  *      protocol layers and you must therefore supply it with a complete frame
1832  */
1833
1834 static int packet_sendmsg_spkt(struct socket *sock, struct msghdr *msg,
1835                                size_t len)
1836 {
1837         struct sock *sk = sock->sk;
1838         DECLARE_SOCKADDR(struct sockaddr_pkt *, saddr, msg->msg_name);
1839         struct sk_buff *skb = NULL;
1840         struct net_device *dev;
1841         struct sockcm_cookie sockc;
1842         __be16 proto = 0;
1843         int err;
1844         int extra_len = 0;
1845
1846         /*
1847          *      Get and verify the address.
1848          */
1849
1850         if (saddr) {
1851                 if (msg->msg_namelen < sizeof(struct sockaddr))
1852                         return -EINVAL;
1853                 if (msg->msg_namelen == sizeof(struct sockaddr_pkt))
1854                         proto = saddr->spkt_protocol;
1855         } else
1856                 return -ENOTCONN;       /* SOCK_PACKET must be sent giving an address */
1857
1858         /*
1859          *      Find the device first to size check it
1860          */
1861
1862         saddr->spkt_device[sizeof(saddr->spkt_device) - 1] = 0;
1863 retry:
1864         rcu_read_lock();
1865         dev = dev_get_by_name_rcu(sock_net(sk), saddr->spkt_device);
1866         err = -ENODEV;
1867         if (dev == NULL)
1868                 goto out_unlock;
1869
1870         err = -ENETDOWN;
1871         if (!(dev->flags & IFF_UP))
1872                 goto out_unlock;
1873
1874         /*
1875          * You may not queue a frame bigger than the mtu. This is the lowest level
1876          * raw protocol and you must do your own fragmentation at this level.
1877          */
1878
1879         if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
1880                 if (!netif_supports_nofcs(dev)) {
1881                         err = -EPROTONOSUPPORT;
1882                         goto out_unlock;
1883                 }
1884                 extra_len = 4; /* We're doing our own CRC */
1885         }
1886
1887         err = -EMSGSIZE;
1888         if (len > dev->mtu + dev->hard_header_len + VLAN_HLEN + extra_len)
1889                 goto out_unlock;
1890
1891         if (!skb) {
1892                 size_t reserved = LL_RESERVED_SPACE(dev);
1893                 int tlen = dev->needed_tailroom;
1894                 unsigned int hhlen = dev->header_ops ? dev->hard_header_len : 0;
1895
1896                 rcu_read_unlock();
1897                 skb = sock_wmalloc(sk, len + reserved + tlen, 0, GFP_KERNEL);
1898                 if (skb == NULL)
1899                         return -ENOBUFS;
1900                 /* FIXME: Save some space for broken drivers that write a hard
1901                  * header at transmission time by themselves. PPP is the notable
1902                  * one here. This should really be fixed at the driver level.
1903                  */
1904                 skb_reserve(skb, reserved);
1905                 skb_reset_network_header(skb);
1906
1907                 /* Try to align data part correctly */
1908                 if (hhlen) {
1909                         skb->data -= hhlen;
1910                         skb->tail -= hhlen;
1911                         if (len < hhlen)
1912                                 skb_reset_network_header(skb);
1913                 }
1914                 err = memcpy_from_msg(skb_put(skb, len), msg, len);
1915                 if (err)
1916                         goto out_free;
1917                 goto retry;
1918         }
1919
1920         if (!dev_validate_header(dev, skb->data, len)) {
1921                 err = -EINVAL;
1922                 goto out_unlock;
1923         }
1924         if (len > (dev->mtu + dev->hard_header_len + extra_len) &&
1925             !packet_extra_vlan_len_allowed(dev, skb)) {
1926                 err = -EMSGSIZE;
1927                 goto out_unlock;
1928         }
1929
1930         sockc.tsflags = sk->sk_tsflags;
1931         if (msg->msg_controllen) {
1932                 err = sock_cmsg_send(sk, msg, &sockc);
1933                 if (unlikely(err))
1934                         goto out_unlock;
1935         }
1936
1937         skb->protocol = proto;
1938         skb->dev = dev;
1939         skb->priority = sk->sk_priority;
1940         skb->mark = sk->sk_mark;
1941
1942         sock_tx_timestamp(sk, sockc.tsflags, &skb_shinfo(skb)->tx_flags);
1943
1944         if (unlikely(extra_len == 4))
1945                 skb->no_fcs = 1;
1946
1947         skb_probe_transport_header(skb, 0);
1948
1949         dev_queue_xmit(skb);
1950         rcu_read_unlock();
1951         return len;
1952
1953 out_unlock:
1954         rcu_read_unlock();
1955 out_free:
1956         kfree_skb(skb);
1957         return err;
1958 }
1959
1960 static unsigned int run_filter(struct sk_buff *skb,
1961                                const struct sock *sk,
1962                                unsigned int res)
1963 {
1964         struct sk_filter *filter;
1965
1966         rcu_read_lock();
1967         filter = rcu_dereference(sk->sk_filter);
1968         if (filter != NULL)
1969                 res = bpf_prog_run_clear_cb(filter->prog, skb);
1970         rcu_read_unlock();
1971
1972         return res;
1973 }
1974
1975 static int __packet_rcv_vnet(const struct sk_buff *skb,
1976                              struct virtio_net_hdr *vnet_hdr)
1977 {
1978         *vnet_hdr = (const struct virtio_net_hdr) { 0 };
1979
1980         if (virtio_net_hdr_from_skb(skb, vnet_hdr, vio_le(), true))
1981                 BUG();
1982
1983         return 0;
1984 }
1985
1986 static int packet_rcv_vnet(struct msghdr *msg, const struct sk_buff *skb,
1987                            size_t *len)
1988 {
1989         struct virtio_net_hdr vnet_hdr;
1990
1991         if (*len < sizeof(vnet_hdr))
1992                 return -EINVAL;
1993         *len -= sizeof(vnet_hdr);
1994
1995         if (__packet_rcv_vnet(skb, &vnet_hdr))
1996                 return -EINVAL;
1997
1998         return memcpy_to_msg(msg, (void *)&vnet_hdr, sizeof(vnet_hdr));
1999 }
2000
2001 /*
2002  * This function makes lazy skb cloning in hope that most of packets
2003  * are discarded by BPF.
2004  *
2005  * Note tricky part: we DO mangle shared skb! skb->data, skb->len
2006  * and skb->cb are mangled. It works because (and until) packets
2007  * falling here are owned by current CPU. Output packets are cloned
2008  * by dev_queue_xmit_nit(), input packets are processed by net_bh
2009  * sequencially, so that if we return skb to original state on exit,
2010  * we will not harm anyone.
2011  */
2012
2013 static int packet_rcv(struct sk_buff *skb, struct net_device *dev,
2014                       struct packet_type *pt, struct net_device *orig_dev)
2015 {
2016         struct sock *sk;
2017         struct sockaddr_ll *sll;
2018         struct packet_sock *po;
2019         u8 *skb_head = skb->data;
2020         int skb_len = skb->len;
2021         unsigned int snaplen, res;
2022         bool is_drop_n_account = false;
2023
2024         if (skb->pkt_type == PACKET_LOOPBACK)
2025                 goto drop;
2026
2027         sk = pt->af_packet_priv;
2028         po = pkt_sk(sk);
2029
2030         if (!net_eq(dev_net(dev), sock_net(sk)))
2031                 goto drop;
2032
2033         skb->dev = dev;
2034
2035         if (dev->header_ops) {
2036                 /* The device has an explicit notion of ll header,
2037                  * exported to higher levels.
2038                  *
2039                  * Otherwise, the device hides details of its frame
2040                  * structure, so that corresponding packet head is
2041                  * never delivered to user.
2042                  */
2043                 if (sk->sk_type != SOCK_DGRAM)
2044                         skb_push(skb, skb->data - skb_mac_header(skb));
2045                 else if (skb->pkt_type == PACKET_OUTGOING) {
2046                         /* Special case: outgoing packets have ll header at head */
2047                         skb_pull(skb, skb_network_offset(skb));
2048                 }
2049         }
2050
2051         snaplen = skb->len;
2052
2053         res = run_filter(skb, sk, snaplen);
2054         if (!res)
2055                 goto drop_n_restore;
2056         if (snaplen > res)
2057                 snaplen = res;
2058
2059         if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
2060                 goto drop_n_acct;
2061
2062         if (skb_shared(skb)) {
2063                 struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
2064                 if (nskb == NULL)
2065                         goto drop_n_acct;
2066
2067                 if (skb_head != skb->data) {
2068                         skb->data = skb_head;
2069                         skb->len = skb_len;
2070                 }
2071                 consume_skb(skb);
2072                 skb = nskb;
2073         }
2074
2075         sock_skb_cb_check_size(sizeof(*PACKET_SKB_CB(skb)) + MAX_ADDR_LEN - 8);
2076
2077         sll = &PACKET_SKB_CB(skb)->sa.ll;
2078         sll->sll_hatype = dev->type;
2079         sll->sll_pkttype = skb->pkt_type;
2080         if (unlikely(po->origdev))
2081                 sll->sll_ifindex = orig_dev->ifindex;
2082         else
2083                 sll->sll_ifindex = dev->ifindex;
2084
2085         sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
2086
2087         /* sll->sll_family and sll->sll_protocol are set in packet_recvmsg().
2088          * Use their space for storing the original skb length.
2089          */
2090         PACKET_SKB_CB(skb)->sa.origlen = skb->len;
2091
2092         if (pskb_trim(skb, snaplen))
2093                 goto drop_n_acct;
2094
2095         skb_set_owner_r(skb, sk);
2096         skb->dev = NULL;
2097         skb_dst_drop(skb);
2098
2099         /* drop conntrack reference */
2100         nf_reset(skb);
2101
2102         spin_lock(&sk->sk_receive_queue.lock);
2103         po->stats.stats1.tp_packets++;
2104         sock_skb_set_dropcount(sk, skb);
2105         __skb_queue_tail(&sk->sk_receive_queue, skb);
2106         spin_unlock(&sk->sk_receive_queue.lock);
2107         sk->sk_data_ready(sk);
2108         return 0;
2109
2110 drop_n_acct:
2111         is_drop_n_account = true;
2112         spin_lock(&sk->sk_receive_queue.lock);
2113         po->stats.stats1.tp_drops++;
2114         atomic_inc(&sk->sk_drops);
2115         spin_unlock(&sk->sk_receive_queue.lock);
2116
2117 drop_n_restore:
2118         if (skb_head != skb->data && skb_shared(skb)) {
2119                 skb->data = skb_head;
2120                 skb->len = skb_len;
2121         }
2122 drop:
2123         if (!is_drop_n_account)
2124                 consume_skb(skb);
2125         else
2126                 kfree_skb(skb);
2127         return 0;
2128 }
2129
2130 static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
2131                        struct packet_type *pt, struct net_device *orig_dev)
2132 {
2133         struct sock *sk;
2134         struct packet_sock *po;
2135         struct sockaddr_ll *sll;
2136         union tpacket_uhdr h;
2137         u8 *skb_head = skb->data;
2138         int skb_len = skb->len;
2139         unsigned int snaplen, res;
2140         unsigned long status = TP_STATUS_USER;
2141         unsigned short macoff, netoff, hdrlen;
2142         struct sk_buff *copy_skb = NULL;
2143         struct timespec ts;
2144         __u32 ts_status;
2145         bool is_drop_n_account = false;
2146
2147         /* struct tpacket{2,3}_hdr is aligned to a multiple of TPACKET_ALIGNMENT.
2148          * We may add members to them until current aligned size without forcing
2149          * userspace to call getsockopt(..., PACKET_HDRLEN, ...).
2150          */
2151         BUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h2)) != 32);
2152         BUILD_BUG_ON(TPACKET_ALIGN(sizeof(*h.h3)) != 48);
2153
2154         if (skb->pkt_type == PACKET_LOOPBACK)
2155                 goto drop;
2156
2157         sk = pt->af_packet_priv;
2158         po = pkt_sk(sk);
2159
2160         if (!net_eq(dev_net(dev), sock_net(sk)))
2161                 goto drop;
2162
2163         if (dev->header_ops) {
2164                 if (sk->sk_type != SOCK_DGRAM)
2165                         skb_push(skb, skb->data - skb_mac_header(skb));
2166                 else if (skb->pkt_type == PACKET_OUTGOING) {
2167                         /* Special case: outgoing packets have ll header at head */
2168                         skb_pull(skb, skb_network_offset(skb));
2169                 }
2170         }
2171
2172         snaplen = skb->len;
2173
2174         res = run_filter(skb, sk, snaplen);
2175         if (!res)
2176                 goto drop_n_restore;
2177
2178         if (skb->ip_summed == CHECKSUM_PARTIAL)
2179                 status |= TP_STATUS_CSUMNOTREADY;
2180         else if (skb->pkt_type != PACKET_OUTGOING &&
2181                  (skb->ip_summed == CHECKSUM_COMPLETE ||
2182                   skb_csum_unnecessary(skb)))
2183                 status |= TP_STATUS_CSUM_VALID;
2184
2185         if (snaplen > res)
2186                 snaplen = res;
2187
2188         if (sk->sk_type == SOCK_DGRAM) {
2189                 macoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +
2190                                   po->tp_reserve;
2191         } else {
2192                 unsigned int maclen = skb_network_offset(skb);
2193                 netoff = TPACKET_ALIGN(po->tp_hdrlen +
2194                                        (maclen < 16 ? 16 : maclen)) +
2195                                        po->tp_reserve;
2196                 if (po->has_vnet_hdr)
2197                         netoff += sizeof(struct virtio_net_hdr);
2198                 macoff = netoff - maclen;
2199         }
2200         if (po->tp_version <= TPACKET_V2) {
2201                 if (macoff + snaplen > po->rx_ring.frame_size) {
2202                         if (po->copy_thresh &&
2203                             atomic_read(&sk->sk_rmem_alloc) < sk->sk_rcvbuf) {
2204                                 if (skb_shared(skb)) {
2205                                         copy_skb = skb_clone(skb, GFP_ATOMIC);
2206                                 } else {
2207                                         copy_skb = skb_get(skb);
2208                                         skb_head = skb->data;
2209                                 }
2210                                 if (copy_skb)
2211                                         skb_set_owner_r(copy_skb, sk);
2212                         }
2213                         snaplen = po->rx_ring.frame_size - macoff;
2214                         if ((int)snaplen < 0)
2215                                 snaplen = 0;
2216                 }
2217         } else if (unlikely(macoff + snaplen >
2218                             GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len)) {
2219                 u32 nval;
2220
2221                 nval = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len - macoff;
2222                 pr_err_once("tpacket_rcv: packet too big, clamped from %u to %u. macoff=%u\n",
2223                             snaplen, nval, macoff);
2224                 snaplen = nval;
2225                 if (unlikely((int)snaplen < 0)) {
2226                         snaplen = 0;
2227                         macoff = GET_PBDQC_FROM_RB(&po->rx_ring)->max_frame_len;
2228                 }
2229         }
2230         spin_lock(&sk->sk_receive_queue.lock);
2231         h.raw = packet_current_rx_frame(po, skb,
2232                                         TP_STATUS_KERNEL, (macoff+snaplen));
2233         if (!h.raw)
2234                 goto drop_n_account;
2235         if (po->tp_version <= TPACKET_V2) {
2236                 packet_increment_rx_head(po, &po->rx_ring);
2237         /*
2238          * LOSING will be reported till you read the stats,
2239          * because it's COR - Clear On Read.
2240          * Anyways, moving it for V1/V2 only as V3 doesn't need this
2241          * at packet level.
2242          */
2243                 if (po->stats.stats1.tp_drops)
2244                         status |= TP_STATUS_LOSING;
2245         }
2246         po->stats.stats1.tp_packets++;
2247         if (copy_skb) {
2248                 status |= TP_STATUS_COPY;
2249                 __skb_queue_tail(&sk->sk_receive_queue, copy_skb);
2250         }
2251         spin_unlock(&sk->sk_receive_queue.lock);
2252
2253         if (po->has_vnet_hdr) {
2254                 if (__packet_rcv_vnet(skb, h.raw + macoff -
2255                                            sizeof(struct virtio_net_hdr))) {
2256                         spin_lock(&sk->sk_receive_queue.lock);
2257                         goto drop_n_account;
2258                 }
2259         }
2260
2261         skb_copy_bits(skb, 0, h.raw + macoff, snaplen);
2262
2263         if (!(ts_status = tpacket_get_timestamp(skb, &ts, po->tp_tstamp)))
2264                 getnstimeofday(&ts);
2265
2266         status |= ts_status;
2267
2268         switch (po->tp_version) {
2269         case TPACKET_V1:
2270                 h.h1->tp_len = skb->len;
2271                 h.h1->tp_snaplen = snaplen;
2272                 h.h1->tp_mac = macoff;
2273                 h.h1->tp_net = netoff;
2274                 h.h1->tp_sec = ts.tv_sec;
2275                 h.h1->tp_usec = ts.tv_nsec / NSEC_PER_USEC;
2276                 hdrlen = sizeof(*h.h1);
2277                 break;
2278         case TPACKET_V2:
2279                 h.h2->tp_len = skb->len;
2280                 h.h2->tp_snaplen = snaplen;
2281                 h.h2->tp_mac = macoff;
2282                 h.h2->tp_net = netoff;
2283                 h.h2->tp_sec = ts.tv_sec;
2284                 h.h2->tp_nsec = ts.tv_nsec;
2285                 if (skb_vlan_tag_present(skb)) {
2286                         h.h2->tp_vlan_tci = skb_vlan_tag_get(skb);
2287                         h.h2->tp_vlan_tpid = ntohs(skb->vlan_proto);
2288                         status |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
2289                 } else {
2290                         h.h2->tp_vlan_tci = 0;
2291                         h.h2->tp_vlan_tpid = 0;
2292                 }
2293                 memset(h.h2->tp_padding, 0, sizeof(h.h2->tp_padding));
2294                 hdrlen = sizeof(*h.h2);
2295                 break;
2296         case TPACKET_V3:
2297                 /* tp_nxt_offset,vlan are already populated above.
2298                  * So DONT clear those fields here
2299                  */
2300                 h.h3->tp_status |= status;
2301                 h.h3->tp_len = skb->len;
2302                 h.h3->tp_snaplen = snaplen;
2303                 h.h3->tp_mac = macoff;
2304                 h.h3->tp_net = netoff;
2305                 h.h3->tp_sec  = ts.tv_sec;
2306                 h.h3->tp_nsec = ts.tv_nsec;
2307                 memset(h.h3->tp_padding, 0, sizeof(h.h3->tp_padding));
2308                 hdrlen = sizeof(*h.h3);
2309                 break;
2310         default:
2311                 BUG();
2312         }
2313
2314         sll = h.raw + TPACKET_ALIGN(hdrlen);
2315         sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
2316         sll->sll_family = AF_PACKET;
2317         sll->sll_hatype = dev->type;
2318         sll->sll_protocol = skb->protocol;
2319         sll->sll_pkttype = skb->pkt_type;
2320         if (unlikely(po->origdev))
2321                 sll->sll_ifindex = orig_dev->ifindex;
2322         else
2323                 sll->sll_ifindex = dev->ifindex;
2324
2325         smp_mb();
2326
2327 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
2328         if (po->tp_version <= TPACKET_V2) {
2329                 u8 *start, *end;
2330
2331                 end = (u8 *) PAGE_ALIGN((unsigned long) h.raw +
2332                                         macoff + snaplen);
2333
2334                 for (start = h.raw; start < end; start += PAGE_SIZE)
2335                         flush_dcache_page(pgv_to_page(start));
2336         }
2337         smp_wmb();
2338 #endif
2339
2340         if (po->tp_version <= TPACKET_V2) {
2341                 __packet_set_status(po, h.raw, status);
2342                 sk->sk_data_ready(sk);
2343         } else {
2344                 prb_clear_blk_fill_status(&po->rx_ring);
2345         }
2346
2347 drop_n_restore:
2348         if (skb_head != skb->data && skb_shared(skb)) {
2349                 skb->data = skb_head;
2350                 skb->len = skb_len;
2351         }
2352 drop:
2353         if (!is_drop_n_account)
2354                 consume_skb(skb);
2355         else
2356                 kfree_skb(skb);
2357         return 0;
2358
2359 drop_n_account:
2360         is_drop_n_account = true;
2361         po->stats.stats1.tp_drops++;
2362         spin_unlock(&sk->sk_receive_queue.lock);
2363
2364         sk->sk_data_ready(sk);
2365         kfree_skb(copy_skb);
2366         goto drop_n_restore;
2367 }
2368
2369 static void tpacket_destruct_skb(struct sk_buff *skb)
2370 {
2371         struct packet_sock *po = pkt_sk(skb->sk);
2372
2373         if (likely(po->tx_ring.pg_vec)) {
2374                 void *ph;
2375                 __u32 ts;
2376
2377                 ph = skb_shinfo(skb)->destructor_arg;
2378                 packet_dec_pending(&po->tx_ring);
2379
2380                 ts = __packet_set_timestamp(po, ph, skb);
2381                 __packet_set_status(po, ph, TP_STATUS_AVAILABLE | ts);
2382         }
2383
2384         sock_wfree(skb);
2385 }
2386
2387 static void tpacket_set_protocol(const struct net_device *dev,
2388                                  struct sk_buff *skb)
2389 {
2390         if (dev->type == ARPHRD_ETHER) {
2391                 skb_reset_mac_header(skb);
2392                 skb->protocol = eth_hdr(skb)->h_proto;
2393         }
2394 }
2395
2396 static int __packet_snd_vnet_parse(struct virtio_net_hdr *vnet_hdr, size_t len)
2397 {
2398         unsigned short gso_type = 0;
2399
2400         if ((vnet_hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
2401             (__virtio16_to_cpu(vio_le(), vnet_hdr->csum_start) +
2402              __virtio16_to_cpu(vio_le(), vnet_hdr->csum_offset) + 2 >
2403               __virtio16_to_cpu(vio_le(), vnet_hdr->hdr_len)))
2404                 vnet_hdr->hdr_len = __cpu_to_virtio16(vio_le(),
2405                          __virtio16_to_cpu(vio_le(), vnet_hdr->csum_start) +
2406                         __virtio16_to_cpu(vio_le(), vnet_hdr->csum_offset) + 2);
2407
2408         if (__virtio16_to_cpu(vio_le(), vnet_hdr->hdr_len) > len)
2409                 return -EINVAL;
2410
2411         if (vnet_hdr->gso_type != VIRTIO_NET_HDR_GSO_NONE) {
2412                 switch (vnet_hdr->gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
2413                 case VIRTIO_NET_HDR_GSO_TCPV4:
2414                         gso_type = SKB_GSO_TCPV4;
2415                         break;
2416                 case VIRTIO_NET_HDR_GSO_TCPV6:
2417                         gso_type = SKB_GSO_TCPV6;
2418                         break;
2419                 case VIRTIO_NET_HDR_GSO_UDP:
2420                         gso_type = SKB_GSO_UDP;
2421                         break;
2422                 default:
2423                         return -EINVAL;
2424                 }
2425
2426                 if (vnet_hdr->gso_type & VIRTIO_NET_HDR_GSO_ECN)
2427                         gso_type |= SKB_GSO_TCP_ECN;
2428
2429                 if (vnet_hdr->gso_size == 0)
2430                         return -EINVAL;
2431         }
2432
2433         vnet_hdr->gso_type = gso_type;  /* changes type, temporary storage */
2434         return 0;
2435 }
2436
2437 static int packet_snd_vnet_parse(struct msghdr *msg, size_t *len,
2438                                  struct virtio_net_hdr *vnet_hdr)
2439 {
2440         int n;
2441
2442         if (*len < sizeof(*vnet_hdr))
2443                 return -EINVAL;
2444         *len -= sizeof(*vnet_hdr);
2445
2446         n = copy_from_iter(vnet_hdr, sizeof(*vnet_hdr), &msg->msg_iter);
2447         if (n != sizeof(*vnet_hdr))
2448                 return -EFAULT;
2449
2450         return __packet_snd_vnet_parse(vnet_hdr, *len);
2451 }
2452
2453 static int packet_snd_vnet_gso(struct sk_buff *skb,
2454                                struct virtio_net_hdr *vnet_hdr)
2455 {
2456         if (vnet_hdr->flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
2457                 u16 s = __virtio16_to_cpu(vio_le(), vnet_hdr->csum_start);
2458                 u16 o = __virtio16_to_cpu(vio_le(), vnet_hdr->csum_offset);
2459
2460                 if (!skb_partial_csum_set(skb, s, o))
2461                         return -EINVAL;
2462         }
2463
2464         skb_shinfo(skb)->gso_size =
2465                 __virtio16_to_cpu(vio_le(), vnet_hdr->gso_size);
2466         skb_shinfo(skb)->gso_type = vnet_hdr->gso_type;
2467
2468         /* Header must be checked, and gso_segs computed. */
2469         skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
2470         skb_shinfo(skb)->gso_segs = 0;
2471         return 0;
2472 }
2473
2474 static int tpacket_fill_skb(struct packet_sock *po, struct sk_buff *skb,
2475                 void *frame, struct net_device *dev, void *data, int tp_len,
2476                 __be16 proto, unsigned char *addr, int hlen, int copylen,
2477                 const struct sockcm_cookie *sockc)
2478 {
2479         union tpacket_uhdr ph;
2480         int to_write, offset, len, nr_frags, len_max;
2481         struct socket *sock = po->sk.sk_socket;
2482         struct page *page;
2483         int err;
2484
2485         ph.raw = frame;
2486
2487         skb->protocol = proto;
2488         skb->dev = dev;
2489         skb->priority = po->sk.sk_priority;
2490         skb->mark = po->sk.sk_mark;
2491         sock_tx_timestamp(&po->sk, sockc->tsflags, &skb_shinfo(skb)->tx_flags);
2492         skb_shinfo(skb)->destructor_arg = ph.raw;
2493
2494         skb_reserve(skb, hlen);
2495         skb_reset_network_header(skb);
2496
2497         to_write = tp_len;
2498
2499         if (sock->type == SOCK_DGRAM) {
2500                 err = dev_hard_header(skb, dev, ntohs(proto), addr,
2501                                 NULL, tp_len);
2502                 if (unlikely(err < 0))
2503                         return -EINVAL;
2504         } else if (copylen) {
2505                 int hdrlen = min_t(int, copylen, tp_len);
2506
2507                 skb_push(skb, dev->hard_header_len);
2508                 skb_put(skb, copylen - dev->hard_header_len);
2509                 err = skb_store_bits(skb, 0, data, hdrlen);
2510                 if (unlikely(err))
2511                         return err;
2512                 if (!dev_validate_header(dev, skb->data, hdrlen))
2513                         return -EINVAL;
2514                 if (!skb->protocol)
2515                         tpacket_set_protocol(dev, skb);
2516
2517                 data += hdrlen;
2518                 to_write -= hdrlen;
2519         }
2520
2521         offset = offset_in_page(data);
2522         len_max = PAGE_SIZE - offset;
2523         len = ((to_write > len_max) ? len_max : to_write);
2524
2525         skb->data_len = to_write;
2526         skb->len += to_write;
2527         skb->truesize += to_write;
2528         atomic_add(to_write, &po->sk.sk_wmem_alloc);
2529
2530         while (likely(to_write)) {
2531                 nr_frags = skb_shinfo(skb)->nr_frags;
2532
2533                 if (unlikely(nr_frags >= MAX_SKB_FRAGS)) {
2534                         pr_err("Packet exceed the number of skb frags(%lu)\n",
2535                                MAX_SKB_FRAGS);
2536                         return -EFAULT;
2537                 }
2538
2539                 page = pgv_to_page(data);
2540                 data += len;
2541                 flush_dcache_page(page);
2542                 get_page(page);
2543                 skb_fill_page_desc(skb, nr_frags, page, offset, len);
2544                 to_write -= len;
2545                 offset = 0;
2546                 len_max = PAGE_SIZE;
2547                 len = ((to_write > len_max) ? len_max : to_write);
2548         }
2549
2550         skb_probe_transport_header(skb, 0);
2551
2552         return tp_len;
2553 }
2554
2555 static int tpacket_parse_header(struct packet_sock *po, void *frame,
2556                                 int size_max, void **data)
2557 {
2558         union tpacket_uhdr ph;
2559         int tp_len, off;
2560
2561         ph.raw = frame;
2562
2563         switch (po->tp_version) {
2564         case TPACKET_V2:
2565                 tp_len = ph.h2->tp_len;
2566                 break;
2567         default:
2568                 tp_len = ph.h1->tp_len;
2569                 break;
2570         }
2571         if (unlikely(tp_len > size_max)) {
2572                 pr_err("packet size is too long (%d > %d)\n", tp_len, size_max);
2573                 return -EMSGSIZE;
2574         }
2575
2576         if (unlikely(po->tp_tx_has_off)) {
2577                 int off_min, off_max;
2578
2579                 off_min = po->tp_hdrlen - sizeof(struct sockaddr_ll);
2580                 off_max = po->tx_ring.frame_size - tp_len;
2581                 if (po->sk.sk_type == SOCK_DGRAM) {
2582                         switch (po->tp_version) {
2583                         case TPACKET_V2:
2584                                 off = ph.h2->tp_net;
2585                                 break;
2586                         default:
2587                                 off = ph.h1->tp_net;
2588                                 break;
2589                         }
2590                 } else {
2591                         switch (po->tp_version) {
2592                         case TPACKET_V2:
2593                                 off = ph.h2->tp_mac;
2594                                 break;
2595                         default:
2596                                 off = ph.h1->tp_mac;
2597                                 break;
2598                         }
2599                 }
2600                 if (unlikely((off < off_min) || (off_max < off)))
2601                         return -EINVAL;
2602         } else {
2603                 off = po->tp_hdrlen - sizeof(struct sockaddr_ll);
2604         }
2605
2606         *data = frame + off;
2607         return tp_len;
2608 }
2609
2610 static int tpacket_snd(struct packet_sock *po, struct msghdr *msg)
2611 {
2612         struct sk_buff *skb;
2613         struct net_device *dev;
2614         struct virtio_net_hdr *vnet_hdr = NULL;
2615         struct sockcm_cookie sockc;
2616         __be16 proto;
2617         int err, reserve = 0;
2618         void *ph;
2619         DECLARE_SOCKADDR(struct sockaddr_ll *, saddr, msg->msg_name);
2620         bool need_wait = !(msg->msg_flags & MSG_DONTWAIT);
2621         int tp_len, size_max;
2622         unsigned char *addr;
2623         void *data;
2624         int len_sum = 0;
2625         int status = TP_STATUS_AVAILABLE;
2626         int hlen, tlen, copylen = 0;
2627
2628         mutex_lock(&po->pg_vec_lock);
2629
2630         if (likely(saddr == NULL)) {
2631                 dev     = packet_cached_dev_get(po);
2632                 proto   = po->num;
2633                 addr    = NULL;
2634         } else {
2635                 err = -EINVAL;
2636                 if (msg->msg_namelen < sizeof(struct sockaddr_ll))
2637                         goto out;
2638                 if (msg->msg_namelen < (saddr->sll_halen
2639                                         + offsetof(struct sockaddr_ll,
2640                                                 sll_addr)))
2641                         goto out;
2642                 proto   = saddr->sll_protocol;
2643                 addr    = saddr->sll_addr;
2644                 dev = dev_get_by_index(sock_net(&po->sk), saddr->sll_ifindex);
2645         }
2646
2647         sockc.tsflags = po->sk.sk_tsflags;
2648         if (msg->msg_controllen) {
2649                 err = sock_cmsg_send(&po->sk, msg, &sockc);
2650                 if (unlikely(err))
2651                         goto out;
2652         }
2653
2654         err = -ENXIO;
2655         if (unlikely(dev == NULL))
2656                 goto out;
2657         err = -ENETDOWN;
2658         if (unlikely(!(dev->flags & IFF_UP)))
2659                 goto out_put;
2660
2661         if (po->sk.sk_socket->type == SOCK_RAW)
2662                 reserve = dev->hard_header_len;
2663         size_max = po->tx_ring.frame_size
2664                 - (po->tp_hdrlen - sizeof(struct sockaddr_ll));
2665
2666         if ((size_max > dev->mtu + reserve + VLAN_HLEN) && !po->has_vnet_hdr)
2667                 size_max = dev->mtu + reserve + VLAN_HLEN;
2668
2669         do {
2670                 ph = packet_current_frame(po, &po->tx_ring,
2671                                           TP_STATUS_SEND_REQUEST);
2672                 if (unlikely(ph == NULL)) {
2673                         if (need_wait && need_resched())
2674                                 schedule();
2675                         continue;
2676                 }
2677
2678                 skb = NULL;
2679                 tp_len = tpacket_parse_header(po, ph, size_max, &data);
2680                 if (tp_len < 0)
2681                         goto tpacket_error;
2682
2683                 status = TP_STATUS_SEND_REQUEST;
2684                 hlen = LL_RESERVED_SPACE(dev);
2685                 tlen = dev->needed_tailroom;
2686                 if (po->has_vnet_hdr) {
2687                         vnet_hdr = data;
2688                         data += sizeof(*vnet_hdr);
2689                         tp_len -= sizeof(*vnet_hdr);
2690                         if (tp_len < 0 ||
2691                             __packet_snd_vnet_parse(vnet_hdr, tp_len)) {
2692                                 tp_len = -EINVAL;
2693                                 goto tpacket_error;
2694                         }
2695                         copylen = __virtio16_to_cpu(vio_le(),
2696                                                     vnet_hdr->hdr_len);
2697                 }
2698                 copylen = max_t(int, copylen, dev->hard_header_len);
2699                 skb = sock_alloc_send_skb(&po->sk,
2700                                 hlen + tlen + sizeof(struct sockaddr_ll) +
2701                                 (copylen - dev->hard_header_len),
2702                                 !need_wait, &err);
2703
2704                 if (unlikely(skb == NULL)) {
2705                         /* we assume the socket was initially writeable ... */
2706                         if (likely(len_sum > 0))
2707                                 err = len_sum;
2708                         goto out_status;
2709                 }
2710                 tp_len = tpacket_fill_skb(po, skb, ph, dev, data, tp_len, proto,
2711                                           addr, hlen, copylen, &sockc);
2712                 if (likely(tp_len >= 0) &&
2713                     tp_len > dev->mtu + reserve &&
2714                     !po->has_vnet_hdr &&
2715                     !packet_extra_vlan_len_allowed(dev, skb))
2716                         tp_len = -EMSGSIZE;
2717
2718                 if (unlikely(tp_len < 0)) {
2719 tpacket_error:
2720                         if (po->tp_loss) {
2721                                 __packet_set_status(po, ph,
2722                                                 TP_STATUS_AVAILABLE);
2723                                 packet_increment_head(&po->tx_ring);
2724                                 kfree_skb(skb);
2725                                 continue;
2726                         } else {
2727                                 status = TP_STATUS_WRONG_FORMAT;
2728                                 err = tp_len;
2729                                 goto out_status;
2730                         }
2731                 }
2732
2733                 if (po->has_vnet_hdr && packet_snd_vnet_gso(skb, vnet_hdr)) {
2734                         tp_len = -EINVAL;
2735                         goto tpacket_error;
2736                 }
2737
2738                 packet_pick_tx_queue(dev, skb);
2739
2740                 skb->destructor = tpacket_destruct_skb;
2741                 __packet_set_status(po, ph, TP_STATUS_SENDING);
2742                 packet_inc_pending(&po->tx_ring);
2743
2744                 status = TP_STATUS_SEND_REQUEST;
2745                 err = po->xmit(skb);
2746                 if (unlikely(err > 0)) {
2747                         err = net_xmit_errno(err);
2748                         if (err && __packet_get_status(po, ph) ==
2749                                    TP_STATUS_AVAILABLE) {
2750                                 /* skb was destructed already */
2751                                 skb = NULL;
2752                                 goto out_status;
2753                         }
2754                         /*
2755                          * skb was dropped but not destructed yet;
2756                          * let's treat it like congestion or err < 0
2757                          */
2758                         err = 0;
2759                 }
2760                 packet_increment_head(&po->tx_ring);
2761                 len_sum += tp_len;
2762         } while (likely((ph != NULL) ||
2763                 /* Note: packet_read_pending() might be slow if we have
2764                  * to call it as it's per_cpu variable, but in fast-path
2765                  * we already short-circuit the loop with the first
2766                  * condition, and luckily don't have to go that path
2767                  * anyway.
2768                  */
2769                  (need_wait && packet_read_pending(&po->tx_ring))));
2770
2771         err = len_sum;
2772         goto out_put;
2773
2774 out_status:
2775         __packet_set_status(po, ph, status);
2776         kfree_skb(skb);
2777 out_put:
2778         dev_put(dev);
2779 out:
2780         mutex_unlock(&po->pg_vec_lock);
2781         return err;
2782 }
2783
2784 static struct sk_buff *packet_alloc_skb(struct sock *sk, size_t prepad,
2785                                         size_t reserve, size_t len,
2786                                         size_t linear, int noblock,
2787                                         int *err)
2788 {
2789         struct sk_buff *skb;
2790
2791         /* Under a page?  Don't bother with paged skb. */
2792         if (prepad + len < PAGE_SIZE || !linear)
2793                 linear = len;
2794
2795         skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
2796                                    err, 0);
2797         if (!skb)
2798                 return NULL;
2799
2800         skb_reserve(skb, reserve);
2801         skb_put(skb, linear);
2802         skb->data_len = len - linear;
2803         skb->len += len - linear;
2804
2805         return skb;
2806 }
2807
2808 static int packet_snd(struct socket *sock, struct msghdr *msg, size_t len)
2809 {
2810         struct sock *sk = sock->sk;
2811         DECLARE_SOCKADDR(struct sockaddr_ll *, saddr, msg->msg_name);
2812         struct sk_buff *skb;
2813         struct net_device *dev;
2814         __be16 proto;
2815         unsigned char *addr;
2816         int err, reserve = 0;
2817         struct sockcm_cookie sockc;
2818         struct virtio_net_hdr vnet_hdr = { 0 };
2819         int offset = 0;
2820         struct packet_sock *po = pkt_sk(sk);
2821         int hlen, tlen, linear;
2822         int extra_len = 0;
2823
2824         /*
2825          *      Get and verify the address.
2826          */
2827
2828         if (likely(saddr == NULL)) {
2829                 dev     = packet_cached_dev_get(po);
2830                 proto   = po->num;
2831                 addr    = NULL;
2832         } else {
2833                 err = -EINVAL;
2834                 if (msg->msg_namelen < sizeof(struct sockaddr_ll))
2835                         goto out;
2836                 if (msg->msg_namelen < (saddr->sll_halen + offsetof(struct sockaddr_ll, sll_addr)))
2837                         goto out;
2838                 proto   = saddr->sll_protocol;
2839                 addr    = saddr->sll_addr;
2840                 dev = dev_get_by_index(sock_net(sk), saddr->sll_ifindex);
2841         }
2842
2843         err = -ENXIO;
2844         if (unlikely(dev == NULL))
2845                 goto out_unlock;
2846         err = -ENETDOWN;
2847         if (unlikely(!(dev->flags & IFF_UP)))
2848                 goto out_unlock;
2849
2850         sockc.tsflags = sk->sk_tsflags;
2851         sockc.mark = sk->sk_mark;
2852         if (msg->msg_controllen) {
2853                 err = sock_cmsg_send(sk, msg, &sockc);
2854                 if (unlikely(err))
2855                         goto out_unlock;
2856         }
2857
2858         if (sock->type == SOCK_RAW)
2859                 reserve = dev->hard_header_len;
2860         if (po->has_vnet_hdr) {
2861                 err = packet_snd_vnet_parse(msg, &len, &vnet_hdr);
2862                 if (err)
2863                         goto out_unlock;
2864         }
2865
2866         if (unlikely(sock_flag(sk, SOCK_NOFCS))) {
2867                 if (!netif_supports_nofcs(dev)) {
2868                         err = -EPROTONOSUPPORT;
2869                         goto out_unlock;
2870                 }
2871                 extra_len = 4; /* We're doing our own CRC */
2872         }
2873
2874         err = -EMSGSIZE;
2875         if (!vnet_hdr.gso_type &&
2876             (len > dev->mtu + reserve + VLAN_HLEN + extra_len))
2877                 goto out_unlock;
2878
2879         err = -ENOBUFS;
2880         hlen = LL_RESERVED_SPACE(dev);
2881         tlen = dev->needed_tailroom;
2882         linear = __virtio16_to_cpu(vio_le(), vnet_hdr.hdr_len);
2883         linear = max(linear, min_t(int, len, dev->hard_header_len));
2884         skb = packet_alloc_skb(sk, hlen + tlen, hlen, len, linear,
2885                                msg->msg_flags & MSG_DONTWAIT, &err);
2886         if (skb == NULL)
2887                 goto out_unlock;
2888
2889         skb_set_network_header(skb, reserve);
2890
2891         err = -EINVAL;
2892         if (sock->type == SOCK_DGRAM) {
2893                 offset = dev_hard_header(skb, dev, ntohs(proto), addr, NULL, len);
2894                 if (unlikely(offset < 0))
2895                         goto out_free;
2896         }
2897
2898         /* Returns -EFAULT on error */
2899         err = skb_copy_datagram_from_iter(skb, offset, &msg->msg_iter, len);
2900         if (err)
2901                 goto out_free;
2902
2903         if (sock->type == SOCK_RAW &&
2904             !dev_validate_header(dev, skb->data, len)) {
2905                 err = -EINVAL;
2906                 goto out_free;
2907         }
2908
2909         sock_tx_timestamp(sk, sockc.tsflags, &skb_shinfo(skb)->tx_flags);
2910
2911         if (!vnet_hdr.gso_type && (len > dev->mtu + reserve + extra_len) &&
2912             !packet_extra_vlan_len_allowed(dev, skb)) {
2913                 err = -EMSGSIZE;
2914                 goto out_free;
2915         }
2916
2917         skb->protocol = proto;
2918         skb->dev = dev;
2919         skb->priority = sk->sk_priority;
2920         skb->mark = sockc.mark;
2921
2922         packet_pick_tx_queue(dev, skb);
2923
2924         if (po->has_vnet_hdr) {
2925                 err = packet_snd_vnet_gso(skb, &vnet_hdr);
2926                 if (err)
2927                         goto out_free;
2928                 len += sizeof(vnet_hdr);
2929         }
2930
2931         skb_probe_transport_header(skb, reserve);
2932
2933         if (unlikely(extra_len == 4))
2934                 skb->no_fcs = 1;
2935
2936         err = po->xmit(skb);
2937         if (err > 0 && (err = net_xmit_errno(err)) != 0)
2938                 goto out_unlock;
2939
2940         dev_put(dev);
2941
2942         return len;
2943
2944 out_free:
2945         kfree_skb(skb);
2946 out_unlock:
2947         if (dev)
2948                 dev_put(dev);
2949 out:
2950         return err;
2951 }
2952
2953 static int packet_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
2954 {
2955         struct sock *sk = sock->sk;
2956         struct packet_sock *po = pkt_sk(sk);
2957
2958         if (po->tx_ring.pg_vec)
2959                 return tpacket_snd(po, msg);
2960         else
2961                 return packet_snd(sock, msg, len);
2962 }
2963
2964 /*
2965  *      Close a PACKET socket. This is fairly simple. We immediately go
2966  *      to 'closed' state and remove our protocol entry in the device list.
2967  */
2968
2969 static int packet_release(struct socket *sock)
2970 {
2971         struct sock *sk = sock->sk;
2972         struct packet_sock *po;
2973         struct net *net;
2974         union tpacket_req_u req_u;
2975
2976         if (!sk)
2977                 return 0;
2978
2979         net = sock_net(sk);
2980         po = pkt_sk(sk);
2981
2982         mutex_lock(&net->packet.sklist_lock);
2983         sk_del_node_init_rcu(sk);
2984         mutex_unlock(&net->packet.sklist_lock);
2985
2986         preempt_disable();
2987         sock_prot_inuse_add(net, sk->sk_prot, -1);
2988         preempt_enable();
2989
2990         spin_lock(&po->bind_lock);
2991         unregister_prot_hook(sk, false);
2992         packet_cached_dev_reset(po);
2993
2994         if (po->prot_hook.dev) {
2995                 dev_put(po->prot_hook.dev);
2996                 po->prot_hook.dev = NULL;
2997         }
2998         spin_unlock(&po->bind_lock);
2999
3000         packet_flush_mclist(sk);
3001
3002         if (po->rx_ring.pg_vec) {
3003                 memset(&req_u, 0, sizeof(req_u));
3004                 packet_set_ring(sk, &req_u, 1, 0);
3005         }
3006
3007         if (po->tx_ring.pg_vec) {
3008                 memset(&req_u, 0, sizeof(req_u));
3009                 packet_set_ring(sk, &req_u, 1, 1);
3010         }
3011
3012         fanout_release(sk);
3013
3014         synchronize_net();
3015         /*
3016          *      Now the socket is dead. No more input will appear.
3017          */
3018         sock_orphan(sk);
3019         sock->sk = NULL;
3020
3021         /* Purge queues */
3022
3023         skb_queue_purge(&sk->sk_receive_queue);
3024         packet_free_pending(po);
3025         sk_refcnt_debug_release(sk);
3026
3027         sock_put(sk);
3028         return 0;
3029 }
3030
3031 /*
3032  *      Attach a packet hook.
3033  */
3034
3035 static int packet_do_bind(struct sock *sk, const char *name, int ifindex,
3036                           __be16 proto)
3037 {
3038         struct packet_sock *po = pkt_sk(sk);
3039         struct net_device *dev_curr;
3040         __be16 proto_curr;
3041         bool need_rehook;
3042         struct net_device *dev = NULL;
3043         int ret = 0;
3044         bool unlisted = false;
3045
3046         if (po->fanout)
3047                 return -EINVAL;
3048
3049         lock_sock(sk);
3050         spin_lock(&po->bind_lock);
3051         rcu_read_lock();
3052
3053         if (name) {
3054                 dev = dev_get_by_name_rcu(sock_net(sk), name);
3055                 if (!dev) {
3056                         ret = -ENODEV;
3057                         goto out_unlock;
3058                 }
3059         } else if (ifindex) {
3060                 dev = dev_get_by_index_rcu(sock_net(sk), ifindex);
3061                 if (!dev) {
3062                         ret = -ENODEV;
3063                         goto out_unlock;
3064                 }
3065         }
3066
3067         if (dev)
3068                 dev_hold(dev);
3069
3070         proto_curr = po->prot_hook.type;
3071         dev_curr = po->prot_hook.dev;
3072
3073         need_rehook = proto_curr != proto || dev_curr != dev;
3074
3075         if (need_rehook) {
3076                 if (po->running) {
3077                         rcu_read_unlock();
3078                         __unregister_prot_hook(sk, true);
3079                         rcu_read_lock();
3080                         dev_curr = po->prot_hook.dev;
3081                         if (dev)
3082                                 unlisted = !dev_get_by_index_rcu(sock_net(sk),
3083                                                                  dev->ifindex);
3084                 }
3085
3086                 po->num = proto;
3087                 po->prot_hook.type = proto;
3088
3089                 if (unlikely(unlisted)) {
3090                         dev_put(dev);
3091                         po->prot_hook.dev = NULL;
3092                         po->ifindex = -1;
3093                         packet_cached_dev_reset(po);
3094                 } else {
3095                         po->prot_hook.dev = dev;
3096                         po->ifindex = dev ? dev->ifindex : 0;
3097                         packet_cached_dev_assign(po, dev);
3098                 }
3099         }
3100         if (dev_curr)
3101                 dev_put(dev_curr);
3102
3103         if (proto == 0 || !need_rehook)
3104                 goto out_unlock;
3105
3106         if (!unlisted && (!dev || (dev->flags & IFF_UP))) {
3107                 register_prot_hook(sk);
3108         } else {
3109                 sk->sk_err = ENETDOWN;
3110                 if (!sock_flag(sk, SOCK_DEAD))
3111                         sk->sk_error_report(sk);
3112         }
3113
3114 out_unlock:
3115         rcu_read_unlock();
3116         spin_unlock(&po->bind_lock);
3117         release_sock(sk);
3118         return ret;
3119 }
3120
3121 /*
3122  *      Bind a packet socket to a device
3123  */
3124
3125 static int packet_bind_spkt(struct socket *sock, struct sockaddr *uaddr,
3126                             int addr_len)
3127 {
3128         struct sock *sk = sock->sk;
3129         char name[15];
3130
3131         /*
3132          *      Check legality
3133          */
3134
3135         if (addr_len != sizeof(struct sockaddr))
3136                 return -EINVAL;
3137         strlcpy(name, uaddr->sa_data, sizeof(name));
3138
3139         return packet_do_bind(sk, name, 0, pkt_sk(sk)->num);
3140 }
3141
3142 static int packet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
3143 {
3144         struct sockaddr_ll *sll = (struct sockaddr_ll *)uaddr;
3145         struct sock *sk = sock->sk;
3146
3147         /*
3148          *      Check legality
3149          */
3150
3151         if (addr_len < sizeof(struct sockaddr_ll))
3152                 return -EINVAL;
3153         if (sll->sll_family != AF_PACKET)
3154                 return -EINVAL;
3155
3156         return packet_do_bind(sk, NULL, sll->sll_ifindex,
3157                               sll->sll_protocol ? : pkt_sk(sk)->num);
3158 }
3159
3160 static struct proto packet_proto = {
3161         .name     = "PACKET",
3162         .owner    = THIS_MODULE,
3163         .obj_size = sizeof(struct packet_sock),
3164 };
3165
3166 /*
3167  *      Create a packet of type SOCK_PACKET.
3168  */
3169
3170 static int packet_create(struct net *net, struct socket *sock, int protocol,
3171                          int kern)
3172 {
3173         struct sock *sk;
3174         struct packet_sock *po;
3175         __be16 proto = (__force __be16)protocol; /* weird, but documented */
3176         int err;
3177
3178         if (!ns_capable(net->user_ns, CAP_NET_RAW))
3179                 return -EPERM;
3180         if (sock->type != SOCK_DGRAM && sock->type != SOCK_RAW &&
3181             sock->type != SOCK_PACKET)
3182                 return -ESOCKTNOSUPPORT;
3183
3184         sock->state = SS_UNCONNECTED;
3185
3186         err = -ENOBUFS;
3187         sk = sk_alloc(net, PF_PACKET, GFP_KERNEL, &packet_proto, kern);
3188         if (sk == NULL)
3189                 goto out;
3190
3191         sock->ops = &packet_ops;
3192         if (sock->type == SOCK_PACKET)
3193                 sock->ops = &packet_ops_spkt;
3194
3195         sock_init_data(sock, sk);
3196
3197         po = pkt_sk(sk);
3198         sk->sk_family = PF_PACKET;
3199         po->num = proto;
3200         po->xmit = dev_queue_xmit;
3201
3202         err = packet_alloc_pending(po);
3203         if (err)
3204                 goto out2;
3205
3206         packet_cached_dev_reset(po);
3207
3208         sk->sk_destruct = packet_sock_destruct;
3209         sk_refcnt_debug_inc(sk);
3210
3211         /*
3212          *      Attach a protocol block
3213          */
3214
3215         spin_lock_init(&po->bind_lock);
3216         mutex_init(&po->pg_vec_lock);
3217         po->rollover = NULL;
3218         po->prot_hook.func = packet_rcv;
3219
3220         if (sock->type == SOCK_PACKET)
3221                 po->prot_hook.func = packet_rcv_spkt;
3222
3223         po->prot_hook.af_packet_priv = sk;
3224
3225         if (proto) {
3226                 po->prot_hook.type = proto;
3227                 register_prot_hook(sk);
3228         }
3229
3230         mutex_lock(&net->packet.sklist_lock);
3231         sk_add_node_rcu(sk, &net->packet.sklist);
3232         mutex_unlock(&net->packet.sklist_lock);
3233
3234         preempt_disable();
3235         sock_prot_inuse_add(net, &packet_proto, 1);
3236         preempt_enable();
3237
3238         return 0;
3239 out2:
3240         sk_free(sk);
3241 out:
3242         return err;
3243 }
3244
3245 /*
3246  *      Pull a packet from our receive queue and hand it to the user.
3247  *      If necessary we block.
3248  */
3249
3250 static int packet_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
3251                           int flags)
3252 {
3253         struct sock *sk = sock->sk;
3254         struct sk_buff *skb;
3255         int copied, err;
3256         int vnet_hdr_len = 0;
3257         unsigned int origlen = 0;
3258
3259         err = -EINVAL;
3260         if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT|MSG_ERRQUEUE))
3261                 goto out;
3262
3263 #if 0
3264         /* What error should we return now? EUNATTACH? */
3265         if (pkt_sk(sk)->ifindex < 0)
3266                 return -ENODEV;
3267 #endif
3268
3269         if (flags & MSG_ERRQUEUE) {
3270                 err = sock_recv_errqueue(sk, msg, len,
3271                                          SOL_PACKET, PACKET_TX_TIMESTAMP);
3272                 goto out;
3273         }
3274
3275         /*
3276          *      Call the generic datagram receiver. This handles all sorts
3277          *      of horrible races and re-entrancy so we can forget about it
3278          *      in the protocol layers.
3279          *
3280          *      Now it will return ENETDOWN, if device have just gone down,
3281          *      but then it will block.
3282          */
3283
3284         skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);
3285
3286         /*
3287          *      An error occurred so return it. Because skb_recv_datagram()
3288          *      handles the blocking we don't see and worry about blocking
3289          *      retries.
3290          */
3291
3292         if (skb == NULL)
3293                 goto out;
3294
3295         if (pkt_sk(sk)->pressure)
3296                 packet_rcv_has_room(pkt_sk(sk), NULL);
3297
3298         if (pkt_sk(sk)->has_vnet_hdr) {
3299                 err = packet_rcv_vnet(msg, skb, &len);
3300                 if (err)
3301                         goto out_free;
3302                 vnet_hdr_len = sizeof(struct virtio_net_hdr);
3303         }
3304
3305         /* You lose any data beyond the buffer you gave. If it worries
3306          * a user program they can ask the device for its MTU
3307          * anyway.
3308          */
3309         copied = skb->len;
3310         if (copied > len) {
3311                 copied = len;
3312                 msg->msg_flags |= MSG_TRUNC;
3313         }
3314
3315         err = skb_copy_datagram_msg(skb, 0, msg, copied);
3316         if (err)
3317                 goto out_free;
3318
3319         if (sock->type != SOCK_PACKET) {
3320                 struct sockaddr_ll *sll = &PACKET_SKB_CB(skb)->sa.ll;
3321
3322                 /* Original length was stored in sockaddr_ll fields */
3323                 origlen = PACKET_SKB_CB(skb)->sa.origlen;
3324                 sll->sll_family = AF_PACKET;
3325                 sll->sll_protocol = skb->protocol;
3326         }
3327
3328         sock_recv_ts_and_drops(msg, sk, skb);
3329
3330         if (msg->msg_name) {
3331                 /* If the address length field is there to be filled
3332                  * in, we fill it in now.
3333                  */
3334                 if (sock->type == SOCK_PACKET) {
3335                         __sockaddr_check_size(sizeof(struct sockaddr_pkt));
3336                         msg->msg_namelen = sizeof(struct sockaddr_pkt);
3337                 } else {
3338                         struct sockaddr_ll *sll = &PACKET_SKB_CB(skb)->sa.ll;
3339
3340                         msg->msg_namelen = sll->sll_halen +
3341                                 offsetof(struct sockaddr_ll, sll_addr);
3342                 }
3343                 memcpy(msg->msg_name, &PACKET_SKB_CB(skb)->sa,
3344                        msg->msg_namelen);
3345         }
3346
3347         if (pkt_sk(sk)->auxdata) {
3348                 struct tpacket_auxdata aux;
3349
3350                 aux.tp_status = TP_STATUS_USER;
3351                 if (skb->ip_summed == CHECKSUM_PARTIAL)
3352                         aux.tp_status |= TP_STATUS_CSUMNOTREADY;
3353                 else if (skb->pkt_type != PACKET_OUTGOING &&
3354                          (skb->ip_summed == CHECKSUM_COMPLETE ||
3355                           skb_csum_unnecessary(skb)))
3356                         aux.tp_status |= TP_STATUS_CSUM_VALID;
3357
3358                 aux.tp_len = origlen;
3359                 aux.tp_snaplen = skb->len;
3360                 aux.tp_mac = 0;
3361                 aux.tp_net = skb_network_offset(skb);
3362                 if (skb_vlan_tag_present(skb)) {
3363                         aux.tp_vlan_tci = skb_vlan_tag_get(skb);
3364                         aux.tp_vlan_tpid = ntohs(skb->vlan_proto);
3365                         aux.tp_status |= TP_STATUS_VLAN_VALID | TP_STATUS_VLAN_TPID_VALID;
3366                 } else {
3367                         aux.tp_vlan_tci = 0;
3368                         aux.tp_vlan_tpid = 0;
3369                 }
3370                 put_cmsg(msg, SOL_PACKET, PACKET_AUXDATA, sizeof(aux), &aux);
3371         }
3372
3373         /*
3374          *      Free or return the buffer as appropriate. Again this
3375          *      hides all the races and re-entrancy issues from us.
3376          */
3377         err = vnet_hdr_len + ((flags&MSG_TRUNC) ? skb->len : copied);
3378
3379 out_free:
3380         skb_free_datagram(sk, skb);
3381 out:
3382         return err;
3383 }
3384
3385 static int packet_getname_spkt(struct socket *sock, struct sockaddr *uaddr,
3386                                int *uaddr_len, int peer)
3387 {
3388         struct net_device *dev;
3389         struct sock *sk = sock->sk;
3390
3391         if (peer)
3392                 return -EOPNOTSUPP;
3393
3394         uaddr->sa_family = AF_PACKET;
3395         memset(uaddr->sa_data, 0, sizeof(uaddr->sa_data));
3396         rcu_read_lock();
3397         dev = dev_get_by_index_rcu(sock_net(sk), pkt_sk(sk)->ifindex);
3398         if (dev)
3399                 strlcpy(uaddr->sa_data, dev->name, sizeof(uaddr->sa_data));
3400         rcu_read_unlock();
3401         *uaddr_len = sizeof(*uaddr);
3402
3403         return 0;
3404 }
3405
3406 static int packet_getname(struct socket *sock, struct sockaddr *uaddr,
3407                           int *uaddr_len, int peer)
3408 {
3409         struct net_device *dev;
3410         struct sock *sk = sock->sk;
3411         struct packet_sock *po = pkt_sk(sk);
3412         DECLARE_SOCKADDR(struct sockaddr_ll *, sll, uaddr);
3413
3414         if (peer)
3415                 return -EOPNOTSUPP;
3416
3417         sll->sll_family = AF_PACKET;
3418         sll->sll_ifindex = po->ifindex;
3419         sll->sll_protocol = po->num;
3420         sll->sll_pkttype = 0;
3421         rcu_read_lock();
3422         dev = dev_get_by_index_rcu(sock_net(sk), po->ifindex);
3423         if (dev) {
3424                 sll->sll_hatype = dev->type;
3425                 sll->sll_halen = dev->addr_len;
3426                 memcpy(sll->sll_addr, dev->dev_addr, dev->addr_len);
3427         } else {
3428                 sll->sll_hatype = 0;    /* Bad: we have no ARPHRD_UNSPEC */
3429                 sll->sll_halen = 0;
3430         }
3431         rcu_read_unlock();
3432         *uaddr_len = offsetof(struct sockaddr_ll, sll_addr) + sll->sll_halen;
3433
3434         return 0;
3435 }
3436
3437 static int packet_dev_mc(struct net_device *dev, struct packet_mclist *i,
3438                          int what)
3439 {
3440         switch (i->type) {
3441         case PACKET_MR_MULTICAST:
3442                 if (i->alen != dev->addr_len)
3443                         return -EINVAL;
3444                 if (what > 0)
3445                         return dev_mc_add(dev, i->addr);
3446                 else
3447                         return dev_mc_del(dev, i->addr);
3448                 break;
3449         case PACKET_MR_PROMISC:
3450                 return dev_set_promiscuity(dev, what);
3451         case PACKET_MR_ALLMULTI:
3452                 return dev_set_allmulti(dev, what);
3453         case PACKET_MR_UNICAST:
3454                 if (i->alen != dev->addr_len)
3455                         return -EINVAL;
3456                 if (what > 0)
3457                         return dev_uc_add(dev, i->addr);
3458                 else
3459                         return dev_uc_del(dev, i->addr);
3460                 break;
3461         default:
3462                 break;
3463         }
3464         return 0;
3465 }
3466
3467 static void packet_dev_mclist_delete(struct net_device *dev,
3468                                      struct packet_mclist **mlp)
3469 {
3470         struct packet_mclist *ml;
3471
3472         while ((ml = *mlp) != NULL) {
3473                 if (ml->ifindex == dev->ifindex) {
3474                         packet_dev_mc(dev, ml, -1);
3475                         *mlp = ml->next;
3476                         kfree(ml);
3477                 } else
3478                         mlp = &ml->next;
3479         }
3480 }
3481
3482 static int packet_mc_add(struct sock *sk, struct packet_mreq_max *mreq)
3483 {
3484         struct packet_sock *po = pkt_sk(sk);
3485         struct packet_mclist *ml, *i;
3486         struct net_device *dev;
3487         int err;
3488
3489         rtnl_lock();
3490
3491         err = -ENODEV;
3492         dev = __dev_get_by_index(sock_net(sk), mreq->mr_ifindex);
3493         if (!dev)
3494                 goto done;
3495
3496         err = -EINVAL;
3497         if (mreq->mr_alen > dev->addr_len)
3498                 goto done;
3499
3500         err = -ENOBUFS;
3501         i = kmalloc(sizeof(*i), GFP_KERNEL);
3502         if (i == NULL)
3503                 goto done;
3504
3505         err = 0;
3506         for (ml = po->mclist; ml; ml = ml->next) {
3507                 if (ml->ifindex == mreq->mr_ifindex &&
3508                     ml->type == mreq->mr_type &&
3509                     ml->alen == mreq->mr_alen &&
3510                     memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
3511                         ml->count++;
3512                         /* Free the new element ... */
3513                         kfree(i);
3514                         goto done;
3515                 }
3516         }
3517
3518         i->type = mreq->mr_type;
3519         i->ifindex = mreq->mr_ifindex;
3520         i->alen = mreq->mr_alen;
3521         memcpy(i->addr, mreq->mr_address, i->alen);
3522         memset(i->addr + i->alen, 0, sizeof(i->addr) - i->alen);
3523         i->count = 1;
3524         i->next = po->mclist;
3525         po->mclist = i;
3526         err = packet_dev_mc(dev, i, 1);
3527         if (err) {
3528                 po->mclist = i->next;
3529                 kfree(i);
3530         }
3531
3532 done:
3533         rtnl_unlock();
3534         return err;
3535 }
3536
3537 static int packet_mc_drop(struct sock *sk, struct packet_mreq_max *mreq)
3538 {
3539         struct packet_mclist *ml, **mlp;
3540
3541         rtnl_lock();
3542
3543         for (mlp = &pkt_sk(sk)->mclist; (ml = *mlp) != NULL; mlp = &ml->next) {
3544                 if (ml->ifindex == mreq->mr_ifindex &&
3545                     ml->type == mreq->mr_type &&
3546                     ml->alen == mreq->mr_alen &&
3547                     memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
3548                         if (--ml->count == 0) {
3549                                 struct net_device *dev;
3550                                 *mlp = ml->next;
3551                                 dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
3552                                 if (dev)
3553                                         packet_dev_mc(dev, ml, -1);
3554                                 kfree(ml);
3555                         }
3556                         break;
3557                 }
3558         }
3559         rtnl_unlock();
3560         return 0;
3561 }
3562
3563 static void packet_flush_mclist(struct sock *sk)
3564 {
3565         struct packet_sock *po = pkt_sk(sk);
3566         struct packet_mclist *ml;
3567
3568         if (!po->mclist)
3569                 return;
3570
3571         rtnl_lock();
3572         while ((ml = po->mclist) != NULL) {
3573                 struct net_device *dev;
3574
3575                 po->mclist = ml->next;
3576                 dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
3577                 if (dev != NULL)
3578                         packet_dev_mc(dev, ml, -1);
3579                 kfree(ml);
3580         }
3581         rtnl_unlock();
3582 }
3583
3584 static int
3585 packet_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen)
3586 {
3587         struct sock *sk = sock->sk;
3588         struct packet_sock *po = pkt_sk(sk);
3589         int ret;
3590
3591         if (level != SOL_PACKET)
3592                 return -ENOPROTOOPT;
3593
3594         switch (optname) {
3595         case PACKET_ADD_MEMBERSHIP:
3596         case PACKET_DROP_MEMBERSHIP:
3597         {
3598                 struct packet_mreq_max mreq;
3599                 int len = optlen;
3600                 memset(&mreq, 0, sizeof(mreq));
3601                 if (len < sizeof(struct packet_mreq))
3602                         return -EINVAL;
3603                 if (len > sizeof(mreq))
3604                         len = sizeof(mreq);
3605                 if (copy_from_user(&mreq, optval, len))
3606                         return -EFAULT;
3607                 if (len < (mreq.mr_alen + offsetof(struct packet_mreq, mr_address)))
3608                         return -EINVAL;
3609                 if (optname == PACKET_ADD_MEMBERSHIP)
3610                         ret = packet_mc_add(sk, &mreq);
3611                 else
3612                         ret = packet_mc_drop(sk, &mreq);
3613                 return ret;
3614         }
3615
3616         case PACKET_RX_RING:
3617         case PACKET_TX_RING:
3618         {
3619                 union tpacket_req_u req_u;
3620                 int len;
3621
3622                 switch (po->tp_version) {
3623                 case TPACKET_V1:
3624                 case TPACKET_V2:
3625                         len = sizeof(req_u.req);
3626                         break;
3627                 case TPACKET_V3:
3628                 default:
3629                         len = sizeof(req_u.req3);
3630                         break;
3631                 }
3632                 if (optlen < len)
3633                         return -EINVAL;
3634                 if (copy_from_user(&req_u.req, optval, len))
3635                         return -EFAULT;
3636                 return packet_set_ring(sk, &req_u, 0,
3637                         optname == PACKET_TX_RING);
3638         }
3639         case PACKET_COPY_THRESH:
3640         {
3641                 int val;
3642
3643                 if (optlen != sizeof(val))
3644                         return -EINVAL;
3645                 if (copy_from_user(&val, optval, sizeof(val)))
3646                         return -EFAULT;
3647
3648                 pkt_sk(sk)->copy_thresh = val;
3649                 return 0;
3650         }
3651         case PACKET_VERSION:
3652         {
3653                 int val;
3654
3655                 if (optlen != sizeof(val))
3656                         return -EINVAL;
3657                 if (copy_from_user(&val, optval, sizeof(val)))
3658                         return -EFAULT;
3659                 switch (val) {
3660                 case TPACKET_V1:
3661                 case TPACKET_V2:
3662                 case TPACKET_V3:
3663                         break;
3664                 default:
3665                         return -EINVAL;
3666                 }
3667                 lock_sock(sk);
3668                 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec) {
3669                         ret = -EBUSY;
3670                 } else {
3671                         po->tp_version = val;
3672                         ret = 0;
3673                 }
3674                 release_sock(sk);
3675                 return ret;
3676         }
3677         case PACKET_RESERVE:
3678         {
3679                 unsigned int val;
3680
3681                 if (optlen != sizeof(val))
3682                         return -EINVAL;
3683                 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3684                         return -EBUSY;
3685                 if (copy_from_user(&val, optval, sizeof(val)))
3686                         return -EFAULT;
3687                 po->tp_reserve = val;
3688                 return 0;
3689         }
3690         case PACKET_LOSS:
3691         {
3692                 unsigned int val;
3693
3694                 if (optlen != sizeof(val))
3695                         return -EINVAL;
3696                 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3697                         return -EBUSY;
3698                 if (copy_from_user(&val, optval, sizeof(val)))
3699                         return -EFAULT;
3700                 po->tp_loss = !!val;
3701                 return 0;
3702         }
3703         case PACKET_AUXDATA:
3704         {
3705                 int val;
3706
3707                 if (optlen < sizeof(val))
3708                         return -EINVAL;
3709                 if (copy_from_user(&val, optval, sizeof(val)))
3710                         return -EFAULT;
3711
3712                 po->auxdata = !!val;
3713                 return 0;
3714         }
3715         case PACKET_ORIGDEV:
3716         {
3717                 int val;
3718
3719                 if (optlen < sizeof(val))
3720                         return -EINVAL;
3721                 if (copy_from_user(&val, optval, sizeof(val)))
3722                         return -EFAULT;
3723
3724                 po->origdev = !!val;
3725                 return 0;
3726         }
3727         case PACKET_VNET_HDR:
3728         {
3729                 int val;
3730
3731                 if (sock->type != SOCK_RAW)
3732                         return -EINVAL;
3733                 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3734                         return -EBUSY;
3735                 if (optlen < sizeof(val))
3736                         return -EINVAL;
3737                 if (copy_from_user(&val, optval, sizeof(val)))
3738                         return -EFAULT;
3739
3740                 po->has_vnet_hdr = !!val;
3741                 return 0;
3742         }
3743         case PACKET_TIMESTAMP:
3744         {
3745                 int val;
3746
3747                 if (optlen != sizeof(val))
3748                         return -EINVAL;
3749                 if (copy_from_user(&val, optval, sizeof(val)))
3750                         return -EFAULT;
3751
3752                 po->tp_tstamp = val;
3753                 return 0;
3754         }
3755         case PACKET_FANOUT:
3756         {
3757                 int val;
3758
3759                 if (optlen != sizeof(val))
3760                         return -EINVAL;
3761                 if (copy_from_user(&val, optval, sizeof(val)))
3762                         return -EFAULT;
3763
3764                 return fanout_add(sk, val & 0xffff, val >> 16);
3765         }
3766         case PACKET_FANOUT_DATA:
3767         {
3768                 if (!po->fanout)
3769                         return -EINVAL;
3770
3771                 return fanout_set_data(po, optval, optlen);
3772         }
3773         case PACKET_TX_HAS_OFF:
3774         {
3775                 unsigned int val;
3776
3777                 if (optlen != sizeof(val))
3778                         return -EINVAL;
3779                 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
3780                         return -EBUSY;
3781                 if (copy_from_user(&val, optval, sizeof(val)))
3782                         return -EFAULT;
3783                 po->tp_tx_has_off = !!val;
3784                 return 0;
3785         }
3786         case PACKET_QDISC_BYPASS:
3787         {
3788                 int val;
3789
3790                 if (optlen != sizeof(val))
3791                         return -EINVAL;
3792                 if (copy_from_user(&val, optval, sizeof(val)))
3793                         return -EFAULT;
3794
3795                 po->xmit = val ? packet_direct_xmit : dev_queue_xmit;
3796                 return 0;
3797         }
3798         default:
3799                 return -ENOPROTOOPT;
3800         }
3801 }
3802
3803 static int packet_getsockopt(struct socket *sock, int level, int optname,
3804                              char __user *optval, int __user *optlen)
3805 {
3806         int len;
3807         int val, lv = sizeof(val);
3808         struct sock *sk = sock->sk;
3809         struct packet_sock *po = pkt_sk(sk);
3810         void *data = &val;
3811         union tpacket_stats_u st;
3812         struct tpacket_rollover_stats rstats;
3813
3814         if (level != SOL_PACKET)
3815                 return -ENOPROTOOPT;
3816
3817         if (get_user(len, optlen))
3818                 return -EFAULT;
3819
3820         if (len < 0)
3821                 return -EINVAL;
3822
3823         switch (optname) {
3824         case PACKET_STATISTICS:
3825                 spin_lock_bh(&sk->sk_receive_queue.lock);
3826                 memcpy(&st, &po->stats, sizeof(st));
3827                 memset(&po->stats, 0, sizeof(po->stats));
3828                 spin_unlock_bh(&sk->sk_receive_queue.lock);
3829
3830                 if (po->tp_version == TPACKET_V3) {
3831                         lv = sizeof(struct tpacket_stats_v3);
3832                         st.stats3.tp_packets += st.stats3.tp_drops;
3833                         data = &st.stats3;
3834                 } else {
3835                         lv = sizeof(struct tpacket_stats);
3836                         st.stats1.tp_packets += st.stats1.tp_drops;
3837                         data = &st.stats1;
3838                 }
3839
3840                 break;
3841         case PACKET_AUXDATA:
3842                 val = po->auxdata;
3843                 break;
3844         case PACKET_ORIGDEV:
3845                 val = po->origdev;
3846                 break;
3847         case PACKET_VNET_HDR:
3848                 val = po->has_vnet_hdr;
3849                 break;
3850         case PACKET_VERSION:
3851                 val = po->tp_version;
3852                 break;
3853         case PACKET_HDRLEN:
3854                 if (len > sizeof(int))
3855                         len = sizeof(int);
3856                 if (copy_from_user(&val, optval, len))
3857                         return -EFAULT;
3858                 switch (val) {
3859                 case TPACKET_V1:
3860                         val = sizeof(struct tpacket_hdr);
3861                         break;
3862                 case TPACKET_V2:
3863                         val = sizeof(struct tpacket2_hdr);
3864                         break;
3865                 case TPACKET_V3:
3866                         val = sizeof(struct tpacket3_hdr);
3867                         break;
3868                 default:
3869                         return -EINVAL;
3870                 }
3871                 break;
3872         case PACKET_RESERVE:
3873                 val = po->tp_reserve;
3874                 break;
3875         case PACKET_LOSS:
3876                 val = po->tp_loss;
3877                 break;
3878         case PACKET_TIMESTAMP:
3879                 val = po->tp_tstamp;
3880                 break;
3881         case PACKET_FANOUT:
3882                 val = (po->fanout ?
3883                        ((u32)po->fanout->id |
3884                         ((u32)po->fanout->type << 16) |
3885                         ((u32)po->fanout->flags << 24)) :
3886                        0);
3887                 break;
3888         case PACKET_ROLLOVER_STATS:
3889                 if (!po->rollover)
3890                         return -EINVAL;
3891                 rstats.tp_all = atomic_long_read(&po->rollover->num);
3892                 rstats.tp_huge = atomic_long_read(&po->rollover->num_huge);
3893                 rstats.tp_failed = atomic_long_read(&po->rollover->num_failed);
3894                 data = &rstats;
3895                 lv = sizeof(rstats);
3896                 break;
3897         case PACKET_TX_HAS_OFF:
3898                 val = po->tp_tx_has_off;
3899                 break;
3900         case PACKET_QDISC_BYPASS:
3901                 val = packet_use_direct_xmit(po);
3902                 break;
3903         default:
3904                 return -ENOPROTOOPT;
3905         }
3906
3907         if (len > lv)
3908                 len = lv;
3909         if (put_user(len, optlen))
3910                 return -EFAULT;
3911         if (copy_to_user(optval, data, len))
3912                 return -EFAULT;
3913         return 0;
3914 }
3915
3916
3917 #ifdef CONFIG_COMPAT
3918 static int compat_packet_setsockopt(struct socket *sock, int level, int optname,
3919                                     char __user *optval, unsigned int optlen)
3920 {
3921         struct packet_sock *po = pkt_sk(sock->sk);
3922
3923         if (level != SOL_PACKET)
3924                 return -ENOPROTOOPT;
3925
3926         if (optname == PACKET_FANOUT_DATA &&
3927             po->fanout && po->fanout->type == PACKET_FANOUT_CBPF) {
3928                 optval = (char __user *)get_compat_bpf_fprog(optval);
3929                 if (!optval)
3930                         return -EFAULT;
3931                 optlen = sizeof(struct sock_fprog);
3932         }
3933
3934         return packet_setsockopt(sock, level, optname, optval, optlen);
3935 }
3936 #endif
3937
3938 static int packet_notifier(struct notifier_block *this,
3939                            unsigned long msg, void *ptr)
3940 {
3941         struct sock *sk;
3942         struct net_device *dev = netdev_notifier_info_to_dev(ptr);
3943         struct net *net = dev_net(dev);
3944
3945         rcu_read_lock();
3946         sk_for_each_rcu(sk, &net->packet.sklist) {
3947                 struct packet_sock *po = pkt_sk(sk);
3948
3949                 switch (msg) {
3950                 case NETDEV_UNREGISTER:
3951                         if (po->mclist)
3952                                 packet_dev_mclist_delete(dev, &po->mclist);
3953                         /* fallthrough */
3954
3955                 case NETDEV_DOWN:
3956                         if (dev->ifindex == po->ifindex) {
3957                                 spin_lock(&po->bind_lock);
3958                                 if (po->running) {
3959                                         __unregister_prot_hook(sk, false);
3960                                         sk->sk_err = ENETDOWN;
3961                                         if (!sock_flag(sk, SOCK_DEAD))
3962                                                 sk->sk_error_report(sk);
3963                                 }
3964                                 if (msg == NETDEV_UNREGISTER) {
3965                                         packet_cached_dev_reset(po);
3966                                         fanout_release(sk);
3967                                         po->ifindex = -1;
3968                                         if (po->prot_hook.dev)
3969                                                 dev_put(po->prot_hook.dev);
3970                                         po->prot_hook.dev = NULL;
3971                                 }
3972                                 spin_unlock(&po->bind_lock);
3973                         }
3974                         break;
3975                 case NETDEV_UP:
3976                         if (dev->ifindex == po->ifindex) {
3977                                 spin_lock(&po->bind_lock);
3978                                 if (po->num)
3979                                         register_prot_hook(sk);
3980                                 spin_unlock(&po->bind_lock);
3981                         }
3982                         break;
3983                 }
3984         }
3985         rcu_read_unlock();
3986         return NOTIFY_DONE;
3987 }
3988
3989
3990 static int packet_ioctl(struct socket *sock, unsigned int cmd,
3991                         unsigned long arg)
3992 {
3993         struct sock *sk = sock->sk;
3994
3995         switch (cmd) {
3996         case SIOCOUTQ:
3997         {
3998                 int amount = sk_wmem_alloc_get(sk);
3999
4000                 return put_user(amount, (int __user *)arg);
4001         }
4002         case SIOCINQ:
4003         {
4004                 struct sk_buff *skb;
4005                 int amount = 0;
4006
4007                 spin_lock_bh(&sk->sk_receive_queue.lock);
4008                 skb = skb_peek(&sk->sk_receive_queue);
4009                 if (skb)
4010                         amount = skb->len;
4011                 spin_unlock_bh(&sk->sk_receive_queue.lock);
4012                 return put_user(amount, (int __user *)arg);
4013         }
4014         case SIOCGSTAMP:
4015                 return sock_get_timestamp(sk, (struct timeval __user *)arg);
4016         case SIOCGSTAMPNS:
4017                 return sock_get_timestampns(sk, (struct timespec __user *)arg);
4018
4019 #ifdef CONFIG_INET
4020         case SIOCADDRT:
4021         case SIOCDELRT:
4022         case SIOCDARP:
4023         case SIOCGARP:
4024         case SIOCSARP:
4025         case SIOCGIFADDR:
4026         case SIOCSIFADDR:
4027         case SIOCGIFBRDADDR:
4028         case SIOCSIFBRDADDR:
4029         case SIOCGIFNETMASK:
4030         case SIOCSIFNETMASK:
4031         case SIOCGIFDSTADDR:
4032         case SIOCSIFDSTADDR:
4033         case SIOCSIFFLAGS:
4034                 return inet_dgram_ops.ioctl(sock, cmd, arg);
4035 #endif
4036
4037         default:
4038                 return -ENOIOCTLCMD;
4039         }
4040         return 0;
4041 }
4042
4043 static unsigned int packet_poll(struct file *file, struct socket *sock,
4044                                 poll_table *wait)
4045 {
4046         struct sock *sk = sock->sk;
4047         struct packet_sock *po = pkt_sk(sk);
4048         unsigned int mask = datagram_poll(file, sock, wait);
4049
4050         spin_lock_bh(&sk->sk_receive_queue.lock);
4051         if (po->rx_ring.pg_vec) {
4052                 if (!packet_previous_rx_frame(po, &po->rx_ring,
4053                         TP_STATUS_KERNEL))
4054                         mask |= POLLIN | POLLRDNORM;
4055         }
4056         if (po->pressure && __packet_rcv_has_room(po, NULL) == ROOM_NORMAL)
4057                 po->pressure = 0;
4058         spin_unlock_bh(&sk->sk_receive_queue.lock);
4059         spin_lock_bh(&sk->sk_write_queue.lock);
4060         if (po->tx_ring.pg_vec) {
4061                 if (packet_current_frame(po, &po->tx_ring, TP_STATUS_AVAILABLE))
4062                         mask |= POLLOUT | POLLWRNORM;
4063         }
4064         spin_unlock_bh(&sk->sk_write_queue.lock);
4065         return mask;
4066 }
4067
4068
4069 /* Dirty? Well, I still did not learn better way to account
4070  * for user mmaps.
4071  */
4072
4073 static void packet_mm_open(struct vm_area_struct *vma)
4074 {
4075         struct file *file = vma->vm_file;
4076         struct socket *sock = file->private_data;
4077         struct sock *sk = sock->sk;
4078
4079         if (sk)
4080                 atomic_inc(&pkt_sk(sk)->mapped);
4081 }
4082
4083 static void packet_mm_close(struct vm_area_struct *vma)
4084 {
4085         struct file *file = vma->vm_file;
4086         struct socket *sock = file->private_data;
4087         struct sock *sk = sock->sk;
4088
4089         if (sk)
4090                 atomic_dec(&pkt_sk(sk)->mapped);
4091 }
4092
4093 static const struct vm_operations_struct packet_mmap_ops = {
4094         .open   =       packet_mm_open,
4095         .close  =       packet_mm_close,
4096 };
4097
4098 static void free_pg_vec(struct pgv *pg_vec, unsigned int order,
4099                         unsigned int len)
4100 {
4101         int i;
4102
4103         for (i = 0; i < len; i++) {
4104                 if (likely(pg_vec[i].buffer)) {
4105                         if (is_vmalloc_addr(pg_vec[i].buffer))
4106                                 vfree(pg_vec[i].buffer);
4107                         else
4108                                 free_pages((unsigned long)pg_vec[i].buffer,
4109                                            order);
4110                         pg_vec[i].buffer = NULL;
4111                 }
4112         }
4113         kfree(pg_vec);
4114 }
4115
4116 static char *alloc_one_pg_vec_page(unsigned long order)
4117 {
4118         char *buffer;
4119         gfp_t gfp_flags = GFP_KERNEL | __GFP_COMP |
4120                           __GFP_ZERO | __GFP_NOWARN | __GFP_NORETRY;
4121
4122         buffer = (char *) __get_free_pages(gfp_flags, order);
4123         if (buffer)
4124                 return buffer;
4125
4126         /* __get_free_pages failed, fall back to vmalloc */
4127         buffer = vzalloc((1 << order) * PAGE_SIZE);
4128         if (buffer)
4129                 return buffer;
4130
4131         /* vmalloc failed, lets dig into swap here */
4132         gfp_flags &= ~__GFP_NORETRY;
4133         buffer = (char *) __get_free_pages(gfp_flags, order);
4134         if (buffer)
4135                 return buffer;
4136
4137         /* complete and utter failure */
4138         return NULL;
4139 }
4140
4141 static struct pgv *alloc_pg_vec(struct tpacket_req *req, int order)
4142 {
4143         unsigned int block_nr = req->tp_block_nr;
4144         struct pgv *pg_vec;
4145         int i;
4146
4147         pg_vec = kcalloc(block_nr, sizeof(struct pgv), GFP_KERNEL);
4148         if (unlikely(!pg_vec))
4149                 goto out;
4150
4151         for (i = 0; i < block_nr; i++) {
4152                 pg_vec[i].buffer = alloc_one_pg_vec_page(order);
4153                 if (unlikely(!pg_vec[i].buffer))
4154                         goto out_free_pgvec;
4155         }
4156
4157 out:
4158         return pg_vec;
4159
4160 out_free_pgvec:
4161         free_pg_vec(pg_vec, order, block_nr);
4162         pg_vec = NULL;
4163         goto out;
4164 }
4165
4166 static int packet_set_ring(struct sock *sk, union tpacket_req_u *req_u,
4167                 int closing, int tx_ring)
4168 {
4169         struct pgv *pg_vec = NULL;
4170         struct packet_sock *po = pkt_sk(sk);
4171         int was_running, order = 0;
4172         struct packet_ring_buffer *rb;
4173         struct sk_buff_head *rb_queue;
4174         __be16 num;
4175         int err = -EINVAL;
4176         /* Added to avoid minimal code churn */
4177         struct tpacket_req *req = &req_u->req;
4178
4179         lock_sock(sk);
4180         /* Opening a Tx-ring is NOT supported in TPACKET_V3 */
4181         if (!closing && tx_ring && (po->tp_version > TPACKET_V2)) {
4182                 net_warn_ratelimited("Tx-ring is not supported.\n");
4183                 goto out;
4184         }
4185
4186         rb = tx_ring ? &po->tx_ring : &po->rx_ring;
4187         rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue;
4188
4189         err = -EBUSY;
4190         if (!closing) {
4191                 if (atomic_read(&po->mapped))
4192                         goto out;
4193                 if (packet_read_pending(rb))
4194                         goto out;
4195         }
4196
4197         if (req->tp_block_nr) {
4198                 /* Sanity tests and some calculations */
4199                 err = -EBUSY;
4200                 if (unlikely(rb->pg_vec))
4201                         goto out;
4202
4203                 switch (po->tp_version) {
4204                 case TPACKET_V1:
4205                         po->tp_hdrlen = TPACKET_HDRLEN;
4206                         break;
4207                 case TPACKET_V2:
4208                         po->tp_hdrlen = TPACKET2_HDRLEN;
4209                         break;
4210                 case TPACKET_V3:
4211                         po->tp_hdrlen = TPACKET3_HDRLEN;
4212                         break;
4213                 }
4214
4215                 err = -EINVAL;
4216                 if (unlikely((int)req->tp_block_size <= 0))
4217                         goto out;
4218                 if (unlikely(!PAGE_ALIGNED(req->tp_block_size)))
4219                         goto out;
4220                 if (po->tp_version >= TPACKET_V3 &&
4221                     (int)(req->tp_block_size -
4222                           BLK_PLUS_PRIV(req_u->req3.tp_sizeof_priv)) <= 0)
4223                         goto out;
4224                 if (unlikely(req->tp_frame_size < po->tp_hdrlen +
4225                                         po->tp_reserve))
4226                         goto out;
4227                 if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1)))
4228                         goto out;
4229
4230                 rb->frames_per_block = req->tp_block_size / req->tp_frame_size;
4231                 if (unlikely(rb->frames_per_block == 0))
4232                         goto out;
4233                 if (unlikely((rb->frames_per_block * req->tp_block_nr) !=
4234                                         req->tp_frame_nr))
4235                         goto out;
4236
4237                 err = -ENOMEM;
4238                 order = get_order(req->tp_block_size);
4239                 pg_vec = alloc_pg_vec(req, order);
4240                 if (unlikely(!pg_vec))
4241                         goto out;
4242                 switch (po->tp_version) {
4243                 case TPACKET_V3:
4244                 /* Transmit path is not supported. We checked
4245                  * it above but just being paranoid
4246                  */
4247                         if (!tx_ring)
4248                                 init_prb_bdqc(po, rb, pg_vec, req_u);
4249                         break;
4250                 default:
4251                         break;
4252                 }
4253         }
4254         /* Done */
4255         else {
4256                 err = -EINVAL;
4257                 if (unlikely(req->tp_frame_nr))
4258                         goto out;
4259         }
4260
4261
4262         /* Detach socket from network */
4263         spin_lock(&po->bind_lock);
4264         was_running = po->running;
4265         num = po->num;
4266         if (was_running) {
4267                 po->num = 0;
4268                 __unregister_prot_hook(sk, false);
4269         }
4270         spin_unlock(&po->bind_lock);
4271
4272         synchronize_net();
4273
4274         err = -EBUSY;
4275         mutex_lock(&po->pg_vec_lock);
4276         if (closing || atomic_read(&po->mapped) == 0) {
4277                 err = 0;
4278                 spin_lock_bh(&rb_queue->lock);
4279                 swap(rb->pg_vec, pg_vec);
4280                 rb->frame_max = (req->tp_frame_nr - 1);
4281                 rb->head = 0;
4282                 rb->frame_size = req->tp_frame_size;
4283                 spin_unlock_bh(&rb_queue->lock);
4284
4285                 swap(rb->pg_vec_order, order);
4286                 swap(rb->pg_vec_len, req->tp_block_nr);
4287
4288                 rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE;
4289                 po->prot_hook.func = (po->rx_ring.pg_vec) ?
4290                                                 tpacket_rcv : packet_rcv;
4291                 skb_queue_purge(rb_queue);
4292                 if (atomic_read(&po->mapped))
4293                         pr_err("packet_mmap: vma is busy: %d\n",
4294                                atomic_read(&po->mapped));
4295         }
4296         mutex_unlock(&po->pg_vec_lock);
4297
4298         spin_lock(&po->bind_lock);
4299         if (was_running) {
4300                 po->num = num;
4301                 register_prot_hook(sk);
4302         }
4303         spin_unlock(&po->bind_lock);
4304         if (closing && (po->tp_version > TPACKET_V2)) {
4305                 /* Because we don't support block-based V3 on tx-ring */
4306                 if (!tx_ring)
4307                         prb_shutdown_retire_blk_timer(po, rb_queue);
4308         }
4309
4310         if (pg_vec)
4311                 free_pg_vec(pg_vec, order, req->tp_block_nr);
4312 out:
4313         release_sock(sk);
4314         return err;
4315 }
4316
4317 static int packet_mmap(struct file *file, struct socket *sock,
4318                 struct vm_area_struct *vma)
4319 {
4320         struct sock *sk = sock->sk;
4321         struct packet_sock *po = pkt_sk(sk);
4322         unsigned long size, expected_size;
4323         struct packet_ring_buffer *rb;
4324         unsigned long start;
4325         int err = -EINVAL;
4326         int i;
4327
4328         if (vma->vm_pgoff)
4329                 return -EINVAL;
4330
4331         mutex_lock(&po->pg_vec_lock);
4332
4333         expected_size = 0;
4334         for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
4335                 if (rb->pg_vec) {
4336                         expected_size += rb->pg_vec_len
4337                                                 * rb->pg_vec_pages
4338                                                 * PAGE_SIZE;
4339                 }
4340         }
4341
4342         if (expected_size == 0)
4343                 goto out;
4344
4345         size = vma->vm_end - vma->vm_start;
4346         if (size != expected_size)
4347                 goto out;
4348
4349         start = vma->vm_start;
4350         for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
4351                 if (rb->pg_vec == NULL)
4352                         continue;
4353
4354                 for (i = 0; i < rb->pg_vec_len; i++) {
4355                         struct page *page;
4356                         void *kaddr = rb->pg_vec[i].buffer;
4357                         int pg_num;
4358
4359                         for (pg_num = 0; pg_num < rb->pg_vec_pages; pg_num++) {
4360                                 page = pgv_to_page(kaddr);
4361                                 err = vm_insert_page(vma, start, page);
4362                                 if (unlikely(err))
4363                                         goto out;
4364                                 start += PAGE_SIZE;
4365                                 kaddr += PAGE_SIZE;
4366                         }
4367                 }
4368         }
4369
4370         atomic_inc(&po->mapped);
4371         vma->vm_ops = &packet_mmap_ops;
4372         err = 0;
4373
4374 out:
4375         mutex_unlock(&po->pg_vec_lock);
4376         return err;
4377 }
4378
4379 static const struct proto_ops packet_ops_spkt = {
4380         .family =       PF_PACKET,
4381         .owner =        THIS_MODULE,
4382         .release =      packet_release,
4383         .bind =         packet_bind_spkt,
4384         .connect =      sock_no_connect,
4385         .socketpair =   sock_no_socketpair,
4386         .accept =       sock_no_accept,
4387         .getname =      packet_getname_spkt,
4388         .poll =         datagram_poll,
4389         .ioctl =        packet_ioctl,
4390         .listen =       sock_no_listen,
4391         .shutdown =     sock_no_shutdown,
4392         .setsockopt =   sock_no_setsockopt,
4393         .getsockopt =   sock_no_getsockopt,
4394         .sendmsg =      packet_sendmsg_spkt,
4395         .recvmsg =      packet_recvmsg,
4396         .mmap =         sock_no_mmap,
4397         .sendpage =     sock_no_sendpage,
4398 };
4399
4400 static const struct proto_ops packet_ops = {
4401         .family =       PF_PACKET,
4402         .owner =        THIS_MODULE,
4403         .release =      packet_release,
4404         .bind =         packet_bind,
4405         .connect =      sock_no_connect,
4406         .socketpair =   sock_no_socketpair,
4407         .accept =       sock_no_accept,
4408         .getname =      packet_getname,
4409         .poll =         packet_poll,
4410         .ioctl =        packet_ioctl,
4411         .listen =       sock_no_listen,
4412         .shutdown =     sock_no_shutdown,
4413         .setsockopt =   packet_setsockopt,
4414         .getsockopt =   packet_getsockopt,
4415 #ifdef CONFIG_COMPAT
4416         .compat_setsockopt = compat_packet_setsockopt,
4417 #endif
4418         .sendmsg =      packet_sendmsg,
4419         .recvmsg =      packet_recvmsg,
4420         .mmap =         packet_mmap,
4421         .sendpage =     sock_no_sendpage,
4422 };
4423
4424 static const struct net_proto_family packet_family_ops = {
4425         .family =       PF_PACKET,
4426         .create =       packet_create,
4427         .owner  =       THIS_MODULE,
4428 };
4429
4430 static struct notifier_block packet_netdev_notifier = {
4431         .notifier_call =        packet_notifier,
4432 };
4433
4434 #ifdef CONFIG_PROC_FS
4435
4436 static void *packet_seq_start(struct seq_file *seq, loff_t *pos)
4437         __acquires(RCU)
4438 {
4439         struct net *net = seq_file_net(seq);
4440
4441         rcu_read_lock();
4442         return seq_hlist_start_head_rcu(&net->packet.sklist, *pos);
4443 }
4444
4445 static void *packet_seq_next(struct seq_file *seq, void *v, loff_t *pos)
4446 {
4447         struct net *net = seq_file_net(seq);
4448         return seq_hlist_next_rcu(v, &net->packet.sklist, pos);
4449 }
4450
4451 static void packet_seq_stop(struct seq_file *seq, void *v)
4452         __releases(RCU)
4453 {
4454         rcu_read_unlock();
4455 }
4456
4457 static int packet_seq_show(struct seq_file *seq, void *v)
4458 {
4459         if (v == SEQ_START_TOKEN)
4460                 seq_puts(seq, "sk       RefCnt Type Proto  Iface R Rmem   User   Inode\n");
4461         else {
4462                 struct sock *s = sk_entry(v);
4463                 const struct packet_sock *po = pkt_sk(s);
4464
4465                 seq_printf(seq,
4466                            "%pK %-6d %-4d %04x   %-5d %1d %-6u %-6u %-6lu\n",
4467                            s,
4468                            atomic_read(&s->sk_refcnt),
4469                            s->sk_type,
4470                            ntohs(po->num),
4471                            po->ifindex,
4472                            po->running,
4473                            atomic_read(&s->sk_rmem_alloc),
4474                            from_kuid_munged(seq_user_ns(seq), sock_i_uid(s)),
4475                            sock_i_ino(s));
4476         }
4477
4478         return 0;
4479 }
4480
4481 static const struct seq_operations packet_seq_ops = {
4482         .start  = packet_seq_start,
4483         .next   = packet_seq_next,
4484         .stop   = packet_seq_stop,
4485         .show   = packet_seq_show,
4486 };
4487
4488 static int packet_seq_open(struct inode *inode, struct file *file)
4489 {
4490         return seq_open_net(inode, file, &packet_seq_ops,
4491                             sizeof(struct seq_net_private));
4492 }
4493
4494 static const struct file_operations packet_seq_fops = {
4495         .owner          = THIS_MODULE,
4496         .open           = packet_seq_open,
4497         .read           = seq_read,
4498         .llseek         = seq_lseek,
4499         .release        = seq_release_net,
4500 };
4501
4502 #endif
4503
4504 static int __net_init packet_net_init(struct net *net)
4505 {
4506         mutex_init(&net->packet.sklist_lock);
4507         INIT_HLIST_HEAD(&net->packet.sklist);
4508
4509         if (!proc_create("packet", 0, net->proc_net, &packet_seq_fops))
4510                 return -ENOMEM;
4511
4512         return 0;
4513 }
4514
4515 static void __net_exit packet_net_exit(struct net *net)
4516 {
4517         remove_proc_entry("packet", net->proc_net);
4518 }
4519
4520 static struct pernet_operations packet_net_ops = {
4521         .init = packet_net_init,
4522         .exit = packet_net_exit,
4523 };
4524
4525
4526 static void __exit packet_exit(void)
4527 {
4528         unregister_netdevice_notifier(&packet_netdev_notifier);
4529         unregister_pernet_subsys(&packet_net_ops);
4530         sock_unregister(PF_PACKET);
4531         proto_unregister(&packet_proto);
4532 }
4533
4534 static int __init packet_init(void)
4535 {
4536         int rc = proto_register(&packet_proto, 0);
4537
4538         if (rc != 0)
4539                 goto out;
4540
4541         sock_register(&packet_family_ops);
4542         register_pernet_subsys(&packet_net_ops);
4543         register_netdevice_notifier(&packet_netdev_notifier);
4544 out:
4545         return rc;
4546 }
4547
4548 module_init(packet_init);
4549 module_exit(packet_exit);
4550 MODULE_LICENSE("GPL");
4551 MODULE_ALIAS_NETPROTO(PF_PACKET);