Merge branches 'acpi-pm' and 'pm-genirq'
[cascardo/linux.git] / net / netlink / af_netlink.c
1 /*
2  * NETLINK      Kernel-user communication protocol.
3  *
4  *              Authors:        Alan Cox <alan@lxorguk.ukuu.org.uk>
5  *                              Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
6  *                              Patrick McHardy <kaber@trash.net>
7  *
8  *              This program is free software; you can redistribute it and/or
9  *              modify it under the terms of the GNU General Public License
10  *              as published by the Free Software Foundation; either version
11  *              2 of the License, or (at your option) any later version.
12  *
13  * Tue Jun 26 14:36:48 MEST 2001 Herbert "herp" Rosmanith
14  *                               added netlink_proto_exit
15  * Tue Jan 22 18:32:44 BRST 2002 Arnaldo C. de Melo <acme@conectiva.com.br>
16  *                               use nlk_sk, as sk->protinfo is on a diet 8)
17  * Fri Jul 22 19:51:12 MEST 2005 Harald Welte <laforge@gnumonks.org>
18  *                               - inc module use count of module that owns
19  *                                 the kernel socket in case userspace opens
20  *                                 socket of same protocol
21  *                               - remove all module support, since netlink is
22  *                                 mandatory if CONFIG_NET=y these days
23  */
24
25 #include <linux/module.h>
26
27 #include <linux/capability.h>
28 #include <linux/kernel.h>
29 #include <linux/init.h>
30 #include <linux/signal.h>
31 #include <linux/sched.h>
32 #include <linux/errno.h>
33 #include <linux/string.h>
34 #include <linux/stat.h>
35 #include <linux/socket.h>
36 #include <linux/un.h>
37 #include <linux/fcntl.h>
38 #include <linux/termios.h>
39 #include <linux/sockios.h>
40 #include <linux/net.h>
41 #include <linux/fs.h>
42 #include <linux/slab.h>
43 #include <asm/uaccess.h>
44 #include <linux/skbuff.h>
45 #include <linux/netdevice.h>
46 #include <linux/rtnetlink.h>
47 #include <linux/proc_fs.h>
48 #include <linux/seq_file.h>
49 #include <linux/notifier.h>
50 #include <linux/security.h>
51 #include <linux/jhash.h>
52 #include <linux/jiffies.h>
53 #include <linux/random.h>
54 #include <linux/bitops.h>
55 #include <linux/mm.h>
56 #include <linux/types.h>
57 #include <linux/audit.h>
58 #include <linux/mutex.h>
59 #include <linux/vmalloc.h>
60 #include <linux/if_arp.h>
61 #include <linux/rhashtable.h>
62 #include <asm/cacheflush.h>
63 #include <linux/hash.h>
64
65 #include <net/net_namespace.h>
66 #include <net/sock.h>
67 #include <net/scm.h>
68 #include <net/netlink.h>
69
70 #include "af_netlink.h"
71
72 struct listeners {
73         struct rcu_head         rcu;
74         unsigned long           masks[0];
75 };
76
77 /* state bits */
78 #define NETLINK_CONGESTED       0x0
79
80 /* flags */
81 #define NETLINK_KERNEL_SOCKET   0x1
82 #define NETLINK_RECV_PKTINFO    0x2
83 #define NETLINK_BROADCAST_SEND_ERROR    0x4
84 #define NETLINK_RECV_NO_ENOBUFS 0x8
85
86 static inline int netlink_is_kernel(struct sock *sk)
87 {
88         return nlk_sk(sk)->flags & NETLINK_KERNEL_SOCKET;
89 }
90
91 struct netlink_table *nl_table;
92 EXPORT_SYMBOL_GPL(nl_table);
93
94 static DECLARE_WAIT_QUEUE_HEAD(nl_table_wait);
95
96 static int netlink_dump(struct sock *sk);
97 static void netlink_skb_destructor(struct sk_buff *skb);
98
99 DEFINE_RWLOCK(nl_table_lock);
100 EXPORT_SYMBOL_GPL(nl_table_lock);
101 static atomic_t nl_table_users = ATOMIC_INIT(0);
102
103 #define nl_deref_protected(X) rcu_dereference_protected(X, lockdep_is_held(&nl_table_lock));
104
105 /* Protects netlink socket hash table mutations */
106 DEFINE_MUTEX(nl_sk_hash_lock);
107 EXPORT_SYMBOL_GPL(nl_sk_hash_lock);
108
109 static int lockdep_nl_sk_hash_is_held(void)
110 {
111 #ifdef CONFIG_LOCKDEP
112         return (debug_locks) ? lockdep_is_held(&nl_sk_hash_lock) : 1;
113 #else
114         return 1;
115 #endif
116 }
117
118 static ATOMIC_NOTIFIER_HEAD(netlink_chain);
119
120 static DEFINE_SPINLOCK(netlink_tap_lock);
121 static struct list_head netlink_tap_all __read_mostly;
122
123 static inline u32 netlink_group_mask(u32 group)
124 {
125         return group ? 1 << (group - 1) : 0;
126 }
127
128 int netlink_add_tap(struct netlink_tap *nt)
129 {
130         if (unlikely(nt->dev->type != ARPHRD_NETLINK))
131                 return -EINVAL;
132
133         spin_lock(&netlink_tap_lock);
134         list_add_rcu(&nt->list, &netlink_tap_all);
135         spin_unlock(&netlink_tap_lock);
136
137         if (nt->module)
138                 __module_get(nt->module);
139
140         return 0;
141 }
142 EXPORT_SYMBOL_GPL(netlink_add_tap);
143
144 static int __netlink_remove_tap(struct netlink_tap *nt)
145 {
146         bool found = false;
147         struct netlink_tap *tmp;
148
149         spin_lock(&netlink_tap_lock);
150
151         list_for_each_entry(tmp, &netlink_tap_all, list) {
152                 if (nt == tmp) {
153                         list_del_rcu(&nt->list);
154                         found = true;
155                         goto out;
156                 }
157         }
158
159         pr_warn("__netlink_remove_tap: %p not found\n", nt);
160 out:
161         spin_unlock(&netlink_tap_lock);
162
163         if (found && nt->module)
164                 module_put(nt->module);
165
166         return found ? 0 : -ENODEV;
167 }
168
169 int netlink_remove_tap(struct netlink_tap *nt)
170 {
171         int ret;
172
173         ret = __netlink_remove_tap(nt);
174         synchronize_net();
175
176         return ret;
177 }
178 EXPORT_SYMBOL_GPL(netlink_remove_tap);
179
180 static bool netlink_filter_tap(const struct sk_buff *skb)
181 {
182         struct sock *sk = skb->sk;
183
184         /* We take the more conservative approach and
185          * whitelist socket protocols that may pass.
186          */
187         switch (sk->sk_protocol) {
188         case NETLINK_ROUTE:
189         case NETLINK_USERSOCK:
190         case NETLINK_SOCK_DIAG:
191         case NETLINK_NFLOG:
192         case NETLINK_XFRM:
193         case NETLINK_FIB_LOOKUP:
194         case NETLINK_NETFILTER:
195         case NETLINK_GENERIC:
196                 return true;
197         }
198
199         return false;
200 }
201
202 static int __netlink_deliver_tap_skb(struct sk_buff *skb,
203                                      struct net_device *dev)
204 {
205         struct sk_buff *nskb;
206         struct sock *sk = skb->sk;
207         int ret = -ENOMEM;
208
209         dev_hold(dev);
210         nskb = skb_clone(skb, GFP_ATOMIC);
211         if (nskb) {
212                 nskb->dev = dev;
213                 nskb->protocol = htons((u16) sk->sk_protocol);
214                 nskb->pkt_type = netlink_is_kernel(sk) ?
215                                  PACKET_KERNEL : PACKET_USER;
216                 skb_reset_network_header(nskb);
217                 ret = dev_queue_xmit(nskb);
218                 if (unlikely(ret > 0))
219                         ret = net_xmit_errno(ret);
220         }
221
222         dev_put(dev);
223         return ret;
224 }
225
226 static void __netlink_deliver_tap(struct sk_buff *skb)
227 {
228         int ret;
229         struct netlink_tap *tmp;
230
231         if (!netlink_filter_tap(skb))
232                 return;
233
234         list_for_each_entry_rcu(tmp, &netlink_tap_all, list) {
235                 ret = __netlink_deliver_tap_skb(skb, tmp->dev);
236                 if (unlikely(ret))
237                         break;
238         }
239 }
240
241 static void netlink_deliver_tap(struct sk_buff *skb)
242 {
243         rcu_read_lock();
244
245         if (unlikely(!list_empty(&netlink_tap_all)))
246                 __netlink_deliver_tap(skb);
247
248         rcu_read_unlock();
249 }
250
251 static void netlink_deliver_tap_kernel(struct sock *dst, struct sock *src,
252                                        struct sk_buff *skb)
253 {
254         if (!(netlink_is_kernel(dst) && netlink_is_kernel(src)))
255                 netlink_deliver_tap(skb);
256 }
257
258 static void netlink_overrun(struct sock *sk)
259 {
260         struct netlink_sock *nlk = nlk_sk(sk);
261
262         if (!(nlk->flags & NETLINK_RECV_NO_ENOBUFS)) {
263                 if (!test_and_set_bit(NETLINK_CONGESTED, &nlk_sk(sk)->state)) {
264                         sk->sk_err = ENOBUFS;
265                         sk->sk_error_report(sk);
266                 }
267         }
268         atomic_inc(&sk->sk_drops);
269 }
270
271 static void netlink_rcv_wake(struct sock *sk)
272 {
273         struct netlink_sock *nlk = nlk_sk(sk);
274
275         if (skb_queue_empty(&sk->sk_receive_queue))
276                 clear_bit(NETLINK_CONGESTED, &nlk->state);
277         if (!test_bit(NETLINK_CONGESTED, &nlk->state))
278                 wake_up_interruptible(&nlk->wait);
279 }
280
281 #ifdef CONFIG_NETLINK_MMAP
282 static bool netlink_skb_is_mmaped(const struct sk_buff *skb)
283 {
284         return NETLINK_CB(skb).flags & NETLINK_SKB_MMAPED;
285 }
286
287 static bool netlink_rx_is_mmaped(struct sock *sk)
288 {
289         return nlk_sk(sk)->rx_ring.pg_vec != NULL;
290 }
291
292 static bool netlink_tx_is_mmaped(struct sock *sk)
293 {
294         return nlk_sk(sk)->tx_ring.pg_vec != NULL;
295 }
296
297 static __pure struct page *pgvec_to_page(const void *addr)
298 {
299         if (is_vmalloc_addr(addr))
300                 return vmalloc_to_page(addr);
301         else
302                 return virt_to_page(addr);
303 }
304
305 static void free_pg_vec(void **pg_vec, unsigned int order, unsigned int len)
306 {
307         unsigned int i;
308
309         for (i = 0; i < len; i++) {
310                 if (pg_vec[i] != NULL) {
311                         if (is_vmalloc_addr(pg_vec[i]))
312                                 vfree(pg_vec[i]);
313                         else
314                                 free_pages((unsigned long)pg_vec[i], order);
315                 }
316         }
317         kfree(pg_vec);
318 }
319
320 static void *alloc_one_pg_vec_page(unsigned long order)
321 {
322         void *buffer;
323         gfp_t gfp_flags = GFP_KERNEL | __GFP_COMP | __GFP_ZERO |
324                           __GFP_NOWARN | __GFP_NORETRY;
325
326         buffer = (void *)__get_free_pages(gfp_flags, order);
327         if (buffer != NULL)
328                 return buffer;
329
330         buffer = vzalloc((1 << order) * PAGE_SIZE);
331         if (buffer != NULL)
332                 return buffer;
333
334         gfp_flags &= ~__GFP_NORETRY;
335         return (void *)__get_free_pages(gfp_flags, order);
336 }
337
338 static void **alloc_pg_vec(struct netlink_sock *nlk,
339                            struct nl_mmap_req *req, unsigned int order)
340 {
341         unsigned int block_nr = req->nm_block_nr;
342         unsigned int i;
343         void **pg_vec;
344
345         pg_vec = kcalloc(block_nr, sizeof(void *), GFP_KERNEL);
346         if (pg_vec == NULL)
347                 return NULL;
348
349         for (i = 0; i < block_nr; i++) {
350                 pg_vec[i] = alloc_one_pg_vec_page(order);
351                 if (pg_vec[i] == NULL)
352                         goto err1;
353         }
354
355         return pg_vec;
356 err1:
357         free_pg_vec(pg_vec, order, block_nr);
358         return NULL;
359 }
360
361 static int netlink_set_ring(struct sock *sk, struct nl_mmap_req *req,
362                             bool closing, bool tx_ring)
363 {
364         struct netlink_sock *nlk = nlk_sk(sk);
365         struct netlink_ring *ring;
366         struct sk_buff_head *queue;
367         void **pg_vec = NULL;
368         unsigned int order = 0;
369         int err;
370
371         ring  = tx_ring ? &nlk->tx_ring : &nlk->rx_ring;
372         queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue;
373
374         if (!closing) {
375                 if (atomic_read(&nlk->mapped))
376                         return -EBUSY;
377                 if (atomic_read(&ring->pending))
378                         return -EBUSY;
379         }
380
381         if (req->nm_block_nr) {
382                 if (ring->pg_vec != NULL)
383                         return -EBUSY;
384
385                 if ((int)req->nm_block_size <= 0)
386                         return -EINVAL;
387                 if (!PAGE_ALIGNED(req->nm_block_size))
388                         return -EINVAL;
389                 if (req->nm_frame_size < NL_MMAP_HDRLEN)
390                         return -EINVAL;
391                 if (!IS_ALIGNED(req->nm_frame_size, NL_MMAP_MSG_ALIGNMENT))
392                         return -EINVAL;
393
394                 ring->frames_per_block = req->nm_block_size /
395                                          req->nm_frame_size;
396                 if (ring->frames_per_block == 0)
397                         return -EINVAL;
398                 if (ring->frames_per_block * req->nm_block_nr !=
399                     req->nm_frame_nr)
400                         return -EINVAL;
401
402                 order = get_order(req->nm_block_size);
403                 pg_vec = alloc_pg_vec(nlk, req, order);
404                 if (pg_vec == NULL)
405                         return -ENOMEM;
406         } else {
407                 if (req->nm_frame_nr)
408                         return -EINVAL;
409         }
410
411         err = -EBUSY;
412         mutex_lock(&nlk->pg_vec_lock);
413         if (closing || atomic_read(&nlk->mapped) == 0) {
414                 err = 0;
415                 spin_lock_bh(&queue->lock);
416
417                 ring->frame_max         = req->nm_frame_nr - 1;
418                 ring->head              = 0;
419                 ring->frame_size        = req->nm_frame_size;
420                 ring->pg_vec_pages      = req->nm_block_size / PAGE_SIZE;
421
422                 swap(ring->pg_vec_len, req->nm_block_nr);
423                 swap(ring->pg_vec_order, order);
424                 swap(ring->pg_vec, pg_vec);
425
426                 __skb_queue_purge(queue);
427                 spin_unlock_bh(&queue->lock);
428
429                 WARN_ON(atomic_read(&nlk->mapped));
430         }
431         mutex_unlock(&nlk->pg_vec_lock);
432
433         if (pg_vec)
434                 free_pg_vec(pg_vec, order, req->nm_block_nr);
435         return err;
436 }
437
438 static void netlink_mm_open(struct vm_area_struct *vma)
439 {
440         struct file *file = vma->vm_file;
441         struct socket *sock = file->private_data;
442         struct sock *sk = sock->sk;
443
444         if (sk)
445                 atomic_inc(&nlk_sk(sk)->mapped);
446 }
447
448 static void netlink_mm_close(struct vm_area_struct *vma)
449 {
450         struct file *file = vma->vm_file;
451         struct socket *sock = file->private_data;
452         struct sock *sk = sock->sk;
453
454         if (sk)
455                 atomic_dec(&nlk_sk(sk)->mapped);
456 }
457
458 static const struct vm_operations_struct netlink_mmap_ops = {
459         .open   = netlink_mm_open,
460         .close  = netlink_mm_close,
461 };
462
463 static int netlink_mmap(struct file *file, struct socket *sock,
464                         struct vm_area_struct *vma)
465 {
466         struct sock *sk = sock->sk;
467         struct netlink_sock *nlk = nlk_sk(sk);
468         struct netlink_ring *ring;
469         unsigned long start, size, expected;
470         unsigned int i;
471         int err = -EINVAL;
472
473         if (vma->vm_pgoff)
474                 return -EINVAL;
475
476         mutex_lock(&nlk->pg_vec_lock);
477
478         expected = 0;
479         for (ring = &nlk->rx_ring; ring <= &nlk->tx_ring; ring++) {
480                 if (ring->pg_vec == NULL)
481                         continue;
482                 expected += ring->pg_vec_len * ring->pg_vec_pages * PAGE_SIZE;
483         }
484
485         if (expected == 0)
486                 goto out;
487
488         size = vma->vm_end - vma->vm_start;
489         if (size != expected)
490                 goto out;
491
492         start = vma->vm_start;
493         for (ring = &nlk->rx_ring; ring <= &nlk->tx_ring; ring++) {
494                 if (ring->pg_vec == NULL)
495                         continue;
496
497                 for (i = 0; i < ring->pg_vec_len; i++) {
498                         struct page *page;
499                         void *kaddr = ring->pg_vec[i];
500                         unsigned int pg_num;
501
502                         for (pg_num = 0; pg_num < ring->pg_vec_pages; pg_num++) {
503                                 page = pgvec_to_page(kaddr);
504                                 err = vm_insert_page(vma, start, page);
505                                 if (err < 0)
506                                         goto out;
507                                 start += PAGE_SIZE;
508                                 kaddr += PAGE_SIZE;
509                         }
510                 }
511         }
512
513         atomic_inc(&nlk->mapped);
514         vma->vm_ops = &netlink_mmap_ops;
515         err = 0;
516 out:
517         mutex_unlock(&nlk->pg_vec_lock);
518         return err;
519 }
520
521 static void netlink_frame_flush_dcache(const struct nl_mmap_hdr *hdr)
522 {
523 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
524         struct page *p_start, *p_end;
525
526         /* First page is flushed through netlink_{get,set}_status */
527         p_start = pgvec_to_page(hdr + PAGE_SIZE);
528         p_end   = pgvec_to_page((void *)hdr + NL_MMAP_HDRLEN + hdr->nm_len - 1);
529         while (p_start <= p_end) {
530                 flush_dcache_page(p_start);
531                 p_start++;
532         }
533 #endif
534 }
535
536 static enum nl_mmap_status netlink_get_status(const struct nl_mmap_hdr *hdr)
537 {
538         smp_rmb();
539         flush_dcache_page(pgvec_to_page(hdr));
540         return hdr->nm_status;
541 }
542
543 static void netlink_set_status(struct nl_mmap_hdr *hdr,
544                                enum nl_mmap_status status)
545 {
546         hdr->nm_status = status;
547         flush_dcache_page(pgvec_to_page(hdr));
548         smp_wmb();
549 }
550
551 static struct nl_mmap_hdr *
552 __netlink_lookup_frame(const struct netlink_ring *ring, unsigned int pos)
553 {
554         unsigned int pg_vec_pos, frame_off;
555
556         pg_vec_pos = pos / ring->frames_per_block;
557         frame_off  = pos % ring->frames_per_block;
558
559         return ring->pg_vec[pg_vec_pos] + (frame_off * ring->frame_size);
560 }
561
562 static struct nl_mmap_hdr *
563 netlink_lookup_frame(const struct netlink_ring *ring, unsigned int pos,
564                      enum nl_mmap_status status)
565 {
566         struct nl_mmap_hdr *hdr;
567
568         hdr = __netlink_lookup_frame(ring, pos);
569         if (netlink_get_status(hdr) != status)
570                 return NULL;
571
572         return hdr;
573 }
574
575 static struct nl_mmap_hdr *
576 netlink_current_frame(const struct netlink_ring *ring,
577                       enum nl_mmap_status status)
578 {
579         return netlink_lookup_frame(ring, ring->head, status);
580 }
581
582 static struct nl_mmap_hdr *
583 netlink_previous_frame(const struct netlink_ring *ring,
584                        enum nl_mmap_status status)
585 {
586         unsigned int prev;
587
588         prev = ring->head ? ring->head - 1 : ring->frame_max;
589         return netlink_lookup_frame(ring, prev, status);
590 }
591
592 static void netlink_increment_head(struct netlink_ring *ring)
593 {
594         ring->head = ring->head != ring->frame_max ? ring->head + 1 : 0;
595 }
596
597 static void netlink_forward_ring(struct netlink_ring *ring)
598 {
599         unsigned int head = ring->head, pos = head;
600         const struct nl_mmap_hdr *hdr;
601
602         do {
603                 hdr = __netlink_lookup_frame(ring, pos);
604                 if (hdr->nm_status == NL_MMAP_STATUS_UNUSED)
605                         break;
606                 if (hdr->nm_status != NL_MMAP_STATUS_SKIP)
607                         break;
608                 netlink_increment_head(ring);
609         } while (ring->head != head);
610 }
611
612 static bool netlink_dump_space(struct netlink_sock *nlk)
613 {
614         struct netlink_ring *ring = &nlk->rx_ring;
615         struct nl_mmap_hdr *hdr;
616         unsigned int n;
617
618         hdr = netlink_current_frame(ring, NL_MMAP_STATUS_UNUSED);
619         if (hdr == NULL)
620                 return false;
621
622         n = ring->head + ring->frame_max / 2;
623         if (n > ring->frame_max)
624                 n -= ring->frame_max;
625
626         hdr = __netlink_lookup_frame(ring, n);
627
628         return hdr->nm_status == NL_MMAP_STATUS_UNUSED;
629 }
630
631 static unsigned int netlink_poll(struct file *file, struct socket *sock,
632                                  poll_table *wait)
633 {
634         struct sock *sk = sock->sk;
635         struct netlink_sock *nlk = nlk_sk(sk);
636         unsigned int mask;
637         int err;
638
639         if (nlk->rx_ring.pg_vec != NULL) {
640                 /* Memory mapped sockets don't call recvmsg(), so flow control
641                  * for dumps is performed here. A dump is allowed to continue
642                  * if at least half the ring is unused.
643                  */
644                 while (nlk->cb_running && netlink_dump_space(nlk)) {
645                         err = netlink_dump(sk);
646                         if (err < 0) {
647                                 sk->sk_err = -err;
648                                 sk->sk_error_report(sk);
649                                 break;
650                         }
651                 }
652                 netlink_rcv_wake(sk);
653         }
654
655         mask = datagram_poll(file, sock, wait);
656
657         spin_lock_bh(&sk->sk_receive_queue.lock);
658         if (nlk->rx_ring.pg_vec) {
659                 netlink_forward_ring(&nlk->rx_ring);
660                 if (!netlink_previous_frame(&nlk->rx_ring, NL_MMAP_STATUS_UNUSED))
661                         mask |= POLLIN | POLLRDNORM;
662         }
663         spin_unlock_bh(&sk->sk_receive_queue.lock);
664
665         spin_lock_bh(&sk->sk_write_queue.lock);
666         if (nlk->tx_ring.pg_vec) {
667                 if (netlink_current_frame(&nlk->tx_ring, NL_MMAP_STATUS_UNUSED))
668                         mask |= POLLOUT | POLLWRNORM;
669         }
670         spin_unlock_bh(&sk->sk_write_queue.lock);
671
672         return mask;
673 }
674
675 static struct nl_mmap_hdr *netlink_mmap_hdr(struct sk_buff *skb)
676 {
677         return (struct nl_mmap_hdr *)(skb->head - NL_MMAP_HDRLEN);
678 }
679
680 static void netlink_ring_setup_skb(struct sk_buff *skb, struct sock *sk,
681                                    struct netlink_ring *ring,
682                                    struct nl_mmap_hdr *hdr)
683 {
684         unsigned int size;
685         void *data;
686
687         size = ring->frame_size - NL_MMAP_HDRLEN;
688         data = (void *)hdr + NL_MMAP_HDRLEN;
689
690         skb->head       = data;
691         skb->data       = data;
692         skb_reset_tail_pointer(skb);
693         skb->end        = skb->tail + size;
694         skb->len        = 0;
695
696         skb->destructor = netlink_skb_destructor;
697         NETLINK_CB(skb).flags |= NETLINK_SKB_MMAPED;
698         NETLINK_CB(skb).sk = sk;
699 }
700
701 static int netlink_mmap_sendmsg(struct sock *sk, struct msghdr *msg,
702                                 u32 dst_portid, u32 dst_group,
703                                 struct sock_iocb *siocb)
704 {
705         struct netlink_sock *nlk = nlk_sk(sk);
706         struct netlink_ring *ring;
707         struct nl_mmap_hdr *hdr;
708         struct sk_buff *skb;
709         unsigned int maxlen;
710         bool excl = true;
711         int err = 0, len = 0;
712
713         /* Netlink messages are validated by the receiver before processing.
714          * In order to avoid userspace changing the contents of the message
715          * after validation, the socket and the ring may only be used by a
716          * single process, otherwise we fall back to copying.
717          */
718         if (atomic_long_read(&sk->sk_socket->file->f_count) > 1 ||
719             atomic_read(&nlk->mapped) > 1)
720                 excl = false;
721
722         mutex_lock(&nlk->pg_vec_lock);
723
724         ring   = &nlk->tx_ring;
725         maxlen = ring->frame_size - NL_MMAP_HDRLEN;
726
727         do {
728                 hdr = netlink_current_frame(ring, NL_MMAP_STATUS_VALID);
729                 if (hdr == NULL) {
730                         if (!(msg->msg_flags & MSG_DONTWAIT) &&
731                             atomic_read(&nlk->tx_ring.pending))
732                                 schedule();
733                         continue;
734                 }
735                 if (hdr->nm_len > maxlen) {
736                         err = -EINVAL;
737                         goto out;
738                 }
739
740                 netlink_frame_flush_dcache(hdr);
741
742                 if (likely(dst_portid == 0 && dst_group == 0 && excl)) {
743                         skb = alloc_skb_head(GFP_KERNEL);
744                         if (skb == NULL) {
745                                 err = -ENOBUFS;
746                                 goto out;
747                         }
748                         sock_hold(sk);
749                         netlink_ring_setup_skb(skb, sk, ring, hdr);
750                         NETLINK_CB(skb).flags |= NETLINK_SKB_TX;
751                         __skb_put(skb, hdr->nm_len);
752                         netlink_set_status(hdr, NL_MMAP_STATUS_RESERVED);
753                         atomic_inc(&ring->pending);
754                 } else {
755                         skb = alloc_skb(hdr->nm_len, GFP_KERNEL);
756                         if (skb == NULL) {
757                                 err = -ENOBUFS;
758                                 goto out;
759                         }
760                         __skb_put(skb, hdr->nm_len);
761                         memcpy(skb->data, (void *)hdr + NL_MMAP_HDRLEN, hdr->nm_len);
762                         netlink_set_status(hdr, NL_MMAP_STATUS_UNUSED);
763                 }
764
765                 netlink_increment_head(ring);
766
767                 NETLINK_CB(skb).portid    = nlk->portid;
768                 NETLINK_CB(skb).dst_group = dst_group;
769                 NETLINK_CB(skb).creds     = siocb->scm->creds;
770
771                 err = security_netlink_send(sk, skb);
772                 if (err) {
773                         kfree_skb(skb);
774                         goto out;
775                 }
776
777                 if (unlikely(dst_group)) {
778                         atomic_inc(&skb->users);
779                         netlink_broadcast(sk, skb, dst_portid, dst_group,
780                                           GFP_KERNEL);
781                 }
782                 err = netlink_unicast(sk, skb, dst_portid,
783                                       msg->msg_flags & MSG_DONTWAIT);
784                 if (err < 0)
785                         goto out;
786                 len += err;
787
788         } while (hdr != NULL ||
789                  (!(msg->msg_flags & MSG_DONTWAIT) &&
790                   atomic_read(&nlk->tx_ring.pending)));
791
792         if (len > 0)
793                 err = len;
794 out:
795         mutex_unlock(&nlk->pg_vec_lock);
796         return err;
797 }
798
799 static void netlink_queue_mmaped_skb(struct sock *sk, struct sk_buff *skb)
800 {
801         struct nl_mmap_hdr *hdr;
802
803         hdr = netlink_mmap_hdr(skb);
804         hdr->nm_len     = skb->len;
805         hdr->nm_group   = NETLINK_CB(skb).dst_group;
806         hdr->nm_pid     = NETLINK_CB(skb).creds.pid;
807         hdr->nm_uid     = from_kuid(sk_user_ns(sk), NETLINK_CB(skb).creds.uid);
808         hdr->nm_gid     = from_kgid(sk_user_ns(sk), NETLINK_CB(skb).creds.gid);
809         netlink_frame_flush_dcache(hdr);
810         netlink_set_status(hdr, NL_MMAP_STATUS_VALID);
811
812         NETLINK_CB(skb).flags |= NETLINK_SKB_DELIVERED;
813         kfree_skb(skb);
814 }
815
816 static void netlink_ring_set_copied(struct sock *sk, struct sk_buff *skb)
817 {
818         struct netlink_sock *nlk = nlk_sk(sk);
819         struct netlink_ring *ring = &nlk->rx_ring;
820         struct nl_mmap_hdr *hdr;
821
822         spin_lock_bh(&sk->sk_receive_queue.lock);
823         hdr = netlink_current_frame(ring, NL_MMAP_STATUS_UNUSED);
824         if (hdr == NULL) {
825                 spin_unlock_bh(&sk->sk_receive_queue.lock);
826                 kfree_skb(skb);
827                 netlink_overrun(sk);
828                 return;
829         }
830         netlink_increment_head(ring);
831         __skb_queue_tail(&sk->sk_receive_queue, skb);
832         spin_unlock_bh(&sk->sk_receive_queue.lock);
833
834         hdr->nm_len     = skb->len;
835         hdr->nm_group   = NETLINK_CB(skb).dst_group;
836         hdr->nm_pid     = NETLINK_CB(skb).creds.pid;
837         hdr->nm_uid     = from_kuid(sk_user_ns(sk), NETLINK_CB(skb).creds.uid);
838         hdr->nm_gid     = from_kgid(sk_user_ns(sk), NETLINK_CB(skb).creds.gid);
839         netlink_set_status(hdr, NL_MMAP_STATUS_COPY);
840 }
841
842 #else /* CONFIG_NETLINK_MMAP */
843 #define netlink_skb_is_mmaped(skb)      false
844 #define netlink_rx_is_mmaped(sk)        false
845 #define netlink_tx_is_mmaped(sk)        false
846 #define netlink_mmap                    sock_no_mmap
847 #define netlink_poll                    datagram_poll
848 #define netlink_mmap_sendmsg(sk, msg, dst_portid, dst_group, siocb)     0
849 #endif /* CONFIG_NETLINK_MMAP */
850
851 static void netlink_skb_destructor(struct sk_buff *skb)
852 {
853 #ifdef CONFIG_NETLINK_MMAP
854         struct nl_mmap_hdr *hdr;
855         struct netlink_ring *ring;
856         struct sock *sk;
857
858         /* If a packet from the kernel to userspace was freed because of an
859          * error without being delivered to userspace, the kernel must reset
860          * the status. In the direction userspace to kernel, the status is
861          * always reset here after the packet was processed and freed.
862          */
863         if (netlink_skb_is_mmaped(skb)) {
864                 hdr = netlink_mmap_hdr(skb);
865                 sk = NETLINK_CB(skb).sk;
866
867                 if (NETLINK_CB(skb).flags & NETLINK_SKB_TX) {
868                         netlink_set_status(hdr, NL_MMAP_STATUS_UNUSED);
869                         ring = &nlk_sk(sk)->tx_ring;
870                 } else {
871                         if (!(NETLINK_CB(skb).flags & NETLINK_SKB_DELIVERED)) {
872                                 hdr->nm_len = 0;
873                                 netlink_set_status(hdr, NL_MMAP_STATUS_VALID);
874                         }
875                         ring = &nlk_sk(sk)->rx_ring;
876                 }
877
878                 WARN_ON(atomic_read(&ring->pending) == 0);
879                 atomic_dec(&ring->pending);
880                 sock_put(sk);
881
882                 skb->head = NULL;
883         }
884 #endif
885         if (is_vmalloc_addr(skb->head)) {
886                 if (!skb->cloned ||
887                     !atomic_dec_return(&(skb_shinfo(skb)->dataref)))
888                         vfree(skb->head);
889
890                 skb->head = NULL;
891         }
892         if (skb->sk != NULL)
893                 sock_rfree(skb);
894 }
895
896 static void netlink_skb_set_owner_r(struct sk_buff *skb, struct sock *sk)
897 {
898         WARN_ON(skb->sk != NULL);
899         skb->sk = sk;
900         skb->destructor = netlink_skb_destructor;
901         atomic_add(skb->truesize, &sk->sk_rmem_alloc);
902         sk_mem_charge(sk, skb->truesize);
903 }
904
905 static void netlink_sock_destruct(struct sock *sk)
906 {
907         struct netlink_sock *nlk = nlk_sk(sk);
908
909         if (nlk->cb_running) {
910                 if (nlk->cb.done)
911                         nlk->cb.done(&nlk->cb);
912
913                 module_put(nlk->cb.module);
914                 kfree_skb(nlk->cb.skb);
915         }
916
917         skb_queue_purge(&sk->sk_receive_queue);
918 #ifdef CONFIG_NETLINK_MMAP
919         if (1) {
920                 struct nl_mmap_req req;
921
922                 memset(&req, 0, sizeof(req));
923                 if (nlk->rx_ring.pg_vec)
924                         netlink_set_ring(sk, &req, true, false);
925                 memset(&req, 0, sizeof(req));
926                 if (nlk->tx_ring.pg_vec)
927                         netlink_set_ring(sk, &req, true, true);
928         }
929 #endif /* CONFIG_NETLINK_MMAP */
930
931         if (!sock_flag(sk, SOCK_DEAD)) {
932                 printk(KERN_ERR "Freeing alive netlink socket %p\n", sk);
933                 return;
934         }
935
936         WARN_ON(atomic_read(&sk->sk_rmem_alloc));
937         WARN_ON(atomic_read(&sk->sk_wmem_alloc));
938         WARN_ON(nlk_sk(sk)->groups);
939 }
940
941 /* This lock without WQ_FLAG_EXCLUSIVE is good on UP and it is _very_ bad on
942  * SMP. Look, when several writers sleep and reader wakes them up, all but one
943  * immediately hit write lock and grab all the cpus. Exclusive sleep solves
944  * this, _but_ remember, it adds useless work on UP machines.
945  */
946
947 void netlink_table_grab(void)
948         __acquires(nl_table_lock)
949 {
950         might_sleep();
951
952         write_lock_irq(&nl_table_lock);
953
954         if (atomic_read(&nl_table_users)) {
955                 DECLARE_WAITQUEUE(wait, current);
956
957                 add_wait_queue_exclusive(&nl_table_wait, &wait);
958                 for (;;) {
959                         set_current_state(TASK_UNINTERRUPTIBLE);
960                         if (atomic_read(&nl_table_users) == 0)
961                                 break;
962                         write_unlock_irq(&nl_table_lock);
963                         schedule();
964                         write_lock_irq(&nl_table_lock);
965                 }
966
967                 __set_current_state(TASK_RUNNING);
968                 remove_wait_queue(&nl_table_wait, &wait);
969         }
970 }
971
972 void netlink_table_ungrab(void)
973         __releases(nl_table_lock)
974 {
975         write_unlock_irq(&nl_table_lock);
976         wake_up(&nl_table_wait);
977 }
978
979 static inline void
980 netlink_lock_table(void)
981 {
982         /* read_lock() synchronizes us to netlink_table_grab */
983
984         read_lock(&nl_table_lock);
985         atomic_inc(&nl_table_users);
986         read_unlock(&nl_table_lock);
987 }
988
989 static inline void
990 netlink_unlock_table(void)
991 {
992         if (atomic_dec_and_test(&nl_table_users))
993                 wake_up(&nl_table_wait);
994 }
995
996 struct netlink_compare_arg
997 {
998         struct net *net;
999         u32 portid;
1000 };
1001
1002 static bool netlink_compare(void *ptr, void *arg)
1003 {
1004         struct netlink_compare_arg *x = arg;
1005         struct sock *sk = ptr;
1006
1007         return nlk_sk(sk)->portid == x->portid &&
1008                net_eq(sock_net(sk), x->net);
1009 }
1010
1011 static struct sock *__netlink_lookup(struct netlink_table *table, u32 portid,
1012                                      struct net *net)
1013 {
1014         struct netlink_compare_arg arg = {
1015                 .net = net,
1016                 .portid = portid,
1017         };
1018         u32 hash;
1019
1020         hash = rhashtable_hashfn(&table->hash, &portid, sizeof(portid));
1021
1022         return rhashtable_lookup_compare(&table->hash, hash,
1023                                          &netlink_compare, &arg);
1024 }
1025
1026 static struct sock *netlink_lookup(struct net *net, int protocol, u32 portid)
1027 {
1028         struct netlink_table *table = &nl_table[protocol];
1029         struct sock *sk;
1030
1031         rcu_read_lock();
1032         sk = __netlink_lookup(table, portid, net);
1033         if (sk)
1034                 sock_hold(sk);
1035         rcu_read_unlock();
1036
1037         return sk;
1038 }
1039
1040 static const struct proto_ops netlink_ops;
1041
1042 static void
1043 netlink_update_listeners(struct sock *sk)
1044 {
1045         struct netlink_table *tbl = &nl_table[sk->sk_protocol];
1046         unsigned long mask;
1047         unsigned int i;
1048         struct listeners *listeners;
1049
1050         listeners = nl_deref_protected(tbl->listeners);
1051         if (!listeners)
1052                 return;
1053
1054         for (i = 0; i < NLGRPLONGS(tbl->groups); i++) {
1055                 mask = 0;
1056                 sk_for_each_bound(sk, &tbl->mc_list) {
1057                         if (i < NLGRPLONGS(nlk_sk(sk)->ngroups))
1058                                 mask |= nlk_sk(sk)->groups[i];
1059                 }
1060                 listeners->masks[i] = mask;
1061         }
1062         /* this function is only called with the netlink table "grabbed", which
1063          * makes sure updates are visible before bind or setsockopt return. */
1064 }
1065
1066 static int netlink_insert(struct sock *sk, struct net *net, u32 portid)
1067 {
1068         struct netlink_table *table = &nl_table[sk->sk_protocol];
1069         int err = -EADDRINUSE;
1070
1071         mutex_lock(&nl_sk_hash_lock);
1072         if (__netlink_lookup(table, portid, net))
1073                 goto err;
1074
1075         err = -EBUSY;
1076         if (nlk_sk(sk)->portid)
1077                 goto err;
1078
1079         err = -ENOMEM;
1080         if (BITS_PER_LONG > 32 && unlikely(table->hash.nelems >= UINT_MAX))
1081                 goto err;
1082
1083         nlk_sk(sk)->portid = portid;
1084         sock_hold(sk);
1085         rhashtable_insert(&table->hash, &nlk_sk(sk)->node, GFP_KERNEL);
1086         err = 0;
1087 err:
1088         mutex_unlock(&nl_sk_hash_lock);
1089         return err;
1090 }
1091
1092 static void netlink_remove(struct sock *sk)
1093 {
1094         struct netlink_table *table;
1095
1096         mutex_lock(&nl_sk_hash_lock);
1097         table = &nl_table[sk->sk_protocol];
1098         if (rhashtable_remove(&table->hash, &nlk_sk(sk)->node, GFP_KERNEL)) {
1099                 WARN_ON(atomic_read(&sk->sk_refcnt) == 1);
1100                 __sock_put(sk);
1101         }
1102         mutex_unlock(&nl_sk_hash_lock);
1103
1104         netlink_table_grab();
1105         if (nlk_sk(sk)->subscriptions)
1106                 __sk_del_bind_node(sk);
1107         netlink_table_ungrab();
1108 }
1109
1110 static struct proto netlink_proto = {
1111         .name     = "NETLINK",
1112         .owner    = THIS_MODULE,
1113         .obj_size = sizeof(struct netlink_sock),
1114 };
1115
1116 static int __netlink_create(struct net *net, struct socket *sock,
1117                             struct mutex *cb_mutex, int protocol)
1118 {
1119         struct sock *sk;
1120         struct netlink_sock *nlk;
1121
1122         sock->ops = &netlink_ops;
1123
1124         sk = sk_alloc(net, PF_NETLINK, GFP_KERNEL, &netlink_proto);
1125         if (!sk)
1126                 return -ENOMEM;
1127
1128         sock_init_data(sock, sk);
1129
1130         nlk = nlk_sk(sk);
1131         if (cb_mutex) {
1132                 nlk->cb_mutex = cb_mutex;
1133         } else {
1134                 nlk->cb_mutex = &nlk->cb_def_mutex;
1135                 mutex_init(nlk->cb_mutex);
1136         }
1137         init_waitqueue_head(&nlk->wait);
1138 #ifdef CONFIG_NETLINK_MMAP
1139         mutex_init(&nlk->pg_vec_lock);
1140 #endif
1141
1142         sk->sk_destruct = netlink_sock_destruct;
1143         sk->sk_protocol = protocol;
1144         return 0;
1145 }
1146
1147 static int netlink_create(struct net *net, struct socket *sock, int protocol,
1148                           int kern)
1149 {
1150         struct module *module = NULL;
1151         struct mutex *cb_mutex;
1152         struct netlink_sock *nlk;
1153         int (*bind)(int group);
1154         void (*unbind)(int group);
1155         int err = 0;
1156
1157         sock->state = SS_UNCONNECTED;
1158
1159         if (sock->type != SOCK_RAW && sock->type != SOCK_DGRAM)
1160                 return -ESOCKTNOSUPPORT;
1161
1162         if (protocol < 0 || protocol >= MAX_LINKS)
1163                 return -EPROTONOSUPPORT;
1164
1165         netlink_lock_table();
1166 #ifdef CONFIG_MODULES
1167         if (!nl_table[protocol].registered) {
1168                 netlink_unlock_table();
1169                 request_module("net-pf-%d-proto-%d", PF_NETLINK, protocol);
1170                 netlink_lock_table();
1171         }
1172 #endif
1173         if (nl_table[protocol].registered &&
1174             try_module_get(nl_table[protocol].module))
1175                 module = nl_table[protocol].module;
1176         else
1177                 err = -EPROTONOSUPPORT;
1178         cb_mutex = nl_table[protocol].cb_mutex;
1179         bind = nl_table[protocol].bind;
1180         unbind = nl_table[protocol].unbind;
1181         netlink_unlock_table();
1182
1183         if (err < 0)
1184                 goto out;
1185
1186         err = __netlink_create(net, sock, cb_mutex, protocol);
1187         if (err < 0)
1188                 goto out_module;
1189
1190         local_bh_disable();
1191         sock_prot_inuse_add(net, &netlink_proto, 1);
1192         local_bh_enable();
1193
1194         nlk = nlk_sk(sock->sk);
1195         nlk->module = module;
1196         nlk->netlink_bind = bind;
1197         nlk->netlink_unbind = unbind;
1198 out:
1199         return err;
1200
1201 out_module:
1202         module_put(module);
1203         goto out;
1204 }
1205
1206 static int netlink_release(struct socket *sock)
1207 {
1208         struct sock *sk = sock->sk;
1209         struct netlink_sock *nlk;
1210
1211         if (!sk)
1212                 return 0;
1213
1214         netlink_remove(sk);
1215         sock_orphan(sk);
1216         nlk = nlk_sk(sk);
1217
1218         /*
1219          * OK. Socket is unlinked, any packets that arrive now
1220          * will be purged.
1221          */
1222
1223         sock->sk = NULL;
1224         wake_up_interruptible_all(&nlk->wait);
1225
1226         skb_queue_purge(&sk->sk_write_queue);
1227
1228         if (nlk->portid) {
1229                 struct netlink_notify n = {
1230                                                 .net = sock_net(sk),
1231                                                 .protocol = sk->sk_protocol,
1232                                                 .portid = nlk->portid,
1233                                           };
1234                 atomic_notifier_call_chain(&netlink_chain,
1235                                 NETLINK_URELEASE, &n);
1236         }
1237
1238         module_put(nlk->module);
1239
1240         netlink_table_grab();
1241         if (netlink_is_kernel(sk)) {
1242                 BUG_ON(nl_table[sk->sk_protocol].registered == 0);
1243                 if (--nl_table[sk->sk_protocol].registered == 0) {
1244                         struct listeners *old;
1245
1246                         old = nl_deref_protected(nl_table[sk->sk_protocol].listeners);
1247                         RCU_INIT_POINTER(nl_table[sk->sk_protocol].listeners, NULL);
1248                         kfree_rcu(old, rcu);
1249                         nl_table[sk->sk_protocol].module = NULL;
1250                         nl_table[sk->sk_protocol].bind = NULL;
1251                         nl_table[sk->sk_protocol].unbind = NULL;
1252                         nl_table[sk->sk_protocol].flags = 0;
1253                         nl_table[sk->sk_protocol].registered = 0;
1254                 }
1255         } else if (nlk->subscriptions) {
1256                 netlink_update_listeners(sk);
1257         }
1258         netlink_table_ungrab();
1259
1260         /* Wait for readers to complete */
1261         synchronize_net();
1262
1263         kfree(nlk->groups);
1264         nlk->groups = NULL;
1265
1266         local_bh_disable();
1267         sock_prot_inuse_add(sock_net(sk), &netlink_proto, -1);
1268         local_bh_enable();
1269         sock_put(sk);
1270         return 0;
1271 }
1272
1273 static int netlink_autobind(struct socket *sock)
1274 {
1275         struct sock *sk = sock->sk;
1276         struct net *net = sock_net(sk);
1277         struct netlink_table *table = &nl_table[sk->sk_protocol];
1278         s32 portid = task_tgid_vnr(current);
1279         int err;
1280         static s32 rover = -4097;
1281
1282 retry:
1283         cond_resched();
1284         rcu_read_lock();
1285         if (__netlink_lookup(table, portid, net)) {
1286                 /* Bind collision, search negative portid values. */
1287                 portid = rover--;
1288                 if (rover > -4097)
1289                         rover = -4097;
1290                 rcu_read_unlock();
1291                 goto retry;
1292         }
1293         rcu_read_unlock();
1294
1295         err = netlink_insert(sk, net, portid);
1296         if (err == -EADDRINUSE)
1297                 goto retry;
1298
1299         /* If 2 threads race to autobind, that is fine.  */
1300         if (err == -EBUSY)
1301                 err = 0;
1302
1303         return err;
1304 }
1305
1306 /**
1307  * __netlink_ns_capable - General netlink message capability test
1308  * @nsp: NETLINK_CB of the socket buffer holding a netlink command from userspace.
1309  * @user_ns: The user namespace of the capability to use
1310  * @cap: The capability to use
1311  *
1312  * Test to see if the opener of the socket we received the message
1313  * from had when the netlink socket was created and the sender of the
1314  * message has has the capability @cap in the user namespace @user_ns.
1315  */
1316 bool __netlink_ns_capable(const struct netlink_skb_parms *nsp,
1317                         struct user_namespace *user_ns, int cap)
1318 {
1319         return ((nsp->flags & NETLINK_SKB_DST) ||
1320                 file_ns_capable(nsp->sk->sk_socket->file, user_ns, cap)) &&
1321                 ns_capable(user_ns, cap);
1322 }
1323 EXPORT_SYMBOL(__netlink_ns_capable);
1324
1325 /**
1326  * netlink_ns_capable - General netlink message capability test
1327  * @skb: socket buffer holding a netlink command from userspace
1328  * @user_ns: The user namespace of the capability to use
1329  * @cap: The capability to use
1330  *
1331  * Test to see if the opener of the socket we received the message
1332  * from had when the netlink socket was created and the sender of the
1333  * message has has the capability @cap in the user namespace @user_ns.
1334  */
1335 bool netlink_ns_capable(const struct sk_buff *skb,
1336                         struct user_namespace *user_ns, int cap)
1337 {
1338         return __netlink_ns_capable(&NETLINK_CB(skb), user_ns, cap);
1339 }
1340 EXPORT_SYMBOL(netlink_ns_capable);
1341
1342 /**
1343  * netlink_capable - Netlink global message capability test
1344  * @skb: socket buffer holding a netlink command from userspace
1345  * @cap: The capability to use
1346  *
1347  * Test to see if the opener of the socket we received the message
1348  * from had when the netlink socket was created and the sender of the
1349  * message has has the capability @cap in all user namespaces.
1350  */
1351 bool netlink_capable(const struct sk_buff *skb, int cap)
1352 {
1353         return netlink_ns_capable(skb, &init_user_ns, cap);
1354 }
1355 EXPORT_SYMBOL(netlink_capable);
1356
1357 /**
1358  * netlink_net_capable - Netlink network namespace message capability test
1359  * @skb: socket buffer holding a netlink command from userspace
1360  * @cap: The capability to use
1361  *
1362  * Test to see if the opener of the socket we received the message
1363  * from had when the netlink socket was created and the sender of the
1364  * message has has the capability @cap over the network namespace of
1365  * the socket we received the message from.
1366  */
1367 bool netlink_net_capable(const struct sk_buff *skb, int cap)
1368 {
1369         return netlink_ns_capable(skb, sock_net(skb->sk)->user_ns, cap);
1370 }
1371 EXPORT_SYMBOL(netlink_net_capable);
1372
1373 static inline int netlink_allowed(const struct socket *sock, unsigned int flag)
1374 {
1375         return (nl_table[sock->sk->sk_protocol].flags & flag) ||
1376                 ns_capable(sock_net(sock->sk)->user_ns, CAP_NET_ADMIN);
1377 }
1378
1379 static void
1380 netlink_update_subscriptions(struct sock *sk, unsigned int subscriptions)
1381 {
1382         struct netlink_sock *nlk = nlk_sk(sk);
1383
1384         if (nlk->subscriptions && !subscriptions)
1385                 __sk_del_bind_node(sk);
1386         else if (!nlk->subscriptions && subscriptions)
1387                 sk_add_bind_node(sk, &nl_table[sk->sk_protocol].mc_list);
1388         nlk->subscriptions = subscriptions;
1389 }
1390
1391 static int netlink_realloc_groups(struct sock *sk)
1392 {
1393         struct netlink_sock *nlk = nlk_sk(sk);
1394         unsigned int groups;
1395         unsigned long *new_groups;
1396         int err = 0;
1397
1398         netlink_table_grab();
1399
1400         groups = nl_table[sk->sk_protocol].groups;
1401         if (!nl_table[sk->sk_protocol].registered) {
1402                 err = -ENOENT;
1403                 goto out_unlock;
1404         }
1405
1406         if (nlk->ngroups >= groups)
1407                 goto out_unlock;
1408
1409         new_groups = krealloc(nlk->groups, NLGRPSZ(groups), GFP_ATOMIC);
1410         if (new_groups == NULL) {
1411                 err = -ENOMEM;
1412                 goto out_unlock;
1413         }
1414         memset((char *)new_groups + NLGRPSZ(nlk->ngroups), 0,
1415                NLGRPSZ(groups) - NLGRPSZ(nlk->ngroups));
1416
1417         nlk->groups = new_groups;
1418         nlk->ngroups = groups;
1419  out_unlock:
1420         netlink_table_ungrab();
1421         return err;
1422 }
1423
1424 static void netlink_unbind(int group, long unsigned int groups,
1425                            struct netlink_sock *nlk)
1426 {
1427         int undo;
1428
1429         if (!nlk->netlink_unbind)
1430                 return;
1431
1432         for (undo = 0; undo < group; undo++)
1433                 if (test_bit(group, &groups))
1434                         nlk->netlink_unbind(undo);
1435 }
1436
1437 static int netlink_bind(struct socket *sock, struct sockaddr *addr,
1438                         int addr_len)
1439 {
1440         struct sock *sk = sock->sk;
1441         struct net *net = sock_net(sk);
1442         struct netlink_sock *nlk = nlk_sk(sk);
1443         struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
1444         int err;
1445         long unsigned int groups = nladdr->nl_groups;
1446
1447         if (addr_len < sizeof(struct sockaddr_nl))
1448                 return -EINVAL;
1449
1450         if (nladdr->nl_family != AF_NETLINK)
1451                 return -EINVAL;
1452
1453         /* Only superuser is allowed to listen multicasts */
1454         if (groups) {
1455                 if (!netlink_allowed(sock, NL_CFG_F_NONROOT_RECV))
1456                         return -EPERM;
1457                 err = netlink_realloc_groups(sk);
1458                 if (err)
1459                         return err;
1460         }
1461
1462         if (nlk->portid)
1463                 if (nladdr->nl_pid != nlk->portid)
1464                         return -EINVAL;
1465
1466         if (nlk->netlink_bind && groups) {
1467                 int group;
1468
1469                 for (group = 0; group < nlk->ngroups; group++) {
1470                         if (!test_bit(group, &groups))
1471                                 continue;
1472                         err = nlk->netlink_bind(group);
1473                         if (!err)
1474                                 continue;
1475                         netlink_unbind(group, groups, nlk);
1476                         return err;
1477                 }
1478         }
1479
1480         if (!nlk->portid) {
1481                 err = nladdr->nl_pid ?
1482                         netlink_insert(sk, net, nladdr->nl_pid) :
1483                         netlink_autobind(sock);
1484                 if (err) {
1485                         netlink_unbind(nlk->ngroups - 1, groups, nlk);
1486                         return err;
1487                 }
1488         }
1489
1490         if (!groups && (nlk->groups == NULL || !(u32)nlk->groups[0]))
1491                 return 0;
1492
1493         netlink_table_grab();
1494         netlink_update_subscriptions(sk, nlk->subscriptions +
1495                                          hweight32(groups) -
1496                                          hweight32(nlk->groups[0]));
1497         nlk->groups[0] = (nlk->groups[0] & ~0xffffffffUL) | groups;
1498         netlink_update_listeners(sk);
1499         netlink_table_ungrab();
1500
1501         return 0;
1502 }
1503
1504 static int netlink_connect(struct socket *sock, struct sockaddr *addr,
1505                            int alen, int flags)
1506 {
1507         int err = 0;
1508         struct sock *sk = sock->sk;
1509         struct netlink_sock *nlk = nlk_sk(sk);
1510         struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
1511
1512         if (alen < sizeof(addr->sa_family))
1513                 return -EINVAL;
1514
1515         if (addr->sa_family == AF_UNSPEC) {
1516                 sk->sk_state    = NETLINK_UNCONNECTED;
1517                 nlk->dst_portid = 0;
1518                 nlk->dst_group  = 0;
1519                 return 0;
1520         }
1521         if (addr->sa_family != AF_NETLINK)
1522                 return -EINVAL;
1523
1524         if ((nladdr->nl_groups || nladdr->nl_pid) &&
1525             !netlink_allowed(sock, NL_CFG_F_NONROOT_SEND))
1526                 return -EPERM;
1527
1528         if (!nlk->portid)
1529                 err = netlink_autobind(sock);
1530
1531         if (err == 0) {
1532                 sk->sk_state    = NETLINK_CONNECTED;
1533                 nlk->dst_portid = nladdr->nl_pid;
1534                 nlk->dst_group  = ffs(nladdr->nl_groups);
1535         }
1536
1537         return err;
1538 }
1539
1540 static int netlink_getname(struct socket *sock, struct sockaddr *addr,
1541                            int *addr_len, int peer)
1542 {
1543         struct sock *sk = sock->sk;
1544         struct netlink_sock *nlk = nlk_sk(sk);
1545         DECLARE_SOCKADDR(struct sockaddr_nl *, nladdr, addr);
1546
1547         nladdr->nl_family = AF_NETLINK;
1548         nladdr->nl_pad = 0;
1549         *addr_len = sizeof(*nladdr);
1550
1551         if (peer) {
1552                 nladdr->nl_pid = nlk->dst_portid;
1553                 nladdr->nl_groups = netlink_group_mask(nlk->dst_group);
1554         } else {
1555                 nladdr->nl_pid = nlk->portid;
1556                 nladdr->nl_groups = nlk->groups ? nlk->groups[0] : 0;
1557         }
1558         return 0;
1559 }
1560
1561 static struct sock *netlink_getsockbyportid(struct sock *ssk, u32 portid)
1562 {
1563         struct sock *sock;
1564         struct netlink_sock *nlk;
1565
1566         sock = netlink_lookup(sock_net(ssk), ssk->sk_protocol, portid);
1567         if (!sock)
1568                 return ERR_PTR(-ECONNREFUSED);
1569
1570         /* Don't bother queuing skb if kernel socket has no input function */
1571         nlk = nlk_sk(sock);
1572         if (sock->sk_state == NETLINK_CONNECTED &&
1573             nlk->dst_portid != nlk_sk(ssk)->portid) {
1574                 sock_put(sock);
1575                 return ERR_PTR(-ECONNREFUSED);
1576         }
1577         return sock;
1578 }
1579
1580 struct sock *netlink_getsockbyfilp(struct file *filp)
1581 {
1582         struct inode *inode = file_inode(filp);
1583         struct sock *sock;
1584
1585         if (!S_ISSOCK(inode->i_mode))
1586                 return ERR_PTR(-ENOTSOCK);
1587
1588         sock = SOCKET_I(inode)->sk;
1589         if (sock->sk_family != AF_NETLINK)
1590                 return ERR_PTR(-EINVAL);
1591
1592         sock_hold(sock);
1593         return sock;
1594 }
1595
1596 static struct sk_buff *netlink_alloc_large_skb(unsigned int size,
1597                                                int broadcast)
1598 {
1599         struct sk_buff *skb;
1600         void *data;
1601
1602         if (size <= NLMSG_GOODSIZE || broadcast)
1603                 return alloc_skb(size, GFP_KERNEL);
1604
1605         size = SKB_DATA_ALIGN(size) +
1606                SKB_DATA_ALIGN(sizeof(struct skb_shared_info));
1607
1608         data = vmalloc(size);
1609         if (data == NULL)
1610                 return NULL;
1611
1612         skb = build_skb(data, size);
1613         if (skb == NULL)
1614                 vfree(data);
1615         else {
1616                 skb->head_frag = 0;
1617                 skb->destructor = netlink_skb_destructor;
1618         }
1619
1620         return skb;
1621 }
1622
1623 /*
1624  * Attach a skb to a netlink socket.
1625  * The caller must hold a reference to the destination socket. On error, the
1626  * reference is dropped. The skb is not send to the destination, just all
1627  * all error checks are performed and memory in the queue is reserved.
1628  * Return values:
1629  * < 0: error. skb freed, reference to sock dropped.
1630  * 0: continue
1631  * 1: repeat lookup - reference dropped while waiting for socket memory.
1632  */
1633 int netlink_attachskb(struct sock *sk, struct sk_buff *skb,
1634                       long *timeo, struct sock *ssk)
1635 {
1636         struct netlink_sock *nlk;
1637
1638         nlk = nlk_sk(sk);
1639
1640         if ((atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
1641              test_bit(NETLINK_CONGESTED, &nlk->state)) &&
1642             !netlink_skb_is_mmaped(skb)) {
1643                 DECLARE_WAITQUEUE(wait, current);
1644                 if (!*timeo) {
1645                         if (!ssk || netlink_is_kernel(ssk))
1646                                 netlink_overrun(sk);
1647                         sock_put(sk);
1648                         kfree_skb(skb);
1649                         return -EAGAIN;
1650                 }
1651
1652                 __set_current_state(TASK_INTERRUPTIBLE);
1653                 add_wait_queue(&nlk->wait, &wait);
1654
1655                 if ((atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
1656                      test_bit(NETLINK_CONGESTED, &nlk->state)) &&
1657                     !sock_flag(sk, SOCK_DEAD))
1658                         *timeo = schedule_timeout(*timeo);
1659
1660                 __set_current_state(TASK_RUNNING);
1661                 remove_wait_queue(&nlk->wait, &wait);
1662                 sock_put(sk);
1663
1664                 if (signal_pending(current)) {
1665                         kfree_skb(skb);
1666                         return sock_intr_errno(*timeo);
1667                 }
1668                 return 1;
1669         }
1670         netlink_skb_set_owner_r(skb, sk);
1671         return 0;
1672 }
1673
1674 static int __netlink_sendskb(struct sock *sk, struct sk_buff *skb)
1675 {
1676         int len = skb->len;
1677
1678         netlink_deliver_tap(skb);
1679
1680 #ifdef CONFIG_NETLINK_MMAP
1681         if (netlink_skb_is_mmaped(skb))
1682                 netlink_queue_mmaped_skb(sk, skb);
1683         else if (netlink_rx_is_mmaped(sk))
1684                 netlink_ring_set_copied(sk, skb);
1685         else
1686 #endif /* CONFIG_NETLINK_MMAP */
1687                 skb_queue_tail(&sk->sk_receive_queue, skb);
1688         sk->sk_data_ready(sk);
1689         return len;
1690 }
1691
1692 int netlink_sendskb(struct sock *sk, struct sk_buff *skb)
1693 {
1694         int len = __netlink_sendskb(sk, skb);
1695
1696         sock_put(sk);
1697         return len;
1698 }
1699
1700 void netlink_detachskb(struct sock *sk, struct sk_buff *skb)
1701 {
1702         kfree_skb(skb);
1703         sock_put(sk);
1704 }
1705
1706 static struct sk_buff *netlink_trim(struct sk_buff *skb, gfp_t allocation)
1707 {
1708         int delta;
1709
1710         WARN_ON(skb->sk != NULL);
1711         if (netlink_skb_is_mmaped(skb))
1712                 return skb;
1713
1714         delta = skb->end - skb->tail;
1715         if (is_vmalloc_addr(skb->head) || delta * 2 < skb->truesize)
1716                 return skb;
1717
1718         if (skb_shared(skb)) {
1719                 struct sk_buff *nskb = skb_clone(skb, allocation);
1720                 if (!nskb)
1721                         return skb;
1722                 consume_skb(skb);
1723                 skb = nskb;
1724         }
1725
1726         if (!pskb_expand_head(skb, 0, -delta, allocation))
1727                 skb->truesize -= delta;
1728
1729         return skb;
1730 }
1731
1732 static int netlink_unicast_kernel(struct sock *sk, struct sk_buff *skb,
1733                                   struct sock *ssk)
1734 {
1735         int ret;
1736         struct netlink_sock *nlk = nlk_sk(sk);
1737
1738         ret = -ECONNREFUSED;
1739         if (nlk->netlink_rcv != NULL) {
1740                 ret = skb->len;
1741                 netlink_skb_set_owner_r(skb, sk);
1742                 NETLINK_CB(skb).sk = ssk;
1743                 netlink_deliver_tap_kernel(sk, ssk, skb);
1744                 nlk->netlink_rcv(skb);
1745                 consume_skb(skb);
1746         } else {
1747                 kfree_skb(skb);
1748         }
1749         sock_put(sk);
1750         return ret;
1751 }
1752
1753 int netlink_unicast(struct sock *ssk, struct sk_buff *skb,
1754                     u32 portid, int nonblock)
1755 {
1756         struct sock *sk;
1757         int err;
1758         long timeo;
1759
1760         skb = netlink_trim(skb, gfp_any());
1761
1762         timeo = sock_sndtimeo(ssk, nonblock);
1763 retry:
1764         sk = netlink_getsockbyportid(ssk, portid);
1765         if (IS_ERR(sk)) {
1766                 kfree_skb(skb);
1767                 return PTR_ERR(sk);
1768         }
1769         if (netlink_is_kernel(sk))
1770                 return netlink_unicast_kernel(sk, skb, ssk);
1771
1772         if (sk_filter(sk, skb)) {
1773                 err = skb->len;
1774                 kfree_skb(skb);
1775                 sock_put(sk);
1776                 return err;
1777         }
1778
1779         err = netlink_attachskb(sk, skb, &timeo, ssk);
1780         if (err == 1)
1781                 goto retry;
1782         if (err)
1783                 return err;
1784
1785         return netlink_sendskb(sk, skb);
1786 }
1787 EXPORT_SYMBOL(netlink_unicast);
1788
1789 struct sk_buff *netlink_alloc_skb(struct sock *ssk, unsigned int size,
1790                                   u32 dst_portid, gfp_t gfp_mask)
1791 {
1792 #ifdef CONFIG_NETLINK_MMAP
1793         struct sock *sk = NULL;
1794         struct sk_buff *skb;
1795         struct netlink_ring *ring;
1796         struct nl_mmap_hdr *hdr;
1797         unsigned int maxlen;
1798
1799         sk = netlink_getsockbyportid(ssk, dst_portid);
1800         if (IS_ERR(sk))
1801                 goto out;
1802
1803         ring = &nlk_sk(sk)->rx_ring;
1804         /* fast-path without atomic ops for common case: non-mmaped receiver */
1805         if (ring->pg_vec == NULL)
1806                 goto out_put;
1807
1808         if (ring->frame_size - NL_MMAP_HDRLEN < size)
1809                 goto out_put;
1810
1811         skb = alloc_skb_head(gfp_mask);
1812         if (skb == NULL)
1813                 goto err1;
1814
1815         spin_lock_bh(&sk->sk_receive_queue.lock);
1816         /* check again under lock */
1817         if (ring->pg_vec == NULL)
1818                 goto out_free;
1819
1820         /* check again under lock */
1821         maxlen = ring->frame_size - NL_MMAP_HDRLEN;
1822         if (maxlen < size)
1823                 goto out_free;
1824
1825         netlink_forward_ring(ring);
1826         hdr = netlink_current_frame(ring, NL_MMAP_STATUS_UNUSED);
1827         if (hdr == NULL)
1828                 goto err2;
1829         netlink_ring_setup_skb(skb, sk, ring, hdr);
1830         netlink_set_status(hdr, NL_MMAP_STATUS_RESERVED);
1831         atomic_inc(&ring->pending);
1832         netlink_increment_head(ring);
1833
1834         spin_unlock_bh(&sk->sk_receive_queue.lock);
1835         return skb;
1836
1837 err2:
1838         kfree_skb(skb);
1839         spin_unlock_bh(&sk->sk_receive_queue.lock);
1840         netlink_overrun(sk);
1841 err1:
1842         sock_put(sk);
1843         return NULL;
1844
1845 out_free:
1846         kfree_skb(skb);
1847         spin_unlock_bh(&sk->sk_receive_queue.lock);
1848 out_put:
1849         sock_put(sk);
1850 out:
1851 #endif
1852         return alloc_skb(size, gfp_mask);
1853 }
1854 EXPORT_SYMBOL_GPL(netlink_alloc_skb);
1855
1856 int netlink_has_listeners(struct sock *sk, unsigned int group)
1857 {
1858         int res = 0;
1859         struct listeners *listeners;
1860
1861         BUG_ON(!netlink_is_kernel(sk));
1862
1863         rcu_read_lock();
1864         listeners = rcu_dereference(nl_table[sk->sk_protocol].listeners);
1865
1866         if (listeners && group - 1 < nl_table[sk->sk_protocol].groups)
1867                 res = test_bit(group - 1, listeners->masks);
1868
1869         rcu_read_unlock();
1870
1871         return res;
1872 }
1873 EXPORT_SYMBOL_GPL(netlink_has_listeners);
1874
1875 static int netlink_broadcast_deliver(struct sock *sk, struct sk_buff *skb)
1876 {
1877         struct netlink_sock *nlk = nlk_sk(sk);
1878
1879         if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf &&
1880             !test_bit(NETLINK_CONGESTED, &nlk->state)) {
1881                 netlink_skb_set_owner_r(skb, sk);
1882                 __netlink_sendskb(sk, skb);
1883                 return atomic_read(&sk->sk_rmem_alloc) > (sk->sk_rcvbuf >> 1);
1884         }
1885         return -1;
1886 }
1887
1888 struct netlink_broadcast_data {
1889         struct sock *exclude_sk;
1890         struct net *net;
1891         u32 portid;
1892         u32 group;
1893         int failure;
1894         int delivery_failure;
1895         int congested;
1896         int delivered;
1897         gfp_t allocation;
1898         struct sk_buff *skb, *skb2;
1899         int (*tx_filter)(struct sock *dsk, struct sk_buff *skb, void *data);
1900         void *tx_data;
1901 };
1902
1903 static void do_one_broadcast(struct sock *sk,
1904                                     struct netlink_broadcast_data *p)
1905 {
1906         struct netlink_sock *nlk = nlk_sk(sk);
1907         int val;
1908
1909         if (p->exclude_sk == sk)
1910                 return;
1911
1912         if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
1913             !test_bit(p->group - 1, nlk->groups))
1914                 return;
1915
1916         if (!net_eq(sock_net(sk), p->net))
1917                 return;
1918
1919         if (p->failure) {
1920                 netlink_overrun(sk);
1921                 return;
1922         }
1923
1924         sock_hold(sk);
1925         if (p->skb2 == NULL) {
1926                 if (skb_shared(p->skb)) {
1927                         p->skb2 = skb_clone(p->skb, p->allocation);
1928                 } else {
1929                         p->skb2 = skb_get(p->skb);
1930                         /*
1931                          * skb ownership may have been set when
1932                          * delivered to a previous socket.
1933                          */
1934                         skb_orphan(p->skb2);
1935                 }
1936         }
1937         if (p->skb2 == NULL) {
1938                 netlink_overrun(sk);
1939                 /* Clone failed. Notify ALL listeners. */
1940                 p->failure = 1;
1941                 if (nlk->flags & NETLINK_BROADCAST_SEND_ERROR)
1942                         p->delivery_failure = 1;
1943         } else if (p->tx_filter && p->tx_filter(sk, p->skb2, p->tx_data)) {
1944                 kfree_skb(p->skb2);
1945                 p->skb2 = NULL;
1946         } else if (sk_filter(sk, p->skb2)) {
1947                 kfree_skb(p->skb2);
1948                 p->skb2 = NULL;
1949         } else if ((val = netlink_broadcast_deliver(sk, p->skb2)) < 0) {
1950                 netlink_overrun(sk);
1951                 if (nlk->flags & NETLINK_BROADCAST_SEND_ERROR)
1952                         p->delivery_failure = 1;
1953         } else {
1954                 p->congested |= val;
1955                 p->delivered = 1;
1956                 p->skb2 = NULL;
1957         }
1958         sock_put(sk);
1959 }
1960
1961 int netlink_broadcast_filtered(struct sock *ssk, struct sk_buff *skb, u32 portid,
1962         u32 group, gfp_t allocation,
1963         int (*filter)(struct sock *dsk, struct sk_buff *skb, void *data),
1964         void *filter_data)
1965 {
1966         struct net *net = sock_net(ssk);
1967         struct netlink_broadcast_data info;
1968         struct sock *sk;
1969
1970         skb = netlink_trim(skb, allocation);
1971
1972         info.exclude_sk = ssk;
1973         info.net = net;
1974         info.portid = portid;
1975         info.group = group;
1976         info.failure = 0;
1977         info.delivery_failure = 0;
1978         info.congested = 0;
1979         info.delivered = 0;
1980         info.allocation = allocation;
1981         info.skb = skb;
1982         info.skb2 = NULL;
1983         info.tx_filter = filter;
1984         info.tx_data = filter_data;
1985
1986         /* While we sleep in clone, do not allow to change socket list */
1987
1988         netlink_lock_table();
1989
1990         sk_for_each_bound(sk, &nl_table[ssk->sk_protocol].mc_list)
1991                 do_one_broadcast(sk, &info);
1992
1993         consume_skb(skb);
1994
1995         netlink_unlock_table();
1996
1997         if (info.delivery_failure) {
1998                 kfree_skb(info.skb2);
1999                 return -ENOBUFS;
2000         }
2001         consume_skb(info.skb2);
2002
2003         if (info.delivered) {
2004                 if (info.congested && (allocation & __GFP_WAIT))
2005                         yield();
2006                 return 0;
2007         }
2008         return -ESRCH;
2009 }
2010 EXPORT_SYMBOL(netlink_broadcast_filtered);
2011
2012 int netlink_broadcast(struct sock *ssk, struct sk_buff *skb, u32 portid,
2013                       u32 group, gfp_t allocation)
2014 {
2015         return netlink_broadcast_filtered(ssk, skb, portid, group, allocation,
2016                 NULL, NULL);
2017 }
2018 EXPORT_SYMBOL(netlink_broadcast);
2019
2020 struct netlink_set_err_data {
2021         struct sock *exclude_sk;
2022         u32 portid;
2023         u32 group;
2024         int code;
2025 };
2026
2027 static int do_one_set_err(struct sock *sk, struct netlink_set_err_data *p)
2028 {
2029         struct netlink_sock *nlk = nlk_sk(sk);
2030         int ret = 0;
2031
2032         if (sk == p->exclude_sk)
2033                 goto out;
2034
2035         if (!net_eq(sock_net(sk), sock_net(p->exclude_sk)))
2036                 goto out;
2037
2038         if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
2039             !test_bit(p->group - 1, nlk->groups))
2040                 goto out;
2041
2042         if (p->code == ENOBUFS && nlk->flags & NETLINK_RECV_NO_ENOBUFS) {
2043                 ret = 1;
2044                 goto out;
2045         }
2046
2047         sk->sk_err = p->code;
2048         sk->sk_error_report(sk);
2049 out:
2050         return ret;
2051 }
2052
2053 /**
2054  * netlink_set_err - report error to broadcast listeners
2055  * @ssk: the kernel netlink socket, as returned by netlink_kernel_create()
2056  * @portid: the PORTID of a process that we want to skip (if any)
2057  * @group: the broadcast group that will notice the error
2058  * @code: error code, must be negative (as usual in kernelspace)
2059  *
2060  * This function returns the number of broadcast listeners that have set the
2061  * NETLINK_RECV_NO_ENOBUFS socket option.
2062  */
2063 int netlink_set_err(struct sock *ssk, u32 portid, u32 group, int code)
2064 {
2065         struct netlink_set_err_data info;
2066         struct sock *sk;
2067         int ret = 0;
2068
2069         info.exclude_sk = ssk;
2070         info.portid = portid;
2071         info.group = group;
2072         /* sk->sk_err wants a positive error value */
2073         info.code = -code;
2074
2075         read_lock(&nl_table_lock);
2076
2077         sk_for_each_bound(sk, &nl_table[ssk->sk_protocol].mc_list)
2078                 ret += do_one_set_err(sk, &info);
2079
2080         read_unlock(&nl_table_lock);
2081         return ret;
2082 }
2083 EXPORT_SYMBOL(netlink_set_err);
2084
2085 /* must be called with netlink table grabbed */
2086 static void netlink_update_socket_mc(struct netlink_sock *nlk,
2087                                      unsigned int group,
2088                                      int is_new)
2089 {
2090         int old, new = !!is_new, subscriptions;
2091
2092         old = test_bit(group - 1, nlk->groups);
2093         subscriptions = nlk->subscriptions - old + new;
2094         if (new)
2095                 __set_bit(group - 1, nlk->groups);
2096         else
2097                 __clear_bit(group - 1, nlk->groups);
2098         netlink_update_subscriptions(&nlk->sk, subscriptions);
2099         netlink_update_listeners(&nlk->sk);
2100 }
2101
2102 static int netlink_setsockopt(struct socket *sock, int level, int optname,
2103                               char __user *optval, unsigned int optlen)
2104 {
2105         struct sock *sk = sock->sk;
2106         struct netlink_sock *nlk = nlk_sk(sk);
2107         unsigned int val = 0;
2108         int err;
2109
2110         if (level != SOL_NETLINK)
2111                 return -ENOPROTOOPT;
2112
2113         if (optname != NETLINK_RX_RING && optname != NETLINK_TX_RING &&
2114             optlen >= sizeof(int) &&
2115             get_user(val, (unsigned int __user *)optval))
2116                 return -EFAULT;
2117
2118         switch (optname) {
2119         case NETLINK_PKTINFO:
2120                 if (val)
2121                         nlk->flags |= NETLINK_RECV_PKTINFO;
2122                 else
2123                         nlk->flags &= ~NETLINK_RECV_PKTINFO;
2124                 err = 0;
2125                 break;
2126         case NETLINK_ADD_MEMBERSHIP:
2127         case NETLINK_DROP_MEMBERSHIP: {
2128                 if (!netlink_allowed(sock, NL_CFG_F_NONROOT_RECV))
2129                         return -EPERM;
2130                 err = netlink_realloc_groups(sk);
2131                 if (err)
2132                         return err;
2133                 if (!val || val - 1 >= nlk->ngroups)
2134                         return -EINVAL;
2135                 if (optname == NETLINK_ADD_MEMBERSHIP && nlk->netlink_bind) {
2136                         err = nlk->netlink_bind(val);
2137                         if (err)
2138                                 return err;
2139                 }
2140                 netlink_table_grab();
2141                 netlink_update_socket_mc(nlk, val,
2142                                          optname == NETLINK_ADD_MEMBERSHIP);
2143                 netlink_table_ungrab();
2144                 if (optname == NETLINK_DROP_MEMBERSHIP && nlk->netlink_unbind)
2145                         nlk->netlink_unbind(val);
2146
2147                 err = 0;
2148                 break;
2149         }
2150         case NETLINK_BROADCAST_ERROR:
2151                 if (val)
2152                         nlk->flags |= NETLINK_BROADCAST_SEND_ERROR;
2153                 else
2154                         nlk->flags &= ~NETLINK_BROADCAST_SEND_ERROR;
2155                 err = 0;
2156                 break;
2157         case NETLINK_NO_ENOBUFS:
2158                 if (val) {
2159                         nlk->flags |= NETLINK_RECV_NO_ENOBUFS;
2160                         clear_bit(NETLINK_CONGESTED, &nlk->state);
2161                         wake_up_interruptible(&nlk->wait);
2162                 } else {
2163                         nlk->flags &= ~NETLINK_RECV_NO_ENOBUFS;
2164                 }
2165                 err = 0;
2166                 break;
2167 #ifdef CONFIG_NETLINK_MMAP
2168         case NETLINK_RX_RING:
2169         case NETLINK_TX_RING: {
2170                 struct nl_mmap_req req;
2171
2172                 /* Rings might consume more memory than queue limits, require
2173                  * CAP_NET_ADMIN.
2174                  */
2175                 if (!capable(CAP_NET_ADMIN))
2176                         return -EPERM;
2177                 if (optlen < sizeof(req))
2178                         return -EINVAL;
2179                 if (copy_from_user(&req, optval, sizeof(req)))
2180                         return -EFAULT;
2181                 err = netlink_set_ring(sk, &req, false,
2182                                        optname == NETLINK_TX_RING);
2183                 break;
2184         }
2185 #endif /* CONFIG_NETLINK_MMAP */
2186         default:
2187                 err = -ENOPROTOOPT;
2188         }
2189         return err;
2190 }
2191
2192 static int netlink_getsockopt(struct socket *sock, int level, int optname,
2193                               char __user *optval, int __user *optlen)
2194 {
2195         struct sock *sk = sock->sk;
2196         struct netlink_sock *nlk = nlk_sk(sk);
2197         int len, val, err;
2198
2199         if (level != SOL_NETLINK)
2200                 return -ENOPROTOOPT;
2201
2202         if (get_user(len, optlen))
2203                 return -EFAULT;
2204         if (len < 0)
2205                 return -EINVAL;
2206
2207         switch (optname) {
2208         case NETLINK_PKTINFO:
2209                 if (len < sizeof(int))
2210                         return -EINVAL;
2211                 len = sizeof(int);
2212                 val = nlk->flags & NETLINK_RECV_PKTINFO ? 1 : 0;
2213                 if (put_user(len, optlen) ||
2214                     put_user(val, optval))
2215                         return -EFAULT;
2216                 err = 0;
2217                 break;
2218         case NETLINK_BROADCAST_ERROR:
2219                 if (len < sizeof(int))
2220                         return -EINVAL;
2221                 len = sizeof(int);
2222                 val = nlk->flags & NETLINK_BROADCAST_SEND_ERROR ? 1 : 0;
2223                 if (put_user(len, optlen) ||
2224                     put_user(val, optval))
2225                         return -EFAULT;
2226                 err = 0;
2227                 break;
2228         case NETLINK_NO_ENOBUFS:
2229                 if (len < sizeof(int))
2230                         return -EINVAL;
2231                 len = sizeof(int);
2232                 val = nlk->flags & NETLINK_RECV_NO_ENOBUFS ? 1 : 0;
2233                 if (put_user(len, optlen) ||
2234                     put_user(val, optval))
2235                         return -EFAULT;
2236                 err = 0;
2237                 break;
2238         default:
2239                 err = -ENOPROTOOPT;
2240         }
2241         return err;
2242 }
2243
2244 static void netlink_cmsg_recv_pktinfo(struct msghdr *msg, struct sk_buff *skb)
2245 {
2246         struct nl_pktinfo info;
2247
2248         info.group = NETLINK_CB(skb).dst_group;
2249         put_cmsg(msg, SOL_NETLINK, NETLINK_PKTINFO, sizeof(info), &info);
2250 }
2251
2252 static int netlink_sendmsg(struct kiocb *kiocb, struct socket *sock,
2253                            struct msghdr *msg, size_t len)
2254 {
2255         struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
2256         struct sock *sk = sock->sk;
2257         struct netlink_sock *nlk = nlk_sk(sk);
2258         DECLARE_SOCKADDR(struct sockaddr_nl *, addr, msg->msg_name);
2259         u32 dst_portid;
2260         u32 dst_group;
2261         struct sk_buff *skb;
2262         int err;
2263         struct scm_cookie scm;
2264         u32 netlink_skb_flags = 0;
2265
2266         if (msg->msg_flags&MSG_OOB)
2267                 return -EOPNOTSUPP;
2268
2269         if (NULL == siocb->scm)
2270                 siocb->scm = &scm;
2271
2272         err = scm_send(sock, msg, siocb->scm, true);
2273         if (err < 0)
2274                 return err;
2275
2276         if (msg->msg_namelen) {
2277                 err = -EINVAL;
2278                 if (addr->nl_family != AF_NETLINK)
2279                         goto out;
2280                 dst_portid = addr->nl_pid;
2281                 dst_group = ffs(addr->nl_groups);
2282                 err =  -EPERM;
2283                 if ((dst_group || dst_portid) &&
2284                     !netlink_allowed(sock, NL_CFG_F_NONROOT_SEND))
2285                         goto out;
2286                 netlink_skb_flags |= NETLINK_SKB_DST;
2287         } else {
2288                 dst_portid = nlk->dst_portid;
2289                 dst_group = nlk->dst_group;
2290         }
2291
2292         if (!nlk->portid) {
2293                 err = netlink_autobind(sock);
2294                 if (err)
2295                         goto out;
2296         }
2297
2298         if (netlink_tx_is_mmaped(sk) &&
2299             msg->msg_iov->iov_base == NULL) {
2300                 err = netlink_mmap_sendmsg(sk, msg, dst_portid, dst_group,
2301                                            siocb);
2302                 goto out;
2303         }
2304
2305         err = -EMSGSIZE;
2306         if (len > sk->sk_sndbuf - 32)
2307                 goto out;
2308         err = -ENOBUFS;
2309         skb = netlink_alloc_large_skb(len, dst_group);
2310         if (skb == NULL)
2311                 goto out;
2312
2313         NETLINK_CB(skb).portid  = nlk->portid;
2314         NETLINK_CB(skb).dst_group = dst_group;
2315         NETLINK_CB(skb).creds   = siocb->scm->creds;
2316         NETLINK_CB(skb).flags   = netlink_skb_flags;
2317
2318         err = -EFAULT;
2319         if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) {
2320                 kfree_skb(skb);
2321                 goto out;
2322         }
2323
2324         err = security_netlink_send(sk, skb);
2325         if (err) {
2326                 kfree_skb(skb);
2327                 goto out;
2328         }
2329
2330         if (dst_group) {
2331                 atomic_inc(&skb->users);
2332                 netlink_broadcast(sk, skb, dst_portid, dst_group, GFP_KERNEL);
2333         }
2334         err = netlink_unicast(sk, skb, dst_portid, msg->msg_flags&MSG_DONTWAIT);
2335
2336 out:
2337         scm_destroy(siocb->scm);
2338         return err;
2339 }
2340
2341 static int netlink_recvmsg(struct kiocb *kiocb, struct socket *sock,
2342                            struct msghdr *msg, size_t len,
2343                            int flags)
2344 {
2345         struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
2346         struct scm_cookie scm;
2347         struct sock *sk = sock->sk;
2348         struct netlink_sock *nlk = nlk_sk(sk);
2349         int noblock = flags&MSG_DONTWAIT;
2350         size_t copied;
2351         struct sk_buff *skb, *data_skb;
2352         int err, ret;
2353
2354         if (flags&MSG_OOB)
2355                 return -EOPNOTSUPP;
2356
2357         copied = 0;
2358
2359         skb = skb_recv_datagram(sk, flags, noblock, &err);
2360         if (skb == NULL)
2361                 goto out;
2362
2363         data_skb = skb;
2364
2365 #ifdef CONFIG_COMPAT_NETLINK_MESSAGES
2366         if (unlikely(skb_shinfo(skb)->frag_list)) {
2367                 /*
2368                  * If this skb has a frag_list, then here that means that we
2369                  * will have to use the frag_list skb's data for compat tasks
2370                  * and the regular skb's data for normal (non-compat) tasks.
2371                  *
2372                  * If we need to send the compat skb, assign it to the
2373                  * 'data_skb' variable so that it will be used below for data
2374                  * copying. We keep 'skb' for everything else, including
2375                  * freeing both later.
2376                  */
2377                 if (flags & MSG_CMSG_COMPAT)
2378                         data_skb = skb_shinfo(skb)->frag_list;
2379         }
2380 #endif
2381
2382         /* Record the max length of recvmsg() calls for future allocations */
2383         nlk->max_recvmsg_len = max(nlk->max_recvmsg_len, len);
2384         nlk->max_recvmsg_len = min_t(size_t, nlk->max_recvmsg_len,
2385                                      16384);
2386
2387         copied = data_skb->len;
2388         if (len < copied) {
2389                 msg->msg_flags |= MSG_TRUNC;
2390                 copied = len;
2391         }
2392
2393         skb_reset_transport_header(data_skb);
2394         err = skb_copy_datagram_iovec(data_skb, 0, msg->msg_iov, copied);
2395
2396         if (msg->msg_name) {
2397                 DECLARE_SOCKADDR(struct sockaddr_nl *, addr, msg->msg_name);
2398                 addr->nl_family = AF_NETLINK;
2399                 addr->nl_pad    = 0;
2400                 addr->nl_pid    = NETLINK_CB(skb).portid;
2401                 addr->nl_groups = netlink_group_mask(NETLINK_CB(skb).dst_group);
2402                 msg->msg_namelen = sizeof(*addr);
2403         }
2404
2405         if (nlk->flags & NETLINK_RECV_PKTINFO)
2406                 netlink_cmsg_recv_pktinfo(msg, skb);
2407
2408         if (NULL == siocb->scm) {
2409                 memset(&scm, 0, sizeof(scm));
2410                 siocb->scm = &scm;
2411         }
2412         siocb->scm->creds = *NETLINK_CREDS(skb);
2413         if (flags & MSG_TRUNC)
2414                 copied = data_skb->len;
2415
2416         skb_free_datagram(sk, skb);
2417
2418         if (nlk->cb_running &&
2419             atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf / 2) {
2420                 ret = netlink_dump(sk);
2421                 if (ret) {
2422                         sk->sk_err = -ret;
2423                         sk->sk_error_report(sk);
2424                 }
2425         }
2426
2427         scm_recv(sock, msg, siocb->scm, flags);
2428 out:
2429         netlink_rcv_wake(sk);
2430         return err ? : copied;
2431 }
2432
2433 static void netlink_data_ready(struct sock *sk)
2434 {
2435         BUG();
2436 }
2437
2438 /*
2439  *      We export these functions to other modules. They provide a
2440  *      complete set of kernel non-blocking support for message
2441  *      queueing.
2442  */
2443
2444 struct sock *
2445 __netlink_kernel_create(struct net *net, int unit, struct module *module,
2446                         struct netlink_kernel_cfg *cfg)
2447 {
2448         struct socket *sock;
2449         struct sock *sk;
2450         struct netlink_sock *nlk;
2451         struct listeners *listeners = NULL;
2452         struct mutex *cb_mutex = cfg ? cfg->cb_mutex : NULL;
2453         unsigned int groups;
2454
2455         BUG_ON(!nl_table);
2456
2457         if (unit < 0 || unit >= MAX_LINKS)
2458                 return NULL;
2459
2460         if (sock_create_lite(PF_NETLINK, SOCK_DGRAM, unit, &sock))
2461                 return NULL;
2462
2463         /*
2464          * We have to just have a reference on the net from sk, but don't
2465          * get_net it. Besides, we cannot get and then put the net here.
2466          * So we create one inside init_net and the move it to net.
2467          */
2468
2469         if (__netlink_create(&init_net, sock, cb_mutex, unit) < 0)
2470                 goto out_sock_release_nosk;
2471
2472         sk = sock->sk;
2473         sk_change_net(sk, net);
2474
2475         if (!cfg || cfg->groups < 32)
2476                 groups = 32;
2477         else
2478                 groups = cfg->groups;
2479
2480         listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
2481         if (!listeners)
2482                 goto out_sock_release;
2483
2484         sk->sk_data_ready = netlink_data_ready;
2485         if (cfg && cfg->input)
2486                 nlk_sk(sk)->netlink_rcv = cfg->input;
2487
2488         if (netlink_insert(sk, net, 0))
2489                 goto out_sock_release;
2490
2491         nlk = nlk_sk(sk);
2492         nlk->flags |= NETLINK_KERNEL_SOCKET;
2493
2494         netlink_table_grab();
2495         if (!nl_table[unit].registered) {
2496                 nl_table[unit].groups = groups;
2497                 rcu_assign_pointer(nl_table[unit].listeners, listeners);
2498                 nl_table[unit].cb_mutex = cb_mutex;
2499                 nl_table[unit].module = module;
2500                 if (cfg) {
2501                         nl_table[unit].bind = cfg->bind;
2502                         nl_table[unit].flags = cfg->flags;
2503                         if (cfg->compare)
2504                                 nl_table[unit].compare = cfg->compare;
2505                 }
2506                 nl_table[unit].registered = 1;
2507         } else {
2508                 kfree(listeners);
2509                 nl_table[unit].registered++;
2510         }
2511         netlink_table_ungrab();
2512         return sk;
2513
2514 out_sock_release:
2515         kfree(listeners);
2516         netlink_kernel_release(sk);
2517         return NULL;
2518
2519 out_sock_release_nosk:
2520         sock_release(sock);
2521         return NULL;
2522 }
2523 EXPORT_SYMBOL(__netlink_kernel_create);
2524
2525 void
2526 netlink_kernel_release(struct sock *sk)
2527 {
2528         sk_release_kernel(sk);
2529 }
2530 EXPORT_SYMBOL(netlink_kernel_release);
2531
2532 int __netlink_change_ngroups(struct sock *sk, unsigned int groups)
2533 {
2534         struct listeners *new, *old;
2535         struct netlink_table *tbl = &nl_table[sk->sk_protocol];
2536
2537         if (groups < 32)
2538                 groups = 32;
2539
2540         if (NLGRPSZ(tbl->groups) < NLGRPSZ(groups)) {
2541                 new = kzalloc(sizeof(*new) + NLGRPSZ(groups), GFP_ATOMIC);
2542                 if (!new)
2543                         return -ENOMEM;
2544                 old = nl_deref_protected(tbl->listeners);
2545                 memcpy(new->masks, old->masks, NLGRPSZ(tbl->groups));
2546                 rcu_assign_pointer(tbl->listeners, new);
2547
2548                 kfree_rcu(old, rcu);
2549         }
2550         tbl->groups = groups;
2551
2552         return 0;
2553 }
2554
2555 /**
2556  * netlink_change_ngroups - change number of multicast groups
2557  *
2558  * This changes the number of multicast groups that are available
2559  * on a certain netlink family. Note that it is not possible to
2560  * change the number of groups to below 32. Also note that it does
2561  * not implicitly call netlink_clear_multicast_users() when the
2562  * number of groups is reduced.
2563  *
2564  * @sk: The kernel netlink socket, as returned by netlink_kernel_create().
2565  * @groups: The new number of groups.
2566  */
2567 int netlink_change_ngroups(struct sock *sk, unsigned int groups)
2568 {
2569         int err;
2570
2571         netlink_table_grab();
2572         err = __netlink_change_ngroups(sk, groups);
2573         netlink_table_ungrab();
2574
2575         return err;
2576 }
2577
2578 void __netlink_clear_multicast_users(struct sock *ksk, unsigned int group)
2579 {
2580         struct sock *sk;
2581         struct netlink_table *tbl = &nl_table[ksk->sk_protocol];
2582
2583         sk_for_each_bound(sk, &tbl->mc_list)
2584                 netlink_update_socket_mc(nlk_sk(sk), group, 0);
2585 }
2586
2587 struct nlmsghdr *
2588 __nlmsg_put(struct sk_buff *skb, u32 portid, u32 seq, int type, int len, int flags)
2589 {
2590         struct nlmsghdr *nlh;
2591         int size = nlmsg_msg_size(len);
2592
2593         nlh = (struct nlmsghdr *)skb_put(skb, NLMSG_ALIGN(size));
2594         nlh->nlmsg_type = type;
2595         nlh->nlmsg_len = size;
2596         nlh->nlmsg_flags = flags;
2597         nlh->nlmsg_pid = portid;
2598         nlh->nlmsg_seq = seq;
2599         if (!__builtin_constant_p(size) || NLMSG_ALIGN(size) - size != 0)
2600                 memset(nlmsg_data(nlh) + len, 0, NLMSG_ALIGN(size) - size);
2601         return nlh;
2602 }
2603 EXPORT_SYMBOL(__nlmsg_put);
2604
2605 /*
2606  * It looks a bit ugly.
2607  * It would be better to create kernel thread.
2608  */
2609
2610 static int netlink_dump(struct sock *sk)
2611 {
2612         struct netlink_sock *nlk = nlk_sk(sk);
2613         struct netlink_callback *cb;
2614         struct sk_buff *skb = NULL;
2615         struct nlmsghdr *nlh;
2616         int len, err = -ENOBUFS;
2617         int alloc_size;
2618
2619         mutex_lock(nlk->cb_mutex);
2620         if (!nlk->cb_running) {
2621                 err = -EINVAL;
2622                 goto errout_skb;
2623         }
2624
2625         cb = &nlk->cb;
2626         alloc_size = max_t(int, cb->min_dump_alloc, NLMSG_GOODSIZE);
2627
2628         if (!netlink_rx_is_mmaped(sk) &&
2629             atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
2630                 goto errout_skb;
2631
2632         /* NLMSG_GOODSIZE is small to avoid high order allocations being
2633          * required, but it makes sense to _attempt_ a 16K bytes allocation
2634          * to reduce number of system calls on dump operations, if user
2635          * ever provided a big enough buffer.
2636          */
2637         if (alloc_size < nlk->max_recvmsg_len) {
2638                 skb = netlink_alloc_skb(sk,
2639                                         nlk->max_recvmsg_len,
2640                                         nlk->portid,
2641                                         GFP_KERNEL |
2642                                         __GFP_NOWARN |
2643                                         __GFP_NORETRY);
2644                 /* available room should be exact amount to avoid MSG_TRUNC */
2645                 if (skb)
2646                         skb_reserve(skb, skb_tailroom(skb) -
2647                                          nlk->max_recvmsg_len);
2648         }
2649         if (!skb)
2650                 skb = netlink_alloc_skb(sk, alloc_size, nlk->portid,
2651                                         GFP_KERNEL);
2652         if (!skb)
2653                 goto errout_skb;
2654         netlink_skb_set_owner_r(skb, sk);
2655
2656         len = cb->dump(skb, cb);
2657
2658         if (len > 0) {
2659                 mutex_unlock(nlk->cb_mutex);
2660
2661                 if (sk_filter(sk, skb))
2662                         kfree_skb(skb);
2663                 else
2664                         __netlink_sendskb(sk, skb);
2665                 return 0;
2666         }
2667
2668         nlh = nlmsg_put_answer(skb, cb, NLMSG_DONE, sizeof(len), NLM_F_MULTI);
2669         if (!nlh)
2670                 goto errout_skb;
2671
2672         nl_dump_check_consistent(cb, nlh);
2673
2674         memcpy(nlmsg_data(nlh), &len, sizeof(len));
2675
2676         if (sk_filter(sk, skb))
2677                 kfree_skb(skb);
2678         else
2679                 __netlink_sendskb(sk, skb);
2680
2681         if (cb->done)
2682                 cb->done(cb);
2683
2684         nlk->cb_running = false;
2685         mutex_unlock(nlk->cb_mutex);
2686         module_put(cb->module);
2687         consume_skb(cb->skb);
2688         return 0;
2689
2690 errout_skb:
2691         mutex_unlock(nlk->cb_mutex);
2692         kfree_skb(skb);
2693         return err;
2694 }
2695
2696 int __netlink_dump_start(struct sock *ssk, struct sk_buff *skb,
2697                          const struct nlmsghdr *nlh,
2698                          struct netlink_dump_control *control)
2699 {
2700         struct netlink_callback *cb;
2701         struct sock *sk;
2702         struct netlink_sock *nlk;
2703         int ret;
2704
2705         /* Memory mapped dump requests need to be copied to avoid looping
2706          * on the pending state in netlink_mmap_sendmsg() while the CB hold
2707          * a reference to the skb.
2708          */
2709         if (netlink_skb_is_mmaped(skb)) {
2710                 skb = skb_copy(skb, GFP_KERNEL);
2711                 if (skb == NULL)
2712                         return -ENOBUFS;
2713         } else
2714                 atomic_inc(&skb->users);
2715
2716         sk = netlink_lookup(sock_net(ssk), ssk->sk_protocol, NETLINK_CB(skb).portid);
2717         if (sk == NULL) {
2718                 ret = -ECONNREFUSED;
2719                 goto error_free;
2720         }
2721
2722         nlk = nlk_sk(sk);
2723         mutex_lock(nlk->cb_mutex);
2724         /* A dump is in progress... */
2725         if (nlk->cb_running) {
2726                 ret = -EBUSY;
2727                 goto error_unlock;
2728         }
2729         /* add reference of module which cb->dump belongs to */
2730         if (!try_module_get(control->module)) {
2731                 ret = -EPROTONOSUPPORT;
2732                 goto error_unlock;
2733         }
2734
2735         cb = &nlk->cb;
2736         memset(cb, 0, sizeof(*cb));
2737         cb->dump = control->dump;
2738         cb->done = control->done;
2739         cb->nlh = nlh;
2740         cb->data = control->data;
2741         cb->module = control->module;
2742         cb->min_dump_alloc = control->min_dump_alloc;
2743         cb->skb = skb;
2744
2745         nlk->cb_running = true;
2746
2747         mutex_unlock(nlk->cb_mutex);
2748
2749         ret = netlink_dump(sk);
2750         sock_put(sk);
2751
2752         if (ret)
2753                 return ret;
2754
2755         /* We successfully started a dump, by returning -EINTR we
2756          * signal not to send ACK even if it was requested.
2757          */
2758         return -EINTR;
2759
2760 error_unlock:
2761         sock_put(sk);
2762         mutex_unlock(nlk->cb_mutex);
2763 error_free:
2764         kfree_skb(skb);
2765         return ret;
2766 }
2767 EXPORT_SYMBOL(__netlink_dump_start);
2768
2769 void netlink_ack(struct sk_buff *in_skb, struct nlmsghdr *nlh, int err)
2770 {
2771         struct sk_buff *skb;
2772         struct nlmsghdr *rep;
2773         struct nlmsgerr *errmsg;
2774         size_t payload = sizeof(*errmsg);
2775
2776         /* error messages get the original request appened */
2777         if (err)
2778                 payload += nlmsg_len(nlh);
2779
2780         skb = netlink_alloc_skb(in_skb->sk, nlmsg_total_size(payload),
2781                                 NETLINK_CB(in_skb).portid, GFP_KERNEL);
2782         if (!skb) {
2783                 struct sock *sk;
2784
2785                 sk = netlink_lookup(sock_net(in_skb->sk),
2786                                     in_skb->sk->sk_protocol,
2787                                     NETLINK_CB(in_skb).portid);
2788                 if (sk) {
2789                         sk->sk_err = ENOBUFS;
2790                         sk->sk_error_report(sk);
2791                         sock_put(sk);
2792                 }
2793                 return;
2794         }
2795
2796         rep = __nlmsg_put(skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq,
2797                           NLMSG_ERROR, payload, 0);
2798         errmsg = nlmsg_data(rep);
2799         errmsg->error = err;
2800         memcpy(&errmsg->msg, nlh, err ? nlh->nlmsg_len : sizeof(*nlh));
2801         netlink_unicast(in_skb->sk, skb, NETLINK_CB(in_skb).portid, MSG_DONTWAIT);
2802 }
2803 EXPORT_SYMBOL(netlink_ack);
2804
2805 int netlink_rcv_skb(struct sk_buff *skb, int (*cb)(struct sk_buff *,
2806                                                      struct nlmsghdr *))
2807 {
2808         struct nlmsghdr *nlh;
2809         int err;
2810
2811         while (skb->len >= nlmsg_total_size(0)) {
2812                 int msglen;
2813
2814                 nlh = nlmsg_hdr(skb);
2815                 err = 0;
2816
2817                 if (nlh->nlmsg_len < NLMSG_HDRLEN || skb->len < nlh->nlmsg_len)
2818                         return 0;
2819
2820                 /* Only requests are handled by the kernel */
2821                 if (!(nlh->nlmsg_flags & NLM_F_REQUEST))
2822                         goto ack;
2823
2824                 /* Skip control messages */
2825                 if (nlh->nlmsg_type < NLMSG_MIN_TYPE)
2826                         goto ack;
2827
2828                 err = cb(skb, nlh);
2829                 if (err == -EINTR)
2830                         goto skip;
2831
2832 ack:
2833                 if (nlh->nlmsg_flags & NLM_F_ACK || err)
2834                         netlink_ack(skb, nlh, err);
2835
2836 skip:
2837                 msglen = NLMSG_ALIGN(nlh->nlmsg_len);
2838                 if (msglen > skb->len)
2839                         msglen = skb->len;
2840                 skb_pull(skb, msglen);
2841         }
2842
2843         return 0;
2844 }
2845 EXPORT_SYMBOL(netlink_rcv_skb);
2846
2847 /**
2848  * nlmsg_notify - send a notification netlink message
2849  * @sk: netlink socket to use
2850  * @skb: notification message
2851  * @portid: destination netlink portid for reports or 0
2852  * @group: destination multicast group or 0
2853  * @report: 1 to report back, 0 to disable
2854  * @flags: allocation flags
2855  */
2856 int nlmsg_notify(struct sock *sk, struct sk_buff *skb, u32 portid,
2857                  unsigned int group, int report, gfp_t flags)
2858 {
2859         int err = 0;
2860
2861         if (group) {
2862                 int exclude_portid = 0;
2863
2864                 if (report) {
2865                         atomic_inc(&skb->users);
2866                         exclude_portid = portid;
2867                 }
2868
2869                 /* errors reported via destination sk->sk_err, but propagate
2870                  * delivery errors if NETLINK_BROADCAST_ERROR flag is set */
2871                 err = nlmsg_multicast(sk, skb, exclude_portid, group, flags);
2872         }
2873
2874         if (report) {
2875                 int err2;
2876
2877                 err2 = nlmsg_unicast(sk, skb, portid);
2878                 if (!err || err == -ESRCH)
2879                         err = err2;
2880         }
2881
2882         return err;
2883 }
2884 EXPORT_SYMBOL(nlmsg_notify);
2885
2886 #ifdef CONFIG_PROC_FS
2887 struct nl_seq_iter {
2888         struct seq_net_private p;
2889         int link;
2890         int hash_idx;
2891 };
2892
2893 static struct sock *netlink_seq_socket_idx(struct seq_file *seq, loff_t pos)
2894 {
2895         struct nl_seq_iter *iter = seq->private;
2896         int i, j;
2897         struct netlink_sock *nlk;
2898         struct sock *s;
2899         loff_t off = 0;
2900
2901         for (i = 0; i < MAX_LINKS; i++) {
2902                 struct rhashtable *ht = &nl_table[i].hash;
2903                 const struct bucket_table *tbl = rht_dereference_rcu(ht->tbl, ht);
2904
2905                 for (j = 0; j < tbl->size; j++) {
2906                         rht_for_each_entry_rcu(nlk, tbl->buckets[j], node) {
2907                                 s = (struct sock *)nlk;
2908
2909                                 if (sock_net(s) != seq_file_net(seq))
2910                                         continue;
2911                                 if (off == pos) {
2912                                         iter->link = i;
2913                                         iter->hash_idx = j;
2914                                         return s;
2915                                 }
2916                                 ++off;
2917                         }
2918                 }
2919         }
2920         return NULL;
2921 }
2922
2923 static void *netlink_seq_start(struct seq_file *seq, loff_t *pos)
2924         __acquires(RCU)
2925 {
2926         rcu_read_lock();
2927         return *pos ? netlink_seq_socket_idx(seq, *pos - 1) : SEQ_START_TOKEN;
2928 }
2929
2930 static void *netlink_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2931 {
2932         struct netlink_sock *nlk;
2933         struct nl_seq_iter *iter;
2934         struct net *net;
2935         int i, j;
2936
2937         ++*pos;
2938
2939         if (v == SEQ_START_TOKEN)
2940                 return netlink_seq_socket_idx(seq, 0);
2941
2942         net = seq_file_net(seq);
2943         iter = seq->private;
2944         nlk = v;
2945
2946         rht_for_each_entry_rcu(nlk, nlk->node.next, node)
2947                 if (net_eq(sock_net((struct sock *)nlk), net))
2948                         return nlk;
2949
2950         i = iter->link;
2951         j = iter->hash_idx + 1;
2952
2953         do {
2954                 struct rhashtable *ht = &nl_table[i].hash;
2955                 const struct bucket_table *tbl = rht_dereference_rcu(ht->tbl, ht);
2956
2957                 for (; j < tbl->size; j++) {
2958                         rht_for_each_entry_rcu(nlk, tbl->buckets[j], node) {
2959                                 if (net_eq(sock_net((struct sock *)nlk), net)) {
2960                                         iter->link = i;
2961                                         iter->hash_idx = j;
2962                                         return nlk;
2963                                 }
2964                         }
2965                 }
2966
2967                 j = 0;
2968         } while (++i < MAX_LINKS);
2969
2970         return NULL;
2971 }
2972
2973 static void netlink_seq_stop(struct seq_file *seq, void *v)
2974         __releases(RCU)
2975 {
2976         rcu_read_unlock();
2977 }
2978
2979
2980 static int netlink_seq_show(struct seq_file *seq, void *v)
2981 {
2982         if (v == SEQ_START_TOKEN) {
2983                 seq_puts(seq,
2984                          "sk       Eth Pid    Groups   "
2985                          "Rmem     Wmem     Dump     Locks     Drops     Inode\n");
2986         } else {
2987                 struct sock *s = v;
2988                 struct netlink_sock *nlk = nlk_sk(s);
2989
2990                 seq_printf(seq, "%pK %-3d %-6u %08x %-8d %-8d %d %-8d %-8d %-8lu\n",
2991                            s,
2992                            s->sk_protocol,
2993                            nlk->portid,
2994                            nlk->groups ? (u32)nlk->groups[0] : 0,
2995                            sk_rmem_alloc_get(s),
2996                            sk_wmem_alloc_get(s),
2997                            nlk->cb_running,
2998                            atomic_read(&s->sk_refcnt),
2999                            atomic_read(&s->sk_drops),
3000                            sock_i_ino(s)
3001                         );
3002
3003         }
3004         return 0;
3005 }
3006
3007 static const struct seq_operations netlink_seq_ops = {
3008         .start  = netlink_seq_start,
3009         .next   = netlink_seq_next,
3010         .stop   = netlink_seq_stop,
3011         .show   = netlink_seq_show,
3012 };
3013
3014
3015 static int netlink_seq_open(struct inode *inode, struct file *file)
3016 {
3017         return seq_open_net(inode, file, &netlink_seq_ops,
3018                                 sizeof(struct nl_seq_iter));
3019 }
3020
3021 static const struct file_operations netlink_seq_fops = {
3022         .owner          = THIS_MODULE,
3023         .open           = netlink_seq_open,
3024         .read           = seq_read,
3025         .llseek         = seq_lseek,
3026         .release        = seq_release_net,
3027 };
3028
3029 #endif
3030
3031 int netlink_register_notifier(struct notifier_block *nb)
3032 {
3033         return atomic_notifier_chain_register(&netlink_chain, nb);
3034 }
3035 EXPORT_SYMBOL(netlink_register_notifier);
3036
3037 int netlink_unregister_notifier(struct notifier_block *nb)
3038 {
3039         return atomic_notifier_chain_unregister(&netlink_chain, nb);
3040 }
3041 EXPORT_SYMBOL(netlink_unregister_notifier);
3042
3043 static const struct proto_ops netlink_ops = {
3044         .family =       PF_NETLINK,
3045         .owner =        THIS_MODULE,
3046         .release =      netlink_release,
3047         .bind =         netlink_bind,
3048         .connect =      netlink_connect,
3049         .socketpair =   sock_no_socketpair,
3050         .accept =       sock_no_accept,
3051         .getname =      netlink_getname,
3052         .poll =         netlink_poll,
3053         .ioctl =        sock_no_ioctl,
3054         .listen =       sock_no_listen,
3055         .shutdown =     sock_no_shutdown,
3056         .setsockopt =   netlink_setsockopt,
3057         .getsockopt =   netlink_getsockopt,
3058         .sendmsg =      netlink_sendmsg,
3059         .recvmsg =      netlink_recvmsg,
3060         .mmap =         netlink_mmap,
3061         .sendpage =     sock_no_sendpage,
3062 };
3063
3064 static const struct net_proto_family netlink_family_ops = {
3065         .family = PF_NETLINK,
3066         .create = netlink_create,
3067         .owner  = THIS_MODULE,  /* for consistency 8) */
3068 };
3069
3070 static int __net_init netlink_net_init(struct net *net)
3071 {
3072 #ifdef CONFIG_PROC_FS
3073         if (!proc_create("netlink", 0, net->proc_net, &netlink_seq_fops))
3074                 return -ENOMEM;
3075 #endif
3076         return 0;
3077 }
3078
3079 static void __net_exit netlink_net_exit(struct net *net)
3080 {
3081 #ifdef CONFIG_PROC_FS
3082         remove_proc_entry("netlink", net->proc_net);
3083 #endif
3084 }
3085
3086 static void __init netlink_add_usersock_entry(void)
3087 {
3088         struct listeners *listeners;
3089         int groups = 32;
3090
3091         listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
3092         if (!listeners)
3093                 panic("netlink_add_usersock_entry: Cannot allocate listeners\n");
3094
3095         netlink_table_grab();
3096
3097         nl_table[NETLINK_USERSOCK].groups = groups;
3098         rcu_assign_pointer(nl_table[NETLINK_USERSOCK].listeners, listeners);
3099         nl_table[NETLINK_USERSOCK].module = THIS_MODULE;
3100         nl_table[NETLINK_USERSOCK].registered = 1;
3101         nl_table[NETLINK_USERSOCK].flags = NL_CFG_F_NONROOT_SEND;
3102
3103         netlink_table_ungrab();
3104 }
3105
3106 static struct pernet_operations __net_initdata netlink_net_ops = {
3107         .init = netlink_net_init,
3108         .exit = netlink_net_exit,
3109 };
3110
3111 static int __init netlink_proto_init(void)
3112 {
3113         int i;
3114         int err = proto_register(&netlink_proto, 0);
3115         struct rhashtable_params ht_params = {
3116                 .head_offset = offsetof(struct netlink_sock, node),
3117                 .key_offset = offsetof(struct netlink_sock, portid),
3118                 .key_len = sizeof(u32), /* portid */
3119                 .hashfn = arch_fast_hash,
3120                 .max_shift = 16, /* 64K */
3121                 .grow_decision = rht_grow_above_75,
3122                 .shrink_decision = rht_shrink_below_30,
3123                 .mutex_is_held = lockdep_nl_sk_hash_is_held,
3124         };
3125
3126         if (err != 0)
3127                 goto out;
3128
3129         BUILD_BUG_ON(sizeof(struct netlink_skb_parms) > FIELD_SIZEOF(struct sk_buff, cb));
3130
3131         nl_table = kcalloc(MAX_LINKS, sizeof(*nl_table), GFP_KERNEL);
3132         if (!nl_table)
3133                 goto panic;
3134
3135         for (i = 0; i < MAX_LINKS; i++) {
3136                 if (rhashtable_init(&nl_table[i].hash, &ht_params) < 0) {
3137                         while (--i > 0)
3138                                 rhashtable_destroy(&nl_table[i].hash);
3139                         kfree(nl_table);
3140                         goto panic;
3141                 }
3142         }
3143
3144         INIT_LIST_HEAD(&netlink_tap_all);
3145
3146         netlink_add_usersock_entry();
3147
3148         sock_register(&netlink_family_ops);
3149         register_pernet_subsys(&netlink_net_ops);
3150         /* The netlink device handler may be needed early. */
3151         rtnetlink_init();
3152 out:
3153         return err;
3154 panic:
3155         panic("netlink_init: Cannot allocate nl_table\n");
3156 }
3157
3158 core_initcall(netlink_proto_init);