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