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