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