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