af_packet: prevent information leak
[linux-2.6.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  *
44  *              This program is free software; you can redistribute it and/or
45  *              modify it under the terms of the GNU General Public License
46  *              as published by the Free Software Foundation; either version
47  *              2 of the License, or (at your option) any later version.
48  *
49  */
50
51 #include <linux/types.h>
52 #include <linux/mm.h>
53 #include <linux/capability.h>
54 #include <linux/fcntl.h>
55 #include <linux/socket.h>
56 #include <linux/in.h>
57 #include <linux/inet.h>
58 #include <linux/netdevice.h>
59 #include <linux/if_packet.h>
60 #include <linux/wireless.h>
61 #include <linux/kernel.h>
62 #include <linux/kmod.h>
63 #include <linux/slab.h>
64 #include <linux/vmalloc.h>
65 #include <net/net_namespace.h>
66 #include <net/ip.h>
67 #include <net/protocol.h>
68 #include <linux/skbuff.h>
69 #include <net/sock.h>
70 #include <linux/errno.h>
71 #include <linux/timer.h>
72 #include <asm/system.h>
73 #include <asm/uaccess.h>
74 #include <asm/ioctls.h>
75 #include <asm/page.h>
76 #include <asm/cacheflush.h>
77 #include <asm/io.h>
78 #include <linux/proc_fs.h>
79 #include <linux/seq_file.h>
80 #include <linux/poll.h>
81 #include <linux/module.h>
82 #include <linux/init.h>
83 #include <linux/mutex.h>
84 #include <linux/if_vlan.h>
85 #include <linux/virtio_net.h>
86 #include <linux/errqueue.h>
87 #include <linux/net_tstamp.h>
88
89 #ifdef CONFIG_INET
90 #include <net/inet_common.h>
91 #endif
92
93 /*
94    Assumptions:
95    - if device has no dev->hard_header routine, it adds and removes ll header
96      inside itself. In this case ll header is invisible outside of device,
97      but higher levels still should reserve dev->hard_header_len.
98      Some devices are enough clever to reallocate skb, when header
99      will not fit to reserved space (tunnel), another ones are silly
100      (PPP).
101    - packet socket receives packets with pulled ll header,
102      so that SOCK_RAW should push it back.
103
104 On receive:
105 -----------
106
107 Incoming, dev->hard_header!=NULL
108    mac_header -> ll header
109    data       -> data
110
111 Outgoing, dev->hard_header!=NULL
112    mac_header -> ll header
113    data       -> ll header
114
115 Incoming, dev->hard_header==NULL
116    mac_header -> UNKNOWN position. It is very likely, that it points to ll
117                  header.  PPP makes it, that is wrong, because introduce
118                  assymetry between rx and tx paths.
119    data       -> data
120
121 Outgoing, dev->hard_header==NULL
122    mac_header -> data. ll header is still not built!
123    data       -> data
124
125 Resume
126   If dev->hard_header==NULL we are unlikely to restore sensible ll header.
127
128
129 On transmit:
130 ------------
131
132 dev->hard_header != NULL
133    mac_header -> ll header
134    data       -> ll header
135
136 dev->hard_header == NULL (ll header is added by device, we cannot control it)
137    mac_header -> data
138    data       -> data
139
140    We should set nh.raw on output to correct posistion,
141    packet classifier depends on it.
142  */
143
144 /* Private packet socket structures. */
145
146 struct packet_mclist {
147         struct packet_mclist    *next;
148         int                     ifindex;
149         int                     count;
150         unsigned short          type;
151         unsigned short          alen;
152         unsigned char           addr[MAX_ADDR_LEN];
153 };
154 /* identical to struct packet_mreq except it has
155  * a longer address field.
156  */
157 struct packet_mreq_max {
158         int             mr_ifindex;
159         unsigned short  mr_type;
160         unsigned short  mr_alen;
161         unsigned char   mr_address[MAX_ADDR_LEN];
162 };
163
164 static int packet_set_ring(struct sock *sk, struct tpacket_req *req,
165                 int closing, int tx_ring);
166
167 struct pgv {
168         char *buffer;
169 };
170
171 struct packet_ring_buffer {
172         struct pgv              *pg_vec;
173         unsigned int            head;
174         unsigned int            frames_per_block;
175         unsigned int            frame_size;
176         unsigned int            frame_max;
177
178         unsigned int            pg_vec_order;
179         unsigned int            pg_vec_pages;
180         unsigned int            pg_vec_len;
181
182         atomic_t                pending;
183 };
184
185 struct packet_sock;
186 static int tpacket_snd(struct packet_sock *po, struct msghdr *msg);
187
188 static void packet_flush_mclist(struct sock *sk);
189
190 struct packet_sock {
191         /* struct sock has to be the first member of packet_sock */
192         struct sock             sk;
193         struct tpacket_stats    stats;
194         struct packet_ring_buffer       rx_ring;
195         struct packet_ring_buffer       tx_ring;
196         int                     copy_thresh;
197         spinlock_t              bind_lock;
198         struct mutex            pg_vec_lock;
199         unsigned int            running:1,      /* prot_hook is attached*/
200                                 auxdata:1,
201                                 origdev:1,
202                                 has_vnet_hdr:1;
203         int                     ifindex;        /* bound device         */
204         __be16                  num;
205         struct packet_mclist    *mclist;
206         atomic_t                mapped;
207         enum tpacket_versions   tp_version;
208         unsigned int            tp_hdrlen;
209         unsigned int            tp_reserve;
210         unsigned int            tp_loss:1;
211         unsigned int            tp_tstamp;
212         struct packet_type      prot_hook ____cacheline_aligned_in_smp;
213 };
214
215 struct packet_skb_cb {
216         unsigned int origlen;
217         union {
218                 struct sockaddr_pkt pkt;
219                 struct sockaddr_ll ll;
220         } sa;
221 };
222
223 #define PACKET_SKB_CB(__skb)    ((struct packet_skb_cb *)((__skb)->cb))
224
225 static inline __pure struct page *pgv_to_page(void *addr)
226 {
227         if (is_vmalloc_addr(addr))
228                 return vmalloc_to_page(addr);
229         return virt_to_page(addr);
230 }
231
232 static void __packet_set_status(struct packet_sock *po, void *frame, int status)
233 {
234         union {
235                 struct tpacket_hdr *h1;
236                 struct tpacket2_hdr *h2;
237                 void *raw;
238         } h;
239
240         h.raw = frame;
241         switch (po->tp_version) {
242         case TPACKET_V1:
243                 h.h1->tp_status = status;
244                 flush_dcache_page(pgv_to_page(&h.h1->tp_status));
245                 break;
246         case TPACKET_V2:
247                 h.h2->tp_status = status;
248                 flush_dcache_page(pgv_to_page(&h.h2->tp_status));
249                 break;
250         default:
251                 pr_err("TPACKET version not supported\n");
252                 BUG();
253         }
254
255         smp_wmb();
256 }
257
258 static int __packet_get_status(struct packet_sock *po, void *frame)
259 {
260         union {
261                 struct tpacket_hdr *h1;
262                 struct tpacket2_hdr *h2;
263                 void *raw;
264         } h;
265
266         smp_rmb();
267
268         h.raw = frame;
269         switch (po->tp_version) {
270         case TPACKET_V1:
271                 flush_dcache_page(pgv_to_page(&h.h1->tp_status));
272                 return h.h1->tp_status;
273         case TPACKET_V2:
274                 flush_dcache_page(pgv_to_page(&h.h2->tp_status));
275                 return h.h2->tp_status;
276         default:
277                 pr_err("TPACKET version not supported\n");
278                 BUG();
279                 return 0;
280         }
281 }
282
283 static void *packet_lookup_frame(struct packet_sock *po,
284                 struct packet_ring_buffer *rb,
285                 unsigned int position,
286                 int status)
287 {
288         unsigned int pg_vec_pos, frame_offset;
289         union {
290                 struct tpacket_hdr *h1;
291                 struct tpacket2_hdr *h2;
292                 void *raw;
293         } h;
294
295         pg_vec_pos = position / rb->frames_per_block;
296         frame_offset = position % rb->frames_per_block;
297
298         h.raw = rb->pg_vec[pg_vec_pos].buffer +
299                 (frame_offset * rb->frame_size);
300
301         if (status != __packet_get_status(po, h.raw))
302                 return NULL;
303
304         return h.raw;
305 }
306
307 static inline void *packet_current_frame(struct packet_sock *po,
308                 struct packet_ring_buffer *rb,
309                 int status)
310 {
311         return packet_lookup_frame(po, rb, rb->head, status);
312 }
313
314 static inline void *packet_previous_frame(struct packet_sock *po,
315                 struct packet_ring_buffer *rb,
316                 int status)
317 {
318         unsigned int previous = rb->head ? rb->head - 1 : rb->frame_max;
319         return packet_lookup_frame(po, rb, previous, status);
320 }
321
322 static inline void packet_increment_head(struct packet_ring_buffer *buff)
323 {
324         buff->head = buff->head != buff->frame_max ? buff->head+1 : 0;
325 }
326
327 static inline struct packet_sock *pkt_sk(struct sock *sk)
328 {
329         return (struct packet_sock *)sk;
330 }
331
332 static void packet_sock_destruct(struct sock *sk)
333 {
334         skb_queue_purge(&sk->sk_error_queue);
335
336         WARN_ON(atomic_read(&sk->sk_rmem_alloc));
337         WARN_ON(atomic_read(&sk->sk_wmem_alloc));
338
339         if (!sock_flag(sk, SOCK_DEAD)) {
340                 pr_err("Attempt to release alive packet socket: %p\n", sk);
341                 return;
342         }
343
344         sk_refcnt_debug_dec(sk);
345 }
346
347
348 static const struct proto_ops packet_ops;
349
350 static const struct proto_ops packet_ops_spkt;
351
352 static int packet_rcv_spkt(struct sk_buff *skb, struct net_device *dev,
353                            struct packet_type *pt, struct net_device *orig_dev)
354 {
355         struct sock *sk;
356         struct sockaddr_pkt *spkt;
357
358         /*
359          *      When we registered the protocol we saved the socket in the data
360          *      field for just this event.
361          */
362
363         sk = pt->af_packet_priv;
364
365         /*
366          *      Yank back the headers [hope the device set this
367          *      right or kerboom...]
368          *
369          *      Incoming packets have ll header pulled,
370          *      push it back.
371          *
372          *      For outgoing ones skb->data == skb_mac_header(skb)
373          *      so that this procedure is noop.
374          */
375
376         if (skb->pkt_type == PACKET_LOOPBACK)
377                 goto out;
378
379         if (!net_eq(dev_net(dev), sock_net(sk)))
380                 goto out;
381
382         skb = skb_share_check(skb, GFP_ATOMIC);
383         if (skb == NULL)
384                 goto oom;
385
386         /* drop any routing info */
387         skb_dst_drop(skb);
388
389         /* drop conntrack reference */
390         nf_reset(skb);
391
392         spkt = &PACKET_SKB_CB(skb)->sa.pkt;
393
394         skb_push(skb, skb->data - skb_mac_header(skb));
395
396         /*
397          *      The SOCK_PACKET socket receives _all_ frames.
398          */
399
400         spkt->spkt_family = dev->type;
401         strlcpy(spkt->spkt_device, dev->name, sizeof(spkt->spkt_device));
402         spkt->spkt_protocol = skb->protocol;
403
404         /*
405          *      Charge the memory to the socket. This is done specifically
406          *      to prevent sockets using all the memory up.
407          */
408
409         if (sock_queue_rcv_skb(sk, skb) == 0)
410                 return 0;
411
412 out:
413         kfree_skb(skb);
414 oom:
415         return 0;
416 }
417
418
419 /*
420  *      Output a raw packet to a device layer. This bypasses all the other
421  *      protocol layers and you must therefore supply it with a complete frame
422  */
423
424 static int packet_sendmsg_spkt(struct kiocb *iocb, struct socket *sock,
425                                struct msghdr *msg, size_t len)
426 {
427         struct sock *sk = sock->sk;
428         struct sockaddr_pkt *saddr = (struct sockaddr_pkt *)msg->msg_name;
429         struct sk_buff *skb = NULL;
430         struct net_device *dev;
431         __be16 proto = 0;
432         int err;
433
434         /*
435          *      Get and verify the address.
436          */
437
438         if (saddr) {
439                 if (msg->msg_namelen < sizeof(struct sockaddr))
440                         return -EINVAL;
441                 if (msg->msg_namelen == sizeof(struct sockaddr_pkt))
442                         proto = saddr->spkt_protocol;
443         } else
444                 return -ENOTCONN;       /* SOCK_PACKET must be sent giving an address */
445
446         /*
447          *      Find the device first to size check it
448          */
449
450         saddr->spkt_device[13] = 0;
451 retry:
452         rcu_read_lock();
453         dev = dev_get_by_name_rcu(sock_net(sk), saddr->spkt_device);
454         err = -ENODEV;
455         if (dev == NULL)
456                 goto out_unlock;
457
458         err = -ENETDOWN;
459         if (!(dev->flags & IFF_UP))
460                 goto out_unlock;
461
462         /*
463          * You may not queue a frame bigger than the mtu. This is the lowest level
464          * raw protocol and you must do your own fragmentation at this level.
465          */
466
467         err = -EMSGSIZE;
468         if (len > dev->mtu + dev->hard_header_len + VLAN_HLEN)
469                 goto out_unlock;
470
471         if (!skb) {
472                 size_t reserved = LL_RESERVED_SPACE(dev);
473                 unsigned int hhlen = dev->header_ops ? dev->hard_header_len : 0;
474
475                 rcu_read_unlock();
476                 skb = sock_wmalloc(sk, len + reserved, 0, GFP_KERNEL);
477                 if (skb == NULL)
478                         return -ENOBUFS;
479                 /* FIXME: Save some space for broken drivers that write a hard
480                  * header at transmission time by themselves. PPP is the notable
481                  * one here. This should really be fixed at the driver level.
482                  */
483                 skb_reserve(skb, reserved);
484                 skb_reset_network_header(skb);
485
486                 /* Try to align data part correctly */
487                 if (hhlen) {
488                         skb->data -= hhlen;
489                         skb->tail -= hhlen;
490                         if (len < hhlen)
491                                 skb_reset_network_header(skb);
492                 }
493                 err = memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len);
494                 if (err)
495                         goto out_free;
496                 goto retry;
497         }
498
499         if (len > (dev->mtu + dev->hard_header_len)) {
500                 /* Earlier code assumed this would be a VLAN pkt,
501                  * double-check this now that we have the actual
502                  * packet in hand.
503                  */
504                 struct ethhdr *ehdr;
505                 skb_reset_mac_header(skb);
506                 ehdr = eth_hdr(skb);
507                 if (ehdr->h_proto != htons(ETH_P_8021Q)) {
508                         err = -EMSGSIZE;
509                         goto out_unlock;
510                 }
511         }
512
513         skb->protocol = proto;
514         skb->dev = dev;
515         skb->priority = sk->sk_priority;
516         skb->mark = sk->sk_mark;
517         err = sock_tx_timestamp(sk, &skb_shinfo(skb)->tx_flags);
518         if (err < 0)
519                 goto out_unlock;
520
521         dev_queue_xmit(skb);
522         rcu_read_unlock();
523         return len;
524
525 out_unlock:
526         rcu_read_unlock();
527 out_free:
528         kfree_skb(skb);
529         return err;
530 }
531
532 static inline unsigned int run_filter(const struct sk_buff *skb,
533                                       const struct sock *sk,
534                                       unsigned int res)
535 {
536         struct sk_filter *filter;
537
538         rcu_read_lock();
539         filter = rcu_dereference(sk->sk_filter);
540         if (filter != NULL)
541                 res = SK_RUN_FILTER(filter, skb);
542         rcu_read_unlock();
543
544         return res;
545 }
546
547 /*
548  * This function makes lazy skb cloning in hope that most of packets
549  * are discarded by BPF.
550  *
551  * Note tricky part: we DO mangle shared skb! skb->data, skb->len
552  * and skb->cb are mangled. It works because (and until) packets
553  * falling here are owned by current CPU. Output packets are cloned
554  * by dev_queue_xmit_nit(), input packets are processed by net_bh
555  * sequencially, so that if we return skb to original state on exit,
556  * we will not harm anyone.
557  */
558
559 static int packet_rcv(struct sk_buff *skb, struct net_device *dev,
560                       struct packet_type *pt, struct net_device *orig_dev)
561 {
562         struct sock *sk;
563         struct sockaddr_ll *sll;
564         struct packet_sock *po;
565         u8 *skb_head = skb->data;
566         int skb_len = skb->len;
567         unsigned int snaplen, res;
568
569         if (skb->pkt_type == PACKET_LOOPBACK)
570                 goto drop;
571
572         sk = pt->af_packet_priv;
573         po = pkt_sk(sk);
574
575         if (!net_eq(dev_net(dev), sock_net(sk)))
576                 goto drop;
577
578         skb->dev = dev;
579
580         if (dev->header_ops) {
581                 /* The device has an explicit notion of ll header,
582                  * exported to higher levels.
583                  *
584                  * Otherwise, the device hides details of its frame
585                  * structure, so that corresponding packet head is
586                  * never delivered to user.
587                  */
588                 if (sk->sk_type != SOCK_DGRAM)
589                         skb_push(skb, skb->data - skb_mac_header(skb));
590                 else if (skb->pkt_type == PACKET_OUTGOING) {
591                         /* Special case: outgoing packets have ll header at head */
592                         skb_pull(skb, skb_network_offset(skb));
593                 }
594         }
595
596         snaplen = skb->len;
597
598         res = run_filter(skb, sk, snaplen);
599         if (!res)
600                 goto drop_n_restore;
601         if (snaplen > res)
602                 snaplen = res;
603
604         if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >=
605             (unsigned)sk->sk_rcvbuf)
606                 goto drop_n_acct;
607
608         if (skb_shared(skb)) {
609                 struct sk_buff *nskb = skb_clone(skb, GFP_ATOMIC);
610                 if (nskb == NULL)
611                         goto drop_n_acct;
612
613                 if (skb_head != skb->data) {
614                         skb->data = skb_head;
615                         skb->len = skb_len;
616                 }
617                 kfree_skb(skb);
618                 skb = nskb;
619         }
620
621         BUILD_BUG_ON(sizeof(*PACKET_SKB_CB(skb)) + MAX_ADDR_LEN - 8 >
622                      sizeof(skb->cb));
623
624         sll = &PACKET_SKB_CB(skb)->sa.ll;
625         sll->sll_family = AF_PACKET;
626         sll->sll_hatype = dev->type;
627         sll->sll_protocol = skb->protocol;
628         sll->sll_pkttype = skb->pkt_type;
629         if (unlikely(po->origdev))
630                 sll->sll_ifindex = orig_dev->ifindex;
631         else
632                 sll->sll_ifindex = dev->ifindex;
633
634         sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
635
636         PACKET_SKB_CB(skb)->origlen = skb->len;
637
638         if (pskb_trim(skb, snaplen))
639                 goto drop_n_acct;
640
641         skb_set_owner_r(skb, sk);
642         skb->dev = NULL;
643         skb_dst_drop(skb);
644
645         /* drop conntrack reference */
646         nf_reset(skb);
647
648         spin_lock(&sk->sk_receive_queue.lock);
649         po->stats.tp_packets++;
650         skb->dropcount = atomic_read(&sk->sk_drops);
651         __skb_queue_tail(&sk->sk_receive_queue, skb);
652         spin_unlock(&sk->sk_receive_queue.lock);
653         sk->sk_data_ready(sk, skb->len);
654         return 0;
655
656 drop_n_acct:
657         po->stats.tp_drops = atomic_inc_return(&sk->sk_drops);
658
659 drop_n_restore:
660         if (skb_head != skb->data && skb_shared(skb)) {
661                 skb->data = skb_head;
662                 skb->len = skb_len;
663         }
664 drop:
665         consume_skb(skb);
666         return 0;
667 }
668
669 static int tpacket_rcv(struct sk_buff *skb, struct net_device *dev,
670                        struct packet_type *pt, struct net_device *orig_dev)
671 {
672         struct sock *sk;
673         struct packet_sock *po;
674         struct sockaddr_ll *sll;
675         union {
676                 struct tpacket_hdr *h1;
677                 struct tpacket2_hdr *h2;
678                 void *raw;
679         } h;
680         u8 *skb_head = skb->data;
681         int skb_len = skb->len;
682         unsigned int snaplen, res;
683         unsigned long status = TP_STATUS_LOSING|TP_STATUS_USER;
684         unsigned short macoff, netoff, hdrlen;
685         struct sk_buff *copy_skb = NULL;
686         struct timeval tv;
687         struct timespec ts;
688         struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);
689
690         if (skb->pkt_type == PACKET_LOOPBACK)
691                 goto drop;
692
693         sk = pt->af_packet_priv;
694         po = pkt_sk(sk);
695
696         if (!net_eq(dev_net(dev), sock_net(sk)))
697                 goto drop;
698
699         if (dev->header_ops) {
700                 if (sk->sk_type != SOCK_DGRAM)
701                         skb_push(skb, skb->data - skb_mac_header(skb));
702                 else if (skb->pkt_type == PACKET_OUTGOING) {
703                         /* Special case: outgoing packets have ll header at head */
704                         skb_pull(skb, skb_network_offset(skb));
705                 }
706         }
707
708         if (skb->ip_summed == CHECKSUM_PARTIAL)
709                 status |= TP_STATUS_CSUMNOTREADY;
710
711         snaplen = skb->len;
712
713         res = run_filter(skb, sk, snaplen);
714         if (!res)
715                 goto drop_n_restore;
716         if (snaplen > res)
717                 snaplen = res;
718
719         if (sk->sk_type == SOCK_DGRAM) {
720                 macoff = netoff = TPACKET_ALIGN(po->tp_hdrlen) + 16 +
721                                   po->tp_reserve;
722         } else {
723                 unsigned maclen = skb_network_offset(skb);
724                 netoff = TPACKET_ALIGN(po->tp_hdrlen +
725                                        (maclen < 16 ? 16 : maclen)) +
726                         po->tp_reserve;
727                 macoff = netoff - maclen;
728         }
729
730         if (macoff + snaplen > po->rx_ring.frame_size) {
731                 if (po->copy_thresh &&
732                     atomic_read(&sk->sk_rmem_alloc) + skb->truesize <
733                     (unsigned)sk->sk_rcvbuf) {
734                         if (skb_shared(skb)) {
735                                 copy_skb = skb_clone(skb, GFP_ATOMIC);
736                         } else {
737                                 copy_skb = skb_get(skb);
738                                 skb_head = skb->data;
739                         }
740                         if (copy_skb)
741                                 skb_set_owner_r(copy_skb, sk);
742                 }
743                 snaplen = po->rx_ring.frame_size - macoff;
744                 if ((int)snaplen < 0)
745                         snaplen = 0;
746         }
747
748         spin_lock(&sk->sk_receive_queue.lock);
749         h.raw = packet_current_frame(po, &po->rx_ring, TP_STATUS_KERNEL);
750         if (!h.raw)
751                 goto ring_is_full;
752         packet_increment_head(&po->rx_ring);
753         po->stats.tp_packets++;
754         if (copy_skb) {
755                 status |= TP_STATUS_COPY;
756                 __skb_queue_tail(&sk->sk_receive_queue, copy_skb);
757         }
758         if (!po->stats.tp_drops)
759                 status &= ~TP_STATUS_LOSING;
760         spin_unlock(&sk->sk_receive_queue.lock);
761
762         skb_copy_bits(skb, 0, h.raw + macoff, snaplen);
763
764         switch (po->tp_version) {
765         case TPACKET_V1:
766                 h.h1->tp_len = skb->len;
767                 h.h1->tp_snaplen = snaplen;
768                 h.h1->tp_mac = macoff;
769                 h.h1->tp_net = netoff;
770                 if ((po->tp_tstamp & SOF_TIMESTAMPING_SYS_HARDWARE)
771                                 && shhwtstamps->syststamp.tv64)
772                         tv = ktime_to_timeval(shhwtstamps->syststamp);
773                 else if ((po->tp_tstamp & SOF_TIMESTAMPING_RAW_HARDWARE)
774                                 && shhwtstamps->hwtstamp.tv64)
775                         tv = ktime_to_timeval(shhwtstamps->hwtstamp);
776                 else if (skb->tstamp.tv64)
777                         tv = ktime_to_timeval(skb->tstamp);
778                 else
779                         do_gettimeofday(&tv);
780                 h.h1->tp_sec = tv.tv_sec;
781                 h.h1->tp_usec = tv.tv_usec;
782                 hdrlen = sizeof(*h.h1);
783                 break;
784         case TPACKET_V2:
785                 h.h2->tp_len = skb->len;
786                 h.h2->tp_snaplen = snaplen;
787                 h.h2->tp_mac = macoff;
788                 h.h2->tp_net = netoff;
789                 if ((po->tp_tstamp & SOF_TIMESTAMPING_SYS_HARDWARE)
790                                 && shhwtstamps->syststamp.tv64)
791                         ts = ktime_to_timespec(shhwtstamps->syststamp);
792                 else if ((po->tp_tstamp & SOF_TIMESTAMPING_RAW_HARDWARE)
793                                 && shhwtstamps->hwtstamp.tv64)
794                         ts = ktime_to_timespec(shhwtstamps->hwtstamp);
795                 else if (skb->tstamp.tv64)
796                         ts = ktime_to_timespec(skb->tstamp);
797                 else
798                         getnstimeofday(&ts);
799                 h.h2->tp_sec = ts.tv_sec;
800                 h.h2->tp_nsec = ts.tv_nsec;
801                 if (vlan_tx_tag_present(skb)) {
802                         h.h2->tp_vlan_tci = vlan_tx_tag_get(skb);
803                         status |= TP_STATUS_VLAN_VALID;
804                 } else {
805                         h.h2->tp_vlan_tci = 0;
806                 }
807                 h.h2->tp_padding = 0;
808                 hdrlen = sizeof(*h.h2);
809                 break;
810         default:
811                 BUG();
812         }
813
814         sll = h.raw + TPACKET_ALIGN(hdrlen);
815         sll->sll_halen = dev_parse_header(skb, sll->sll_addr);
816         sll->sll_family = AF_PACKET;
817         sll->sll_hatype = dev->type;
818         sll->sll_protocol = skb->protocol;
819         sll->sll_pkttype = skb->pkt_type;
820         if (unlikely(po->origdev))
821                 sll->sll_ifindex = orig_dev->ifindex;
822         else
823                 sll->sll_ifindex = dev->ifindex;
824
825         __packet_set_status(po, h.raw, status);
826         smp_mb();
827 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
828         {
829                 u8 *start, *end;
830
831                 end = (u8 *)PAGE_ALIGN((unsigned long)h.raw + macoff + snaplen);
832                 for (start = h.raw; start < end; start += PAGE_SIZE)
833                         flush_dcache_page(pgv_to_page(start));
834         }
835 #endif
836
837         sk->sk_data_ready(sk, 0);
838
839 drop_n_restore:
840         if (skb_head != skb->data && skb_shared(skb)) {
841                 skb->data = skb_head;
842                 skb->len = skb_len;
843         }
844 drop:
845         kfree_skb(skb);
846         return 0;
847
848 ring_is_full:
849         po->stats.tp_drops++;
850         spin_unlock(&sk->sk_receive_queue.lock);
851
852         sk->sk_data_ready(sk, 0);
853         kfree_skb(copy_skb);
854         goto drop_n_restore;
855 }
856
857 static void tpacket_destruct_skb(struct sk_buff *skb)
858 {
859         struct packet_sock *po = pkt_sk(skb->sk);
860         void *ph;
861
862         BUG_ON(skb == NULL);
863
864         if (likely(po->tx_ring.pg_vec)) {
865                 ph = skb_shinfo(skb)->destructor_arg;
866                 BUG_ON(__packet_get_status(po, ph) != TP_STATUS_SENDING);
867                 BUG_ON(atomic_read(&po->tx_ring.pending) == 0);
868                 atomic_dec(&po->tx_ring.pending);
869                 __packet_set_status(po, ph, TP_STATUS_AVAILABLE);
870         }
871
872         sock_wfree(skb);
873 }
874
875 static int tpacket_fill_skb(struct packet_sock *po, struct sk_buff *skb,
876                 void *frame, struct net_device *dev, int size_max,
877                 __be16 proto, unsigned char *addr)
878 {
879         union {
880                 struct tpacket_hdr *h1;
881                 struct tpacket2_hdr *h2;
882                 void *raw;
883         } ph;
884         int to_write, offset, len, tp_len, nr_frags, len_max;
885         struct socket *sock = po->sk.sk_socket;
886         struct page *page;
887         void *data;
888         int err;
889
890         ph.raw = frame;
891
892         skb->protocol = proto;
893         skb->dev = dev;
894         skb->priority = po->sk.sk_priority;
895         skb->mark = po->sk.sk_mark;
896         skb_shinfo(skb)->destructor_arg = ph.raw;
897
898         switch (po->tp_version) {
899         case TPACKET_V2:
900                 tp_len = ph.h2->tp_len;
901                 break;
902         default:
903                 tp_len = ph.h1->tp_len;
904                 break;
905         }
906         if (unlikely(tp_len > size_max)) {
907                 pr_err("packet size is too long (%d > %d)\n", tp_len, size_max);
908                 return -EMSGSIZE;
909         }
910
911         skb_reserve(skb, LL_RESERVED_SPACE(dev));
912         skb_reset_network_header(skb);
913
914         data = ph.raw + po->tp_hdrlen - sizeof(struct sockaddr_ll);
915         to_write = tp_len;
916
917         if (sock->type == SOCK_DGRAM) {
918                 err = dev_hard_header(skb, dev, ntohs(proto), addr,
919                                 NULL, tp_len);
920                 if (unlikely(err < 0))
921                         return -EINVAL;
922         } else if (dev->hard_header_len) {
923                 /* net device doesn't like empty head */
924                 if (unlikely(tp_len <= dev->hard_header_len)) {
925                         pr_err("packet size is too short (%d < %d)\n",
926                                tp_len, dev->hard_header_len);
927                         return -EINVAL;
928                 }
929
930                 skb_push(skb, dev->hard_header_len);
931                 err = skb_store_bits(skb, 0, data,
932                                 dev->hard_header_len);
933                 if (unlikely(err))
934                         return err;
935
936                 data += dev->hard_header_len;
937                 to_write -= dev->hard_header_len;
938         }
939
940         err = -EFAULT;
941         offset = offset_in_page(data);
942         len_max = PAGE_SIZE - offset;
943         len = ((to_write > len_max) ? len_max : to_write);
944
945         skb->data_len = to_write;
946         skb->len += to_write;
947         skb->truesize += to_write;
948         atomic_add(to_write, &po->sk.sk_wmem_alloc);
949
950         while (likely(to_write)) {
951                 nr_frags = skb_shinfo(skb)->nr_frags;
952
953                 if (unlikely(nr_frags >= MAX_SKB_FRAGS)) {
954                         pr_err("Packet exceed the number of skb frags(%lu)\n",
955                                MAX_SKB_FRAGS);
956                         return -EFAULT;
957                 }
958
959                 page = pgv_to_page(data);
960                 data += len;
961                 flush_dcache_page(page);
962                 get_page(page);
963                 skb_fill_page_desc(skb, nr_frags, page, offset, len);
964                 to_write -= len;
965                 offset = 0;
966                 len_max = PAGE_SIZE;
967                 len = ((to_write > len_max) ? len_max : to_write);
968         }
969
970         return tp_len;
971 }
972
973 static int tpacket_snd(struct packet_sock *po, struct msghdr *msg)
974 {
975         struct sk_buff *skb;
976         struct net_device *dev;
977         __be16 proto;
978         int ifindex, err, reserve = 0;
979         void *ph;
980         struct sockaddr_ll *saddr = (struct sockaddr_ll *)msg->msg_name;
981         int tp_len, size_max;
982         unsigned char *addr;
983         int len_sum = 0;
984         int status = 0;
985
986         mutex_lock(&po->pg_vec_lock);
987
988         err = -EBUSY;
989         if (saddr == NULL) {
990                 ifindex = po->ifindex;
991                 proto   = po->num;
992                 addr    = NULL;
993         } else {
994                 err = -EINVAL;
995                 if (msg->msg_namelen < sizeof(struct sockaddr_ll))
996                         goto out;
997                 if (msg->msg_namelen < (saddr->sll_halen
998                                         + offsetof(struct sockaddr_ll,
999                                                 sll_addr)))
1000                         goto out;
1001                 ifindex = saddr->sll_ifindex;
1002                 proto   = saddr->sll_protocol;
1003                 addr    = saddr->sll_addr;
1004         }
1005
1006         dev = dev_get_by_index(sock_net(&po->sk), ifindex);
1007         err = -ENXIO;
1008         if (unlikely(dev == NULL))
1009                 goto out;
1010
1011         reserve = dev->hard_header_len;
1012
1013         err = -ENETDOWN;
1014         if (unlikely(!(dev->flags & IFF_UP)))
1015                 goto out_put;
1016
1017         size_max = po->tx_ring.frame_size
1018                 - (po->tp_hdrlen - sizeof(struct sockaddr_ll));
1019
1020         if (size_max > dev->mtu + reserve)
1021                 size_max = dev->mtu + reserve;
1022
1023         do {
1024                 ph = packet_current_frame(po, &po->tx_ring,
1025                                 TP_STATUS_SEND_REQUEST);
1026
1027                 if (unlikely(ph == NULL)) {
1028                         schedule();
1029                         continue;
1030                 }
1031
1032                 status = TP_STATUS_SEND_REQUEST;
1033                 skb = sock_alloc_send_skb(&po->sk,
1034                                 LL_ALLOCATED_SPACE(dev)
1035                                 + sizeof(struct sockaddr_ll),
1036                                 0, &err);
1037
1038                 if (unlikely(skb == NULL))
1039                         goto out_status;
1040
1041                 tp_len = tpacket_fill_skb(po, skb, ph, dev, size_max, proto,
1042                                 addr);
1043
1044                 if (unlikely(tp_len < 0)) {
1045                         if (po->tp_loss) {
1046                                 __packet_set_status(po, ph,
1047                                                 TP_STATUS_AVAILABLE);
1048                                 packet_increment_head(&po->tx_ring);
1049                                 kfree_skb(skb);
1050                                 continue;
1051                         } else {
1052                                 status = TP_STATUS_WRONG_FORMAT;
1053                                 err = tp_len;
1054                                 goto out_status;
1055                         }
1056                 }
1057
1058                 skb->destructor = tpacket_destruct_skb;
1059                 __packet_set_status(po, ph, TP_STATUS_SENDING);
1060                 atomic_inc(&po->tx_ring.pending);
1061
1062                 status = TP_STATUS_SEND_REQUEST;
1063                 err = dev_queue_xmit(skb);
1064                 if (unlikely(err > 0)) {
1065                         err = net_xmit_errno(err);
1066                         if (err && __packet_get_status(po, ph) ==
1067                                    TP_STATUS_AVAILABLE) {
1068                                 /* skb was destructed already */
1069                                 skb = NULL;
1070                                 goto out_status;
1071                         }
1072                         /*
1073                          * skb was dropped but not destructed yet;
1074                          * let's treat it like congestion or err < 0
1075                          */
1076                         err = 0;
1077                 }
1078                 packet_increment_head(&po->tx_ring);
1079                 len_sum += tp_len;
1080         } while (likely((ph != NULL) ||
1081                         ((!(msg->msg_flags & MSG_DONTWAIT)) &&
1082                          (atomic_read(&po->tx_ring.pending))))
1083                 );
1084
1085         err = len_sum;
1086         goto out_put;
1087
1088 out_status:
1089         __packet_set_status(po, ph, status);
1090         kfree_skb(skb);
1091 out_put:
1092         dev_put(dev);
1093 out:
1094         mutex_unlock(&po->pg_vec_lock);
1095         return err;
1096 }
1097
1098 static inline struct sk_buff *packet_alloc_skb(struct sock *sk, size_t prepad,
1099                                                size_t reserve, size_t len,
1100                                                size_t linear, int noblock,
1101                                                int *err)
1102 {
1103         struct sk_buff *skb;
1104
1105         /* Under a page?  Don't bother with paged skb. */
1106         if (prepad + len < PAGE_SIZE || !linear)
1107                 linear = len;
1108
1109         skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock,
1110                                    err);
1111         if (!skb)
1112                 return NULL;
1113
1114         skb_reserve(skb, reserve);
1115         skb_put(skb, linear);
1116         skb->data_len = len - linear;
1117         skb->len += len - linear;
1118
1119         return skb;
1120 }
1121
1122 static int packet_snd(struct socket *sock,
1123                           struct msghdr *msg, size_t len)
1124 {
1125         struct sock *sk = sock->sk;
1126         struct sockaddr_ll *saddr = (struct sockaddr_ll *)msg->msg_name;
1127         struct sk_buff *skb;
1128         struct net_device *dev;
1129         __be16 proto;
1130         unsigned char *addr;
1131         int ifindex, err, reserve = 0;
1132         struct virtio_net_hdr vnet_hdr = { 0 };
1133         int offset = 0;
1134         int vnet_hdr_len;
1135         struct packet_sock *po = pkt_sk(sk);
1136         unsigned short gso_type = 0;
1137
1138         /*
1139          *      Get and verify the address.
1140          */
1141
1142         if (saddr == NULL) {
1143                 ifindex = po->ifindex;
1144                 proto   = po->num;
1145                 addr    = NULL;
1146         } else {
1147                 err = -EINVAL;
1148                 if (msg->msg_namelen < sizeof(struct sockaddr_ll))
1149                         goto out;
1150                 if (msg->msg_namelen < (saddr->sll_halen + offsetof(struct sockaddr_ll, sll_addr)))
1151                         goto out;
1152                 ifindex = saddr->sll_ifindex;
1153                 proto   = saddr->sll_protocol;
1154                 addr    = saddr->sll_addr;
1155         }
1156
1157
1158         dev = dev_get_by_index(sock_net(sk), ifindex);
1159         err = -ENXIO;
1160         if (dev == NULL)
1161                 goto out_unlock;
1162         if (sock->type == SOCK_RAW)
1163                 reserve = dev->hard_header_len;
1164
1165         err = -ENETDOWN;
1166         if (!(dev->flags & IFF_UP))
1167                 goto out_unlock;
1168
1169         if (po->has_vnet_hdr) {
1170                 vnet_hdr_len = sizeof(vnet_hdr);
1171
1172                 err = -EINVAL;
1173                 if (len < vnet_hdr_len)
1174                         goto out_unlock;
1175
1176                 len -= vnet_hdr_len;
1177
1178                 err = memcpy_fromiovec((void *)&vnet_hdr, msg->msg_iov,
1179                                        vnet_hdr_len);
1180                 if (err < 0)
1181                         goto out_unlock;
1182
1183                 if ((vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) &&
1184                     (vnet_hdr.csum_start + vnet_hdr.csum_offset + 2 >
1185                       vnet_hdr.hdr_len))
1186                         vnet_hdr.hdr_len = vnet_hdr.csum_start +
1187                                                  vnet_hdr.csum_offset + 2;
1188
1189                 err = -EINVAL;
1190                 if (vnet_hdr.hdr_len > len)
1191                         goto out_unlock;
1192
1193                 if (vnet_hdr.gso_type != VIRTIO_NET_HDR_GSO_NONE) {
1194                         switch (vnet_hdr.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) {
1195                         case VIRTIO_NET_HDR_GSO_TCPV4:
1196                                 gso_type = SKB_GSO_TCPV4;
1197                                 break;
1198                         case VIRTIO_NET_HDR_GSO_TCPV6:
1199                                 gso_type = SKB_GSO_TCPV6;
1200                                 break;
1201                         case VIRTIO_NET_HDR_GSO_UDP:
1202                                 gso_type = SKB_GSO_UDP;
1203                                 break;
1204                         default:
1205                                 goto out_unlock;
1206                         }
1207
1208                         if (vnet_hdr.gso_type & VIRTIO_NET_HDR_GSO_ECN)
1209                                 gso_type |= SKB_GSO_TCP_ECN;
1210
1211                         if (vnet_hdr.gso_size == 0)
1212                                 goto out_unlock;
1213
1214                 }
1215         }
1216
1217         err = -EMSGSIZE;
1218         if (!gso_type && (len > dev->mtu + reserve + VLAN_HLEN))
1219                 goto out_unlock;
1220
1221         err = -ENOBUFS;
1222         skb = packet_alloc_skb(sk, LL_ALLOCATED_SPACE(dev),
1223                                LL_RESERVED_SPACE(dev), len, vnet_hdr.hdr_len,
1224                                msg->msg_flags & MSG_DONTWAIT, &err);
1225         if (skb == NULL)
1226                 goto out_unlock;
1227
1228         skb_set_network_header(skb, reserve);
1229
1230         err = -EINVAL;
1231         if (sock->type == SOCK_DGRAM &&
1232             (offset = dev_hard_header(skb, dev, ntohs(proto), addr, NULL, len)) < 0)
1233                 goto out_free;
1234
1235         /* Returns -EFAULT on error */
1236         err = skb_copy_datagram_from_iovec(skb, offset, msg->msg_iov, 0, len);
1237         if (err)
1238                 goto out_free;
1239         err = sock_tx_timestamp(sk, &skb_shinfo(skb)->tx_flags);
1240         if (err < 0)
1241                 goto out_free;
1242
1243         if (!gso_type && (len > dev->mtu + reserve)) {
1244                 /* Earlier code assumed this would be a VLAN pkt,
1245                  * double-check this now that we have the actual
1246                  * packet in hand.
1247                  */
1248                 struct ethhdr *ehdr;
1249                 skb_reset_mac_header(skb);
1250                 ehdr = eth_hdr(skb);
1251                 if (ehdr->h_proto != htons(ETH_P_8021Q)) {
1252                         err = -EMSGSIZE;
1253                         goto out_free;
1254                 }
1255         }
1256
1257         skb->protocol = proto;
1258         skb->dev = dev;
1259         skb->priority = sk->sk_priority;
1260         skb->mark = sk->sk_mark;
1261
1262         if (po->has_vnet_hdr) {
1263                 if (vnet_hdr.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) {
1264                         if (!skb_partial_csum_set(skb, vnet_hdr.csum_start,
1265                                                   vnet_hdr.csum_offset)) {
1266                                 err = -EINVAL;
1267                                 goto out_free;
1268                         }
1269                 }
1270
1271                 skb_shinfo(skb)->gso_size = vnet_hdr.gso_size;
1272                 skb_shinfo(skb)->gso_type = gso_type;
1273
1274                 /* Header must be checked, and gso_segs computed. */
1275                 skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY;
1276                 skb_shinfo(skb)->gso_segs = 0;
1277
1278                 len += vnet_hdr_len;
1279         }
1280
1281         /*
1282          *      Now send it
1283          */
1284
1285         err = dev_queue_xmit(skb);
1286         if (err > 0 && (err = net_xmit_errno(err)) != 0)
1287                 goto out_unlock;
1288
1289         dev_put(dev);
1290
1291         return len;
1292
1293 out_free:
1294         kfree_skb(skb);
1295 out_unlock:
1296         if (dev)
1297                 dev_put(dev);
1298 out:
1299         return err;
1300 }
1301
1302 static int packet_sendmsg(struct kiocb *iocb, struct socket *sock,
1303                 struct msghdr *msg, size_t len)
1304 {
1305         struct sock *sk = sock->sk;
1306         struct packet_sock *po = pkt_sk(sk);
1307         if (po->tx_ring.pg_vec)
1308                 return tpacket_snd(po, msg);
1309         else
1310                 return packet_snd(sock, msg, len);
1311 }
1312
1313 /*
1314  *      Close a PACKET socket. This is fairly simple. We immediately go
1315  *      to 'closed' state and remove our protocol entry in the device list.
1316  */
1317
1318 static int packet_release(struct socket *sock)
1319 {
1320         struct sock *sk = sock->sk;
1321         struct packet_sock *po;
1322         struct net *net;
1323         struct tpacket_req req;
1324
1325         if (!sk)
1326                 return 0;
1327
1328         net = sock_net(sk);
1329         po = pkt_sk(sk);
1330
1331         spin_lock_bh(&net->packet.sklist_lock);
1332         sk_del_node_init_rcu(sk);
1333         sock_prot_inuse_add(net, sk->sk_prot, -1);
1334         spin_unlock_bh(&net->packet.sklist_lock);
1335
1336         spin_lock(&po->bind_lock);
1337         if (po->running) {
1338                 /*
1339                  * Remove from protocol table
1340                  */
1341                 po->running = 0;
1342                 po->num = 0;
1343                 __dev_remove_pack(&po->prot_hook);
1344                 __sock_put(sk);
1345         }
1346         spin_unlock(&po->bind_lock);
1347
1348         packet_flush_mclist(sk);
1349
1350         memset(&req, 0, sizeof(req));
1351
1352         if (po->rx_ring.pg_vec)
1353                 packet_set_ring(sk, &req, 1, 0);
1354
1355         if (po->tx_ring.pg_vec)
1356                 packet_set_ring(sk, &req, 1, 1);
1357
1358         synchronize_net();
1359         /*
1360          *      Now the socket is dead. No more input will appear.
1361          */
1362         sock_orphan(sk);
1363         sock->sk = NULL;
1364
1365         /* Purge queues */
1366
1367         skb_queue_purge(&sk->sk_receive_queue);
1368         sk_refcnt_debug_release(sk);
1369
1370         sock_put(sk);
1371         return 0;
1372 }
1373
1374 /*
1375  *      Attach a packet hook.
1376  */
1377
1378 static int packet_do_bind(struct sock *sk, struct net_device *dev, __be16 protocol)
1379 {
1380         struct packet_sock *po = pkt_sk(sk);
1381         /*
1382          *      Detach an existing hook if present.
1383          */
1384
1385         lock_sock(sk);
1386
1387         spin_lock(&po->bind_lock);
1388         if (po->running) {
1389                 __sock_put(sk);
1390                 po->running = 0;
1391                 po->num = 0;
1392                 spin_unlock(&po->bind_lock);
1393                 dev_remove_pack(&po->prot_hook);
1394                 spin_lock(&po->bind_lock);
1395         }
1396
1397         po->num = protocol;
1398         po->prot_hook.type = protocol;
1399         po->prot_hook.dev = dev;
1400
1401         po->ifindex = dev ? dev->ifindex : 0;
1402
1403         if (protocol == 0)
1404                 goto out_unlock;
1405
1406         if (!dev || (dev->flags & IFF_UP)) {
1407                 dev_add_pack(&po->prot_hook);
1408                 sock_hold(sk);
1409                 po->running = 1;
1410         } else {
1411                 sk->sk_err = ENETDOWN;
1412                 if (!sock_flag(sk, SOCK_DEAD))
1413                         sk->sk_error_report(sk);
1414         }
1415
1416 out_unlock:
1417         spin_unlock(&po->bind_lock);
1418         release_sock(sk);
1419         return 0;
1420 }
1421
1422 /*
1423  *      Bind a packet socket to a device
1424  */
1425
1426 static int packet_bind_spkt(struct socket *sock, struct sockaddr *uaddr,
1427                             int addr_len)
1428 {
1429         struct sock *sk = sock->sk;
1430         char name[15];
1431         struct net_device *dev;
1432         int err = -ENODEV;
1433
1434         /*
1435          *      Check legality
1436          */
1437
1438         if (addr_len != sizeof(struct sockaddr))
1439                 return -EINVAL;
1440         strlcpy(name, uaddr->sa_data, sizeof(name));
1441
1442         dev = dev_get_by_name(sock_net(sk), name);
1443         if (dev) {
1444                 err = packet_do_bind(sk, dev, pkt_sk(sk)->num);
1445                 dev_put(dev);
1446         }
1447         return err;
1448 }
1449
1450 static int packet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
1451 {
1452         struct sockaddr_ll *sll = (struct sockaddr_ll *)uaddr;
1453         struct sock *sk = sock->sk;
1454         struct net_device *dev = NULL;
1455         int err;
1456
1457
1458         /*
1459          *      Check legality
1460          */
1461
1462         if (addr_len < sizeof(struct sockaddr_ll))
1463                 return -EINVAL;
1464         if (sll->sll_family != AF_PACKET)
1465                 return -EINVAL;
1466
1467         if (sll->sll_ifindex) {
1468                 err = -ENODEV;
1469                 dev = dev_get_by_index(sock_net(sk), sll->sll_ifindex);
1470                 if (dev == NULL)
1471                         goto out;
1472         }
1473         err = packet_do_bind(sk, dev, sll->sll_protocol ? : pkt_sk(sk)->num);
1474         if (dev)
1475                 dev_put(dev);
1476
1477 out:
1478         return err;
1479 }
1480
1481 static struct proto packet_proto = {
1482         .name     = "PACKET",
1483         .owner    = THIS_MODULE,
1484         .obj_size = sizeof(struct packet_sock),
1485 };
1486
1487 /*
1488  *      Create a packet of type SOCK_PACKET.
1489  */
1490
1491 static int packet_create(struct net *net, struct socket *sock, int protocol,
1492                          int kern)
1493 {
1494         struct sock *sk;
1495         struct packet_sock *po;
1496         __be16 proto = (__force __be16)protocol; /* weird, but documented */
1497         int err;
1498
1499         if (!capable(CAP_NET_RAW))
1500                 return -EPERM;
1501         if (sock->type != SOCK_DGRAM && sock->type != SOCK_RAW &&
1502             sock->type != SOCK_PACKET)
1503                 return -ESOCKTNOSUPPORT;
1504
1505         sock->state = SS_UNCONNECTED;
1506
1507         err = -ENOBUFS;
1508         sk = sk_alloc(net, PF_PACKET, GFP_KERNEL, &packet_proto);
1509         if (sk == NULL)
1510                 goto out;
1511
1512         sock->ops = &packet_ops;
1513         if (sock->type == SOCK_PACKET)
1514                 sock->ops = &packet_ops_spkt;
1515
1516         sock_init_data(sock, sk);
1517
1518         po = pkt_sk(sk);
1519         sk->sk_family = PF_PACKET;
1520         po->num = proto;
1521
1522         sk->sk_destruct = packet_sock_destruct;
1523         sk_refcnt_debug_inc(sk);
1524
1525         /*
1526          *      Attach a protocol block
1527          */
1528
1529         spin_lock_init(&po->bind_lock);
1530         mutex_init(&po->pg_vec_lock);
1531         po->prot_hook.func = packet_rcv;
1532
1533         if (sock->type == SOCK_PACKET)
1534                 po->prot_hook.func = packet_rcv_spkt;
1535
1536         po->prot_hook.af_packet_priv = sk;
1537
1538         if (proto) {
1539                 po->prot_hook.type = proto;
1540                 dev_add_pack(&po->prot_hook);
1541                 sock_hold(sk);
1542                 po->running = 1;
1543         }
1544
1545         spin_lock_bh(&net->packet.sklist_lock);
1546         sk_add_node_rcu(sk, &net->packet.sklist);
1547         sock_prot_inuse_add(net, &packet_proto, 1);
1548         spin_unlock_bh(&net->packet.sklist_lock);
1549
1550         return 0;
1551 out:
1552         return err;
1553 }
1554
1555 static int packet_recv_error(struct sock *sk, struct msghdr *msg, int len)
1556 {
1557         struct sock_exterr_skb *serr;
1558         struct sk_buff *skb, *skb2;
1559         int copied, err;
1560
1561         err = -EAGAIN;
1562         skb = skb_dequeue(&sk->sk_error_queue);
1563         if (skb == NULL)
1564                 goto out;
1565
1566         copied = skb->len;
1567         if (copied > len) {
1568                 msg->msg_flags |= MSG_TRUNC;
1569                 copied = len;
1570         }
1571         err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
1572         if (err)
1573                 goto out_free_skb;
1574
1575         sock_recv_timestamp(msg, sk, skb);
1576
1577         serr = SKB_EXT_ERR(skb);
1578         put_cmsg(msg, SOL_PACKET, PACKET_TX_TIMESTAMP,
1579                  sizeof(serr->ee), &serr->ee);
1580
1581         msg->msg_flags |= MSG_ERRQUEUE;
1582         err = copied;
1583
1584         /* Reset and regenerate socket error */
1585         spin_lock_bh(&sk->sk_error_queue.lock);
1586         sk->sk_err = 0;
1587         if ((skb2 = skb_peek(&sk->sk_error_queue)) != NULL) {
1588                 sk->sk_err = SKB_EXT_ERR(skb2)->ee.ee_errno;
1589                 spin_unlock_bh(&sk->sk_error_queue.lock);
1590                 sk->sk_error_report(sk);
1591         } else
1592                 spin_unlock_bh(&sk->sk_error_queue.lock);
1593
1594 out_free_skb:
1595         kfree_skb(skb);
1596 out:
1597         return err;
1598 }
1599
1600 /*
1601  *      Pull a packet from our receive queue and hand it to the user.
1602  *      If necessary we block.
1603  */
1604
1605 static int packet_recvmsg(struct kiocb *iocb, struct socket *sock,
1606                           struct msghdr *msg, size_t len, int flags)
1607 {
1608         struct sock *sk = sock->sk;
1609         struct sk_buff *skb;
1610         int copied, err;
1611         struct sockaddr_ll *sll;
1612         int vnet_hdr_len = 0;
1613
1614         err = -EINVAL;
1615         if (flags & ~(MSG_PEEK|MSG_DONTWAIT|MSG_TRUNC|MSG_CMSG_COMPAT|MSG_ERRQUEUE))
1616                 goto out;
1617
1618 #if 0
1619         /* What error should we return now? EUNATTACH? */
1620         if (pkt_sk(sk)->ifindex < 0)
1621                 return -ENODEV;
1622 #endif
1623
1624         if (flags & MSG_ERRQUEUE) {
1625                 err = packet_recv_error(sk, msg, len);
1626                 goto out;
1627         }
1628
1629         /*
1630          *      Call the generic datagram receiver. This handles all sorts
1631          *      of horrible races and re-entrancy so we can forget about it
1632          *      in the protocol layers.
1633          *
1634          *      Now it will return ENETDOWN, if device have just gone down,
1635          *      but then it will block.
1636          */
1637
1638         skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &err);
1639
1640         /*
1641          *      An error occurred so return it. Because skb_recv_datagram()
1642          *      handles the blocking we don't see and worry about blocking
1643          *      retries.
1644          */
1645
1646         if (skb == NULL)
1647                 goto out;
1648
1649         if (pkt_sk(sk)->has_vnet_hdr) {
1650                 struct virtio_net_hdr vnet_hdr = { 0 };
1651
1652                 err = -EINVAL;
1653                 vnet_hdr_len = sizeof(vnet_hdr);
1654                 if (len < vnet_hdr_len)
1655                         goto out_free;
1656
1657                 len -= vnet_hdr_len;
1658
1659                 if (skb_is_gso(skb)) {
1660                         struct skb_shared_info *sinfo = skb_shinfo(skb);
1661
1662                         /* This is a hint as to how much should be linear. */
1663                         vnet_hdr.hdr_len = skb_headlen(skb);
1664                         vnet_hdr.gso_size = sinfo->gso_size;
1665                         if (sinfo->gso_type & SKB_GSO_TCPV4)
1666                                 vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV4;
1667                         else if (sinfo->gso_type & SKB_GSO_TCPV6)
1668                                 vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_TCPV6;
1669                         else if (sinfo->gso_type & SKB_GSO_UDP)
1670                                 vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_UDP;
1671                         else if (sinfo->gso_type & SKB_GSO_FCOE)
1672                                 goto out_free;
1673                         else
1674                                 BUG();
1675                         if (sinfo->gso_type & SKB_GSO_TCP_ECN)
1676                                 vnet_hdr.gso_type |= VIRTIO_NET_HDR_GSO_ECN;
1677                 } else
1678                         vnet_hdr.gso_type = VIRTIO_NET_HDR_GSO_NONE;
1679
1680                 if (skb->ip_summed == CHECKSUM_PARTIAL) {
1681                         vnet_hdr.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM;
1682                         vnet_hdr.csum_start = skb_checksum_start_offset(skb);
1683                         vnet_hdr.csum_offset = skb->csum_offset;
1684                 } /* else everything is zero */
1685
1686                 err = memcpy_toiovec(msg->msg_iov, (void *)&vnet_hdr,
1687                                      vnet_hdr_len);
1688                 if (err < 0)
1689                         goto out_free;
1690         }
1691
1692         /*
1693          *      If the address length field is there to be filled in, we fill
1694          *      it in now.
1695          */
1696
1697         sll = &PACKET_SKB_CB(skb)->sa.ll;
1698         if (sock->type == SOCK_PACKET)
1699                 msg->msg_namelen = sizeof(struct sockaddr_pkt);
1700         else
1701                 msg->msg_namelen = sll->sll_halen + offsetof(struct sockaddr_ll, sll_addr);
1702
1703         /*
1704          *      You lose any data beyond the buffer you gave. If it worries a
1705          *      user program they can ask the device for its MTU anyway.
1706          */
1707
1708         copied = skb->len;
1709         if (copied > len) {
1710                 copied = len;
1711                 msg->msg_flags |= MSG_TRUNC;
1712         }
1713
1714         err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
1715         if (err)
1716                 goto out_free;
1717
1718         sock_recv_ts_and_drops(msg, sk, skb);
1719
1720         if (msg->msg_name)
1721                 memcpy(msg->msg_name, &PACKET_SKB_CB(skb)->sa,
1722                        msg->msg_namelen);
1723
1724         if (pkt_sk(sk)->auxdata) {
1725                 struct tpacket_auxdata aux;
1726
1727                 aux.tp_status = TP_STATUS_USER;
1728                 if (skb->ip_summed == CHECKSUM_PARTIAL)
1729                         aux.tp_status |= TP_STATUS_CSUMNOTREADY;
1730                 aux.tp_len = PACKET_SKB_CB(skb)->origlen;
1731                 aux.tp_snaplen = skb->len;
1732                 aux.tp_mac = 0;
1733                 aux.tp_net = skb_network_offset(skb);
1734                 if (vlan_tx_tag_present(skb)) {
1735                         aux.tp_vlan_tci = vlan_tx_tag_get(skb);
1736                         aux.tp_status |= TP_STATUS_VLAN_VALID;
1737                 } else {
1738                         aux.tp_vlan_tci = 0;
1739                 }
1740                 aux.tp_padding = 0;
1741                 put_cmsg(msg, SOL_PACKET, PACKET_AUXDATA, sizeof(aux), &aux);
1742         }
1743
1744         /*
1745          *      Free or return the buffer as appropriate. Again this
1746          *      hides all the races and re-entrancy issues from us.
1747          */
1748         err = vnet_hdr_len + ((flags&MSG_TRUNC) ? skb->len : copied);
1749
1750 out_free:
1751         skb_free_datagram(sk, skb);
1752 out:
1753         return err;
1754 }
1755
1756 static int packet_getname_spkt(struct socket *sock, struct sockaddr *uaddr,
1757                                int *uaddr_len, int peer)
1758 {
1759         struct net_device *dev;
1760         struct sock *sk = sock->sk;
1761
1762         if (peer)
1763                 return -EOPNOTSUPP;
1764
1765         uaddr->sa_family = AF_PACKET;
1766         rcu_read_lock();
1767         dev = dev_get_by_index_rcu(sock_net(sk), pkt_sk(sk)->ifindex);
1768         if (dev)
1769                 strncpy(uaddr->sa_data, dev->name, 14);
1770         else
1771                 memset(uaddr->sa_data, 0, 14);
1772         rcu_read_unlock();
1773         *uaddr_len = sizeof(*uaddr);
1774
1775         return 0;
1776 }
1777
1778 static int packet_getname(struct socket *sock, struct sockaddr *uaddr,
1779                           int *uaddr_len, int peer)
1780 {
1781         struct net_device *dev;
1782         struct sock *sk = sock->sk;
1783         struct packet_sock *po = pkt_sk(sk);
1784         DECLARE_SOCKADDR(struct sockaddr_ll *, sll, uaddr);
1785
1786         if (peer)
1787                 return -EOPNOTSUPP;
1788
1789         sll->sll_family = AF_PACKET;
1790         sll->sll_ifindex = po->ifindex;
1791         sll->sll_protocol = po->num;
1792         sll->sll_pkttype = 0;
1793         rcu_read_lock();
1794         dev = dev_get_by_index_rcu(sock_net(sk), po->ifindex);
1795         if (dev) {
1796                 sll->sll_hatype = dev->type;
1797                 sll->sll_halen = dev->addr_len;
1798                 memcpy(sll->sll_addr, dev->dev_addr, dev->addr_len);
1799         } else {
1800                 sll->sll_hatype = 0;    /* Bad: we have no ARPHRD_UNSPEC */
1801                 sll->sll_halen = 0;
1802         }
1803         rcu_read_unlock();
1804         *uaddr_len = offsetof(struct sockaddr_ll, sll_addr) + sll->sll_halen;
1805
1806         return 0;
1807 }
1808
1809 static int packet_dev_mc(struct net_device *dev, struct packet_mclist *i,
1810                          int what)
1811 {
1812         switch (i->type) {
1813         case PACKET_MR_MULTICAST:
1814                 if (i->alen != dev->addr_len)
1815                         return -EINVAL;
1816                 if (what > 0)
1817                         return dev_mc_add(dev, i->addr);
1818                 else
1819                         return dev_mc_del(dev, i->addr);
1820                 break;
1821         case PACKET_MR_PROMISC:
1822                 return dev_set_promiscuity(dev, what);
1823                 break;
1824         case PACKET_MR_ALLMULTI:
1825                 return dev_set_allmulti(dev, what);
1826                 break;
1827         case PACKET_MR_UNICAST:
1828                 if (i->alen != dev->addr_len)
1829                         return -EINVAL;
1830                 if (what > 0)
1831                         return dev_uc_add(dev, i->addr);
1832                 else
1833                         return dev_uc_del(dev, i->addr);
1834                 break;
1835         default:
1836                 break;
1837         }
1838         return 0;
1839 }
1840
1841 static void packet_dev_mclist(struct net_device *dev, struct packet_mclist *i, int what)
1842 {
1843         for ( ; i; i = i->next) {
1844                 if (i->ifindex == dev->ifindex)
1845                         packet_dev_mc(dev, i, what);
1846         }
1847 }
1848
1849 static int packet_mc_add(struct sock *sk, struct packet_mreq_max *mreq)
1850 {
1851         struct packet_sock *po = pkt_sk(sk);
1852         struct packet_mclist *ml, *i;
1853         struct net_device *dev;
1854         int err;
1855
1856         rtnl_lock();
1857
1858         err = -ENODEV;
1859         dev = __dev_get_by_index(sock_net(sk), mreq->mr_ifindex);
1860         if (!dev)
1861                 goto done;
1862
1863         err = -EINVAL;
1864         if (mreq->mr_alen > dev->addr_len)
1865                 goto done;
1866
1867         err = -ENOBUFS;
1868         i = kmalloc(sizeof(*i), GFP_KERNEL);
1869         if (i == NULL)
1870                 goto done;
1871
1872         err = 0;
1873         for (ml = po->mclist; ml; ml = ml->next) {
1874                 if (ml->ifindex == mreq->mr_ifindex &&
1875                     ml->type == mreq->mr_type &&
1876                     ml->alen == mreq->mr_alen &&
1877                     memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
1878                         ml->count++;
1879                         /* Free the new element ... */
1880                         kfree(i);
1881                         goto done;
1882                 }
1883         }
1884
1885         i->type = mreq->mr_type;
1886         i->ifindex = mreq->mr_ifindex;
1887         i->alen = mreq->mr_alen;
1888         memcpy(i->addr, mreq->mr_address, i->alen);
1889         i->count = 1;
1890         i->next = po->mclist;
1891         po->mclist = i;
1892         err = packet_dev_mc(dev, i, 1);
1893         if (err) {
1894                 po->mclist = i->next;
1895                 kfree(i);
1896         }
1897
1898 done:
1899         rtnl_unlock();
1900         return err;
1901 }
1902
1903 static int packet_mc_drop(struct sock *sk, struct packet_mreq_max *mreq)
1904 {
1905         struct packet_mclist *ml, **mlp;
1906
1907         rtnl_lock();
1908
1909         for (mlp = &pkt_sk(sk)->mclist; (ml = *mlp) != NULL; mlp = &ml->next) {
1910                 if (ml->ifindex == mreq->mr_ifindex &&
1911                     ml->type == mreq->mr_type &&
1912                     ml->alen == mreq->mr_alen &&
1913                     memcmp(ml->addr, mreq->mr_address, ml->alen) == 0) {
1914                         if (--ml->count == 0) {
1915                                 struct net_device *dev;
1916                                 *mlp = ml->next;
1917                                 dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
1918                                 if (dev)
1919                                         packet_dev_mc(dev, ml, -1);
1920                                 kfree(ml);
1921                         }
1922                         rtnl_unlock();
1923                         return 0;
1924                 }
1925         }
1926         rtnl_unlock();
1927         return -EADDRNOTAVAIL;
1928 }
1929
1930 static void packet_flush_mclist(struct sock *sk)
1931 {
1932         struct packet_sock *po = pkt_sk(sk);
1933         struct packet_mclist *ml;
1934
1935         if (!po->mclist)
1936                 return;
1937
1938         rtnl_lock();
1939         while ((ml = po->mclist) != NULL) {
1940                 struct net_device *dev;
1941
1942                 po->mclist = ml->next;
1943                 dev = __dev_get_by_index(sock_net(sk), ml->ifindex);
1944                 if (dev != NULL)
1945                         packet_dev_mc(dev, ml, -1);
1946                 kfree(ml);
1947         }
1948         rtnl_unlock();
1949 }
1950
1951 static int
1952 packet_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen)
1953 {
1954         struct sock *sk = sock->sk;
1955         struct packet_sock *po = pkt_sk(sk);
1956         int ret;
1957
1958         if (level != SOL_PACKET)
1959                 return -ENOPROTOOPT;
1960
1961         switch (optname) {
1962         case PACKET_ADD_MEMBERSHIP:
1963         case PACKET_DROP_MEMBERSHIP:
1964         {
1965                 struct packet_mreq_max mreq;
1966                 int len = optlen;
1967                 memset(&mreq, 0, sizeof(mreq));
1968                 if (len < sizeof(struct packet_mreq))
1969                         return -EINVAL;
1970                 if (len > sizeof(mreq))
1971                         len = sizeof(mreq);
1972                 if (copy_from_user(&mreq, optval, len))
1973                         return -EFAULT;
1974                 if (len < (mreq.mr_alen + offsetof(struct packet_mreq, mr_address)))
1975                         return -EINVAL;
1976                 if (optname == PACKET_ADD_MEMBERSHIP)
1977                         ret = packet_mc_add(sk, &mreq);
1978                 else
1979                         ret = packet_mc_drop(sk, &mreq);
1980                 return ret;
1981         }
1982
1983         case PACKET_RX_RING:
1984         case PACKET_TX_RING:
1985         {
1986                 struct tpacket_req req;
1987
1988                 if (optlen < sizeof(req))
1989                         return -EINVAL;
1990                 if (pkt_sk(sk)->has_vnet_hdr)
1991                         return -EINVAL;
1992                 if (copy_from_user(&req, optval, sizeof(req)))
1993                         return -EFAULT;
1994                 return packet_set_ring(sk, &req, 0, optname == PACKET_TX_RING);
1995         }
1996         case PACKET_COPY_THRESH:
1997         {
1998                 int val;
1999
2000                 if (optlen != sizeof(val))
2001                         return -EINVAL;
2002                 if (copy_from_user(&val, optval, sizeof(val)))
2003                         return -EFAULT;
2004
2005                 pkt_sk(sk)->copy_thresh = val;
2006                 return 0;
2007         }
2008         case PACKET_VERSION:
2009         {
2010                 int val;
2011
2012                 if (optlen != sizeof(val))
2013                         return -EINVAL;
2014                 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
2015                         return -EBUSY;
2016                 if (copy_from_user(&val, optval, sizeof(val)))
2017                         return -EFAULT;
2018                 switch (val) {
2019                 case TPACKET_V1:
2020                 case TPACKET_V2:
2021                         po->tp_version = val;
2022                         return 0;
2023                 default:
2024                         return -EINVAL;
2025                 }
2026         }
2027         case PACKET_RESERVE:
2028         {
2029                 unsigned int val;
2030
2031                 if (optlen != sizeof(val))
2032                         return -EINVAL;
2033                 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
2034                         return -EBUSY;
2035                 if (copy_from_user(&val, optval, sizeof(val)))
2036                         return -EFAULT;
2037                 po->tp_reserve = val;
2038                 return 0;
2039         }
2040         case PACKET_LOSS:
2041         {
2042                 unsigned int val;
2043
2044                 if (optlen != sizeof(val))
2045                         return -EINVAL;
2046                 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
2047                         return -EBUSY;
2048                 if (copy_from_user(&val, optval, sizeof(val)))
2049                         return -EFAULT;
2050                 po->tp_loss = !!val;
2051                 return 0;
2052         }
2053         case PACKET_AUXDATA:
2054         {
2055                 int val;
2056
2057                 if (optlen < sizeof(val))
2058                         return -EINVAL;
2059                 if (copy_from_user(&val, optval, sizeof(val)))
2060                         return -EFAULT;
2061
2062                 po->auxdata = !!val;
2063                 return 0;
2064         }
2065         case PACKET_ORIGDEV:
2066         {
2067                 int val;
2068
2069                 if (optlen < sizeof(val))
2070                         return -EINVAL;
2071                 if (copy_from_user(&val, optval, sizeof(val)))
2072                         return -EFAULT;
2073
2074                 po->origdev = !!val;
2075                 return 0;
2076         }
2077         case PACKET_VNET_HDR:
2078         {
2079                 int val;
2080
2081                 if (sock->type != SOCK_RAW)
2082                         return -EINVAL;
2083                 if (po->rx_ring.pg_vec || po->tx_ring.pg_vec)
2084                         return -EBUSY;
2085                 if (optlen < sizeof(val))
2086                         return -EINVAL;
2087                 if (copy_from_user(&val, optval, sizeof(val)))
2088                         return -EFAULT;
2089
2090                 po->has_vnet_hdr = !!val;
2091                 return 0;
2092         }
2093         case PACKET_TIMESTAMP:
2094         {
2095                 int val;
2096
2097                 if (optlen != sizeof(val))
2098                         return -EINVAL;
2099                 if (copy_from_user(&val, optval, sizeof(val)))
2100                         return -EFAULT;
2101
2102                 po->tp_tstamp = val;
2103                 return 0;
2104         }
2105         default:
2106                 return -ENOPROTOOPT;
2107         }
2108 }
2109
2110 static int packet_getsockopt(struct socket *sock, int level, int optname,
2111                              char __user *optval, int __user *optlen)
2112 {
2113         int len;
2114         int val;
2115         struct sock *sk = sock->sk;
2116         struct packet_sock *po = pkt_sk(sk);
2117         void *data;
2118         struct tpacket_stats st;
2119
2120         if (level != SOL_PACKET)
2121                 return -ENOPROTOOPT;
2122
2123         if (get_user(len, optlen))
2124                 return -EFAULT;
2125
2126         if (len < 0)
2127                 return -EINVAL;
2128
2129         switch (optname) {
2130         case PACKET_STATISTICS:
2131                 if (len > sizeof(struct tpacket_stats))
2132                         len = sizeof(struct tpacket_stats);
2133                 spin_lock_bh(&sk->sk_receive_queue.lock);
2134                 st = po->stats;
2135                 memset(&po->stats, 0, sizeof(st));
2136                 spin_unlock_bh(&sk->sk_receive_queue.lock);
2137                 st.tp_packets += st.tp_drops;
2138
2139                 data = &st;
2140                 break;
2141         case PACKET_AUXDATA:
2142                 if (len > sizeof(int))
2143                         len = sizeof(int);
2144                 val = po->auxdata;
2145
2146                 data = &val;
2147                 break;
2148         case PACKET_ORIGDEV:
2149                 if (len > sizeof(int))
2150                         len = sizeof(int);
2151                 val = po->origdev;
2152
2153                 data = &val;
2154                 break;
2155         case PACKET_VNET_HDR:
2156                 if (len > sizeof(int))
2157                         len = sizeof(int);
2158                 val = po->has_vnet_hdr;
2159
2160                 data = &val;
2161                 break;
2162         case PACKET_VERSION:
2163                 if (len > sizeof(int))
2164                         len = sizeof(int);
2165                 val = po->tp_version;
2166                 data = &val;
2167                 break;
2168         case PACKET_HDRLEN:
2169                 if (len > sizeof(int))
2170                         len = sizeof(int);
2171                 if (copy_from_user(&val, optval, len))
2172                         return -EFAULT;
2173                 switch (val) {
2174                 case TPACKET_V1:
2175                         val = sizeof(struct tpacket_hdr);
2176                         break;
2177                 case TPACKET_V2:
2178                         val = sizeof(struct tpacket2_hdr);
2179                         break;
2180                 default:
2181                         return -EINVAL;
2182                 }
2183                 data = &val;
2184                 break;
2185         case PACKET_RESERVE:
2186                 if (len > sizeof(unsigned int))
2187                         len = sizeof(unsigned int);
2188                 val = po->tp_reserve;
2189                 data = &val;
2190                 break;
2191         case PACKET_LOSS:
2192                 if (len > sizeof(unsigned int))
2193                         len = sizeof(unsigned int);
2194                 val = po->tp_loss;
2195                 data = &val;
2196                 break;
2197         case PACKET_TIMESTAMP:
2198                 if (len > sizeof(int))
2199                         len = sizeof(int);
2200                 val = po->tp_tstamp;
2201                 data = &val;
2202                 break;
2203         default:
2204                 return -ENOPROTOOPT;
2205         }
2206
2207         if (put_user(len, optlen))
2208                 return -EFAULT;
2209         if (copy_to_user(optval, data, len))
2210                 return -EFAULT;
2211         return 0;
2212 }
2213
2214
2215 static int packet_notifier(struct notifier_block *this, unsigned long msg, void *data)
2216 {
2217         struct sock *sk;
2218         struct hlist_node *node;
2219         struct net_device *dev = data;
2220         struct net *net = dev_net(dev);
2221
2222         rcu_read_lock();
2223         sk_for_each_rcu(sk, node, &net->packet.sklist) {
2224                 struct packet_sock *po = pkt_sk(sk);
2225
2226                 switch (msg) {
2227                 case NETDEV_UNREGISTER:
2228                         if (po->mclist)
2229                                 packet_dev_mclist(dev, po->mclist, -1);
2230                         /* fallthrough */
2231
2232                 case NETDEV_DOWN:
2233                         if (dev->ifindex == po->ifindex) {
2234                                 spin_lock(&po->bind_lock);
2235                                 if (po->running) {
2236                                         __dev_remove_pack(&po->prot_hook);
2237                                         __sock_put(sk);
2238                                         po->running = 0;
2239                                         sk->sk_err = ENETDOWN;
2240                                         if (!sock_flag(sk, SOCK_DEAD))
2241                                                 sk->sk_error_report(sk);
2242                                 }
2243                                 if (msg == NETDEV_UNREGISTER) {
2244                                         po->ifindex = -1;
2245                                         po->prot_hook.dev = NULL;
2246                                 }
2247                                 spin_unlock(&po->bind_lock);
2248                         }
2249                         break;
2250                 case NETDEV_UP:
2251                         if (dev->ifindex == po->ifindex) {
2252                                 spin_lock(&po->bind_lock);
2253                                 if (po->num && !po->running) {
2254                                         dev_add_pack(&po->prot_hook);
2255                                         sock_hold(sk);
2256                                         po->running = 1;
2257                                 }
2258                                 spin_unlock(&po->bind_lock);
2259                         }
2260                         break;
2261                 }
2262         }
2263         rcu_read_unlock();
2264         return NOTIFY_DONE;
2265 }
2266
2267
2268 static int packet_ioctl(struct socket *sock, unsigned int cmd,
2269                         unsigned long arg)
2270 {
2271         struct sock *sk = sock->sk;
2272
2273         switch (cmd) {
2274         case SIOCOUTQ:
2275         {
2276                 int amount = sk_wmem_alloc_get(sk);
2277
2278                 return put_user(amount, (int __user *)arg);
2279         }
2280         case SIOCINQ:
2281         {
2282                 struct sk_buff *skb;
2283                 int amount = 0;
2284
2285                 spin_lock_bh(&sk->sk_receive_queue.lock);
2286                 skb = skb_peek(&sk->sk_receive_queue);
2287                 if (skb)
2288                         amount = skb->len;
2289                 spin_unlock_bh(&sk->sk_receive_queue.lock);
2290                 return put_user(amount, (int __user *)arg);
2291         }
2292         case SIOCGSTAMP:
2293                 return sock_get_timestamp(sk, (struct timeval __user *)arg);
2294         case SIOCGSTAMPNS:
2295                 return sock_get_timestampns(sk, (struct timespec __user *)arg);
2296
2297 #ifdef CONFIG_INET
2298         case SIOCADDRT:
2299         case SIOCDELRT:
2300         case SIOCDARP:
2301         case SIOCGARP:
2302         case SIOCSARP:
2303         case SIOCGIFADDR:
2304         case SIOCSIFADDR:
2305         case SIOCGIFBRDADDR:
2306         case SIOCSIFBRDADDR:
2307         case SIOCGIFNETMASK:
2308         case SIOCSIFNETMASK:
2309         case SIOCGIFDSTADDR:
2310         case SIOCSIFDSTADDR:
2311         case SIOCSIFFLAGS:
2312                 return inet_dgram_ops.ioctl(sock, cmd, arg);
2313 #endif
2314
2315         default:
2316                 return -ENOIOCTLCMD;
2317         }
2318         return 0;
2319 }
2320
2321 static unsigned int packet_poll(struct file *file, struct socket *sock,
2322                                 poll_table *wait)
2323 {
2324         struct sock *sk = sock->sk;
2325         struct packet_sock *po = pkt_sk(sk);
2326         unsigned int mask = datagram_poll(file, sock, wait);
2327
2328         spin_lock_bh(&sk->sk_receive_queue.lock);
2329         if (po->rx_ring.pg_vec) {
2330                 if (!packet_previous_frame(po, &po->rx_ring, TP_STATUS_KERNEL))
2331                         mask |= POLLIN | POLLRDNORM;
2332         }
2333         spin_unlock_bh(&sk->sk_receive_queue.lock);
2334         spin_lock_bh(&sk->sk_write_queue.lock);
2335         if (po->tx_ring.pg_vec) {
2336                 if (packet_current_frame(po, &po->tx_ring, TP_STATUS_AVAILABLE))
2337                         mask |= POLLOUT | POLLWRNORM;
2338         }
2339         spin_unlock_bh(&sk->sk_write_queue.lock);
2340         return mask;
2341 }
2342
2343
2344 /* Dirty? Well, I still did not learn better way to account
2345  * for user mmaps.
2346  */
2347
2348 static void packet_mm_open(struct vm_area_struct *vma)
2349 {
2350         struct file *file = vma->vm_file;
2351         struct socket *sock = file->private_data;
2352         struct sock *sk = sock->sk;
2353
2354         if (sk)
2355                 atomic_inc(&pkt_sk(sk)->mapped);
2356 }
2357
2358 static void packet_mm_close(struct vm_area_struct *vma)
2359 {
2360         struct file *file = vma->vm_file;
2361         struct socket *sock = file->private_data;
2362         struct sock *sk = sock->sk;
2363
2364         if (sk)
2365                 atomic_dec(&pkt_sk(sk)->mapped);
2366 }
2367
2368 static const struct vm_operations_struct packet_mmap_ops = {
2369         .open   =       packet_mm_open,
2370         .close  =       packet_mm_close,
2371 };
2372
2373 static void free_pg_vec(struct pgv *pg_vec, unsigned int order,
2374                         unsigned int len)
2375 {
2376         int i;
2377
2378         for (i = 0; i < len; i++) {
2379                 if (likely(pg_vec[i].buffer)) {
2380                         if (is_vmalloc_addr(pg_vec[i].buffer))
2381                                 vfree(pg_vec[i].buffer);
2382                         else
2383                                 free_pages((unsigned long)pg_vec[i].buffer,
2384                                            order);
2385                         pg_vec[i].buffer = NULL;
2386                 }
2387         }
2388         kfree(pg_vec);
2389 }
2390
2391 static inline char *alloc_one_pg_vec_page(unsigned long order)
2392 {
2393         char *buffer = NULL;
2394         gfp_t gfp_flags = GFP_KERNEL | __GFP_COMP |
2395                           __GFP_ZERO | __GFP_NOWARN | __GFP_NORETRY;
2396
2397         buffer = (char *) __get_free_pages(gfp_flags, order);
2398
2399         if (buffer)
2400                 return buffer;
2401
2402         /*
2403          * __get_free_pages failed, fall back to vmalloc
2404          */
2405         buffer = vzalloc((1 << order) * PAGE_SIZE);
2406
2407         if (buffer)
2408                 return buffer;
2409
2410         /*
2411          * vmalloc failed, lets dig into swap here
2412          */
2413         gfp_flags &= ~__GFP_NORETRY;
2414         buffer = (char *)__get_free_pages(gfp_flags, order);
2415         if (buffer)
2416                 return buffer;
2417
2418         /*
2419          * complete and utter failure
2420          */
2421         return NULL;
2422 }
2423
2424 static struct pgv *alloc_pg_vec(struct tpacket_req *req, int order)
2425 {
2426         unsigned int block_nr = req->tp_block_nr;
2427         struct pgv *pg_vec;
2428         int i;
2429
2430         pg_vec = kcalloc(block_nr, sizeof(struct pgv), GFP_KERNEL);
2431         if (unlikely(!pg_vec))
2432                 goto out;
2433
2434         for (i = 0; i < block_nr; i++) {
2435                 pg_vec[i].buffer = alloc_one_pg_vec_page(order);
2436                 if (unlikely(!pg_vec[i].buffer))
2437                         goto out_free_pgvec;
2438         }
2439
2440 out:
2441         return pg_vec;
2442
2443 out_free_pgvec:
2444         free_pg_vec(pg_vec, order, block_nr);
2445         pg_vec = NULL;
2446         goto out;
2447 }
2448
2449 static int packet_set_ring(struct sock *sk, struct tpacket_req *req,
2450                 int closing, int tx_ring)
2451 {
2452         struct pgv *pg_vec = NULL;
2453         struct packet_sock *po = pkt_sk(sk);
2454         int was_running, order = 0;
2455         struct packet_ring_buffer *rb;
2456         struct sk_buff_head *rb_queue;
2457         __be16 num;
2458         int err;
2459
2460         rb = tx_ring ? &po->tx_ring : &po->rx_ring;
2461         rb_queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue;
2462
2463         err = -EBUSY;
2464         if (!closing) {
2465                 if (atomic_read(&po->mapped))
2466                         goto out;
2467                 if (atomic_read(&rb->pending))
2468                         goto out;
2469         }
2470
2471         if (req->tp_block_nr) {
2472                 /* Sanity tests and some calculations */
2473                 err = -EBUSY;
2474                 if (unlikely(rb->pg_vec))
2475                         goto out;
2476
2477                 switch (po->tp_version) {
2478                 case TPACKET_V1:
2479                         po->tp_hdrlen = TPACKET_HDRLEN;
2480                         break;
2481                 case TPACKET_V2:
2482                         po->tp_hdrlen = TPACKET2_HDRLEN;
2483                         break;
2484                 }
2485
2486                 err = -EINVAL;
2487                 if (unlikely((int)req->tp_block_size <= 0))
2488                         goto out;
2489                 if (unlikely(req->tp_block_size & (PAGE_SIZE - 1)))
2490                         goto out;
2491                 if (unlikely(req->tp_frame_size < po->tp_hdrlen +
2492                                         po->tp_reserve))
2493                         goto out;
2494                 if (unlikely(req->tp_frame_size & (TPACKET_ALIGNMENT - 1)))
2495                         goto out;
2496
2497                 rb->frames_per_block = req->tp_block_size/req->tp_frame_size;
2498                 if (unlikely(rb->frames_per_block <= 0))
2499                         goto out;
2500                 if (unlikely((rb->frames_per_block * req->tp_block_nr) !=
2501                                         req->tp_frame_nr))
2502                         goto out;
2503
2504                 err = -ENOMEM;
2505                 order = get_order(req->tp_block_size);
2506                 pg_vec = alloc_pg_vec(req, order);
2507                 if (unlikely(!pg_vec))
2508                         goto out;
2509         }
2510         /* Done */
2511         else {
2512                 err = -EINVAL;
2513                 if (unlikely(req->tp_frame_nr))
2514                         goto out;
2515         }
2516
2517         lock_sock(sk);
2518
2519         /* Detach socket from network */
2520         spin_lock(&po->bind_lock);
2521         was_running = po->running;
2522         num = po->num;
2523         if (was_running) {
2524                 __dev_remove_pack(&po->prot_hook);
2525                 po->num = 0;
2526                 po->running = 0;
2527                 __sock_put(sk);
2528         }
2529         spin_unlock(&po->bind_lock);
2530
2531         synchronize_net();
2532
2533         err = -EBUSY;
2534         mutex_lock(&po->pg_vec_lock);
2535         if (closing || atomic_read(&po->mapped) == 0) {
2536                 err = 0;
2537                 spin_lock_bh(&rb_queue->lock);
2538                 swap(rb->pg_vec, pg_vec);
2539                 rb->frame_max = (req->tp_frame_nr - 1);
2540                 rb->head = 0;
2541                 rb->frame_size = req->tp_frame_size;
2542                 spin_unlock_bh(&rb_queue->lock);
2543
2544                 swap(rb->pg_vec_order, order);
2545                 swap(rb->pg_vec_len, req->tp_block_nr);
2546
2547                 rb->pg_vec_pages = req->tp_block_size/PAGE_SIZE;
2548                 po->prot_hook.func = (po->rx_ring.pg_vec) ?
2549                                                 tpacket_rcv : packet_rcv;
2550                 skb_queue_purge(rb_queue);
2551                 if (atomic_read(&po->mapped))
2552                         pr_err("packet_mmap: vma is busy: %d\n",
2553                                atomic_read(&po->mapped));
2554         }
2555         mutex_unlock(&po->pg_vec_lock);
2556
2557         spin_lock(&po->bind_lock);
2558         if (was_running && !po->running) {
2559                 sock_hold(sk);
2560                 po->running = 1;
2561                 po->num = num;
2562                 dev_add_pack(&po->prot_hook);
2563         }
2564         spin_unlock(&po->bind_lock);
2565
2566         release_sock(sk);
2567
2568         if (pg_vec)
2569                 free_pg_vec(pg_vec, order, req->tp_block_nr);
2570 out:
2571         return err;
2572 }
2573
2574 static int packet_mmap(struct file *file, struct socket *sock,
2575                 struct vm_area_struct *vma)
2576 {
2577         struct sock *sk = sock->sk;
2578         struct packet_sock *po = pkt_sk(sk);
2579         unsigned long size, expected_size;
2580         struct packet_ring_buffer *rb;
2581         unsigned long start;
2582         int err = -EINVAL;
2583         int i;
2584
2585         if (vma->vm_pgoff)
2586                 return -EINVAL;
2587
2588         mutex_lock(&po->pg_vec_lock);
2589
2590         expected_size = 0;
2591         for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
2592                 if (rb->pg_vec) {
2593                         expected_size += rb->pg_vec_len
2594                                                 * rb->pg_vec_pages
2595                                                 * PAGE_SIZE;
2596                 }
2597         }
2598
2599         if (expected_size == 0)
2600                 goto out;
2601
2602         size = vma->vm_end - vma->vm_start;
2603         if (size != expected_size)
2604                 goto out;
2605
2606         start = vma->vm_start;
2607         for (rb = &po->rx_ring; rb <= &po->tx_ring; rb++) {
2608                 if (rb->pg_vec == NULL)
2609                         continue;
2610
2611                 for (i = 0; i < rb->pg_vec_len; i++) {
2612                         struct page *page;
2613                         void *kaddr = rb->pg_vec[i].buffer;
2614                         int pg_num;
2615
2616                         for (pg_num = 0; pg_num < rb->pg_vec_pages; pg_num++) {
2617                                 page = pgv_to_page(kaddr);
2618                                 err = vm_insert_page(vma, start, page);
2619                                 if (unlikely(err))
2620                                         goto out;
2621                                 start += PAGE_SIZE;
2622                                 kaddr += PAGE_SIZE;
2623                         }
2624                 }
2625         }
2626
2627         atomic_inc(&po->mapped);
2628         vma->vm_ops = &packet_mmap_ops;
2629         err = 0;
2630
2631 out:
2632         mutex_unlock(&po->pg_vec_lock);
2633         return err;
2634 }
2635
2636 static const struct proto_ops packet_ops_spkt = {
2637         .family =       PF_PACKET,
2638         .owner =        THIS_MODULE,
2639         .release =      packet_release,
2640         .bind =         packet_bind_spkt,
2641         .connect =      sock_no_connect,
2642         .socketpair =   sock_no_socketpair,
2643         .accept =       sock_no_accept,
2644         .getname =      packet_getname_spkt,
2645         .poll =         datagram_poll,
2646         .ioctl =        packet_ioctl,
2647         .listen =       sock_no_listen,
2648         .shutdown =     sock_no_shutdown,
2649         .setsockopt =   sock_no_setsockopt,
2650         .getsockopt =   sock_no_getsockopt,
2651         .sendmsg =      packet_sendmsg_spkt,
2652         .recvmsg =      packet_recvmsg,
2653         .mmap =         sock_no_mmap,
2654         .sendpage =     sock_no_sendpage,
2655 };
2656
2657 static const struct proto_ops packet_ops = {
2658         .family =       PF_PACKET,
2659         .owner =        THIS_MODULE,
2660         .release =      packet_release,
2661         .bind =         packet_bind,
2662         .connect =      sock_no_connect,
2663         .socketpair =   sock_no_socketpair,
2664         .accept =       sock_no_accept,
2665         .getname =      packet_getname,
2666         .poll =         packet_poll,
2667         .ioctl =        packet_ioctl,
2668         .listen =       sock_no_listen,
2669         .shutdown =     sock_no_shutdown,
2670         .setsockopt =   packet_setsockopt,
2671         .getsockopt =   packet_getsockopt,
2672         .sendmsg =      packet_sendmsg,
2673         .recvmsg =      packet_recvmsg,
2674         .mmap =         packet_mmap,
2675         .sendpage =     sock_no_sendpage,
2676 };
2677
2678 static const struct net_proto_family packet_family_ops = {
2679         .family =       PF_PACKET,
2680         .create =       packet_create,
2681         .owner  =       THIS_MODULE,
2682 };
2683
2684 static struct notifier_block packet_netdev_notifier = {
2685         .notifier_call =        packet_notifier,
2686 };
2687
2688 #ifdef CONFIG_PROC_FS
2689
2690 static void *packet_seq_start(struct seq_file *seq, loff_t *pos)
2691         __acquires(RCU)
2692 {
2693         struct net *net = seq_file_net(seq);
2694
2695         rcu_read_lock();
2696         return seq_hlist_start_head_rcu(&net->packet.sklist, *pos);
2697 }
2698
2699 static void *packet_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2700 {
2701         struct net *net = seq_file_net(seq);
2702         return seq_hlist_next_rcu(v, &net->packet.sklist, pos);
2703 }
2704
2705 static void packet_seq_stop(struct seq_file *seq, void *v)
2706         __releases(RCU)
2707 {
2708         rcu_read_unlock();
2709 }
2710
2711 static int packet_seq_show(struct seq_file *seq, void *v)
2712 {
2713         if (v == SEQ_START_TOKEN)
2714                 seq_puts(seq, "sk       RefCnt Type Proto  Iface R Rmem   User   Inode\n");
2715         else {
2716                 struct sock *s = sk_entry(v);
2717                 const struct packet_sock *po = pkt_sk(s);
2718
2719                 seq_printf(seq,
2720                            "%pK %-6d %-4d %04x   %-5d %1d %-6u %-6u %-6lu\n",
2721                            s,
2722                            atomic_read(&s->sk_refcnt),
2723                            s->sk_type,
2724                            ntohs(po->num),
2725                            po->ifindex,
2726                            po->running,
2727                            atomic_read(&s->sk_rmem_alloc),
2728                            sock_i_uid(s),
2729                            sock_i_ino(s));
2730         }
2731
2732         return 0;
2733 }
2734
2735 static const struct seq_operations packet_seq_ops = {
2736         .start  = packet_seq_start,
2737         .next   = packet_seq_next,
2738         .stop   = packet_seq_stop,
2739         .show   = packet_seq_show,
2740 };
2741
2742 static int packet_seq_open(struct inode *inode, struct file *file)
2743 {
2744         return seq_open_net(inode, file, &packet_seq_ops,
2745                             sizeof(struct seq_net_private));
2746 }
2747
2748 static const struct file_operations packet_seq_fops = {
2749         .owner          = THIS_MODULE,
2750         .open           = packet_seq_open,
2751         .read           = seq_read,
2752         .llseek         = seq_lseek,
2753         .release        = seq_release_net,
2754 };
2755
2756 #endif
2757
2758 static int __net_init packet_net_init(struct net *net)
2759 {
2760         spin_lock_init(&net->packet.sklist_lock);
2761         INIT_HLIST_HEAD(&net->packet.sklist);
2762
2763         if (!proc_net_fops_create(net, "packet", 0, &packet_seq_fops))
2764                 return -ENOMEM;
2765
2766         return 0;
2767 }
2768
2769 static void __net_exit packet_net_exit(struct net *net)
2770 {
2771         proc_net_remove(net, "packet");
2772 }
2773
2774 static struct pernet_operations packet_net_ops = {
2775         .init = packet_net_init,
2776         .exit = packet_net_exit,
2777 };
2778
2779
2780 static void __exit packet_exit(void)
2781 {
2782         unregister_netdevice_notifier(&packet_netdev_notifier);
2783         unregister_pernet_subsys(&packet_net_ops);
2784         sock_unregister(PF_PACKET);
2785         proto_unregister(&packet_proto);
2786 }
2787
2788 static int __init packet_init(void)
2789 {
2790         int rc = proto_register(&packet_proto, 0);
2791
2792         if (rc != 0)
2793                 goto out;
2794
2795         sock_register(&packet_family_ops);
2796         register_pernet_subsys(&packet_net_ops);
2797         register_netdevice_notifier(&packet_netdev_notifier);
2798 out:
2799         return rc;
2800 }
2801
2802 module_init(packet_init);
2803 module_exit(packet_exit);
2804 MODULE_LICENSE("GPL");
2805 MODULE_ALIAS_NETPROTO(PF_PACKET);