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