OSDN Git Service

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