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