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