xref: /linux/net/netlink/af_netlink.c (revision f88bb3606e4bd11ee035b682cddc2999e604609a)
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 	u64 net_cookie;
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 	       sock_net(&nlk->sk)->net_cookie != x->net_cookie;
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 	arg->net_cookie = net->net_cookie;
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 	skb_reset_network_header(skb);
1367 	skb_reset_mac_header(skb);
1368 	if (sk_filter(sk, skb)) {
1369 		err = skb->len;
1370 		kfree_skb(skb);
1371 		sock_put(sk);
1372 		return err;
1373 	}
1374 
1375 	err = netlink_attachskb(sk, skb, &timeo, ssk);
1376 	if (err == 1)
1377 		goto retry;
1378 	if (err)
1379 		return err;
1380 
1381 	return netlink_sendskb(sk, skb);
1382 }
1383 EXPORT_SYMBOL(netlink_unicast);
1384 
1385 int netlink_has_listeners(struct sock *sk, unsigned int group)
1386 {
1387 	int res = 0;
1388 	struct listeners *listeners;
1389 
1390 	BUG_ON(!netlink_is_kernel(sk));
1391 
1392 	rcu_read_lock();
1393 	listeners = rcu_dereference(nl_table[sk->sk_protocol].listeners);
1394 
1395 	if (listeners && group - 1 < nl_table[sk->sk_protocol].groups)
1396 		res = test_bit(group - 1, listeners->masks);
1397 
1398 	rcu_read_unlock();
1399 
1400 	return res;
1401 }
1402 EXPORT_SYMBOL_GPL(netlink_has_listeners);
1403 
1404 bool netlink_strict_get_check(struct sk_buff *skb)
1405 {
1406 	return nlk_test_bit(STRICT_CHK, NETLINK_CB(skb).sk);
1407 }
1408 EXPORT_SYMBOL_GPL(netlink_strict_get_check);
1409 
1410 static int netlink_broadcast_deliver(struct sock *sk, struct sk_buff *skb)
1411 {
1412 	struct netlink_sock *nlk = nlk_sk(sk);
1413 	unsigned int rmem, rcvbuf;
1414 
1415 	rmem = atomic_add_return(skb->truesize, &sk->sk_rmem_alloc);
1416 	rcvbuf = READ_ONCE(sk->sk_rcvbuf);
1417 
1418 	if ((rmem == skb->truesize || rmem <= rcvbuf) &&
1419 	    !test_bit(NETLINK_S_CONGESTED, &nlk->state)) {
1420 		netlink_skb_set_owner_r(skb, sk);
1421 		__netlink_sendskb(sk, skb);
1422 		return rmem > (rcvbuf >> 1);
1423 	}
1424 
1425 	atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
1426 	return -1;
1427 }
1428 
1429 struct netlink_broadcast_data {
1430 	struct sock *exclude_sk;
1431 	struct net *net;
1432 	u32 portid;
1433 	u32 group;
1434 	int failure;
1435 	int delivery_failure;
1436 	int congested;
1437 	int delivered;
1438 	gfp_t allocation;
1439 	struct sk_buff *skb, *skb2;
1440 	int (*tx_filter)(struct sock *dsk, struct sk_buff *skb, void *data);
1441 	void *tx_data;
1442 };
1443 
1444 static void do_one_broadcast(struct sock *sk,
1445 				    struct netlink_broadcast_data *p)
1446 {
1447 	struct netlink_sock *nlk = nlk_sk(sk);
1448 	int val;
1449 
1450 	if (p->exclude_sk == sk)
1451 		return;
1452 
1453 	if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
1454 	    !test_bit(p->group - 1, nlk->groups))
1455 		return;
1456 
1457 	if (!net_eq(sock_net(sk), p->net)) {
1458 		if (!nlk_test_bit(LISTEN_ALL_NSID, sk))
1459 			return;
1460 
1461 		if (!peernet_has_id(sock_net(sk), p->net))
1462 			return;
1463 
1464 		if (!file_ns_capable(sk->sk_socket->file, p->net->user_ns,
1465 				     CAP_NET_BROADCAST))
1466 			return;
1467 	}
1468 
1469 	if (p->failure) {
1470 		netlink_overrun(sk);
1471 		return;
1472 	}
1473 
1474 	sock_hold(sk);
1475 	if (p->skb2 == NULL) {
1476 		if (skb_shared(p->skb)) {
1477 			p->skb2 = skb_clone(p->skb, p->allocation);
1478 		} else {
1479 			p->skb2 = skb_get(p->skb);
1480 			/*
1481 			 * skb ownership may have been set when
1482 			 * delivered to a previous socket.
1483 			 */
1484 			skb_orphan(p->skb2);
1485 		}
1486 	}
1487 	if (p->skb2 == NULL) {
1488 		netlink_overrun(sk);
1489 		/* Clone failed. Notify ALL listeners. */
1490 		p->failure = 1;
1491 		if (nlk_test_bit(BROADCAST_SEND_ERROR, sk))
1492 			p->delivery_failure = 1;
1493 		goto out;
1494 	}
1495 
1496 	if (p->tx_filter && p->tx_filter(sk, p->skb2, p->tx_data)) {
1497 		kfree_skb(p->skb2);
1498 		p->skb2 = NULL;
1499 		goto out;
1500 	}
1501 
1502 	skb_reset_network_header(p->skb2);
1503 	skb_reset_mac_header(p->skb2);
1504 	if (sk_filter(sk, p->skb2)) {
1505 		kfree_skb(p->skb2);
1506 		p->skb2 = NULL;
1507 		goto out;
1508 	}
1509 
1510 	NETLINK_CB(p->skb2).nsid_is_set = false;
1511 	if (!net_eq(sock_net(sk), p->net)) {
1512 		NETLINK_CB(p->skb2).nsid = peernet2id(sock_net(sk), p->net);
1513 		if (NETLINK_CB(p->skb2).nsid != NETNSA_NSID_NOT_ASSIGNED)
1514 			NETLINK_CB(p->skb2).nsid_is_set = true;
1515 	}
1516 
1517 	val = netlink_broadcast_deliver(sk, p->skb2);
1518 	if (val < 0) {
1519 		netlink_overrun(sk);
1520 		if (nlk_test_bit(BROADCAST_SEND_ERROR, sk))
1521 			p->delivery_failure = 1;
1522 	} else {
1523 		p->congested |= val;
1524 		p->delivered = 1;
1525 		p->skb2 = NULL;
1526 	}
1527 out:
1528 	sock_put(sk);
1529 }
1530 
1531 int netlink_broadcast_filtered(struct sock *ssk, struct sk_buff *skb,
1532 			       u32 portid,
1533 			       u32 group, gfp_t allocation,
1534 			       netlink_filter_fn filter,
1535 			       void *filter_data)
1536 {
1537 	struct net *net = sock_net(ssk);
1538 	struct netlink_broadcast_data info;
1539 	struct sock *sk;
1540 
1541 	skb = netlink_trim(skb, allocation);
1542 
1543 	info.exclude_sk = ssk;
1544 	info.net = net;
1545 	info.portid = portid;
1546 	info.group = group;
1547 	info.failure = 0;
1548 	info.delivery_failure = 0;
1549 	info.congested = 0;
1550 	info.delivered = 0;
1551 	info.allocation = allocation;
1552 	info.skb = skb;
1553 	info.skb2 = NULL;
1554 	info.tx_filter = filter;
1555 	info.tx_data = filter_data;
1556 
1557 	/* While we sleep in clone, do not allow to change socket list */
1558 
1559 	netlink_lock_table();
1560 
1561 	sk_for_each_bound(sk, &nl_table[ssk->sk_protocol].mc_list)
1562 		do_one_broadcast(sk, &info);
1563 
1564 	consume_skb(skb);
1565 
1566 	netlink_unlock_table();
1567 
1568 	if (info.delivery_failure) {
1569 		kfree_skb(info.skb2);
1570 		return -ENOBUFS;
1571 	}
1572 	consume_skb(info.skb2);
1573 
1574 	if (info.delivered) {
1575 		if (info.congested && gfpflags_allow_blocking(allocation))
1576 			yield();
1577 		return 0;
1578 	}
1579 	return -ESRCH;
1580 }
1581 EXPORT_SYMBOL(netlink_broadcast_filtered);
1582 
1583 int netlink_broadcast(struct sock *ssk, struct sk_buff *skb, u32 portid,
1584 		      u32 group, gfp_t allocation)
1585 {
1586 	return netlink_broadcast_filtered(ssk, skb, portid, group, allocation,
1587 					  NULL, NULL);
1588 }
1589 EXPORT_SYMBOL(netlink_broadcast);
1590 
1591 struct netlink_set_err_data {
1592 	struct sock *exclude_sk;
1593 	u32 portid;
1594 	u32 group;
1595 	int code;
1596 };
1597 
1598 static int do_one_set_err(struct sock *sk, struct netlink_set_err_data *p)
1599 {
1600 	struct netlink_sock *nlk = nlk_sk(sk);
1601 	int ret = 0;
1602 
1603 	if (sk == p->exclude_sk)
1604 		goto out;
1605 
1606 	if (!net_eq(sock_net(sk), sock_net(p->exclude_sk)))
1607 		goto out;
1608 
1609 	if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
1610 	    !test_bit(p->group - 1, nlk->groups))
1611 		goto out;
1612 
1613 	if (p->code == ENOBUFS && nlk_test_bit(RECV_NO_ENOBUFS, sk)) {
1614 		ret = 1;
1615 		goto out;
1616 	}
1617 
1618 	WRITE_ONCE(sk->sk_err, p->code);
1619 	sk_error_report(sk);
1620 out:
1621 	return ret;
1622 }
1623 
1624 /**
1625  * netlink_set_err - report error to broadcast listeners
1626  * @ssk: the kernel netlink socket, as returned by netlink_kernel_create()
1627  * @portid: the PORTID of a process that we want to skip (if any)
1628  * @group: the broadcast group that will notice the error
1629  * @code: error code, must be negative (as usual in kernelspace)
1630  *
1631  * This function returns the number of broadcast listeners that have set the
1632  * NETLINK_NO_ENOBUFS socket option.
1633  */
1634 int netlink_set_err(struct sock *ssk, u32 portid, u32 group, int code)
1635 {
1636 	struct netlink_set_err_data info;
1637 	unsigned long flags;
1638 	struct sock *sk;
1639 	int ret = 0;
1640 
1641 	info.exclude_sk = ssk;
1642 	info.portid = portid;
1643 	info.group = group;
1644 	/* sk->sk_err wants a positive error value */
1645 	info.code = -code;
1646 
1647 	read_lock_irqsave(&nl_table_lock, flags);
1648 
1649 	sk_for_each_bound(sk, &nl_table[ssk->sk_protocol].mc_list)
1650 		ret += do_one_set_err(sk, &info);
1651 
1652 	read_unlock_irqrestore(&nl_table_lock, flags);
1653 	return ret;
1654 }
1655 EXPORT_SYMBOL(netlink_set_err);
1656 
1657 /* must be called with netlink table grabbed */
1658 static void netlink_update_socket_mc(struct netlink_sock *nlk,
1659 				     unsigned int group,
1660 				     int is_new)
1661 {
1662 	int old, new = !!is_new, subscriptions;
1663 
1664 	old = test_bit(group - 1, nlk->groups);
1665 	subscriptions = nlk->subscriptions - old + new;
1666 	__assign_bit(group - 1, nlk->groups, new);
1667 	netlink_update_subscriptions(&nlk->sk, subscriptions);
1668 	netlink_update_listeners(&nlk->sk);
1669 }
1670 
1671 static int netlink_setsockopt(struct socket *sock, int level, int optname,
1672 			      sockptr_t optval, unsigned int optlen)
1673 {
1674 	struct sock *sk = sock->sk;
1675 	struct netlink_sock *nlk = nlk_sk(sk);
1676 	unsigned int val = 0;
1677 	int nr = -1;
1678 
1679 	if (level != SOL_NETLINK)
1680 		return -ENOPROTOOPT;
1681 
1682 	if (optlen >= sizeof(int) &&
1683 	    copy_from_sockptr(&val, optval, sizeof(val)))
1684 		return -EFAULT;
1685 
1686 	switch (optname) {
1687 	case NETLINK_PKTINFO:
1688 		nr = NETLINK_F_RECV_PKTINFO;
1689 		break;
1690 	case NETLINK_ADD_MEMBERSHIP:
1691 	case NETLINK_DROP_MEMBERSHIP: {
1692 		int err;
1693 
1694 		if (!netlink_allowed(sock, NL_CFG_F_NONROOT_RECV))
1695 			return -EPERM;
1696 		err = netlink_realloc_groups(sk);
1697 		if (err)
1698 			return err;
1699 		if (!val || val - 1 >= nlk->ngroups)
1700 			return -EINVAL;
1701 		if (optname == NETLINK_ADD_MEMBERSHIP && nlk->netlink_bind) {
1702 			err = nlk->netlink_bind(sock_net(sk), val);
1703 			if (err)
1704 				return err;
1705 		}
1706 		netlink_table_grab();
1707 		netlink_update_socket_mc(nlk, val,
1708 					 optname == NETLINK_ADD_MEMBERSHIP);
1709 		netlink_table_ungrab();
1710 		if (optname == NETLINK_DROP_MEMBERSHIP && nlk->netlink_unbind)
1711 			nlk->netlink_unbind(sock_net(sk), val);
1712 
1713 		break;
1714 	}
1715 	case NETLINK_BROADCAST_ERROR:
1716 		nr = NETLINK_F_BROADCAST_SEND_ERROR;
1717 		break;
1718 	case NETLINK_NO_ENOBUFS:
1719 		assign_bit(NETLINK_F_RECV_NO_ENOBUFS, &nlk->flags, val);
1720 		if (val) {
1721 			clear_bit(NETLINK_S_CONGESTED, &nlk->state);
1722 			wake_up_interruptible(&nlk->wait);
1723 		}
1724 		break;
1725 	case NETLINK_LISTEN_ALL_NSID:
1726 		if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_BROADCAST))
1727 			return -EPERM;
1728 		nr = NETLINK_F_LISTEN_ALL_NSID;
1729 		break;
1730 	case NETLINK_CAP_ACK:
1731 		nr = NETLINK_F_CAP_ACK;
1732 		break;
1733 	case NETLINK_EXT_ACK:
1734 		nr = NETLINK_F_EXT_ACK;
1735 		break;
1736 	case NETLINK_GET_STRICT_CHK:
1737 		nr = NETLINK_F_STRICT_CHK;
1738 		break;
1739 	default:
1740 		return -ENOPROTOOPT;
1741 	}
1742 	if (nr >= 0)
1743 		assign_bit(nr, &nlk->flags, val);
1744 	return 0;
1745 }
1746 
1747 static int netlink_getsockopt(struct socket *sock, int level, int optname,
1748 			      sockopt_t *opt)
1749 {
1750 	struct sock *sk = sock->sk;
1751 	struct netlink_sock *nlk = nlk_sk(sk);
1752 	unsigned int flag;
1753 	int len, val;
1754 	u32 group;
1755 
1756 	if (level != SOL_NETLINK)
1757 		return -ENOPROTOOPT;
1758 
1759 	len = opt->optlen;
1760 	if (len < 0)
1761 		return -EINVAL;
1762 
1763 	switch (optname) {
1764 	case NETLINK_PKTINFO:
1765 		flag = NETLINK_F_RECV_PKTINFO;
1766 		break;
1767 	case NETLINK_BROADCAST_ERROR:
1768 		flag = NETLINK_F_BROADCAST_SEND_ERROR;
1769 		break;
1770 	case NETLINK_NO_ENOBUFS:
1771 		flag = NETLINK_F_RECV_NO_ENOBUFS;
1772 		break;
1773 	case NETLINK_LIST_MEMBERSHIPS: {
1774 		int pos, idx, shift, err = 0;
1775 
1776 		netlink_lock_table();
1777 		for (pos = 0; pos * 8 < nlk->ngroups; pos += sizeof(u32)) {
1778 			if (len - pos < sizeof(u32))
1779 				break;
1780 
1781 			idx = pos / sizeof(unsigned long);
1782 			shift = (pos % sizeof(unsigned long)) * 8;
1783 			group = (u32)(nlk->groups[idx] >> shift);
1784 			if (copy_to_iter(&group, sizeof(u32),
1785 					 &opt->iter_out) != sizeof(u32)) {
1786 				err = -EFAULT;
1787 				break;
1788 			}
1789 		}
1790 		opt->optlen = ALIGN(BITS_TO_BYTES(nlk->ngroups), sizeof(u32));
1791 		netlink_unlock_table();
1792 		return err;
1793 	}
1794 	case NETLINK_LISTEN_ALL_NSID:
1795 		flag = NETLINK_F_LISTEN_ALL_NSID;
1796 		break;
1797 	case NETLINK_CAP_ACK:
1798 		flag = NETLINK_F_CAP_ACK;
1799 		break;
1800 	case NETLINK_EXT_ACK:
1801 		flag = NETLINK_F_EXT_ACK;
1802 		break;
1803 	case NETLINK_GET_STRICT_CHK:
1804 		flag = NETLINK_F_STRICT_CHK;
1805 		break;
1806 	default:
1807 		return -ENOPROTOOPT;
1808 	}
1809 
1810 	if (len < sizeof(int))
1811 		return -EINVAL;
1812 
1813 	len = sizeof(int);
1814 	val = test_bit(flag, &nlk->flags);
1815 
1816 	opt->optlen = len;
1817 	if (copy_to_iter(&val, len, &opt->iter_out) != len)
1818 		return -EFAULT;
1819 
1820 	return 0;
1821 }
1822 
1823 static void netlink_cmsg_recv_pktinfo(struct msghdr *msg, struct sk_buff *skb)
1824 {
1825 	struct nl_pktinfo info;
1826 
1827 	info.group = NETLINK_CB(skb).dst_group;
1828 	put_cmsg(msg, SOL_NETLINK, NETLINK_PKTINFO, sizeof(info), &info);
1829 }
1830 
1831 static void netlink_cmsg_listen_all_nsid(struct sock *sk, struct msghdr *msg,
1832 					 struct sk_buff *skb)
1833 {
1834 	if (!NETLINK_CB(skb).nsid_is_set)
1835 		return;
1836 
1837 	put_cmsg(msg, SOL_NETLINK, NETLINK_LISTEN_ALL_NSID, sizeof(int),
1838 		 &NETLINK_CB(skb).nsid);
1839 }
1840 
1841 static int netlink_sendmsg(struct socket *sock, struct msghdr *msg, size_t len)
1842 {
1843 	struct sock *sk = sock->sk;
1844 	struct netlink_sock *nlk = nlk_sk(sk);
1845 	DECLARE_SOCKADDR(struct sockaddr_nl *, addr, msg->msg_name);
1846 	u32 dst_portid;
1847 	u32 dst_group;
1848 	struct sk_buff *skb;
1849 	int err;
1850 	struct scm_cookie scm;
1851 	u32 netlink_skb_flags = 0;
1852 
1853 	if (msg->msg_flags & MSG_OOB)
1854 		return -EOPNOTSUPP;
1855 
1856 	if (len == 0) {
1857 		pr_warn_once("Zero length message leads to an empty skb\n");
1858 		return -ENODATA;
1859 	}
1860 
1861 	err = scm_send(sock, msg, &scm, true);
1862 	if (err < 0)
1863 		return err;
1864 
1865 	if (msg->msg_namelen) {
1866 		err = -EINVAL;
1867 		if (msg->msg_namelen < sizeof(struct sockaddr_nl))
1868 			goto out;
1869 		if (addr->nl_family != AF_NETLINK)
1870 			goto out;
1871 		dst_portid = addr->nl_pid;
1872 		dst_group = ffs(addr->nl_groups);
1873 		err =  -EPERM;
1874 		if ((dst_group || dst_portid) &&
1875 		    !netlink_allowed(sock, NL_CFG_F_NONROOT_SEND))
1876 			goto out;
1877 		netlink_skb_flags |= NETLINK_SKB_DST;
1878 	} else {
1879 		/* Paired with WRITE_ONCE() in netlink_connect() */
1880 		dst_portid = READ_ONCE(nlk->dst_portid);
1881 		dst_group = READ_ONCE(nlk->dst_group);
1882 	}
1883 
1884 	/* Paired with WRITE_ONCE() in netlink_insert() */
1885 	if (!READ_ONCE(nlk->bound)) {
1886 		err = netlink_autobind(sock);
1887 		if (err)
1888 			goto out;
1889 	} else {
1890 		/* Ensure nlk is hashed and visible. */
1891 		smp_rmb();
1892 	}
1893 
1894 	err = -EMSGSIZE;
1895 	if (len > sk->sk_sndbuf - 32)
1896 		goto out;
1897 	err = -ENOBUFS;
1898 	skb = netlink_alloc_large_skb(len, dst_group);
1899 	if (skb == NULL)
1900 		goto out;
1901 
1902 	NETLINK_CB(skb).portid	= nlk->portid;
1903 	NETLINK_CB(skb).dst_group = dst_group;
1904 	NETLINK_CB(skb).creds	= scm.creds;
1905 	NETLINK_CB(skb).flags	= netlink_skb_flags;
1906 
1907 	err = -EFAULT;
1908 	if (memcpy_from_msg(skb_put(skb, len), msg, len)) {
1909 		kfree_skb(skb);
1910 		goto out;
1911 	}
1912 
1913 	err = security_netlink_send(sk, skb);
1914 	if (err) {
1915 		kfree_skb(skb);
1916 		goto out;
1917 	}
1918 
1919 	if (dst_group) {
1920 		refcount_inc(&skb->users);
1921 		netlink_broadcast(sk, skb, dst_portid, dst_group, GFP_KERNEL);
1922 	}
1923 	err = netlink_unicast(sk, skb, dst_portid, msg->msg_flags & MSG_DONTWAIT);
1924 
1925 out:
1926 	scm_destroy(&scm);
1927 	return err;
1928 }
1929 
1930 static int netlink_recvmsg(struct socket *sock, struct msghdr *msg, size_t len,
1931 			   int flags)
1932 {
1933 	struct scm_cookie scm;
1934 	struct sock *sk = sock->sk;
1935 	struct netlink_sock *nlk = nlk_sk(sk);
1936 	size_t copied, max_recvmsg_len;
1937 	struct sk_buff *skb, *data_skb;
1938 	int err, ret;
1939 
1940 	if (flags & MSG_OOB)
1941 		return -EOPNOTSUPP;
1942 
1943 	copied = 0;
1944 
1945 	skb = skb_recv_datagram(sk, flags, &err);
1946 	if (skb == NULL)
1947 		goto out;
1948 
1949 	data_skb = skb;
1950 
1951 #ifdef CONFIG_COMPAT_NETLINK_MESSAGES
1952 	if (unlikely(skb_shinfo(skb)->frag_list)) {
1953 		/*
1954 		 * If this skb has a frag_list, then here that means that we
1955 		 * will have to use the frag_list skb's data for compat tasks
1956 		 * and the regular skb's data for normal (non-compat) tasks.
1957 		 *
1958 		 * If we need to send the compat skb, assign it to the
1959 		 * 'data_skb' variable so that it will be used below for data
1960 		 * copying. We keep 'skb' for everything else, including
1961 		 * freeing both later.
1962 		 */
1963 		if (flags & MSG_CMSG_COMPAT)
1964 			data_skb = skb_shinfo(skb)->frag_list;
1965 	}
1966 #endif
1967 
1968 	/* Record the max length of recvmsg() calls for future allocations */
1969 	max_recvmsg_len = max(READ_ONCE(nlk->max_recvmsg_len), len);
1970 	max_recvmsg_len = min_t(size_t, max_recvmsg_len,
1971 				SKB_WITH_OVERHEAD(32768));
1972 	WRITE_ONCE(nlk->max_recvmsg_len, max_recvmsg_len);
1973 
1974 	copied = data_skb->len;
1975 	if (len < copied) {
1976 		msg->msg_flags |= MSG_TRUNC;
1977 		copied = len;
1978 	}
1979 
1980 	err = skb_copy_datagram_msg(data_skb, 0, msg, copied);
1981 
1982 	if (msg->msg_name) {
1983 		DECLARE_SOCKADDR(struct sockaddr_nl *, addr, msg->msg_name);
1984 		addr->nl_family = AF_NETLINK;
1985 		addr->nl_pad    = 0;
1986 		addr->nl_pid	= NETLINK_CB(skb).portid;
1987 		addr->nl_groups	= netlink_group_mask(NETLINK_CB(skb).dst_group);
1988 		msg->msg_namelen = sizeof(*addr);
1989 	}
1990 
1991 	if (nlk_test_bit(RECV_PKTINFO, sk))
1992 		netlink_cmsg_recv_pktinfo(msg, skb);
1993 	if (nlk_test_bit(LISTEN_ALL_NSID, sk))
1994 		netlink_cmsg_listen_all_nsid(sk, msg, skb);
1995 
1996 	memset(&scm, 0, sizeof(scm));
1997 	scm.creds = *NETLINK_CREDS(skb);
1998 	if (flags & MSG_TRUNC)
1999 		copied = data_skb->len;
2000 
2001 	skb_free_datagram(sk, skb);
2002 
2003 	if (READ_ONCE(nlk->cb_running) &&
2004 	    atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf / 2) {
2005 		ret = netlink_dump(sk, false);
2006 		if (ret) {
2007 			WRITE_ONCE(sk->sk_err, -ret);
2008 			sk_error_report(sk);
2009 		}
2010 	}
2011 
2012 	scm_recv(sock, msg, &scm, flags);
2013 out:
2014 	netlink_rcv_wake(sk);
2015 	return err ? : copied;
2016 }
2017 
2018 static void netlink_data_ready(struct sock *sk)
2019 {
2020 	BUG();
2021 }
2022 
2023 /*
2024  *	We export these functions to other modules. They provide a
2025  *	complete set of kernel non-blocking support for message
2026  *	queueing.
2027  */
2028 
2029 struct sock *
2030 __netlink_kernel_create(struct net *net, int unit, struct module *module,
2031 			struct netlink_kernel_cfg *cfg)
2032 {
2033 	struct socket *sock;
2034 	struct sock *sk;
2035 	struct netlink_sock *nlk;
2036 	struct listeners *listeners = NULL;
2037 	unsigned int groups;
2038 
2039 	BUG_ON(!nl_table);
2040 
2041 	if (unit < 0 || unit >= MAX_LINKS)
2042 		return NULL;
2043 
2044 	if (sock_create_lite(PF_NETLINK, SOCK_DGRAM, unit, &sock))
2045 		return NULL;
2046 
2047 	if (__netlink_create(net, sock, unit, 1) < 0)
2048 		goto out_sock_release_nosk;
2049 
2050 	sk = sock->sk;
2051 
2052 	if (!cfg || cfg->groups < 32)
2053 		groups = 32;
2054 	else
2055 		groups = cfg->groups;
2056 
2057 	listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
2058 	if (!listeners)
2059 		goto out_sock_release;
2060 
2061 	sk->sk_data_ready = netlink_data_ready;
2062 	if (cfg && cfg->input)
2063 		nlk_sk(sk)->netlink_rcv = cfg->input;
2064 
2065 	if (netlink_insert(sk, 0))
2066 		goto out_sock_release;
2067 
2068 	nlk = nlk_sk(sk);
2069 	set_bit(NETLINK_F_KERNEL_SOCKET, &nlk->flags);
2070 
2071 	netlink_table_grab();
2072 	if (!nl_table[unit].registered) {
2073 		nl_table[unit].groups = groups;
2074 		rcu_assign_pointer(nl_table[unit].listeners, listeners);
2075 		nl_table[unit].module = module;
2076 		if (cfg) {
2077 			nl_table[unit].bind = cfg->bind;
2078 			nl_table[unit].unbind = cfg->unbind;
2079 			nl_table[unit].release = cfg->release;
2080 			nl_table[unit].flags = cfg->flags;
2081 		}
2082 		nl_table[unit].registered = 1;
2083 	} else {
2084 		kfree(listeners);
2085 		nl_table[unit].registered++;
2086 	}
2087 	netlink_table_ungrab();
2088 	return sk;
2089 
2090 out_sock_release:
2091 	kfree(listeners);
2092 	netlink_kernel_release(sk);
2093 	return NULL;
2094 
2095 out_sock_release_nosk:
2096 	sock_release(sock);
2097 	return NULL;
2098 }
2099 EXPORT_SYMBOL(__netlink_kernel_create);
2100 
2101 void
2102 netlink_kernel_release(struct sock *sk)
2103 {
2104 	if (sk == NULL || sk->sk_socket == NULL)
2105 		return;
2106 
2107 	sock_release(sk->sk_socket);
2108 }
2109 EXPORT_SYMBOL(netlink_kernel_release);
2110 
2111 int __netlink_change_ngroups(struct sock *sk, unsigned int groups)
2112 {
2113 	struct listeners *new, *old;
2114 	struct netlink_table *tbl = &nl_table[sk->sk_protocol];
2115 
2116 	if (groups < 32)
2117 		groups = 32;
2118 
2119 	if (NLGRPSZ(tbl->groups) < NLGRPSZ(groups)) {
2120 		new = kzalloc(sizeof(*new) + NLGRPSZ(groups), GFP_ATOMIC);
2121 		if (!new)
2122 			return -ENOMEM;
2123 		old = nl_deref_protected(tbl->listeners);
2124 		memcpy(new->masks, old->masks, NLGRPSZ(tbl->groups));
2125 		rcu_assign_pointer(tbl->listeners, new);
2126 
2127 		kfree_rcu(old, rcu);
2128 	}
2129 	tbl->groups = groups;
2130 
2131 	return 0;
2132 }
2133 
2134 /**
2135  * netlink_change_ngroups - change number of multicast groups
2136  *
2137  * This changes the number of multicast groups that are available
2138  * on a certain netlink family. Note that it is not possible to
2139  * change the number of groups to below 32. Also note that it does
2140  * not implicitly clear listeners from groups that are removed when
2141  * the number of groups is reduced.
2142  *
2143  * @sk: The kernel netlink socket, as returned by netlink_kernel_create().
2144  * @groups: The new number of groups.
2145  */
2146 int netlink_change_ngroups(struct sock *sk, unsigned int groups)
2147 {
2148 	int err;
2149 
2150 	netlink_table_grab();
2151 	err = __netlink_change_ngroups(sk, groups);
2152 	netlink_table_ungrab();
2153 
2154 	return err;
2155 }
2156 
2157 void __netlink_clear_multicast_users(struct sock *ksk, unsigned int group)
2158 {
2159 	struct sock *sk;
2160 	struct netlink_table *tbl = &nl_table[ksk->sk_protocol];
2161 	struct hlist_node *tmp;
2162 
2163 	sk_for_each_bound_safe(sk, tmp, &tbl->mc_list)
2164 		netlink_update_socket_mc(nlk_sk(sk), group, 0);
2165 }
2166 
2167 struct nlmsghdr *
2168 __nlmsg_put(struct sk_buff *skb, u32 portid, u32 seq, int type, int len, int flags)
2169 {
2170 	struct nlmsghdr *nlh;
2171 	int size = nlmsg_msg_size(len);
2172 
2173 	nlh = skb_put(skb, NLMSG_ALIGN(size));
2174 	nlh->nlmsg_type = type;
2175 	nlh->nlmsg_len = size;
2176 	nlh->nlmsg_flags = flags;
2177 	nlh->nlmsg_pid = portid;
2178 	nlh->nlmsg_seq = seq;
2179 	if (!__builtin_constant_p(size) || NLMSG_ALIGN(size) - size != 0)
2180 		memset(nlmsg_data(nlh) + len, 0, NLMSG_ALIGN(size) - size);
2181 	return nlh;
2182 }
2183 EXPORT_SYMBOL(__nlmsg_put);
2184 
2185 static size_t
2186 netlink_ack_tlv_len(struct netlink_sock *nlk, int err,
2187 		    const struct netlink_ext_ack *extack)
2188 {
2189 	size_t tlvlen;
2190 
2191 	if (!extack || !test_bit(NETLINK_F_EXT_ACK, &nlk->flags))
2192 		return 0;
2193 
2194 	tlvlen = 0;
2195 	if (extack->_msg)
2196 		tlvlen += nla_total_size(strlen(extack->_msg) + 1);
2197 	if (extack->cookie_len)
2198 		tlvlen += nla_total_size(extack->cookie_len);
2199 
2200 	/* Following attributes are only reported as error (not warning) */
2201 	if (!err)
2202 		return tlvlen;
2203 
2204 	if (extack->bad_attr)
2205 		tlvlen += nla_total_size(sizeof(u32));
2206 	if (extack->policy)
2207 		tlvlen += netlink_policy_dump_attr_size_estimate(extack->policy);
2208 	if (extack->miss_type)
2209 		tlvlen += nla_total_size(sizeof(u32));
2210 	if (extack->miss_nest)
2211 		tlvlen += nla_total_size(sizeof(u32));
2212 
2213 	return tlvlen;
2214 }
2215 
2216 static bool nlmsg_check_in_payload(const struct nlmsghdr *nlh, const void *addr)
2217 {
2218 	return !WARN_ON(addr < nlmsg_data(nlh) ||
2219 			addr - (const void *) nlh >= nlh->nlmsg_len);
2220 }
2221 
2222 static void
2223 netlink_ack_tlv_fill(struct sk_buff *skb, const struct nlmsghdr *nlh, int err,
2224 		     const struct netlink_ext_ack *extack)
2225 {
2226 	if (extack->_msg)
2227 		WARN_ON(nla_put_string(skb, NLMSGERR_ATTR_MSG, extack->_msg));
2228 	if (extack->cookie_len)
2229 		WARN_ON(nla_put(skb, NLMSGERR_ATTR_COOKIE,
2230 				extack->cookie_len, extack->cookie));
2231 
2232 	if (!err)
2233 		return;
2234 
2235 	if (extack->bad_attr && nlmsg_check_in_payload(nlh, extack->bad_attr))
2236 		WARN_ON(nla_put_u32(skb, NLMSGERR_ATTR_OFFS,
2237 				    (u8 *)extack->bad_attr - (const u8 *)nlh));
2238 	if (extack->policy)
2239 		netlink_policy_dump_write_attr(skb, extack->policy,
2240 					       NLMSGERR_ATTR_POLICY);
2241 	if (extack->miss_type)
2242 		WARN_ON(nla_put_u32(skb, NLMSGERR_ATTR_MISS_TYPE,
2243 				    extack->miss_type));
2244 	if (extack->miss_nest && nlmsg_check_in_payload(nlh, extack->miss_nest))
2245 		WARN_ON(nla_put_u32(skb, NLMSGERR_ATTR_MISS_NEST,
2246 				    (u8 *)extack->miss_nest - (const u8 *)nlh));
2247 }
2248 
2249 /*
2250  * It looks a bit ugly.
2251  * It would be better to create kernel thread.
2252  */
2253 
2254 static int netlink_dump_done(struct netlink_sock *nlk, struct sk_buff *skb,
2255 			     struct netlink_callback *cb,
2256 			     struct netlink_ext_ack *extack)
2257 {
2258 	struct nlmsghdr *nlh;
2259 	size_t extack_len;
2260 
2261 	nlh = nlmsg_put_answer(skb, cb, NLMSG_DONE, sizeof(nlk->dump_done_errno),
2262 			       NLM_F_MULTI | cb->answer_flags);
2263 	if (WARN_ON(!nlh))
2264 		return -ENOBUFS;
2265 
2266 	nl_dump_check_consistent(cb, nlh);
2267 	memcpy(nlmsg_data(nlh), &nlk->dump_done_errno, sizeof(nlk->dump_done_errno));
2268 
2269 	extack_len = netlink_ack_tlv_len(nlk, nlk->dump_done_errno, extack);
2270 	if (extack_len) {
2271 		nlh->nlmsg_flags |= NLM_F_ACK_TLVS;
2272 		if (skb_tailroom(skb) >= extack_len) {
2273 			netlink_ack_tlv_fill(skb, cb->nlh,
2274 					     nlk->dump_done_errno, extack);
2275 			nlmsg_end(skb, nlh);
2276 		}
2277 	}
2278 
2279 	return 0;
2280 }
2281 
2282 static int netlink_dump(struct sock *sk, bool lock_taken)
2283 {
2284 	struct netlink_sock *nlk = nlk_sk(sk);
2285 	struct netlink_ext_ack extack = {};
2286 	struct netlink_callback *cb;
2287 	struct sk_buff *skb = NULL;
2288 	unsigned int rmem, rcvbuf;
2289 	size_t max_recvmsg_len;
2290 	struct module *module;
2291 	int err = -ENOBUFS;
2292 	int alloc_min_size;
2293 	int alloc_size;
2294 
2295 	if (!lock_taken)
2296 		mutex_lock(&nlk->nl_cb_mutex);
2297 	if (!nlk->cb_running) {
2298 		err = -EINVAL;
2299 		goto errout_skb;
2300 	}
2301 
2302 	/* NLMSG_GOODSIZE is small to avoid high order allocations being
2303 	 * required, but it makes sense to _attempt_ a 32KiB allocation
2304 	 * to reduce number of system calls on dump operations, if user
2305 	 * ever provided a big enough buffer.
2306 	 */
2307 	cb = &nlk->cb;
2308 	alloc_min_size = max_t(int, cb->min_dump_alloc, NLMSG_GOODSIZE);
2309 
2310 	max_recvmsg_len = READ_ONCE(nlk->max_recvmsg_len);
2311 	if (alloc_min_size < max_recvmsg_len) {
2312 		alloc_size = max_recvmsg_len;
2313 		skb = alloc_skb(alloc_size,
2314 				(GFP_KERNEL & ~__GFP_DIRECT_RECLAIM) |
2315 				__GFP_NOWARN | __GFP_NORETRY);
2316 	}
2317 	if (!skb) {
2318 		alloc_size = alloc_min_size;
2319 		skb = alloc_skb(alloc_size, GFP_KERNEL);
2320 	}
2321 	if (!skb)
2322 		goto errout_skb;
2323 
2324 	rcvbuf = READ_ONCE(sk->sk_rcvbuf);
2325 	rmem = atomic_add_return(skb->truesize, &sk->sk_rmem_alloc);
2326 	if (rmem != skb->truesize && rmem >= rcvbuf) {
2327 		atomic_sub(skb->truesize, &sk->sk_rmem_alloc);
2328 		goto errout_skb;
2329 	}
2330 
2331 	/* Trim skb to allocated size. User is expected to provide buffer as
2332 	 * large as max(min_dump_alloc, 32KiB (max_recvmsg_len capped at
2333 	 * netlink_recvmsg())). dump will pack as many smaller messages as
2334 	 * could fit within the allocated skb. skb is typically allocated
2335 	 * with larger space than required (could be as much as near 2x the
2336 	 * requested size with align to next power of 2 approach). Allowing
2337 	 * dump to use the excess space makes it difficult for a user to have a
2338 	 * reasonable static buffer based on the expected largest dump of a
2339 	 * single netdev. The outcome is MSG_TRUNC error.
2340 	 */
2341 	skb_reserve(skb, skb_tailroom(skb) - alloc_size);
2342 
2343 	/* Make sure malicious BPF programs can not read unitialized memory
2344 	 * from skb->head -> skb->data
2345 	 */
2346 	skb_reset_network_header(skb);
2347 	skb_reset_mac_header(skb);
2348 
2349 	netlink_skb_set_owner_r(skb, sk);
2350 
2351 	if (nlk->dump_done_errno > 0) {
2352 		cb->extack = &extack;
2353 
2354 		nlk->dump_done_errno = cb->dump(skb, cb);
2355 
2356 		/* EMSGSIZE plus something already in the skb means
2357 		 * that there's more to dump but current skb has filled up.
2358 		 * If the callback really wants to return EMSGSIZE to user space
2359 		 * it needs to do so again, on the next cb->dump() call,
2360 		 * without putting data in the skb.
2361 		 */
2362 		if (nlk->dump_done_errno == -EMSGSIZE && skb->len)
2363 			nlk->dump_done_errno = skb->len;
2364 
2365 		cb->extack = NULL;
2366 	}
2367 
2368 	if (nlk->dump_done_errno > 0 ||
2369 	    skb_tailroom(skb) < nlmsg_total_size(sizeof(nlk->dump_done_errno))) {
2370 		mutex_unlock(&nlk->nl_cb_mutex);
2371 
2372 		if (sk_filter(sk, skb))
2373 			kfree_skb(skb);
2374 		else
2375 			__netlink_sendskb(sk, skb);
2376 		return 0;
2377 	}
2378 
2379 	if (netlink_dump_done(nlk, skb, cb, &extack))
2380 		goto errout_skb;
2381 
2382 #ifdef CONFIG_COMPAT_NETLINK_MESSAGES
2383 	/* frag_list skb's data is used for compat tasks
2384 	 * and the regular skb's data for normal (non-compat) tasks.
2385 	 * See netlink_recvmsg().
2386 	 */
2387 	if (unlikely(skb_shinfo(skb)->frag_list)) {
2388 		if (netlink_dump_done(nlk, skb_shinfo(skb)->frag_list, cb, &extack))
2389 			goto errout_skb;
2390 	}
2391 #endif
2392 
2393 	if (sk_filter(sk, skb))
2394 		kfree_skb(skb);
2395 	else
2396 		__netlink_sendskb(sk, skb);
2397 
2398 	if (cb->done)
2399 		cb->done(cb);
2400 
2401 	WRITE_ONCE(nlk->cb_running, false);
2402 	module = cb->module;
2403 	skb = cb->skb;
2404 	mutex_unlock(&nlk->nl_cb_mutex);
2405 	module_put(module);
2406 	consume_skb(skb);
2407 	return 0;
2408 
2409 errout_skb:
2410 	mutex_unlock(&nlk->nl_cb_mutex);
2411 	kfree_skb(skb);
2412 	return err;
2413 }
2414 
2415 int __netlink_dump_start(struct sock *ssk, struct sk_buff *skb,
2416 			 const struct nlmsghdr *nlh,
2417 			 struct netlink_dump_control *control)
2418 {
2419 	struct netlink_callback *cb;
2420 	struct netlink_sock *nlk;
2421 	struct sock *sk;
2422 	int ret;
2423 
2424 	refcount_inc(&skb->users);
2425 
2426 	sk = netlink_lookup(sock_net(ssk), ssk->sk_protocol, NETLINK_CB(skb).portid);
2427 	if (sk == NULL) {
2428 		ret = -ECONNREFUSED;
2429 		goto error_free;
2430 	}
2431 
2432 	nlk = nlk_sk(sk);
2433 	mutex_lock(&nlk->nl_cb_mutex);
2434 	/* A dump is in progress... */
2435 	if (nlk->cb_running) {
2436 		ret = -EBUSY;
2437 		goto error_unlock;
2438 	}
2439 	/* add reference of module which cb->dump belongs to */
2440 	if (!try_module_get(control->module)) {
2441 		ret = -EPROTONOSUPPORT;
2442 		goto error_unlock;
2443 	}
2444 
2445 	cb = &nlk->cb;
2446 	memset(cb, 0, sizeof(*cb));
2447 	cb->dump = control->dump;
2448 	cb->done = control->done;
2449 	cb->nlh = nlh;
2450 	cb->data = control->data;
2451 	cb->module = control->module;
2452 	cb->min_dump_alloc = control->min_dump_alloc;
2453 	cb->flags = control->flags;
2454 	cb->skb = skb;
2455 
2456 	cb->strict_check = nlk_test_bit(STRICT_CHK, NETLINK_CB(skb).sk);
2457 
2458 	if (control->start) {
2459 		cb->extack = control->extack;
2460 		ret = control->start(cb);
2461 		cb->extack = NULL;
2462 		if (ret)
2463 			goto error_put;
2464 	}
2465 
2466 	WRITE_ONCE(nlk->cb_running, true);
2467 	nlk->dump_done_errno = INT_MAX;
2468 
2469 	ret = netlink_dump(sk, true);
2470 
2471 	sock_put(sk);
2472 
2473 	if (ret)
2474 		return ret;
2475 
2476 	/* We successfully started a dump, by returning -EINTR we
2477 	 * signal not to send ACK even if it was requested.
2478 	 */
2479 	return -EINTR;
2480 
2481 error_put:
2482 	module_put(control->module);
2483 error_unlock:
2484 	sock_put(sk);
2485 	mutex_unlock(&nlk->nl_cb_mutex);
2486 error_free:
2487 	kfree_skb(skb);
2488 	return ret;
2489 }
2490 EXPORT_SYMBOL(__netlink_dump_start);
2491 
2492 void netlink_ack(struct sk_buff *in_skb, struct nlmsghdr *nlh, int err,
2493 		 const struct netlink_ext_ack *extack)
2494 {
2495 	struct sk_buff *skb;
2496 	struct nlmsghdr *rep;
2497 	struct nlmsgerr *errmsg;
2498 	size_t payload = sizeof(*errmsg);
2499 	struct netlink_sock *nlk = nlk_sk(NETLINK_CB(in_skb).sk);
2500 	unsigned int flags = 0;
2501 	size_t tlvlen;
2502 
2503 	/* Error messages get the original request appended, unless the user
2504 	 * requests to cap the error message, and get extra error data if
2505 	 * requested.
2506 	 */
2507 	if (err && !test_bit(NETLINK_F_CAP_ACK, &nlk->flags))
2508 		payload += nlmsg_len(nlh);
2509 	else
2510 		flags |= NLM_F_CAPPED;
2511 
2512 	tlvlen = netlink_ack_tlv_len(nlk, err, extack);
2513 	if (tlvlen)
2514 		flags |= NLM_F_ACK_TLVS;
2515 
2516 	skb = nlmsg_new(payload + tlvlen, GFP_KERNEL);
2517 	if (!skb)
2518 		goto err_skb;
2519 
2520 	rep = nlmsg_put(skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq,
2521 			NLMSG_ERROR, sizeof(*errmsg), flags);
2522 	if (!rep)
2523 		goto err_bad_put;
2524 	errmsg = nlmsg_data(rep);
2525 	errmsg->error = err;
2526 	errmsg->msg = *nlh;
2527 
2528 	if (!(flags & NLM_F_CAPPED)) {
2529 		if (!nlmsg_append(skb, nlmsg_len(nlh)))
2530 			goto err_bad_put;
2531 
2532 		memcpy(nlmsg_data(&errmsg->msg), nlmsg_data(nlh),
2533 		       nlmsg_len(nlh));
2534 	}
2535 
2536 	if (tlvlen)
2537 		netlink_ack_tlv_fill(skb, nlh, err, extack);
2538 
2539 	nlmsg_end(skb, rep);
2540 
2541 	nlmsg_unicast(in_skb->sk, skb, NETLINK_CB(in_skb).portid);
2542 
2543 	return;
2544 
2545 err_bad_put:
2546 	nlmsg_free(skb);
2547 err_skb:
2548 	WRITE_ONCE(NETLINK_CB(in_skb).sk->sk_err, ENOBUFS);
2549 	sk_error_report(NETLINK_CB(in_skb).sk);
2550 }
2551 EXPORT_SYMBOL(netlink_ack);
2552 
2553 int netlink_rcv_skb(struct sk_buff *skb, int (*cb)(struct sk_buff *,
2554 						   struct nlmsghdr *,
2555 						   struct netlink_ext_ack *))
2556 {
2557 	struct netlink_ext_ack extack;
2558 	struct nlmsghdr *nlh;
2559 	int err;
2560 
2561 	while (skb->len >= nlmsg_total_size(0)) {
2562 		int msglen;
2563 
2564 		memset(&extack, 0, sizeof(extack));
2565 		nlh = nlmsg_hdr(skb);
2566 		err = 0;
2567 
2568 		if (nlh->nlmsg_len < NLMSG_HDRLEN || skb->len < nlh->nlmsg_len)
2569 			return 0;
2570 
2571 		/* Only requests are handled by the kernel */
2572 		if (!(nlh->nlmsg_flags & NLM_F_REQUEST))
2573 			goto ack;
2574 
2575 		/* Skip control messages */
2576 		if (nlh->nlmsg_type < NLMSG_MIN_TYPE)
2577 			goto ack;
2578 
2579 		err = cb(skb, nlh, &extack);
2580 		if (err == -EINTR)
2581 			goto skip;
2582 
2583 ack:
2584 		if (nlh->nlmsg_flags & NLM_F_ACK || err)
2585 			netlink_ack(skb, nlh, err, &extack);
2586 
2587 skip:
2588 		msglen = NLMSG_ALIGN(nlh->nlmsg_len);
2589 		if (msglen > skb->len)
2590 			msglen = skb->len;
2591 		skb_pull(skb, msglen);
2592 	}
2593 
2594 	return 0;
2595 }
2596 EXPORT_SYMBOL(netlink_rcv_skb);
2597 
2598 /**
2599  * nlmsg_notify - send a notification netlink message
2600  * @sk: netlink socket to use
2601  * @skb: notification message
2602  * @portid: destination netlink portid for reports or 0
2603  * @group: destination multicast group or 0
2604  * @report: 1 to report back, 0 to disable
2605  * @flags: allocation flags
2606  */
2607 int nlmsg_notify(struct sock *sk, struct sk_buff *skb, u32 portid,
2608 		 unsigned int group, int report, gfp_t flags)
2609 {
2610 	int err = 0;
2611 
2612 	if (group) {
2613 		int exclude_portid = 0;
2614 
2615 		if (report) {
2616 			refcount_inc(&skb->users);
2617 			exclude_portid = portid;
2618 		}
2619 
2620 		/* errors reported via destination sk->sk_err, but propagate
2621 		 * delivery errors if NETLINK_BROADCAST_ERROR flag is set */
2622 		err = nlmsg_multicast(sk, skb, exclude_portid, group, flags);
2623 		if (err == -ESRCH)
2624 			err = 0;
2625 	}
2626 
2627 	if (report) {
2628 		int err2;
2629 
2630 		err2 = nlmsg_unicast(sk, skb, portid);
2631 		if (!err)
2632 			err = err2;
2633 	}
2634 
2635 	return err;
2636 }
2637 EXPORT_SYMBOL(nlmsg_notify);
2638 
2639 #ifdef CONFIG_PROC_FS
2640 struct nl_seq_iter {
2641 	struct seq_net_private p;
2642 	struct rhashtable_iter hti;
2643 	int link;
2644 };
2645 
2646 static void netlink_walk_start(struct nl_seq_iter *iter)
2647 {
2648 	rhashtable_walk_enter(&nl_table[iter->link].hash, &iter->hti);
2649 	rhashtable_walk_start(&iter->hti);
2650 }
2651 
2652 static void netlink_walk_stop(struct nl_seq_iter *iter)
2653 {
2654 	rhashtable_walk_stop(&iter->hti);
2655 	rhashtable_walk_exit(&iter->hti);
2656 }
2657 
2658 static void *__netlink_seq_next(struct seq_file *seq)
2659 {
2660 	struct nl_seq_iter *iter = seq->private;
2661 	struct netlink_sock *nlk;
2662 
2663 	do {
2664 		for (;;) {
2665 			nlk = rhashtable_walk_next(&iter->hti);
2666 
2667 			if (IS_ERR(nlk)) {
2668 				if (PTR_ERR(nlk) == -EAGAIN)
2669 					continue;
2670 
2671 				return nlk;
2672 			}
2673 
2674 			if (nlk)
2675 				break;
2676 
2677 			netlink_walk_stop(iter);
2678 			if (++iter->link >= MAX_LINKS)
2679 				return NULL;
2680 
2681 			netlink_walk_start(iter);
2682 		}
2683 	} while (sock_net(&nlk->sk) != seq_file_net(seq));
2684 
2685 	return nlk;
2686 }
2687 
2688 static void *netlink_seq_start(struct seq_file *seq, loff_t *posp)
2689 	__acquires(RCU)
2690 {
2691 	struct nl_seq_iter *iter = seq->private;
2692 	void *obj = SEQ_START_TOKEN;
2693 	loff_t pos;
2694 
2695 	iter->link = 0;
2696 
2697 	netlink_walk_start(iter);
2698 
2699 	for (pos = *posp; pos && obj && !IS_ERR(obj); pos--)
2700 		obj = __netlink_seq_next(seq);
2701 
2702 	return obj;
2703 }
2704 
2705 static void *netlink_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2706 {
2707 	++*pos;
2708 	return __netlink_seq_next(seq);
2709 }
2710 
2711 static void netlink_native_seq_stop(struct seq_file *seq, void *v)
2712 {
2713 	struct nl_seq_iter *iter = seq->private;
2714 
2715 	if (iter->link >= MAX_LINKS)
2716 		return;
2717 
2718 	netlink_walk_stop(iter);
2719 }
2720 
2721 
2722 static int netlink_native_seq_show(struct seq_file *seq, void *v)
2723 {
2724 	if (v == SEQ_START_TOKEN) {
2725 		seq_puts(seq,
2726 			 "sk               Eth Pid        Groups   "
2727 			 "Rmem     Wmem     Dump  Locks    Drops    Inode\n");
2728 	} else {
2729 		struct sock *s = v;
2730 		struct netlink_sock *nlk = nlk_sk(s);
2731 		const unsigned long *groups;
2732 
2733 		/* Lockless read : netlink_realloc_groups() can change
2734 		 * nlk->groups under us. The old buffer is freed after an
2735 		 * RCU grace period, and this walk is RCU protected.
2736 		 */
2737 		groups = READ_ONCE(nlk->groups);
2738 
2739 		seq_printf(seq, "%pK %-3d %-10u %08x %-8d %-8d %-5d %-8d %-8u %-8llu\n",
2740 			   s,
2741 			   s->sk_protocol,
2742 			   nlk->portid,
2743 			   groups ? (u32)groups[0] : 0,
2744 			   sk_rmem_alloc_get(s),
2745 			   sk_wmem_alloc_get(s),
2746 			   READ_ONCE(nlk->cb_running),
2747 			   refcount_read(&s->sk_refcnt),
2748 			   sk_drops_read(s),
2749 			   sock_i_ino(s)
2750 			);
2751 
2752 	}
2753 	return 0;
2754 }
2755 
2756 #ifdef CONFIG_BPF_SYSCALL
2757 struct bpf_iter__netlink {
2758 	__bpf_md_ptr(struct bpf_iter_meta *, meta);
2759 	__bpf_md_ptr(struct netlink_sock *, sk);
2760 };
2761 
2762 DEFINE_BPF_ITER_FUNC(netlink, struct bpf_iter_meta *meta, struct netlink_sock *sk)
2763 
2764 static int netlink_prog_seq_show(struct bpf_prog *prog,
2765 				  struct bpf_iter_meta *meta,
2766 				  void *v)
2767 {
2768 	struct bpf_iter__netlink ctx;
2769 
2770 	meta->seq_num--;  /* skip SEQ_START_TOKEN */
2771 	ctx.meta = meta;
2772 	ctx.sk = nlk_sk((struct sock *)v);
2773 	return bpf_iter_run_prog(prog, &ctx);
2774 }
2775 
2776 static int netlink_seq_show(struct seq_file *seq, void *v)
2777 {
2778 	struct bpf_iter_meta meta;
2779 	struct bpf_prog *prog;
2780 
2781 	meta.seq = seq;
2782 	prog = bpf_iter_get_info(&meta, false);
2783 	if (!prog)
2784 		return netlink_native_seq_show(seq, v);
2785 
2786 	if (v != SEQ_START_TOKEN)
2787 		return netlink_prog_seq_show(prog, &meta, v);
2788 
2789 	return 0;
2790 }
2791 
2792 static void netlink_seq_stop(struct seq_file *seq, void *v)
2793 {
2794 	struct bpf_iter_meta meta;
2795 	struct bpf_prog *prog;
2796 
2797 	if (!v) {
2798 		meta.seq = seq;
2799 		prog = bpf_iter_get_info(&meta, true);
2800 		if (prog)
2801 			(void)netlink_prog_seq_show(prog, &meta, v);
2802 	}
2803 
2804 	netlink_native_seq_stop(seq, v);
2805 }
2806 #else
2807 static int netlink_seq_show(struct seq_file *seq, void *v)
2808 {
2809 	return netlink_native_seq_show(seq, v);
2810 }
2811 
2812 static void netlink_seq_stop(struct seq_file *seq, void *v)
2813 {
2814 	netlink_native_seq_stop(seq, v);
2815 }
2816 #endif
2817 
2818 static const struct seq_operations netlink_seq_ops = {
2819 	.start  = netlink_seq_start,
2820 	.next   = netlink_seq_next,
2821 	.stop   = netlink_seq_stop,
2822 	.show   = netlink_seq_show,
2823 };
2824 #endif
2825 
2826 int netlink_register_notifier(struct notifier_block *nb)
2827 {
2828 	return blocking_notifier_chain_register(&netlink_chain, nb);
2829 }
2830 EXPORT_SYMBOL(netlink_register_notifier);
2831 
2832 int netlink_unregister_notifier(struct notifier_block *nb)
2833 {
2834 	return blocking_notifier_chain_unregister(&netlink_chain, nb);
2835 }
2836 EXPORT_SYMBOL(netlink_unregister_notifier);
2837 
2838 static const struct proto_ops netlink_ops = {
2839 	.family =	PF_NETLINK,
2840 	.owner =	THIS_MODULE,
2841 	.release =	netlink_release,
2842 	.bind =		netlink_bind,
2843 	.connect =	netlink_connect,
2844 	.socketpair =	sock_no_socketpair,
2845 	.accept =	sock_no_accept,
2846 	.getname =	netlink_getname,
2847 	.poll =		datagram_poll,
2848 	.ioctl =	netlink_ioctl,
2849 	.listen =	sock_no_listen,
2850 	.shutdown =	sock_no_shutdown,
2851 	.setsockopt =	netlink_setsockopt,
2852 	.getsockopt_iter = netlink_getsockopt,
2853 	.sendmsg =	netlink_sendmsg,
2854 	.recvmsg =	netlink_recvmsg,
2855 	.mmap =		sock_no_mmap,
2856 };
2857 
2858 static const struct net_proto_family netlink_family_ops = {
2859 	.family = PF_NETLINK,
2860 	.create = netlink_create,
2861 	.owner	= THIS_MODULE,	/* for consistency 8) */
2862 };
2863 
2864 static int __net_init netlink_net_init(struct net *net)
2865 {
2866 #ifdef CONFIG_PROC_FS
2867 	if (!proc_create_net("netlink", 0, net->proc_net, &netlink_seq_ops,
2868 			sizeof(struct nl_seq_iter)))
2869 		return -ENOMEM;
2870 #endif
2871 	return 0;
2872 }
2873 
2874 static void __net_exit netlink_net_exit(struct net *net)
2875 {
2876 #ifdef CONFIG_PROC_FS
2877 	remove_proc_entry("netlink", net->proc_net);
2878 #endif
2879 }
2880 
2881 static void __init netlink_add_usersock_entry(void)
2882 {
2883 	struct listeners *listeners;
2884 	int groups = 32;
2885 
2886 	listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
2887 	if (!listeners)
2888 		panic("netlink_add_usersock_entry: Cannot allocate listeners\n");
2889 
2890 	netlink_table_grab();
2891 
2892 	nl_table[NETLINK_USERSOCK].groups = groups;
2893 	rcu_assign_pointer(nl_table[NETLINK_USERSOCK].listeners, listeners);
2894 	nl_table[NETLINK_USERSOCK].module = THIS_MODULE;
2895 	nl_table[NETLINK_USERSOCK].registered = 1;
2896 	nl_table[NETLINK_USERSOCK].flags = NL_CFG_F_NONROOT_SEND;
2897 
2898 	netlink_table_ungrab();
2899 }
2900 
2901 static struct pernet_operations __net_initdata netlink_net_ops = {
2902 	.init = netlink_net_init,
2903 	.exit = netlink_net_exit,
2904 };
2905 
2906 static inline u32 netlink_hash(const void *data, u32 len, u32 seed)
2907 {
2908 	const struct netlink_sock *nlk = data;
2909 	struct netlink_compare_arg arg;
2910 
2911 	netlink_compare_arg_init(&arg, sock_net(&nlk->sk), nlk->portid);
2912 	return jhash2((u32 *)&arg, netlink_compare_arg_len / sizeof(u32), seed);
2913 }
2914 
2915 static const struct rhashtable_params netlink_rhashtable_params = {
2916 	.head_offset = offsetof(struct netlink_sock, node),
2917 	.key_len = netlink_compare_arg_len,
2918 	.obj_hashfn = netlink_hash,
2919 	.obj_cmpfn = netlink_compare,
2920 	.automatic_shrinking = true,
2921 };
2922 
2923 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
2924 BTF_ID_LIST_SINGLE(btf_netlink_sock_id, struct, netlink_sock)
2925 
2926 static const struct bpf_iter_seq_info netlink_seq_info = {
2927 	.seq_ops		= &netlink_seq_ops,
2928 	.init_seq_private	= bpf_iter_init_seq_net,
2929 	.fini_seq_private	= bpf_iter_fini_seq_net,
2930 	.seq_priv_size		= sizeof(struct nl_seq_iter),
2931 };
2932 
2933 static struct bpf_iter_reg netlink_reg_info = {
2934 	.target			= "netlink",
2935 	.ctx_arg_info_size	= 1,
2936 	.ctx_arg_info		= {
2937 		{ offsetof(struct bpf_iter__netlink, sk),
2938 		  PTR_TO_BTF_ID_OR_NULL },
2939 	},
2940 	.seq_info		= &netlink_seq_info,
2941 };
2942 
2943 static int __init bpf_iter_register(void)
2944 {
2945 	netlink_reg_info.ctx_arg_info[0].btf_id = *btf_netlink_sock_id;
2946 	return bpf_iter_reg_target(&netlink_reg_info);
2947 }
2948 #endif
2949 
2950 static int __init netlink_proto_init(void)
2951 {
2952 	int i;
2953 	int err = proto_register(&netlink_proto, 0);
2954 
2955 	if (err != 0)
2956 		goto out;
2957 
2958 #if defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
2959 	err = bpf_iter_register();
2960 	if (err)
2961 		goto out;
2962 #endif
2963 
2964 	BUILD_BUG_ON(sizeof(struct netlink_skb_parms) > sizeof_field(struct sk_buff, cb));
2965 
2966 	nl_table = kzalloc_objs(*nl_table, MAX_LINKS);
2967 	if (!nl_table)
2968 		goto panic;
2969 
2970 	for (i = 0; i < MAX_LINKS; i++) {
2971 		if (rhashtable_init(&nl_table[i].hash,
2972 				    &netlink_rhashtable_params) < 0)
2973 			goto panic;
2974 	}
2975 
2976 	netlink_add_usersock_entry();
2977 
2978 	sock_register(&netlink_family_ops);
2979 	register_pernet_subsys(&netlink_net_ops);
2980 	register_pernet_subsys(&netlink_tap_net_ops);
2981 	/* The netlink device handler may be needed early. */
2982 	rtnetlink_init();
2983 out:
2984 	return err;
2985 panic:
2986 	panic("netlink_init: Cannot allocate nl_table\n");
2987 }
2988 
2989 core_initcall(netlink_proto_init);
2990