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