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