]> Pileus Git - ~andy/linux/blob - net/netlink/af_netlink.c
netlink: make compare exist all the time
[~andy/linux] / 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 0;
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 (is_vmalloc_addr(skb->head)) {
754                 vfree(skb->head);
755                 skb->head = NULL;
756         }
757         if (skb->sk != NULL)
758                 sock_rfree(skb);
759 }
760
761 static void netlink_skb_set_owner_r(struct sk_buff *skb, struct sock *sk)
762 {
763         WARN_ON(skb->sk != NULL);
764         skb->sk = sk;
765         skb->destructor = netlink_skb_destructor;
766         atomic_add(skb->truesize, &sk->sk_rmem_alloc);
767         sk_mem_charge(sk, skb->truesize);
768 }
769
770 static void netlink_sock_destruct(struct sock *sk)
771 {
772         struct netlink_sock *nlk = nlk_sk(sk);
773
774         if (nlk->cb) {
775                 if (nlk->cb->done)
776                         nlk->cb->done(nlk->cb);
777
778                 module_put(nlk->cb->module);
779                 netlink_destroy_callback(nlk->cb);
780         }
781
782         skb_queue_purge(&sk->sk_receive_queue);
783 #ifdef CONFIG_NETLINK_MMAP
784         if (1) {
785                 struct nl_mmap_req req;
786
787                 memset(&req, 0, sizeof(req));
788                 if (nlk->rx_ring.pg_vec)
789                         netlink_set_ring(sk, &req, true, false);
790                 memset(&req, 0, sizeof(req));
791                 if (nlk->tx_ring.pg_vec)
792                         netlink_set_ring(sk, &req, true, true);
793         }
794 #endif /* CONFIG_NETLINK_MMAP */
795
796         if (!sock_flag(sk, SOCK_DEAD)) {
797                 printk(KERN_ERR "Freeing alive netlink socket %p\n", sk);
798                 return;
799         }
800
801         WARN_ON(atomic_read(&sk->sk_rmem_alloc));
802         WARN_ON(atomic_read(&sk->sk_wmem_alloc));
803         WARN_ON(nlk_sk(sk)->groups);
804 }
805
806 /* This lock without WQ_FLAG_EXCLUSIVE is good on UP and it is _very_ bad on
807  * SMP. Look, when several writers sleep and reader wakes them up, all but one
808  * immediately hit write lock and grab all the cpus. Exclusive sleep solves
809  * this, _but_ remember, it adds useless work on UP machines.
810  */
811
812 void netlink_table_grab(void)
813         __acquires(nl_table_lock)
814 {
815         might_sleep();
816
817         write_lock_irq(&nl_table_lock);
818
819         if (atomic_read(&nl_table_users)) {
820                 DECLARE_WAITQUEUE(wait, current);
821
822                 add_wait_queue_exclusive(&nl_table_wait, &wait);
823                 for (;;) {
824                         set_current_state(TASK_UNINTERRUPTIBLE);
825                         if (atomic_read(&nl_table_users) == 0)
826                                 break;
827                         write_unlock_irq(&nl_table_lock);
828                         schedule();
829                         write_lock_irq(&nl_table_lock);
830                 }
831
832                 __set_current_state(TASK_RUNNING);
833                 remove_wait_queue(&nl_table_wait, &wait);
834         }
835 }
836
837 void netlink_table_ungrab(void)
838         __releases(nl_table_lock)
839 {
840         write_unlock_irq(&nl_table_lock);
841         wake_up(&nl_table_wait);
842 }
843
844 static inline void
845 netlink_lock_table(void)
846 {
847         /* read_lock() synchronizes us to netlink_table_grab */
848
849         read_lock(&nl_table_lock);
850         atomic_inc(&nl_table_users);
851         read_unlock(&nl_table_lock);
852 }
853
854 static inline void
855 netlink_unlock_table(void)
856 {
857         if (atomic_dec_and_test(&nl_table_users))
858                 wake_up(&nl_table_wait);
859 }
860
861 static bool netlink_compare(struct net *net, struct sock *sk)
862 {
863         return net_eq(sock_net(sk), net);
864 }
865
866 static struct sock *netlink_lookup(struct net *net, int protocol, u32 portid)
867 {
868         struct netlink_table *table = &nl_table[protocol];
869         struct nl_portid_hash *hash = &table->hash;
870         struct hlist_head *head;
871         struct sock *sk;
872
873         read_lock(&nl_table_lock);
874         head = nl_portid_hashfn(hash, portid);
875         sk_for_each(sk, head) {
876                 if (table->compare(net, sk) &&
877                     (nlk_sk(sk)->portid == portid)) {
878                         sock_hold(sk);
879                         goto found;
880                 }
881         }
882         sk = NULL;
883 found:
884         read_unlock(&nl_table_lock);
885         return sk;
886 }
887
888 static struct hlist_head *nl_portid_hash_zalloc(size_t size)
889 {
890         if (size <= PAGE_SIZE)
891                 return kzalloc(size, GFP_ATOMIC);
892         else
893                 return (struct hlist_head *)
894                         __get_free_pages(GFP_ATOMIC | __GFP_ZERO,
895                                          get_order(size));
896 }
897
898 static void nl_portid_hash_free(struct hlist_head *table, size_t size)
899 {
900         if (size <= PAGE_SIZE)
901                 kfree(table);
902         else
903                 free_pages((unsigned long)table, get_order(size));
904 }
905
906 static int nl_portid_hash_rehash(struct nl_portid_hash *hash, int grow)
907 {
908         unsigned int omask, mask, shift;
909         size_t osize, size;
910         struct hlist_head *otable, *table;
911         int i;
912
913         omask = mask = hash->mask;
914         osize = size = (mask + 1) * sizeof(*table);
915         shift = hash->shift;
916
917         if (grow) {
918                 if (++shift > hash->max_shift)
919                         return 0;
920                 mask = mask * 2 + 1;
921                 size *= 2;
922         }
923
924         table = nl_portid_hash_zalloc(size);
925         if (!table)
926                 return 0;
927
928         otable = hash->table;
929         hash->table = table;
930         hash->mask = mask;
931         hash->shift = shift;
932         get_random_bytes(&hash->rnd, sizeof(hash->rnd));
933
934         for (i = 0; i <= omask; i++) {
935                 struct sock *sk;
936                 struct hlist_node *tmp;
937
938                 sk_for_each_safe(sk, tmp, &otable[i])
939                         __sk_add_node(sk, nl_portid_hashfn(hash, nlk_sk(sk)->portid));
940         }
941
942         nl_portid_hash_free(otable, osize);
943         hash->rehash_time = jiffies + 10 * 60 * HZ;
944         return 1;
945 }
946
947 static inline int nl_portid_hash_dilute(struct nl_portid_hash *hash, int len)
948 {
949         int avg = hash->entries >> hash->shift;
950
951         if (unlikely(avg > 1) && nl_portid_hash_rehash(hash, 1))
952                 return 1;
953
954         if (unlikely(len > avg) && time_after(jiffies, hash->rehash_time)) {
955                 nl_portid_hash_rehash(hash, 0);
956                 return 1;
957         }
958
959         return 0;
960 }
961
962 static const struct proto_ops netlink_ops;
963
964 static void
965 netlink_update_listeners(struct sock *sk)
966 {
967         struct netlink_table *tbl = &nl_table[sk->sk_protocol];
968         unsigned long mask;
969         unsigned int i;
970         struct listeners *listeners;
971
972         listeners = nl_deref_protected(tbl->listeners);
973         if (!listeners)
974                 return;
975
976         for (i = 0; i < NLGRPLONGS(tbl->groups); i++) {
977                 mask = 0;
978                 sk_for_each_bound(sk, &tbl->mc_list) {
979                         if (i < NLGRPLONGS(nlk_sk(sk)->ngroups))
980                                 mask |= nlk_sk(sk)->groups[i];
981                 }
982                 listeners->masks[i] = mask;
983         }
984         /* this function is only called with the netlink table "grabbed", which
985          * makes sure updates are visible before bind or setsockopt return. */
986 }
987
988 static int netlink_insert(struct sock *sk, struct net *net, u32 portid)
989 {
990         struct netlink_table *table = &nl_table[sk->sk_protocol];
991         struct nl_portid_hash *hash = &table->hash;
992         struct hlist_head *head;
993         int err = -EADDRINUSE;
994         struct sock *osk;
995         int len;
996
997         netlink_table_grab();
998         head = nl_portid_hashfn(hash, portid);
999         len = 0;
1000         sk_for_each(osk, head) {
1001                 if (table->compare(net, osk) &&
1002                     (nlk_sk(osk)->portid == portid))
1003                         break;
1004                 len++;
1005         }
1006         if (osk)
1007                 goto err;
1008
1009         err = -EBUSY;
1010         if (nlk_sk(sk)->portid)
1011                 goto err;
1012
1013         err = -ENOMEM;
1014         if (BITS_PER_LONG > 32 && unlikely(hash->entries >= UINT_MAX))
1015                 goto err;
1016
1017         if (len && nl_portid_hash_dilute(hash, len))
1018                 head = nl_portid_hashfn(hash, portid);
1019         hash->entries++;
1020         nlk_sk(sk)->portid = portid;
1021         sk_add_node(sk, head);
1022         err = 0;
1023
1024 err:
1025         netlink_table_ungrab();
1026         return err;
1027 }
1028
1029 static void netlink_remove(struct sock *sk)
1030 {
1031         netlink_table_grab();
1032         if (sk_del_node_init(sk))
1033                 nl_table[sk->sk_protocol].hash.entries--;
1034         if (nlk_sk(sk)->subscriptions)
1035                 __sk_del_bind_node(sk);
1036         netlink_table_ungrab();
1037 }
1038
1039 static struct proto netlink_proto = {
1040         .name     = "NETLINK",
1041         .owner    = THIS_MODULE,
1042         .obj_size = sizeof(struct netlink_sock),
1043 };
1044
1045 static int __netlink_create(struct net *net, struct socket *sock,
1046                             struct mutex *cb_mutex, int protocol)
1047 {
1048         struct sock *sk;
1049         struct netlink_sock *nlk;
1050
1051         sock->ops = &netlink_ops;
1052
1053         sk = sk_alloc(net, PF_NETLINK, GFP_KERNEL, &netlink_proto);
1054         if (!sk)
1055                 return -ENOMEM;
1056
1057         sock_init_data(sock, sk);
1058
1059         nlk = nlk_sk(sk);
1060         if (cb_mutex) {
1061                 nlk->cb_mutex = cb_mutex;
1062         } else {
1063                 nlk->cb_mutex = &nlk->cb_def_mutex;
1064                 mutex_init(nlk->cb_mutex);
1065         }
1066         init_waitqueue_head(&nlk->wait);
1067 #ifdef CONFIG_NETLINK_MMAP
1068         mutex_init(&nlk->pg_vec_lock);
1069 #endif
1070
1071         sk->sk_destruct = netlink_sock_destruct;
1072         sk->sk_protocol = protocol;
1073         return 0;
1074 }
1075
1076 static int netlink_create(struct net *net, struct socket *sock, int protocol,
1077                           int kern)
1078 {
1079         struct module *module = NULL;
1080         struct mutex *cb_mutex;
1081         struct netlink_sock *nlk;
1082         void (*bind)(int group);
1083         int err = 0;
1084
1085         sock->state = SS_UNCONNECTED;
1086
1087         if (sock->type != SOCK_RAW && sock->type != SOCK_DGRAM)
1088                 return -ESOCKTNOSUPPORT;
1089
1090         if (protocol < 0 || protocol >= MAX_LINKS)
1091                 return -EPROTONOSUPPORT;
1092
1093         netlink_lock_table();
1094 #ifdef CONFIG_MODULES
1095         if (!nl_table[protocol].registered) {
1096                 netlink_unlock_table();
1097                 request_module("net-pf-%d-proto-%d", PF_NETLINK, protocol);
1098                 netlink_lock_table();
1099         }
1100 #endif
1101         if (nl_table[protocol].registered &&
1102             try_module_get(nl_table[protocol].module))
1103                 module = nl_table[protocol].module;
1104         else
1105                 err = -EPROTONOSUPPORT;
1106         cb_mutex = nl_table[protocol].cb_mutex;
1107         bind = nl_table[protocol].bind;
1108         netlink_unlock_table();
1109
1110         if (err < 0)
1111                 goto out;
1112
1113         err = __netlink_create(net, sock, cb_mutex, protocol);
1114         if (err < 0)
1115                 goto out_module;
1116
1117         local_bh_disable();
1118         sock_prot_inuse_add(net, &netlink_proto, 1);
1119         local_bh_enable();
1120
1121         nlk = nlk_sk(sock->sk);
1122         nlk->module = module;
1123         nlk->netlink_bind = bind;
1124 out:
1125         return err;
1126
1127 out_module:
1128         module_put(module);
1129         goto out;
1130 }
1131
1132 static int netlink_release(struct socket *sock)
1133 {
1134         struct sock *sk = sock->sk;
1135         struct netlink_sock *nlk;
1136
1137         if (!sk)
1138                 return 0;
1139
1140         netlink_remove(sk);
1141         sock_orphan(sk);
1142         nlk = nlk_sk(sk);
1143
1144         /*
1145          * OK. Socket is unlinked, any packets that arrive now
1146          * will be purged.
1147          */
1148
1149         sock->sk = NULL;
1150         wake_up_interruptible_all(&nlk->wait);
1151
1152         skb_queue_purge(&sk->sk_write_queue);
1153
1154         if (nlk->portid) {
1155                 struct netlink_notify n = {
1156                                                 .net = sock_net(sk),
1157                                                 .protocol = sk->sk_protocol,
1158                                                 .portid = nlk->portid,
1159                                           };
1160                 atomic_notifier_call_chain(&netlink_chain,
1161                                 NETLINK_URELEASE, &n);
1162         }
1163
1164         module_put(nlk->module);
1165
1166         netlink_table_grab();
1167         if (netlink_is_kernel(sk)) {
1168                 BUG_ON(nl_table[sk->sk_protocol].registered == 0);
1169                 if (--nl_table[sk->sk_protocol].registered == 0) {
1170                         struct listeners *old;
1171
1172                         old = nl_deref_protected(nl_table[sk->sk_protocol].listeners);
1173                         RCU_INIT_POINTER(nl_table[sk->sk_protocol].listeners, NULL);
1174                         kfree_rcu(old, rcu);
1175                         nl_table[sk->sk_protocol].module = NULL;
1176                         nl_table[sk->sk_protocol].bind = NULL;
1177                         nl_table[sk->sk_protocol].flags = 0;
1178                         nl_table[sk->sk_protocol].registered = 0;
1179                 }
1180         } else if (nlk->subscriptions) {
1181                 netlink_update_listeners(sk);
1182         }
1183         netlink_table_ungrab();
1184
1185         kfree(nlk->groups);
1186         nlk->groups = NULL;
1187
1188         local_bh_disable();
1189         sock_prot_inuse_add(sock_net(sk), &netlink_proto, -1);
1190         local_bh_enable();
1191         sock_put(sk);
1192         return 0;
1193 }
1194
1195 static int netlink_autobind(struct socket *sock)
1196 {
1197         struct sock *sk = sock->sk;
1198         struct net *net = sock_net(sk);
1199         struct netlink_table *table = &nl_table[sk->sk_protocol];
1200         struct nl_portid_hash *hash = &table->hash;
1201         struct hlist_head *head;
1202         struct sock *osk;
1203         s32 portid = task_tgid_vnr(current);
1204         int err;
1205         static s32 rover = -4097;
1206
1207 retry:
1208         cond_resched();
1209         netlink_table_grab();
1210         head = nl_portid_hashfn(hash, portid);
1211         sk_for_each(osk, head) {
1212                 if (!table->compare(net, osk))
1213                         continue;
1214                 if (nlk_sk(osk)->portid == portid) {
1215                         /* Bind collision, search negative portid values. */
1216                         portid = rover--;
1217                         if (rover > -4097)
1218                                 rover = -4097;
1219                         netlink_table_ungrab();
1220                         goto retry;
1221                 }
1222         }
1223         netlink_table_ungrab();
1224
1225         err = netlink_insert(sk, net, portid);
1226         if (err == -EADDRINUSE)
1227                 goto retry;
1228
1229         /* If 2 threads race to autobind, that is fine.  */
1230         if (err == -EBUSY)
1231                 err = 0;
1232
1233         return err;
1234 }
1235
1236 static inline int netlink_capable(const struct socket *sock, unsigned int flag)
1237 {
1238         return (nl_table[sock->sk->sk_protocol].flags & flag) ||
1239                 ns_capable(sock_net(sock->sk)->user_ns, CAP_NET_ADMIN);
1240 }
1241
1242 static void
1243 netlink_update_subscriptions(struct sock *sk, unsigned int subscriptions)
1244 {
1245         struct netlink_sock *nlk = nlk_sk(sk);
1246
1247         if (nlk->subscriptions && !subscriptions)
1248                 __sk_del_bind_node(sk);
1249         else if (!nlk->subscriptions && subscriptions)
1250                 sk_add_bind_node(sk, &nl_table[sk->sk_protocol].mc_list);
1251         nlk->subscriptions = subscriptions;
1252 }
1253
1254 static int netlink_realloc_groups(struct sock *sk)
1255 {
1256         struct netlink_sock *nlk = nlk_sk(sk);
1257         unsigned int groups;
1258         unsigned long *new_groups;
1259         int err = 0;
1260
1261         netlink_table_grab();
1262
1263         groups = nl_table[sk->sk_protocol].groups;
1264         if (!nl_table[sk->sk_protocol].registered) {
1265                 err = -ENOENT;
1266                 goto out_unlock;
1267         }
1268
1269         if (nlk->ngroups >= groups)
1270                 goto out_unlock;
1271
1272         new_groups = krealloc(nlk->groups, NLGRPSZ(groups), GFP_ATOMIC);
1273         if (new_groups == NULL) {
1274                 err = -ENOMEM;
1275                 goto out_unlock;
1276         }
1277         memset((char *)new_groups + NLGRPSZ(nlk->ngroups), 0,
1278                NLGRPSZ(groups) - NLGRPSZ(nlk->ngroups));
1279
1280         nlk->groups = new_groups;
1281         nlk->ngroups = groups;
1282  out_unlock:
1283         netlink_table_ungrab();
1284         return err;
1285 }
1286
1287 static int netlink_bind(struct socket *sock, struct sockaddr *addr,
1288                         int addr_len)
1289 {
1290         struct sock *sk = sock->sk;
1291         struct net *net = sock_net(sk);
1292         struct netlink_sock *nlk = nlk_sk(sk);
1293         struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
1294         int err;
1295
1296         if (addr_len < sizeof(struct sockaddr_nl))
1297                 return -EINVAL;
1298
1299         if (nladdr->nl_family != AF_NETLINK)
1300                 return -EINVAL;
1301
1302         /* Only superuser is allowed to listen multicasts */
1303         if (nladdr->nl_groups) {
1304                 if (!netlink_capable(sock, NL_CFG_F_NONROOT_RECV))
1305                         return -EPERM;
1306                 err = netlink_realloc_groups(sk);
1307                 if (err)
1308                         return err;
1309         }
1310
1311         if (nlk->portid) {
1312                 if (nladdr->nl_pid != nlk->portid)
1313                         return -EINVAL;
1314         } else {
1315                 err = nladdr->nl_pid ?
1316                         netlink_insert(sk, net, nladdr->nl_pid) :
1317                         netlink_autobind(sock);
1318                 if (err)
1319                         return err;
1320         }
1321
1322         if (!nladdr->nl_groups && (nlk->groups == NULL || !(u32)nlk->groups[0]))
1323                 return 0;
1324
1325         netlink_table_grab();
1326         netlink_update_subscriptions(sk, nlk->subscriptions +
1327                                          hweight32(nladdr->nl_groups) -
1328                                          hweight32(nlk->groups[0]));
1329         nlk->groups[0] = (nlk->groups[0] & ~0xffffffffUL) | nladdr->nl_groups;
1330         netlink_update_listeners(sk);
1331         netlink_table_ungrab();
1332
1333         if (nlk->netlink_bind && nlk->groups[0]) {
1334                 int i;
1335
1336                 for (i=0; i<nlk->ngroups; i++) {
1337                         if (test_bit(i, nlk->groups))
1338                                 nlk->netlink_bind(i);
1339                 }
1340         }
1341
1342         return 0;
1343 }
1344
1345 static int netlink_connect(struct socket *sock, struct sockaddr *addr,
1346                            int alen, int flags)
1347 {
1348         int err = 0;
1349         struct sock *sk = sock->sk;
1350         struct netlink_sock *nlk = nlk_sk(sk);
1351         struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
1352
1353         if (alen < sizeof(addr->sa_family))
1354                 return -EINVAL;
1355
1356         if (addr->sa_family == AF_UNSPEC) {
1357                 sk->sk_state    = NETLINK_UNCONNECTED;
1358                 nlk->dst_portid = 0;
1359                 nlk->dst_group  = 0;
1360                 return 0;
1361         }
1362         if (addr->sa_family != AF_NETLINK)
1363                 return -EINVAL;
1364
1365         /* Only superuser is allowed to send multicasts */
1366         if (nladdr->nl_groups && !netlink_capable(sock, NL_CFG_F_NONROOT_SEND))
1367                 return -EPERM;
1368
1369         if (!nlk->portid)
1370                 err = netlink_autobind(sock);
1371
1372         if (err == 0) {
1373                 sk->sk_state    = NETLINK_CONNECTED;
1374                 nlk->dst_portid = nladdr->nl_pid;
1375                 nlk->dst_group  = ffs(nladdr->nl_groups);
1376         }
1377
1378         return err;
1379 }
1380
1381 static int netlink_getname(struct socket *sock, struct sockaddr *addr,
1382                            int *addr_len, int peer)
1383 {
1384         struct sock *sk = sock->sk;
1385         struct netlink_sock *nlk = nlk_sk(sk);
1386         DECLARE_SOCKADDR(struct sockaddr_nl *, nladdr, addr);
1387
1388         nladdr->nl_family = AF_NETLINK;
1389         nladdr->nl_pad = 0;
1390         *addr_len = sizeof(*nladdr);
1391
1392         if (peer) {
1393                 nladdr->nl_pid = nlk->dst_portid;
1394                 nladdr->nl_groups = netlink_group_mask(nlk->dst_group);
1395         } else {
1396                 nladdr->nl_pid = nlk->portid;
1397                 nladdr->nl_groups = nlk->groups ? nlk->groups[0] : 0;
1398         }
1399         return 0;
1400 }
1401
1402 static struct sock *netlink_getsockbyportid(struct sock *ssk, u32 portid)
1403 {
1404         struct sock *sock;
1405         struct netlink_sock *nlk;
1406
1407         sock = netlink_lookup(sock_net(ssk), ssk->sk_protocol, portid);
1408         if (!sock)
1409                 return ERR_PTR(-ECONNREFUSED);
1410
1411         /* Don't bother queuing skb if kernel socket has no input function */
1412         nlk = nlk_sk(sock);
1413         if (sock->sk_state == NETLINK_CONNECTED &&
1414             nlk->dst_portid != nlk_sk(ssk)->portid) {
1415                 sock_put(sock);
1416                 return ERR_PTR(-ECONNREFUSED);
1417         }
1418         return sock;
1419 }
1420
1421 struct sock *netlink_getsockbyfilp(struct file *filp)
1422 {
1423         struct inode *inode = file_inode(filp);
1424         struct sock *sock;
1425
1426         if (!S_ISSOCK(inode->i_mode))
1427                 return ERR_PTR(-ENOTSOCK);
1428
1429         sock = SOCKET_I(inode)->sk;
1430         if (sock->sk_family != AF_NETLINK)
1431                 return ERR_PTR(-EINVAL);
1432
1433         sock_hold(sock);
1434         return sock;
1435 }
1436
1437 static struct sk_buff *netlink_alloc_large_skb(unsigned int size)
1438 {
1439         struct sk_buff *skb;
1440         void *data;
1441
1442         if (size <= NLMSG_GOODSIZE)
1443                 return alloc_skb(size, GFP_KERNEL);
1444
1445         skb = alloc_skb_head(GFP_KERNEL);
1446         if (skb == NULL)
1447                 return NULL;
1448
1449         data = vmalloc(size);
1450         if (data == NULL)
1451                 goto err;
1452
1453         skb->head       = data;
1454         skb->data       = data;
1455         skb_reset_tail_pointer(skb);
1456         skb->end        = skb->tail + size;
1457         skb->len        = 0;
1458         skb->destructor = netlink_skb_destructor;
1459
1460         return skb;
1461 err:
1462         kfree_skb(skb);
1463         return NULL;
1464 }
1465
1466 /*
1467  * Attach a skb to a netlink socket.
1468  * The caller must hold a reference to the destination socket. On error, the
1469  * reference is dropped. The skb is not send to the destination, just all
1470  * all error checks are performed and memory in the queue is reserved.
1471  * Return values:
1472  * < 0: error. skb freed, reference to sock dropped.
1473  * 0: continue
1474  * 1: repeat lookup - reference dropped while waiting for socket memory.
1475  */
1476 int netlink_attachskb(struct sock *sk, struct sk_buff *skb,
1477                       long *timeo, struct sock *ssk)
1478 {
1479         struct netlink_sock *nlk;
1480
1481         nlk = nlk_sk(sk);
1482
1483         if ((atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
1484              test_bit(NETLINK_CONGESTED, &nlk->state)) &&
1485             !netlink_skb_is_mmaped(skb)) {
1486                 DECLARE_WAITQUEUE(wait, current);
1487                 if (!*timeo) {
1488                         if (!ssk || netlink_is_kernel(ssk))
1489                                 netlink_overrun(sk);
1490                         sock_put(sk);
1491                         kfree_skb(skb);
1492                         return -EAGAIN;
1493                 }
1494
1495                 __set_current_state(TASK_INTERRUPTIBLE);
1496                 add_wait_queue(&nlk->wait, &wait);
1497
1498                 if ((atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
1499                      test_bit(NETLINK_CONGESTED, &nlk->state)) &&
1500                     !sock_flag(sk, SOCK_DEAD))
1501                         *timeo = schedule_timeout(*timeo);
1502
1503                 __set_current_state(TASK_RUNNING);
1504                 remove_wait_queue(&nlk->wait, &wait);
1505                 sock_put(sk);
1506
1507                 if (signal_pending(current)) {
1508                         kfree_skb(skb);
1509                         return sock_intr_errno(*timeo);
1510                 }
1511                 return 1;
1512         }
1513         netlink_skb_set_owner_r(skb, sk);
1514         return 0;
1515 }
1516
1517 static int __netlink_sendskb(struct sock *sk, struct sk_buff *skb)
1518 {
1519         int len = skb->len;
1520
1521 #ifdef CONFIG_NETLINK_MMAP
1522         if (netlink_skb_is_mmaped(skb))
1523                 netlink_queue_mmaped_skb(sk, skb);
1524         else if (netlink_rx_is_mmaped(sk))
1525                 netlink_ring_set_copied(sk, skb);
1526         else
1527 #endif /* CONFIG_NETLINK_MMAP */
1528                 skb_queue_tail(&sk->sk_receive_queue, skb);
1529         sk->sk_data_ready(sk, len);
1530         return len;
1531 }
1532
1533 int netlink_sendskb(struct sock *sk, struct sk_buff *skb)
1534 {
1535         int len = __netlink_sendskb(sk, skb);
1536
1537         sock_put(sk);
1538         return len;
1539 }
1540
1541 void netlink_detachskb(struct sock *sk, struct sk_buff *skb)
1542 {
1543         kfree_skb(skb);
1544         sock_put(sk);
1545 }
1546
1547 static struct sk_buff *netlink_trim(struct sk_buff *skb, gfp_t allocation)
1548 {
1549         int delta;
1550
1551         WARN_ON(skb->sk != NULL);
1552         if (netlink_skb_is_mmaped(skb))
1553                 return skb;
1554
1555         delta = skb->end - skb->tail;
1556         if (is_vmalloc_addr(skb->head) || delta * 2 < skb->truesize)
1557                 return skb;
1558
1559         if (skb_shared(skb)) {
1560                 struct sk_buff *nskb = skb_clone(skb, allocation);
1561                 if (!nskb)
1562                         return skb;
1563                 consume_skb(skb);
1564                 skb = nskb;
1565         }
1566
1567         if (!pskb_expand_head(skb, 0, -delta, allocation))
1568                 skb->truesize -= delta;
1569
1570         return skb;
1571 }
1572
1573 static int netlink_unicast_kernel(struct sock *sk, struct sk_buff *skb,
1574                                   struct sock *ssk)
1575 {
1576         int ret;
1577         struct netlink_sock *nlk = nlk_sk(sk);
1578
1579         ret = -ECONNREFUSED;
1580         if (nlk->netlink_rcv != NULL) {
1581                 ret = skb->len;
1582                 netlink_skb_set_owner_r(skb, sk);
1583                 NETLINK_CB(skb).sk = ssk;
1584                 nlk->netlink_rcv(skb);
1585                 consume_skb(skb);
1586         } else {
1587                 kfree_skb(skb);
1588         }
1589         sock_put(sk);
1590         return ret;
1591 }
1592
1593 int netlink_unicast(struct sock *ssk, struct sk_buff *skb,
1594                     u32 portid, int nonblock)
1595 {
1596         struct sock *sk;
1597         int err;
1598         long timeo;
1599
1600         skb = netlink_trim(skb, gfp_any());
1601
1602         timeo = sock_sndtimeo(ssk, nonblock);
1603 retry:
1604         sk = netlink_getsockbyportid(ssk, portid);
1605         if (IS_ERR(sk)) {
1606                 kfree_skb(skb);
1607                 return PTR_ERR(sk);
1608         }
1609         if (netlink_is_kernel(sk))
1610                 return netlink_unicast_kernel(sk, skb, ssk);
1611
1612         if (sk_filter(sk, skb)) {
1613                 err = skb->len;
1614                 kfree_skb(skb);
1615                 sock_put(sk);
1616                 return err;
1617         }
1618
1619         err = netlink_attachskb(sk, skb, &timeo, ssk);
1620         if (err == 1)
1621                 goto retry;
1622         if (err)
1623                 return err;
1624
1625         return netlink_sendskb(sk, skb);
1626 }
1627 EXPORT_SYMBOL(netlink_unicast);
1628
1629 struct sk_buff *netlink_alloc_skb(struct sock *ssk, unsigned int size,
1630                                   u32 dst_portid, gfp_t gfp_mask)
1631 {
1632 #ifdef CONFIG_NETLINK_MMAP
1633         struct sock *sk = NULL;
1634         struct sk_buff *skb;
1635         struct netlink_ring *ring;
1636         struct nl_mmap_hdr *hdr;
1637         unsigned int maxlen;
1638
1639         sk = netlink_getsockbyportid(ssk, dst_portid);
1640         if (IS_ERR(sk))
1641                 goto out;
1642
1643         ring = &nlk_sk(sk)->rx_ring;
1644         /* fast-path without atomic ops for common case: non-mmaped receiver */
1645         if (ring->pg_vec == NULL)
1646                 goto out_put;
1647
1648         skb = alloc_skb_head(gfp_mask);
1649         if (skb == NULL)
1650                 goto err1;
1651
1652         spin_lock_bh(&sk->sk_receive_queue.lock);
1653         /* check again under lock */
1654         if (ring->pg_vec == NULL)
1655                 goto out_free;
1656
1657         maxlen = ring->frame_size - NL_MMAP_HDRLEN;
1658         if (maxlen < size)
1659                 goto out_free;
1660
1661         netlink_forward_ring(ring);
1662         hdr = netlink_current_frame(ring, NL_MMAP_STATUS_UNUSED);
1663         if (hdr == NULL)
1664                 goto err2;
1665         netlink_ring_setup_skb(skb, sk, ring, hdr);
1666         netlink_set_status(hdr, NL_MMAP_STATUS_RESERVED);
1667         atomic_inc(&ring->pending);
1668         netlink_increment_head(ring);
1669
1670         spin_unlock_bh(&sk->sk_receive_queue.lock);
1671         return skb;
1672
1673 err2:
1674         kfree_skb(skb);
1675         spin_unlock_bh(&sk->sk_receive_queue.lock);
1676         netlink_overrun(sk);
1677 err1:
1678         sock_put(sk);
1679         return NULL;
1680
1681 out_free:
1682         kfree_skb(skb);
1683         spin_unlock_bh(&sk->sk_receive_queue.lock);
1684 out_put:
1685         sock_put(sk);
1686 out:
1687 #endif
1688         return alloc_skb(size, gfp_mask);
1689 }
1690 EXPORT_SYMBOL_GPL(netlink_alloc_skb);
1691
1692 int netlink_has_listeners(struct sock *sk, unsigned int group)
1693 {
1694         int res = 0;
1695         struct listeners *listeners;
1696
1697         BUG_ON(!netlink_is_kernel(sk));
1698
1699         rcu_read_lock();
1700         listeners = rcu_dereference(nl_table[sk->sk_protocol].listeners);
1701
1702         if (listeners && group - 1 < nl_table[sk->sk_protocol].groups)
1703                 res = test_bit(group - 1, listeners->masks);
1704
1705         rcu_read_unlock();
1706
1707         return res;
1708 }
1709 EXPORT_SYMBOL_GPL(netlink_has_listeners);
1710
1711 static int netlink_broadcast_deliver(struct sock *sk, struct sk_buff *skb)
1712 {
1713         struct netlink_sock *nlk = nlk_sk(sk);
1714
1715         if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf &&
1716             !test_bit(NETLINK_CONGESTED, &nlk->state)) {
1717                 netlink_skb_set_owner_r(skb, sk);
1718                 __netlink_sendskb(sk, skb);
1719                 return atomic_read(&sk->sk_rmem_alloc) > (sk->sk_rcvbuf >> 1);
1720         }
1721         return -1;
1722 }
1723
1724 struct netlink_broadcast_data {
1725         struct sock *exclude_sk;
1726         struct net *net;
1727         u32 portid;
1728         u32 group;
1729         int failure;
1730         int delivery_failure;
1731         int congested;
1732         int delivered;
1733         gfp_t allocation;
1734         struct sk_buff *skb, *skb2;
1735         int (*tx_filter)(struct sock *dsk, struct sk_buff *skb, void *data);
1736         void *tx_data;
1737 };
1738
1739 static int do_one_broadcast(struct sock *sk,
1740                                    struct netlink_broadcast_data *p)
1741 {
1742         struct netlink_sock *nlk = nlk_sk(sk);
1743         int val;
1744
1745         if (p->exclude_sk == sk)
1746                 goto out;
1747
1748         if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
1749             !test_bit(p->group - 1, nlk->groups))
1750                 goto out;
1751
1752         if (!net_eq(sock_net(sk), p->net))
1753                 goto out;
1754
1755         if (p->failure) {
1756                 netlink_overrun(sk);
1757                 goto out;
1758         }
1759
1760         sock_hold(sk);
1761         if (p->skb2 == NULL) {
1762                 if (skb_shared(p->skb)) {
1763                         p->skb2 = skb_clone(p->skb, p->allocation);
1764                 } else {
1765                         p->skb2 = skb_get(p->skb);
1766                         /*
1767                          * skb ownership may have been set when
1768                          * delivered to a previous socket.
1769                          */
1770                         skb_orphan(p->skb2);
1771                 }
1772         }
1773         if (p->skb2 == NULL) {
1774                 netlink_overrun(sk);
1775                 /* Clone failed. Notify ALL listeners. */
1776                 p->failure = 1;
1777                 if (nlk->flags & NETLINK_BROADCAST_SEND_ERROR)
1778                         p->delivery_failure = 1;
1779         } else if (p->tx_filter && p->tx_filter(sk, p->skb2, p->tx_data)) {
1780                 kfree_skb(p->skb2);
1781                 p->skb2 = NULL;
1782         } else if (sk_filter(sk, p->skb2)) {
1783                 kfree_skb(p->skb2);
1784                 p->skb2 = NULL;
1785         } else if ((val = netlink_broadcast_deliver(sk, p->skb2)) < 0) {
1786                 netlink_overrun(sk);
1787                 if (nlk->flags & NETLINK_BROADCAST_SEND_ERROR)
1788                         p->delivery_failure = 1;
1789         } else {
1790                 p->congested |= val;
1791                 p->delivered = 1;
1792                 p->skb2 = NULL;
1793         }
1794         sock_put(sk);
1795
1796 out:
1797         return 0;
1798 }
1799
1800 int netlink_broadcast_filtered(struct sock *ssk, struct sk_buff *skb, u32 portid,
1801         u32 group, gfp_t allocation,
1802         int (*filter)(struct sock *dsk, struct sk_buff *skb, void *data),
1803         void *filter_data)
1804 {
1805         struct net *net = sock_net(ssk);
1806         struct netlink_broadcast_data info;
1807         struct sock *sk;
1808
1809         skb = netlink_trim(skb, allocation);
1810
1811         info.exclude_sk = ssk;
1812         info.net = net;
1813         info.portid = portid;
1814         info.group = group;
1815         info.failure = 0;
1816         info.delivery_failure = 0;
1817         info.congested = 0;
1818         info.delivered = 0;
1819         info.allocation = allocation;
1820         info.skb = skb;
1821         info.skb2 = NULL;
1822         info.tx_filter = filter;
1823         info.tx_data = filter_data;
1824
1825         /* While we sleep in clone, do not allow to change socket list */
1826
1827         netlink_lock_table();
1828
1829         sk_for_each_bound(sk, &nl_table[ssk->sk_protocol].mc_list)
1830                 do_one_broadcast(sk, &info);
1831
1832         consume_skb(skb);
1833
1834         netlink_unlock_table();
1835
1836         if (info.delivery_failure) {
1837                 kfree_skb(info.skb2);
1838                 return -ENOBUFS;
1839         }
1840         consume_skb(info.skb2);
1841
1842         if (info.delivered) {
1843                 if (info.congested && (allocation & __GFP_WAIT))
1844                         yield();
1845                 return 0;
1846         }
1847         return -ESRCH;
1848 }
1849 EXPORT_SYMBOL(netlink_broadcast_filtered);
1850
1851 int netlink_broadcast(struct sock *ssk, struct sk_buff *skb, u32 portid,
1852                       u32 group, gfp_t allocation)
1853 {
1854         return netlink_broadcast_filtered(ssk, skb, portid, group, allocation,
1855                 NULL, NULL);
1856 }
1857 EXPORT_SYMBOL(netlink_broadcast);
1858
1859 struct netlink_set_err_data {
1860         struct sock *exclude_sk;
1861         u32 portid;
1862         u32 group;
1863         int code;
1864 };
1865
1866 static int do_one_set_err(struct sock *sk, struct netlink_set_err_data *p)
1867 {
1868         struct netlink_sock *nlk = nlk_sk(sk);
1869         int ret = 0;
1870
1871         if (sk == p->exclude_sk)
1872                 goto out;
1873
1874         if (!net_eq(sock_net(sk), sock_net(p->exclude_sk)))
1875                 goto out;
1876
1877         if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
1878             !test_bit(p->group - 1, nlk->groups))
1879                 goto out;
1880
1881         if (p->code == ENOBUFS && nlk->flags & NETLINK_RECV_NO_ENOBUFS) {
1882                 ret = 1;
1883                 goto out;
1884         }
1885
1886         sk->sk_err = p->code;
1887         sk->sk_error_report(sk);
1888 out:
1889         return ret;
1890 }
1891
1892 /**
1893  * netlink_set_err - report error to broadcast listeners
1894  * @ssk: the kernel netlink socket, as returned by netlink_kernel_create()
1895  * @portid: the PORTID of a process that we want to skip (if any)
1896  * @groups: the broadcast group that will notice the error
1897  * @code: error code, must be negative (as usual in kernelspace)
1898  *
1899  * This function returns the number of broadcast listeners that have set the
1900  * NETLINK_RECV_NO_ENOBUFS socket option.
1901  */
1902 int netlink_set_err(struct sock *ssk, u32 portid, u32 group, int code)
1903 {
1904         struct netlink_set_err_data info;
1905         struct sock *sk;
1906         int ret = 0;
1907
1908         info.exclude_sk = ssk;
1909         info.portid = portid;
1910         info.group = group;
1911         /* sk->sk_err wants a positive error value */
1912         info.code = -code;
1913
1914         read_lock(&nl_table_lock);
1915
1916         sk_for_each_bound(sk, &nl_table[ssk->sk_protocol].mc_list)
1917                 ret += do_one_set_err(sk, &info);
1918
1919         read_unlock(&nl_table_lock);
1920         return ret;
1921 }
1922 EXPORT_SYMBOL(netlink_set_err);
1923
1924 /* must be called with netlink table grabbed */
1925 static void netlink_update_socket_mc(struct netlink_sock *nlk,
1926                                      unsigned int group,
1927                                      int is_new)
1928 {
1929         int old, new = !!is_new, subscriptions;
1930
1931         old = test_bit(group - 1, nlk->groups);
1932         subscriptions = nlk->subscriptions - old + new;
1933         if (new)
1934                 __set_bit(group - 1, nlk->groups);
1935         else
1936                 __clear_bit(group - 1, nlk->groups);
1937         netlink_update_subscriptions(&nlk->sk, subscriptions);
1938         netlink_update_listeners(&nlk->sk);
1939 }
1940
1941 static int netlink_setsockopt(struct socket *sock, int level, int optname,
1942                               char __user *optval, unsigned int optlen)
1943 {
1944         struct sock *sk = sock->sk;
1945         struct netlink_sock *nlk = nlk_sk(sk);
1946         unsigned int val = 0;
1947         int err;
1948
1949         if (level != SOL_NETLINK)
1950                 return -ENOPROTOOPT;
1951
1952         if (optname != NETLINK_RX_RING && optname != NETLINK_TX_RING &&
1953             optlen >= sizeof(int) &&
1954             get_user(val, (unsigned int __user *)optval))
1955                 return -EFAULT;
1956
1957         switch (optname) {
1958         case NETLINK_PKTINFO:
1959                 if (val)
1960                         nlk->flags |= NETLINK_RECV_PKTINFO;
1961                 else
1962                         nlk->flags &= ~NETLINK_RECV_PKTINFO;
1963                 err = 0;
1964                 break;
1965         case NETLINK_ADD_MEMBERSHIP:
1966         case NETLINK_DROP_MEMBERSHIP: {
1967                 if (!netlink_capable(sock, NL_CFG_F_NONROOT_RECV))
1968                         return -EPERM;
1969                 err = netlink_realloc_groups(sk);
1970                 if (err)
1971                         return err;
1972                 if (!val || val - 1 >= nlk->ngroups)
1973                         return -EINVAL;
1974                 netlink_table_grab();
1975                 netlink_update_socket_mc(nlk, val,
1976                                          optname == NETLINK_ADD_MEMBERSHIP);
1977                 netlink_table_ungrab();
1978
1979                 if (nlk->netlink_bind)
1980                         nlk->netlink_bind(val);
1981
1982                 err = 0;
1983                 break;
1984         }
1985         case NETLINK_BROADCAST_ERROR:
1986                 if (val)
1987                         nlk->flags |= NETLINK_BROADCAST_SEND_ERROR;
1988                 else
1989                         nlk->flags &= ~NETLINK_BROADCAST_SEND_ERROR;
1990                 err = 0;
1991                 break;
1992         case NETLINK_NO_ENOBUFS:
1993                 if (val) {
1994                         nlk->flags |= NETLINK_RECV_NO_ENOBUFS;
1995                         clear_bit(NETLINK_CONGESTED, &nlk->state);
1996                         wake_up_interruptible(&nlk->wait);
1997                 } else {
1998                         nlk->flags &= ~NETLINK_RECV_NO_ENOBUFS;
1999                 }
2000                 err = 0;
2001                 break;
2002 #ifdef CONFIG_NETLINK_MMAP
2003         case NETLINK_RX_RING:
2004         case NETLINK_TX_RING: {
2005                 struct nl_mmap_req req;
2006
2007                 /* Rings might consume more memory than queue limits, require
2008                  * CAP_NET_ADMIN.
2009                  */
2010                 if (!capable(CAP_NET_ADMIN))
2011                         return -EPERM;
2012                 if (optlen < sizeof(req))
2013                         return -EINVAL;
2014                 if (copy_from_user(&req, optval, sizeof(req)))
2015                         return -EFAULT;
2016                 err = netlink_set_ring(sk, &req, false,
2017                                        optname == NETLINK_TX_RING);
2018                 break;
2019         }
2020 #endif /* CONFIG_NETLINK_MMAP */
2021         default:
2022                 err = -ENOPROTOOPT;
2023         }
2024         return err;
2025 }
2026
2027 static int netlink_getsockopt(struct socket *sock, int level, int optname,
2028                               char __user *optval, int __user *optlen)
2029 {
2030         struct sock *sk = sock->sk;
2031         struct netlink_sock *nlk = nlk_sk(sk);
2032         int len, val, err;
2033
2034         if (level != SOL_NETLINK)
2035                 return -ENOPROTOOPT;
2036
2037         if (get_user(len, optlen))
2038                 return -EFAULT;
2039         if (len < 0)
2040                 return -EINVAL;
2041
2042         switch (optname) {
2043         case NETLINK_PKTINFO:
2044                 if (len < sizeof(int))
2045                         return -EINVAL;
2046                 len = sizeof(int);
2047                 val = nlk->flags & NETLINK_RECV_PKTINFO ? 1 : 0;
2048                 if (put_user(len, optlen) ||
2049                     put_user(val, optval))
2050                         return -EFAULT;
2051                 err = 0;
2052                 break;
2053         case NETLINK_BROADCAST_ERROR:
2054                 if (len < sizeof(int))
2055                         return -EINVAL;
2056                 len = sizeof(int);
2057                 val = nlk->flags & NETLINK_BROADCAST_SEND_ERROR ? 1 : 0;
2058                 if (put_user(len, optlen) ||
2059                     put_user(val, optval))
2060                         return -EFAULT;
2061                 err = 0;
2062                 break;
2063         case NETLINK_NO_ENOBUFS:
2064                 if (len < sizeof(int))
2065                         return -EINVAL;
2066                 len = sizeof(int);
2067                 val = nlk->flags & NETLINK_RECV_NO_ENOBUFS ? 1 : 0;
2068                 if (put_user(len, optlen) ||
2069                     put_user(val, optval))
2070                         return -EFAULT;
2071                 err = 0;
2072                 break;
2073         default:
2074                 err = -ENOPROTOOPT;
2075         }
2076         return err;
2077 }
2078
2079 static void netlink_cmsg_recv_pktinfo(struct msghdr *msg, struct sk_buff *skb)
2080 {
2081         struct nl_pktinfo info;
2082
2083         info.group = NETLINK_CB(skb).dst_group;
2084         put_cmsg(msg, SOL_NETLINK, NETLINK_PKTINFO, sizeof(info), &info);
2085 }
2086
2087 static int netlink_sendmsg(struct kiocb *kiocb, struct socket *sock,
2088                            struct msghdr *msg, size_t len)
2089 {
2090         struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
2091         struct sock *sk = sock->sk;
2092         struct netlink_sock *nlk = nlk_sk(sk);
2093         struct sockaddr_nl *addr = msg->msg_name;
2094         u32 dst_portid;
2095         u32 dst_group;
2096         struct sk_buff *skb;
2097         int err;
2098         struct scm_cookie scm;
2099
2100         if (msg->msg_flags&MSG_OOB)
2101                 return -EOPNOTSUPP;
2102
2103         if (NULL == siocb->scm)
2104                 siocb->scm = &scm;
2105
2106         err = scm_send(sock, msg, siocb->scm, true);
2107         if (err < 0)
2108                 return err;
2109
2110         if (msg->msg_namelen) {
2111                 err = -EINVAL;
2112                 if (addr->nl_family != AF_NETLINK)
2113                         goto out;
2114                 dst_portid = addr->nl_pid;
2115                 dst_group = ffs(addr->nl_groups);
2116                 err =  -EPERM;
2117                 if ((dst_group || dst_portid) &&
2118                     !netlink_capable(sock, NL_CFG_F_NONROOT_SEND))
2119                         goto out;
2120         } else {
2121                 dst_portid = nlk->dst_portid;
2122                 dst_group = nlk->dst_group;
2123         }
2124
2125         if (!nlk->portid) {
2126                 err = netlink_autobind(sock);
2127                 if (err)
2128                         goto out;
2129         }
2130
2131         if (netlink_tx_is_mmaped(sk) &&
2132             msg->msg_iov->iov_base == NULL) {
2133                 err = netlink_mmap_sendmsg(sk, msg, dst_portid, dst_group,
2134                                            siocb);
2135                 goto out;
2136         }
2137
2138         err = -EMSGSIZE;
2139         if (len > sk->sk_sndbuf - 32)
2140                 goto out;
2141         err = -ENOBUFS;
2142         skb = netlink_alloc_large_skb(len);
2143         if (skb == NULL)
2144                 goto out;
2145
2146         NETLINK_CB(skb).portid  = nlk->portid;
2147         NETLINK_CB(skb).dst_group = dst_group;
2148         NETLINK_CB(skb).creds   = siocb->scm->creds;
2149
2150         err = -EFAULT;
2151         if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) {
2152                 kfree_skb(skb);
2153                 goto out;
2154         }
2155
2156         err = security_netlink_send(sk, skb);
2157         if (err) {
2158                 kfree_skb(skb);
2159                 goto out;
2160         }
2161
2162         if (dst_group) {
2163                 atomic_inc(&skb->users);
2164                 netlink_broadcast(sk, skb, dst_portid, dst_group, GFP_KERNEL);
2165         }
2166         err = netlink_unicast(sk, skb, dst_portid, msg->msg_flags&MSG_DONTWAIT);
2167
2168 out:
2169         scm_destroy(siocb->scm);
2170         return err;
2171 }
2172
2173 static int netlink_recvmsg(struct kiocb *kiocb, struct socket *sock,
2174                            struct msghdr *msg, size_t len,
2175                            int flags)
2176 {
2177         struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
2178         struct scm_cookie scm;
2179         struct sock *sk = sock->sk;
2180         struct netlink_sock *nlk = nlk_sk(sk);
2181         int noblock = flags&MSG_DONTWAIT;
2182         size_t copied;
2183         struct sk_buff *skb, *data_skb;
2184         int err, ret;
2185
2186         if (flags&MSG_OOB)
2187                 return -EOPNOTSUPP;
2188
2189         copied = 0;
2190
2191         skb = skb_recv_datagram(sk, flags, noblock, &err);
2192         if (skb == NULL)
2193                 goto out;
2194
2195         data_skb = skb;
2196
2197 #ifdef CONFIG_COMPAT_NETLINK_MESSAGES
2198         if (unlikely(skb_shinfo(skb)->frag_list)) {
2199                 /*
2200                  * If this skb has a frag_list, then here that means that we
2201                  * will have to use the frag_list skb's data for compat tasks
2202                  * and the regular skb's data for normal (non-compat) tasks.
2203                  *
2204                  * If we need to send the compat skb, assign it to the
2205                  * 'data_skb' variable so that it will be used below for data
2206                  * copying. We keep 'skb' for everything else, including
2207                  * freeing both later.
2208                  */
2209                 if (flags & MSG_CMSG_COMPAT)
2210                         data_skb = skb_shinfo(skb)->frag_list;
2211         }
2212 #endif
2213
2214         msg->msg_namelen = 0;
2215
2216         copied = data_skb->len;
2217         if (len < copied) {
2218                 msg->msg_flags |= MSG_TRUNC;
2219                 copied = len;
2220         }
2221
2222         skb_reset_transport_header(data_skb);
2223         err = skb_copy_datagram_iovec(data_skb, 0, msg->msg_iov, copied);
2224
2225         if (msg->msg_name) {
2226                 struct sockaddr_nl *addr = (struct sockaddr_nl *)msg->msg_name;
2227                 addr->nl_family = AF_NETLINK;
2228                 addr->nl_pad    = 0;
2229                 addr->nl_pid    = NETLINK_CB(skb).portid;
2230                 addr->nl_groups = netlink_group_mask(NETLINK_CB(skb).dst_group);
2231                 msg->msg_namelen = sizeof(*addr);
2232         }
2233
2234         if (nlk->flags & NETLINK_RECV_PKTINFO)
2235                 netlink_cmsg_recv_pktinfo(msg, skb);
2236
2237         if (NULL == siocb->scm) {
2238                 memset(&scm, 0, sizeof(scm));
2239                 siocb->scm = &scm;
2240         }
2241         siocb->scm->creds = *NETLINK_CREDS(skb);
2242         if (flags & MSG_TRUNC)
2243                 copied = data_skb->len;
2244
2245         skb_free_datagram(sk, skb);
2246
2247         if (nlk->cb && atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf / 2) {
2248                 ret = netlink_dump(sk);
2249                 if (ret) {
2250                         sk->sk_err = ret;
2251                         sk->sk_error_report(sk);
2252                 }
2253         }
2254
2255         scm_recv(sock, msg, siocb->scm, flags);
2256 out:
2257         netlink_rcv_wake(sk);
2258         return err ? : copied;
2259 }
2260
2261 static void netlink_data_ready(struct sock *sk, int len)
2262 {
2263         BUG();
2264 }
2265
2266 /*
2267  *      We export these functions to other modules. They provide a
2268  *      complete set of kernel non-blocking support for message
2269  *      queueing.
2270  */
2271
2272 struct sock *
2273 __netlink_kernel_create(struct net *net, int unit, struct module *module,
2274                         struct netlink_kernel_cfg *cfg)
2275 {
2276         struct socket *sock;
2277         struct sock *sk;
2278         struct netlink_sock *nlk;
2279         struct listeners *listeners = NULL;
2280         struct mutex *cb_mutex = cfg ? cfg->cb_mutex : NULL;
2281         unsigned int groups;
2282
2283         BUG_ON(!nl_table);
2284
2285         if (unit < 0 || unit >= MAX_LINKS)
2286                 return NULL;
2287
2288         if (sock_create_lite(PF_NETLINK, SOCK_DGRAM, unit, &sock))
2289                 return NULL;
2290
2291         /*
2292          * We have to just have a reference on the net from sk, but don't
2293          * get_net it. Besides, we cannot get and then put the net here.
2294          * So we create one inside init_net and the move it to net.
2295          */
2296
2297         if (__netlink_create(&init_net, sock, cb_mutex, unit) < 0)
2298                 goto out_sock_release_nosk;
2299
2300         sk = sock->sk;
2301         sk_change_net(sk, net);
2302
2303         if (!cfg || cfg->groups < 32)
2304                 groups = 32;
2305         else
2306                 groups = cfg->groups;
2307
2308         listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
2309         if (!listeners)
2310                 goto out_sock_release;
2311
2312         sk->sk_data_ready = netlink_data_ready;
2313         if (cfg && cfg->input)
2314                 nlk_sk(sk)->netlink_rcv = cfg->input;
2315
2316         if (netlink_insert(sk, net, 0))
2317                 goto out_sock_release;
2318
2319         nlk = nlk_sk(sk);
2320         nlk->flags |= NETLINK_KERNEL_SOCKET;
2321
2322         netlink_table_grab();
2323         if (!nl_table[unit].registered) {
2324                 nl_table[unit].groups = groups;
2325                 rcu_assign_pointer(nl_table[unit].listeners, listeners);
2326                 nl_table[unit].cb_mutex = cb_mutex;
2327                 nl_table[unit].module = module;
2328                 if (cfg) {
2329                         nl_table[unit].bind = cfg->bind;
2330                         nl_table[unit].flags = cfg->flags;
2331                         if (cfg->compare)
2332                                 nl_table[unit].compare = cfg->compare;
2333                 }
2334                 nl_table[unit].registered = 1;
2335         } else {
2336                 kfree(listeners);
2337                 nl_table[unit].registered++;
2338         }
2339         netlink_table_ungrab();
2340         return sk;
2341
2342 out_sock_release:
2343         kfree(listeners);
2344         netlink_kernel_release(sk);
2345         return NULL;
2346
2347 out_sock_release_nosk:
2348         sock_release(sock);
2349         return NULL;
2350 }
2351 EXPORT_SYMBOL(__netlink_kernel_create);
2352
2353 void
2354 netlink_kernel_release(struct sock *sk)
2355 {
2356         sk_release_kernel(sk);
2357 }
2358 EXPORT_SYMBOL(netlink_kernel_release);
2359
2360 int __netlink_change_ngroups(struct sock *sk, unsigned int groups)
2361 {
2362         struct listeners *new, *old;
2363         struct netlink_table *tbl = &nl_table[sk->sk_protocol];
2364
2365         if (groups < 32)
2366                 groups = 32;
2367
2368         if (NLGRPSZ(tbl->groups) < NLGRPSZ(groups)) {
2369                 new = kzalloc(sizeof(*new) + NLGRPSZ(groups), GFP_ATOMIC);
2370                 if (!new)
2371                         return -ENOMEM;
2372                 old = nl_deref_protected(tbl->listeners);
2373                 memcpy(new->masks, old->masks, NLGRPSZ(tbl->groups));
2374                 rcu_assign_pointer(tbl->listeners, new);
2375
2376                 kfree_rcu(old, rcu);
2377         }
2378         tbl->groups = groups;
2379
2380         return 0;
2381 }
2382
2383 /**
2384  * netlink_change_ngroups - change number of multicast groups
2385  *
2386  * This changes the number of multicast groups that are available
2387  * on a certain netlink family. Note that it is not possible to
2388  * change the number of groups to below 32. Also note that it does
2389  * not implicitly call netlink_clear_multicast_users() when the
2390  * number of groups is reduced.
2391  *
2392  * @sk: The kernel netlink socket, as returned by netlink_kernel_create().
2393  * @groups: The new number of groups.
2394  */
2395 int netlink_change_ngroups(struct sock *sk, unsigned int groups)
2396 {
2397         int err;
2398
2399         netlink_table_grab();
2400         err = __netlink_change_ngroups(sk, groups);
2401         netlink_table_ungrab();
2402
2403         return err;
2404 }
2405
2406 void __netlink_clear_multicast_users(struct sock *ksk, unsigned int group)
2407 {
2408         struct sock *sk;
2409         struct netlink_table *tbl = &nl_table[ksk->sk_protocol];
2410
2411         sk_for_each_bound(sk, &tbl->mc_list)
2412                 netlink_update_socket_mc(nlk_sk(sk), group, 0);
2413 }
2414
2415 /**
2416  * netlink_clear_multicast_users - kick off multicast listeners
2417  *
2418  * This function removes all listeners from the given group.
2419  * @ksk: The kernel netlink socket, as returned by
2420  *      netlink_kernel_create().
2421  * @group: The multicast group to clear.
2422  */
2423 void netlink_clear_multicast_users(struct sock *ksk, unsigned int group)
2424 {
2425         netlink_table_grab();
2426         __netlink_clear_multicast_users(ksk, group);
2427         netlink_table_ungrab();
2428 }
2429
2430 struct nlmsghdr *
2431 __nlmsg_put(struct sk_buff *skb, u32 portid, u32 seq, int type, int len, int flags)
2432 {
2433         struct nlmsghdr *nlh;
2434         int size = nlmsg_msg_size(len);
2435
2436         nlh = (struct nlmsghdr*)skb_put(skb, NLMSG_ALIGN(size));
2437         nlh->nlmsg_type = type;
2438         nlh->nlmsg_len = size;
2439         nlh->nlmsg_flags = flags;
2440         nlh->nlmsg_pid = portid;
2441         nlh->nlmsg_seq = seq;
2442         if (!__builtin_constant_p(size) || NLMSG_ALIGN(size) - size != 0)
2443                 memset(nlmsg_data(nlh) + len, 0, NLMSG_ALIGN(size) - size);
2444         return nlh;
2445 }
2446 EXPORT_SYMBOL(__nlmsg_put);
2447
2448 /*
2449  * It looks a bit ugly.
2450  * It would be better to create kernel thread.
2451  */
2452
2453 static int netlink_dump(struct sock *sk)
2454 {
2455         struct netlink_sock *nlk = nlk_sk(sk);
2456         struct netlink_callback *cb;
2457         struct sk_buff *skb = NULL;
2458         struct nlmsghdr *nlh;
2459         int len, err = -ENOBUFS;
2460         int alloc_size;
2461
2462         mutex_lock(nlk->cb_mutex);
2463
2464         cb = nlk->cb;
2465         if (cb == NULL) {
2466                 err = -EINVAL;
2467                 goto errout_skb;
2468         }
2469
2470         alloc_size = max_t(int, cb->min_dump_alloc, NLMSG_GOODSIZE);
2471
2472         if (!netlink_rx_is_mmaped(sk) &&
2473             atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
2474                 goto errout_skb;
2475         skb = netlink_alloc_skb(sk, alloc_size, nlk->portid, GFP_KERNEL);
2476         if (!skb)
2477                 goto errout_skb;
2478         netlink_skb_set_owner_r(skb, sk);
2479
2480         len = cb->dump(skb, cb);
2481
2482         if (len > 0) {
2483                 mutex_unlock(nlk->cb_mutex);
2484
2485                 if (sk_filter(sk, skb))
2486                         kfree_skb(skb);
2487                 else
2488                         __netlink_sendskb(sk, skb);
2489                 return 0;
2490         }
2491
2492         nlh = nlmsg_put_answer(skb, cb, NLMSG_DONE, sizeof(len), NLM_F_MULTI);
2493         if (!nlh)
2494                 goto errout_skb;
2495
2496         nl_dump_check_consistent(cb, nlh);
2497
2498         memcpy(nlmsg_data(nlh), &len, sizeof(len));
2499
2500         if (sk_filter(sk, skb))
2501                 kfree_skb(skb);
2502         else
2503                 __netlink_sendskb(sk, skb);
2504
2505         if (cb->done)
2506                 cb->done(cb);
2507         nlk->cb = NULL;
2508         mutex_unlock(nlk->cb_mutex);
2509
2510         module_put(cb->module);
2511         netlink_consume_callback(cb);
2512         return 0;
2513
2514 errout_skb:
2515         mutex_unlock(nlk->cb_mutex);
2516         kfree_skb(skb);
2517         return err;
2518 }
2519
2520 int __netlink_dump_start(struct sock *ssk, struct sk_buff *skb,
2521                          const struct nlmsghdr *nlh,
2522                          struct netlink_dump_control *control)
2523 {
2524         struct netlink_callback *cb;
2525         struct sock *sk;
2526         struct netlink_sock *nlk;
2527         int ret;
2528
2529         cb = kzalloc(sizeof(*cb), GFP_KERNEL);
2530         if (cb == NULL)
2531                 return -ENOBUFS;
2532
2533         /* Memory mapped dump requests need to be copied to avoid looping
2534          * on the pending state in netlink_mmap_sendmsg() while the CB hold
2535          * a reference to the skb.
2536          */
2537         if (netlink_skb_is_mmaped(skb)) {
2538                 skb = skb_copy(skb, GFP_KERNEL);
2539                 if (skb == NULL) {
2540                         kfree(cb);
2541                         return -ENOBUFS;
2542                 }
2543         } else
2544                 atomic_inc(&skb->users);
2545
2546         cb->dump = control->dump;
2547         cb->done = control->done;
2548         cb->nlh = nlh;
2549         cb->data = control->data;
2550         cb->module = control->module;
2551         cb->min_dump_alloc = control->min_dump_alloc;
2552         cb->skb = skb;
2553
2554         sk = netlink_lookup(sock_net(ssk), ssk->sk_protocol, NETLINK_CB(skb).portid);
2555         if (sk == NULL) {
2556                 netlink_destroy_callback(cb);
2557                 return -ECONNREFUSED;
2558         }
2559         nlk = nlk_sk(sk);
2560
2561         mutex_lock(nlk->cb_mutex);
2562         /* A dump is in progress... */
2563         if (nlk->cb) {
2564                 mutex_unlock(nlk->cb_mutex);
2565                 netlink_destroy_callback(cb);
2566                 ret = -EBUSY;
2567                 goto out;
2568         }
2569         /* add reference of module which cb->dump belongs to */
2570         if (!try_module_get(cb->module)) {
2571                 mutex_unlock(nlk->cb_mutex);
2572                 netlink_destroy_callback(cb);
2573                 ret = -EPROTONOSUPPORT;
2574                 goto out;
2575         }
2576
2577         nlk->cb = cb;
2578         mutex_unlock(nlk->cb_mutex);
2579
2580         ret = netlink_dump(sk);
2581 out:
2582         sock_put(sk);
2583
2584         if (ret)
2585                 return ret;
2586
2587         /* We successfully started a dump, by returning -EINTR we
2588          * signal not to send ACK even if it was requested.
2589          */
2590         return -EINTR;
2591 }
2592 EXPORT_SYMBOL(__netlink_dump_start);
2593
2594 void netlink_ack(struct sk_buff *in_skb, struct nlmsghdr *nlh, int err)
2595 {
2596         struct sk_buff *skb;
2597         struct nlmsghdr *rep;
2598         struct nlmsgerr *errmsg;
2599         size_t payload = sizeof(*errmsg);
2600
2601         /* error messages get the original request appened */
2602         if (err)
2603                 payload += nlmsg_len(nlh);
2604
2605         skb = netlink_alloc_skb(in_skb->sk, nlmsg_total_size(payload),
2606                                 NETLINK_CB(in_skb).portid, GFP_KERNEL);
2607         if (!skb) {
2608                 struct sock *sk;
2609
2610                 sk = netlink_lookup(sock_net(in_skb->sk),
2611                                     in_skb->sk->sk_protocol,
2612                                     NETLINK_CB(in_skb).portid);
2613                 if (sk) {
2614                         sk->sk_err = ENOBUFS;
2615                         sk->sk_error_report(sk);
2616                         sock_put(sk);
2617                 }
2618                 return;
2619         }
2620
2621         rep = __nlmsg_put(skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq,
2622                           NLMSG_ERROR, payload, 0);
2623         errmsg = nlmsg_data(rep);
2624         errmsg->error = err;
2625         memcpy(&errmsg->msg, nlh, err ? nlh->nlmsg_len : sizeof(*nlh));
2626         netlink_unicast(in_skb->sk, skb, NETLINK_CB(in_skb).portid, MSG_DONTWAIT);
2627 }
2628 EXPORT_SYMBOL(netlink_ack);
2629
2630 int netlink_rcv_skb(struct sk_buff *skb, int (*cb)(struct sk_buff *,
2631                                                      struct nlmsghdr *))
2632 {
2633         struct nlmsghdr *nlh;
2634         int err;
2635
2636         while (skb->len >= nlmsg_total_size(0)) {
2637                 int msglen;
2638
2639                 nlh = nlmsg_hdr(skb);
2640                 err = 0;
2641
2642                 if (nlh->nlmsg_len < NLMSG_HDRLEN || skb->len < nlh->nlmsg_len)
2643                         return 0;
2644
2645                 /* Only requests are handled by the kernel */
2646                 if (!(nlh->nlmsg_flags & NLM_F_REQUEST))
2647                         goto ack;
2648
2649                 /* Skip control messages */
2650                 if (nlh->nlmsg_type < NLMSG_MIN_TYPE)
2651                         goto ack;
2652
2653                 err = cb(skb, nlh);
2654                 if (err == -EINTR)
2655                         goto skip;
2656
2657 ack:
2658                 if (nlh->nlmsg_flags & NLM_F_ACK || err)
2659                         netlink_ack(skb, nlh, err);
2660
2661 skip:
2662                 msglen = NLMSG_ALIGN(nlh->nlmsg_len);
2663                 if (msglen > skb->len)
2664                         msglen = skb->len;
2665                 skb_pull(skb, msglen);
2666         }
2667
2668         return 0;
2669 }
2670 EXPORT_SYMBOL(netlink_rcv_skb);
2671
2672 /**
2673  * nlmsg_notify - send a notification netlink message
2674  * @sk: netlink socket to use
2675  * @skb: notification message
2676  * @portid: destination netlink portid for reports or 0
2677  * @group: destination multicast group or 0
2678  * @report: 1 to report back, 0 to disable
2679  * @flags: allocation flags
2680  */
2681 int nlmsg_notify(struct sock *sk, struct sk_buff *skb, u32 portid,
2682                  unsigned int group, int report, gfp_t flags)
2683 {
2684         int err = 0;
2685
2686         if (group) {
2687                 int exclude_portid = 0;
2688
2689                 if (report) {
2690                         atomic_inc(&skb->users);
2691                         exclude_portid = portid;
2692                 }
2693
2694                 /* errors reported via destination sk->sk_err, but propagate
2695                  * delivery errors if NETLINK_BROADCAST_ERROR flag is set */
2696                 err = nlmsg_multicast(sk, skb, exclude_portid, group, flags);
2697         }
2698
2699         if (report) {
2700                 int err2;
2701
2702                 err2 = nlmsg_unicast(sk, skb, portid);
2703                 if (!err || err == -ESRCH)
2704                         err = err2;
2705         }
2706
2707         return err;
2708 }
2709 EXPORT_SYMBOL(nlmsg_notify);
2710
2711 #ifdef CONFIG_PROC_FS
2712 struct nl_seq_iter {
2713         struct seq_net_private p;
2714         int link;
2715         int hash_idx;
2716 };
2717
2718 static struct sock *netlink_seq_socket_idx(struct seq_file *seq, loff_t pos)
2719 {
2720         struct nl_seq_iter *iter = seq->private;
2721         int i, j;
2722         struct sock *s;
2723         loff_t off = 0;
2724
2725         for (i = 0; i < MAX_LINKS; i++) {
2726                 struct nl_portid_hash *hash = &nl_table[i].hash;
2727
2728                 for (j = 0; j <= hash->mask; j++) {
2729                         sk_for_each(s, &hash->table[j]) {
2730                                 if (sock_net(s) != seq_file_net(seq))
2731                                         continue;
2732                                 if (off == pos) {
2733                                         iter->link = i;
2734                                         iter->hash_idx = j;
2735                                         return s;
2736                                 }
2737                                 ++off;
2738                         }
2739                 }
2740         }
2741         return NULL;
2742 }
2743
2744 static void *netlink_seq_start(struct seq_file *seq, loff_t *pos)
2745         __acquires(nl_table_lock)
2746 {
2747         read_lock(&nl_table_lock);
2748         return *pos ? netlink_seq_socket_idx(seq, *pos - 1) : SEQ_START_TOKEN;
2749 }
2750
2751 static void *netlink_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2752 {
2753         struct sock *s;
2754         struct nl_seq_iter *iter;
2755         struct net *net;
2756         int i, j;
2757
2758         ++*pos;
2759
2760         if (v == SEQ_START_TOKEN)
2761                 return netlink_seq_socket_idx(seq, 0);
2762
2763         net = seq_file_net(seq);
2764         iter = seq->private;
2765         s = v;
2766         do {
2767                 s = sk_next(s);
2768         } while (s && !nl_table[s->sk_protocol].compare(net, s));
2769         if (s)
2770                 return s;
2771
2772         i = iter->link;
2773         j = iter->hash_idx + 1;
2774
2775         do {
2776                 struct nl_portid_hash *hash = &nl_table[i].hash;
2777
2778                 for (; j <= hash->mask; j++) {
2779                         s = sk_head(&hash->table[j]);
2780
2781                         while (s && !nl_table[s->sk_protocol].compare(net, s))
2782                                 s = sk_next(s);
2783                         if (s) {
2784                                 iter->link = i;
2785                                 iter->hash_idx = j;
2786                                 return s;
2787                         }
2788                 }
2789
2790                 j = 0;
2791         } while (++i < MAX_LINKS);
2792
2793         return NULL;
2794 }
2795
2796 static void netlink_seq_stop(struct seq_file *seq, void *v)
2797         __releases(nl_table_lock)
2798 {
2799         read_unlock(&nl_table_lock);
2800 }
2801
2802
2803 static int netlink_seq_show(struct seq_file *seq, void *v)
2804 {
2805         if (v == SEQ_START_TOKEN) {
2806                 seq_puts(seq,
2807                          "sk       Eth Pid    Groups   "
2808                          "Rmem     Wmem     Dump     Locks     Drops     Inode\n");
2809         } else {
2810                 struct sock *s = v;
2811                 struct netlink_sock *nlk = nlk_sk(s);
2812
2813                 seq_printf(seq, "%pK %-3d %-6u %08x %-8d %-8d %pK %-8d %-8d %-8lu\n",
2814                            s,
2815                            s->sk_protocol,
2816                            nlk->portid,
2817                            nlk->groups ? (u32)nlk->groups[0] : 0,
2818                            sk_rmem_alloc_get(s),
2819                            sk_wmem_alloc_get(s),
2820                            nlk->cb,
2821                            atomic_read(&s->sk_refcnt),
2822                            atomic_read(&s->sk_drops),
2823                            sock_i_ino(s)
2824                         );
2825
2826         }
2827         return 0;
2828 }
2829
2830 static const struct seq_operations netlink_seq_ops = {
2831         .start  = netlink_seq_start,
2832         .next   = netlink_seq_next,
2833         .stop   = netlink_seq_stop,
2834         .show   = netlink_seq_show,
2835 };
2836
2837
2838 static int netlink_seq_open(struct inode *inode, struct file *file)
2839 {
2840         return seq_open_net(inode, file, &netlink_seq_ops,
2841                                 sizeof(struct nl_seq_iter));
2842 }
2843
2844 static const struct file_operations netlink_seq_fops = {
2845         .owner          = THIS_MODULE,
2846         .open           = netlink_seq_open,
2847         .read           = seq_read,
2848         .llseek         = seq_lseek,
2849         .release        = seq_release_net,
2850 };
2851
2852 #endif
2853
2854 int netlink_register_notifier(struct notifier_block *nb)
2855 {
2856         return atomic_notifier_chain_register(&netlink_chain, nb);
2857 }
2858 EXPORT_SYMBOL(netlink_register_notifier);
2859
2860 int netlink_unregister_notifier(struct notifier_block *nb)
2861 {
2862         return atomic_notifier_chain_unregister(&netlink_chain, nb);
2863 }
2864 EXPORT_SYMBOL(netlink_unregister_notifier);
2865
2866 static const struct proto_ops netlink_ops = {
2867         .family =       PF_NETLINK,
2868         .owner =        THIS_MODULE,
2869         .release =      netlink_release,
2870         .bind =         netlink_bind,
2871         .connect =      netlink_connect,
2872         .socketpair =   sock_no_socketpair,
2873         .accept =       sock_no_accept,
2874         .getname =      netlink_getname,
2875         .poll =         netlink_poll,
2876         .ioctl =        sock_no_ioctl,
2877         .listen =       sock_no_listen,
2878         .shutdown =     sock_no_shutdown,
2879         .setsockopt =   netlink_setsockopt,
2880         .getsockopt =   netlink_getsockopt,
2881         .sendmsg =      netlink_sendmsg,
2882         .recvmsg =      netlink_recvmsg,
2883         .mmap =         netlink_mmap,
2884         .sendpage =     sock_no_sendpage,
2885 };
2886
2887 static const struct net_proto_family netlink_family_ops = {
2888         .family = PF_NETLINK,
2889         .create = netlink_create,
2890         .owner  = THIS_MODULE,  /* for consistency 8) */
2891 };
2892
2893 static int __net_init netlink_net_init(struct net *net)
2894 {
2895 #ifdef CONFIG_PROC_FS
2896         if (!proc_create("netlink", 0, net->proc_net, &netlink_seq_fops))
2897                 return -ENOMEM;
2898 #endif
2899         return 0;
2900 }
2901
2902 static void __net_exit netlink_net_exit(struct net *net)
2903 {
2904 #ifdef CONFIG_PROC_FS
2905         remove_proc_entry("netlink", net->proc_net);
2906 #endif
2907 }
2908
2909 static void __init netlink_add_usersock_entry(void)
2910 {
2911         struct listeners *listeners;
2912         int groups = 32;
2913
2914         listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
2915         if (!listeners)
2916                 panic("netlink_add_usersock_entry: Cannot allocate listeners\n");
2917
2918         netlink_table_grab();
2919
2920         nl_table[NETLINK_USERSOCK].groups = groups;
2921         rcu_assign_pointer(nl_table[NETLINK_USERSOCK].listeners, listeners);
2922         nl_table[NETLINK_USERSOCK].module = THIS_MODULE;
2923         nl_table[NETLINK_USERSOCK].registered = 1;
2924         nl_table[NETLINK_USERSOCK].flags = NL_CFG_F_NONROOT_SEND;
2925
2926         netlink_table_ungrab();
2927 }
2928
2929 static struct pernet_operations __net_initdata netlink_net_ops = {
2930         .init = netlink_net_init,
2931         .exit = netlink_net_exit,
2932 };
2933
2934 static int __init netlink_proto_init(void)
2935 {
2936         int i;
2937         unsigned long limit;
2938         unsigned int order;
2939         int err = proto_register(&netlink_proto, 0);
2940
2941         if (err != 0)
2942                 goto out;
2943
2944         BUILD_BUG_ON(sizeof(struct netlink_skb_parms) > FIELD_SIZEOF(struct sk_buff, cb));
2945
2946         nl_table = kcalloc(MAX_LINKS, sizeof(*nl_table), GFP_KERNEL);
2947         if (!nl_table)
2948                 goto panic;
2949
2950         if (totalram_pages >= (128 * 1024))
2951                 limit = totalram_pages >> (21 - PAGE_SHIFT);
2952         else
2953                 limit = totalram_pages >> (23 - PAGE_SHIFT);
2954
2955         order = get_bitmask_order(limit) - 1 + PAGE_SHIFT;
2956         limit = (1UL << order) / sizeof(struct hlist_head);
2957         order = get_bitmask_order(min(limit, (unsigned long)UINT_MAX)) - 1;
2958
2959         for (i = 0; i < MAX_LINKS; i++) {
2960                 struct nl_portid_hash *hash = &nl_table[i].hash;
2961
2962                 hash->table = nl_portid_hash_zalloc(1 * sizeof(*hash->table));
2963                 if (!hash->table) {
2964                         while (i-- > 0)
2965                                 nl_portid_hash_free(nl_table[i].hash.table,
2966                                                  1 * sizeof(*hash->table));
2967                         kfree(nl_table);
2968                         goto panic;
2969                 }
2970                 hash->max_shift = order;
2971                 hash->shift = 0;
2972                 hash->mask = 0;
2973                 hash->rehash_time = jiffies;
2974
2975                 nl_table[i].compare = netlink_compare;
2976         }
2977
2978         netlink_add_usersock_entry();
2979
2980         sock_register(&netlink_family_ops);
2981         register_pernet_subsys(&netlink_net_ops);
2982         /* The netlink device handler may be needed early. */
2983         rtnetlink_init();
2984 out:
2985         return err;
2986 panic:
2987         panic("netlink_init: Cannot allocate nl_table\n");
2988 }
2989
2990 core_initcall(netlink_proto_init);