xref: /linux/net/netlink/af_netlink.c (revision f3d9478b2ce468c3115b02ecae7e975990697f15)
1 /*
2  * NETLINK      Kernel-user communication protocol.
3  *
4  * 		Authors:	Alan Cox <alan@redhat.com>
5  * 				Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
6  *
7  *		This program is free software; you can redistribute it and/or
8  *		modify it under the terms of the GNU General Public License
9  *		as published by the Free Software Foundation; either version
10  *		2 of the License, or (at your option) any later version.
11  *
12  * Tue Jun 26 14:36:48 MEST 2001 Herbert "herp" Rosmanith
13  *                               added netlink_proto_exit
14  * Tue Jan 22 18:32:44 BRST 2002 Arnaldo C. de Melo <acme@conectiva.com.br>
15  * 				 use nlk_sk, as sk->protinfo is on a diet 8)
16  * Fri Jul 22 19:51:12 MEST 2005 Harald Welte <laforge@gnumonks.org>
17  * 				 - inc module use count of module that owns
18  * 				   the kernel socket in case userspace opens
19  * 				   socket of same protocol
20  * 				 - remove all module support, since netlink is
21  * 				   mandatory if CONFIG_NET=y these days
22  */
23 
24 #include <linux/config.h>
25 #include <linux/module.h>
26 
27 #include <linux/capability.h>
28 #include <linux/kernel.h>
29 #include <linux/init.h>
30 #include <linux/signal.h>
31 #include <linux/sched.h>
32 #include <linux/errno.h>
33 #include <linux/string.h>
34 #include <linux/stat.h>
35 #include <linux/socket.h>
36 #include <linux/un.h>
37 #include <linux/fcntl.h>
38 #include <linux/termios.h>
39 #include <linux/sockios.h>
40 #include <linux/net.h>
41 #include <linux/fs.h>
42 #include <linux/slab.h>
43 #include <asm/uaccess.h>
44 #include <linux/skbuff.h>
45 #include <linux/netdevice.h>
46 #include <linux/rtnetlink.h>
47 #include <linux/proc_fs.h>
48 #include <linux/seq_file.h>
49 #include <linux/smp_lock.h>
50 #include <linux/notifier.h>
51 #include <linux/security.h>
52 #include <linux/jhash.h>
53 #include <linux/jiffies.h>
54 #include <linux/random.h>
55 #include <linux/bitops.h>
56 #include <linux/mm.h>
57 #include <linux/types.h>
58 #include <linux/audit.h>
59 #include <linux/selinux.h>
60 
61 #include <net/sock.h>
62 #include <net/scm.h>
63 #include <net/netlink.h>
64 
65 #define NLGRPSZ(x)	(ALIGN(x, sizeof(unsigned long) * 8) / 8)
66 
67 struct netlink_sock {
68 	/* struct sock has to be the first member of netlink_sock */
69 	struct sock		sk;
70 	u32			pid;
71 	u32			dst_pid;
72 	u32			dst_group;
73 	u32			flags;
74 	u32			subscriptions;
75 	u32			ngroups;
76 	unsigned long		*groups;
77 	unsigned long		state;
78 	wait_queue_head_t	wait;
79 	struct netlink_callback	*cb;
80 	spinlock_t		cb_lock;
81 	void			(*data_ready)(struct sock *sk, int bytes);
82 	struct module		*module;
83 };
84 
85 #define NETLINK_KERNEL_SOCKET	0x1
86 #define NETLINK_RECV_PKTINFO	0x2
87 
88 static inline struct netlink_sock *nlk_sk(struct sock *sk)
89 {
90 	return (struct netlink_sock *)sk;
91 }
92 
93 struct nl_pid_hash {
94 	struct hlist_head *table;
95 	unsigned long rehash_time;
96 
97 	unsigned int mask;
98 	unsigned int shift;
99 
100 	unsigned int entries;
101 	unsigned int max_shift;
102 
103 	u32 rnd;
104 };
105 
106 struct netlink_table {
107 	struct nl_pid_hash hash;
108 	struct hlist_head mc_list;
109 	unsigned long *listeners;
110 	unsigned int nl_nonroot;
111 	unsigned int groups;
112 	struct module *module;
113 	int registered;
114 };
115 
116 static struct netlink_table *nl_table;
117 
118 static DECLARE_WAIT_QUEUE_HEAD(nl_table_wait);
119 
120 static int netlink_dump(struct sock *sk);
121 static void netlink_destroy_callback(struct netlink_callback *cb);
122 
123 static DEFINE_RWLOCK(nl_table_lock);
124 static atomic_t nl_table_users = ATOMIC_INIT(0);
125 
126 static ATOMIC_NOTIFIER_HEAD(netlink_chain);
127 
128 static u32 netlink_group_mask(u32 group)
129 {
130 	return group ? 1 << (group - 1) : 0;
131 }
132 
133 static struct hlist_head *nl_pid_hashfn(struct nl_pid_hash *hash, u32 pid)
134 {
135 	return &hash->table[jhash_1word(pid, hash->rnd) & hash->mask];
136 }
137 
138 static void netlink_sock_destruct(struct sock *sk)
139 {
140 	skb_queue_purge(&sk->sk_receive_queue);
141 
142 	if (!sock_flag(sk, SOCK_DEAD)) {
143 		printk("Freeing alive netlink socket %p\n", sk);
144 		return;
145 	}
146 	BUG_TRAP(!atomic_read(&sk->sk_rmem_alloc));
147 	BUG_TRAP(!atomic_read(&sk->sk_wmem_alloc));
148 	BUG_TRAP(!nlk_sk(sk)->cb);
149 	BUG_TRAP(!nlk_sk(sk)->groups);
150 }
151 
152 /* This lock without WQ_FLAG_EXCLUSIVE is good on UP and it is _very_ bad on SMP.
153  * Look, when several writers sleep and reader wakes them up, all but one
154  * immediately hit write lock and grab all the cpus. Exclusive sleep solves
155  * this, _but_ remember, it adds useless work on UP machines.
156  */
157 
158 static void netlink_table_grab(void)
159 {
160 	write_lock_bh(&nl_table_lock);
161 
162 	if (atomic_read(&nl_table_users)) {
163 		DECLARE_WAITQUEUE(wait, current);
164 
165 		add_wait_queue_exclusive(&nl_table_wait, &wait);
166 		for(;;) {
167 			set_current_state(TASK_UNINTERRUPTIBLE);
168 			if (atomic_read(&nl_table_users) == 0)
169 				break;
170 			write_unlock_bh(&nl_table_lock);
171 			schedule();
172 			write_lock_bh(&nl_table_lock);
173 		}
174 
175 		__set_current_state(TASK_RUNNING);
176 		remove_wait_queue(&nl_table_wait, &wait);
177 	}
178 }
179 
180 static __inline__ void netlink_table_ungrab(void)
181 {
182 	write_unlock_bh(&nl_table_lock);
183 	wake_up(&nl_table_wait);
184 }
185 
186 static __inline__ void
187 netlink_lock_table(void)
188 {
189 	/* read_lock() synchronizes us to netlink_table_grab */
190 
191 	read_lock(&nl_table_lock);
192 	atomic_inc(&nl_table_users);
193 	read_unlock(&nl_table_lock);
194 }
195 
196 static __inline__ void
197 netlink_unlock_table(void)
198 {
199 	if (atomic_dec_and_test(&nl_table_users))
200 		wake_up(&nl_table_wait);
201 }
202 
203 static __inline__ struct sock *netlink_lookup(int protocol, u32 pid)
204 {
205 	struct nl_pid_hash *hash = &nl_table[protocol].hash;
206 	struct hlist_head *head;
207 	struct sock *sk;
208 	struct hlist_node *node;
209 
210 	read_lock(&nl_table_lock);
211 	head = nl_pid_hashfn(hash, pid);
212 	sk_for_each(sk, node, head) {
213 		if (nlk_sk(sk)->pid == pid) {
214 			sock_hold(sk);
215 			goto found;
216 		}
217 	}
218 	sk = NULL;
219 found:
220 	read_unlock(&nl_table_lock);
221 	return sk;
222 }
223 
224 static inline struct hlist_head *nl_pid_hash_alloc(size_t size)
225 {
226 	if (size <= PAGE_SIZE)
227 		return kmalloc(size, GFP_ATOMIC);
228 	else
229 		return (struct hlist_head *)
230 			__get_free_pages(GFP_ATOMIC, get_order(size));
231 }
232 
233 static inline void nl_pid_hash_free(struct hlist_head *table, size_t size)
234 {
235 	if (size <= PAGE_SIZE)
236 		kfree(table);
237 	else
238 		free_pages((unsigned long)table, get_order(size));
239 }
240 
241 static int nl_pid_hash_rehash(struct nl_pid_hash *hash, int grow)
242 {
243 	unsigned int omask, mask, shift;
244 	size_t osize, size;
245 	struct hlist_head *otable, *table;
246 	int i;
247 
248 	omask = mask = hash->mask;
249 	osize = size = (mask + 1) * sizeof(*table);
250 	shift = hash->shift;
251 
252 	if (grow) {
253 		if (++shift > hash->max_shift)
254 			return 0;
255 		mask = mask * 2 + 1;
256 		size *= 2;
257 	}
258 
259 	table = nl_pid_hash_alloc(size);
260 	if (!table)
261 		return 0;
262 
263 	memset(table, 0, size);
264 	otable = hash->table;
265 	hash->table = table;
266 	hash->mask = mask;
267 	hash->shift = shift;
268 	get_random_bytes(&hash->rnd, sizeof(hash->rnd));
269 
270 	for (i = 0; i <= omask; i++) {
271 		struct sock *sk;
272 		struct hlist_node *node, *tmp;
273 
274 		sk_for_each_safe(sk, node, tmp, &otable[i])
275 			__sk_add_node(sk, nl_pid_hashfn(hash, nlk_sk(sk)->pid));
276 	}
277 
278 	nl_pid_hash_free(otable, osize);
279 	hash->rehash_time = jiffies + 10 * 60 * HZ;
280 	return 1;
281 }
282 
283 static inline int nl_pid_hash_dilute(struct nl_pid_hash *hash, int len)
284 {
285 	int avg = hash->entries >> hash->shift;
286 
287 	if (unlikely(avg > 1) && nl_pid_hash_rehash(hash, 1))
288 		return 1;
289 
290 	if (unlikely(len > avg) && time_after(jiffies, hash->rehash_time)) {
291 		nl_pid_hash_rehash(hash, 0);
292 		return 1;
293 	}
294 
295 	return 0;
296 }
297 
298 static const struct proto_ops netlink_ops;
299 
300 static void
301 netlink_update_listeners(struct sock *sk)
302 {
303 	struct netlink_table *tbl = &nl_table[sk->sk_protocol];
304 	struct hlist_node *node;
305 	unsigned long mask;
306 	unsigned int i;
307 
308 	for (i = 0; i < NLGRPSZ(tbl->groups)/sizeof(unsigned long); i++) {
309 		mask = 0;
310 		sk_for_each_bound(sk, node, &tbl->mc_list)
311 			mask |= nlk_sk(sk)->groups[i];
312 		tbl->listeners[i] = mask;
313 	}
314 	/* this function is only called with the netlink table "grabbed", which
315 	 * makes sure updates are visible before bind or setsockopt return. */
316 }
317 
318 static int netlink_insert(struct sock *sk, u32 pid)
319 {
320 	struct nl_pid_hash *hash = &nl_table[sk->sk_protocol].hash;
321 	struct hlist_head *head;
322 	int err = -EADDRINUSE;
323 	struct sock *osk;
324 	struct hlist_node *node;
325 	int len;
326 
327 	netlink_table_grab();
328 	head = nl_pid_hashfn(hash, pid);
329 	len = 0;
330 	sk_for_each(osk, node, head) {
331 		if (nlk_sk(osk)->pid == pid)
332 			break;
333 		len++;
334 	}
335 	if (node)
336 		goto err;
337 
338 	err = -EBUSY;
339 	if (nlk_sk(sk)->pid)
340 		goto err;
341 
342 	err = -ENOMEM;
343 	if (BITS_PER_LONG > 32 && unlikely(hash->entries >= UINT_MAX))
344 		goto err;
345 
346 	if (len && nl_pid_hash_dilute(hash, len))
347 		head = nl_pid_hashfn(hash, pid);
348 	hash->entries++;
349 	nlk_sk(sk)->pid = pid;
350 	sk_add_node(sk, head);
351 	err = 0;
352 
353 err:
354 	netlink_table_ungrab();
355 	return err;
356 }
357 
358 static void netlink_remove(struct sock *sk)
359 {
360 	netlink_table_grab();
361 	if (sk_del_node_init(sk))
362 		nl_table[sk->sk_protocol].hash.entries--;
363 	if (nlk_sk(sk)->subscriptions)
364 		__sk_del_bind_node(sk);
365 	netlink_table_ungrab();
366 }
367 
368 static struct proto netlink_proto = {
369 	.name	  = "NETLINK",
370 	.owner	  = THIS_MODULE,
371 	.obj_size = sizeof(struct netlink_sock),
372 };
373 
374 static int __netlink_create(struct socket *sock, int protocol)
375 {
376 	struct sock *sk;
377 	struct netlink_sock *nlk;
378 
379 	sock->ops = &netlink_ops;
380 
381 	sk = sk_alloc(PF_NETLINK, GFP_KERNEL, &netlink_proto, 1);
382 	if (!sk)
383 		return -ENOMEM;
384 
385 	sock_init_data(sock, sk);
386 
387 	nlk = nlk_sk(sk);
388 	spin_lock_init(&nlk->cb_lock);
389 	init_waitqueue_head(&nlk->wait);
390 
391 	sk->sk_destruct = netlink_sock_destruct;
392 	sk->sk_protocol = protocol;
393 	return 0;
394 }
395 
396 static int netlink_create(struct socket *sock, int protocol)
397 {
398 	struct module *module = NULL;
399 	struct netlink_sock *nlk;
400 	unsigned int groups;
401 	int err = 0;
402 
403 	sock->state = SS_UNCONNECTED;
404 
405 	if (sock->type != SOCK_RAW && sock->type != SOCK_DGRAM)
406 		return -ESOCKTNOSUPPORT;
407 
408 	if (protocol<0 || protocol >= MAX_LINKS)
409 		return -EPROTONOSUPPORT;
410 
411 	netlink_lock_table();
412 #ifdef CONFIG_KMOD
413 	if (!nl_table[protocol].registered) {
414 		netlink_unlock_table();
415 		request_module("net-pf-%d-proto-%d", PF_NETLINK, protocol);
416 		netlink_lock_table();
417 	}
418 #endif
419 	if (nl_table[protocol].registered &&
420 	    try_module_get(nl_table[protocol].module))
421 		module = nl_table[protocol].module;
422 	groups = nl_table[protocol].groups;
423 	netlink_unlock_table();
424 
425 	if ((err = __netlink_create(sock, protocol)) < 0)
426 		goto out_module;
427 
428 	nlk = nlk_sk(sock->sk);
429 	nlk->module = module;
430 out:
431 	return err;
432 
433 out_module:
434 	module_put(module);
435 	goto out;
436 }
437 
438 static int netlink_release(struct socket *sock)
439 {
440 	struct sock *sk = sock->sk;
441 	struct netlink_sock *nlk;
442 
443 	if (!sk)
444 		return 0;
445 
446 	netlink_remove(sk);
447 	nlk = nlk_sk(sk);
448 
449 	spin_lock(&nlk->cb_lock);
450 	if (nlk->cb) {
451 		if (nlk->cb->done)
452 			nlk->cb->done(nlk->cb);
453 		netlink_destroy_callback(nlk->cb);
454 		nlk->cb = NULL;
455 	}
456 	spin_unlock(&nlk->cb_lock);
457 
458 	/* OK. Socket is unlinked, and, therefore,
459 	   no new packets will arrive */
460 
461 	sock_orphan(sk);
462 	sock->sk = NULL;
463 	wake_up_interruptible_all(&nlk->wait);
464 
465 	skb_queue_purge(&sk->sk_write_queue);
466 
467 	if (nlk->pid && !nlk->subscriptions) {
468 		struct netlink_notify n = {
469 						.protocol = sk->sk_protocol,
470 						.pid = nlk->pid,
471 					  };
472 		atomic_notifier_call_chain(&netlink_chain,
473 				NETLINK_URELEASE, &n);
474 	}
475 
476 	if (nlk->module)
477 		module_put(nlk->module);
478 
479 	netlink_table_grab();
480 	if (nlk->flags & NETLINK_KERNEL_SOCKET) {
481 		kfree(nl_table[sk->sk_protocol].listeners);
482 		nl_table[sk->sk_protocol].module = NULL;
483 		nl_table[sk->sk_protocol].registered = 0;
484 	} else if (nlk->subscriptions)
485 		netlink_update_listeners(sk);
486 	netlink_table_ungrab();
487 
488 	kfree(nlk->groups);
489 	nlk->groups = NULL;
490 
491 	sock_put(sk);
492 	return 0;
493 }
494 
495 static int netlink_autobind(struct socket *sock)
496 {
497 	struct sock *sk = sock->sk;
498 	struct nl_pid_hash *hash = &nl_table[sk->sk_protocol].hash;
499 	struct hlist_head *head;
500 	struct sock *osk;
501 	struct hlist_node *node;
502 	s32 pid = current->tgid;
503 	int err;
504 	static s32 rover = -4097;
505 
506 retry:
507 	cond_resched();
508 	netlink_table_grab();
509 	head = nl_pid_hashfn(hash, pid);
510 	sk_for_each(osk, node, head) {
511 		if (nlk_sk(osk)->pid == pid) {
512 			/* Bind collision, search negative pid values. */
513 			pid = rover--;
514 			if (rover > -4097)
515 				rover = -4097;
516 			netlink_table_ungrab();
517 			goto retry;
518 		}
519 	}
520 	netlink_table_ungrab();
521 
522 	err = netlink_insert(sk, pid);
523 	if (err == -EADDRINUSE)
524 		goto retry;
525 
526 	/* If 2 threads race to autobind, that is fine.  */
527 	if (err == -EBUSY)
528 		err = 0;
529 
530 	return err;
531 }
532 
533 static inline int netlink_capable(struct socket *sock, unsigned int flag)
534 {
535 	return (nl_table[sock->sk->sk_protocol].nl_nonroot & flag) ||
536 	       capable(CAP_NET_ADMIN);
537 }
538 
539 static void
540 netlink_update_subscriptions(struct sock *sk, unsigned int subscriptions)
541 {
542 	struct netlink_sock *nlk = nlk_sk(sk);
543 
544 	if (nlk->subscriptions && !subscriptions)
545 		__sk_del_bind_node(sk);
546 	else if (!nlk->subscriptions && subscriptions)
547 		sk_add_bind_node(sk, &nl_table[sk->sk_protocol].mc_list);
548 	nlk->subscriptions = subscriptions;
549 }
550 
551 static int netlink_alloc_groups(struct sock *sk)
552 {
553 	struct netlink_sock *nlk = nlk_sk(sk);
554 	unsigned int groups;
555 	int err = 0;
556 
557 	netlink_lock_table();
558 	groups = nl_table[sk->sk_protocol].groups;
559 	if (!nl_table[sk->sk_protocol].registered)
560 		err = -ENOENT;
561 	netlink_unlock_table();
562 
563 	if (err)
564 		return err;
565 
566 	nlk->groups = kmalloc(NLGRPSZ(groups), GFP_KERNEL);
567 	if (nlk->groups == NULL)
568 		return -ENOMEM;
569 	memset(nlk->groups, 0, NLGRPSZ(groups));
570 	nlk->ngroups = groups;
571 	return 0;
572 }
573 
574 static int netlink_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
575 {
576 	struct sock *sk = sock->sk;
577 	struct netlink_sock *nlk = nlk_sk(sk);
578 	struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
579 	int err;
580 
581 	if (nladdr->nl_family != AF_NETLINK)
582 		return -EINVAL;
583 
584 	/* Only superuser is allowed to listen multicasts */
585 	if (nladdr->nl_groups) {
586 		if (!netlink_capable(sock, NL_NONROOT_RECV))
587 			return -EPERM;
588 		if (nlk->groups == NULL) {
589 			err = netlink_alloc_groups(sk);
590 			if (err)
591 				return err;
592 		}
593 	}
594 
595 	if (nlk->pid) {
596 		if (nladdr->nl_pid != nlk->pid)
597 			return -EINVAL;
598 	} else {
599 		err = nladdr->nl_pid ?
600 			netlink_insert(sk, nladdr->nl_pid) :
601 			netlink_autobind(sock);
602 		if (err)
603 			return err;
604 	}
605 
606 	if (!nladdr->nl_groups && (nlk->groups == NULL || !(u32)nlk->groups[0]))
607 		return 0;
608 
609 	netlink_table_grab();
610 	netlink_update_subscriptions(sk, nlk->subscriptions +
611 	                                 hweight32(nladdr->nl_groups) -
612 	                                 hweight32(nlk->groups[0]));
613 	nlk->groups[0] = (nlk->groups[0] & ~0xffffffffUL) | nladdr->nl_groups;
614 	netlink_update_listeners(sk);
615 	netlink_table_ungrab();
616 
617 	return 0;
618 }
619 
620 static int netlink_connect(struct socket *sock, struct sockaddr *addr,
621 			   int alen, int flags)
622 {
623 	int err = 0;
624 	struct sock *sk = sock->sk;
625 	struct netlink_sock *nlk = nlk_sk(sk);
626 	struct sockaddr_nl *nladdr=(struct sockaddr_nl*)addr;
627 
628 	if (addr->sa_family == AF_UNSPEC) {
629 		sk->sk_state	= NETLINK_UNCONNECTED;
630 		nlk->dst_pid	= 0;
631 		nlk->dst_group  = 0;
632 		return 0;
633 	}
634 	if (addr->sa_family != AF_NETLINK)
635 		return -EINVAL;
636 
637 	/* Only superuser is allowed to send multicasts */
638 	if (nladdr->nl_groups && !netlink_capable(sock, NL_NONROOT_SEND))
639 		return -EPERM;
640 
641 	if (!nlk->pid)
642 		err = netlink_autobind(sock);
643 
644 	if (err == 0) {
645 		sk->sk_state	= NETLINK_CONNECTED;
646 		nlk->dst_pid 	= nladdr->nl_pid;
647 		nlk->dst_group  = ffs(nladdr->nl_groups);
648 	}
649 
650 	return err;
651 }
652 
653 static int netlink_getname(struct socket *sock, struct sockaddr *addr, int *addr_len, int peer)
654 {
655 	struct sock *sk = sock->sk;
656 	struct netlink_sock *nlk = nlk_sk(sk);
657 	struct sockaddr_nl *nladdr=(struct sockaddr_nl *)addr;
658 
659 	nladdr->nl_family = AF_NETLINK;
660 	nladdr->nl_pad = 0;
661 	*addr_len = sizeof(*nladdr);
662 
663 	if (peer) {
664 		nladdr->nl_pid = nlk->dst_pid;
665 		nladdr->nl_groups = netlink_group_mask(nlk->dst_group);
666 	} else {
667 		nladdr->nl_pid = nlk->pid;
668 		nladdr->nl_groups = nlk->groups ? nlk->groups[0] : 0;
669 	}
670 	return 0;
671 }
672 
673 static void netlink_overrun(struct sock *sk)
674 {
675 	if (!test_and_set_bit(0, &nlk_sk(sk)->state)) {
676 		sk->sk_err = ENOBUFS;
677 		sk->sk_error_report(sk);
678 	}
679 }
680 
681 static struct sock *netlink_getsockbypid(struct sock *ssk, u32 pid)
682 {
683 	int protocol = ssk->sk_protocol;
684 	struct sock *sock;
685 	struct netlink_sock *nlk;
686 
687 	sock = netlink_lookup(protocol, pid);
688 	if (!sock)
689 		return ERR_PTR(-ECONNREFUSED);
690 
691 	/* Don't bother queuing skb if kernel socket has no input function */
692 	nlk = nlk_sk(sock);
693 	if ((nlk->pid == 0 && !nlk->data_ready) ||
694 	    (sock->sk_state == NETLINK_CONNECTED &&
695 	     nlk->dst_pid != nlk_sk(ssk)->pid)) {
696 		sock_put(sock);
697 		return ERR_PTR(-ECONNREFUSED);
698 	}
699 	return sock;
700 }
701 
702 struct sock *netlink_getsockbyfilp(struct file *filp)
703 {
704 	struct inode *inode = filp->f_dentry->d_inode;
705 	struct sock *sock;
706 
707 	if (!S_ISSOCK(inode->i_mode))
708 		return ERR_PTR(-ENOTSOCK);
709 
710 	sock = SOCKET_I(inode)->sk;
711 	if (sock->sk_family != AF_NETLINK)
712 		return ERR_PTR(-EINVAL);
713 
714 	sock_hold(sock);
715 	return sock;
716 }
717 
718 /*
719  * Attach a skb to a netlink socket.
720  * The caller must hold a reference to the destination socket. On error, the
721  * reference is dropped. The skb is not send to the destination, just all
722  * all error checks are performed and memory in the queue is reserved.
723  * Return values:
724  * < 0: error. skb freed, reference to sock dropped.
725  * 0: continue
726  * 1: repeat lookup - reference dropped while waiting for socket memory.
727  */
728 int netlink_attachskb(struct sock *sk, struct sk_buff *skb, int nonblock,
729 		long timeo, struct sock *ssk)
730 {
731 	struct netlink_sock *nlk;
732 
733 	nlk = nlk_sk(sk);
734 
735 	if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
736 	    test_bit(0, &nlk->state)) {
737 		DECLARE_WAITQUEUE(wait, current);
738 		if (!timeo) {
739 			if (!ssk || nlk_sk(ssk)->pid == 0)
740 				netlink_overrun(sk);
741 			sock_put(sk);
742 			kfree_skb(skb);
743 			return -EAGAIN;
744 		}
745 
746 		__set_current_state(TASK_INTERRUPTIBLE);
747 		add_wait_queue(&nlk->wait, &wait);
748 
749 		if ((atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
750 		     test_bit(0, &nlk->state)) &&
751 		    !sock_flag(sk, SOCK_DEAD))
752 			timeo = schedule_timeout(timeo);
753 
754 		__set_current_state(TASK_RUNNING);
755 		remove_wait_queue(&nlk->wait, &wait);
756 		sock_put(sk);
757 
758 		if (signal_pending(current)) {
759 			kfree_skb(skb);
760 			return sock_intr_errno(timeo);
761 		}
762 		return 1;
763 	}
764 	skb_set_owner_r(skb, sk);
765 	return 0;
766 }
767 
768 int netlink_sendskb(struct sock *sk, struct sk_buff *skb, int protocol)
769 {
770 	int len = skb->len;
771 
772 	skb_queue_tail(&sk->sk_receive_queue, skb);
773 	sk->sk_data_ready(sk, len);
774 	sock_put(sk);
775 	return len;
776 }
777 
778 void netlink_detachskb(struct sock *sk, struct sk_buff *skb)
779 {
780 	kfree_skb(skb);
781 	sock_put(sk);
782 }
783 
784 static inline struct sk_buff *netlink_trim(struct sk_buff *skb,
785 					   gfp_t allocation)
786 {
787 	int delta;
788 
789 	skb_orphan(skb);
790 
791 	delta = skb->end - skb->tail;
792 	if (delta * 2 < skb->truesize)
793 		return skb;
794 
795 	if (skb_shared(skb)) {
796 		struct sk_buff *nskb = skb_clone(skb, allocation);
797 		if (!nskb)
798 			return skb;
799 		kfree_skb(skb);
800 		skb = nskb;
801 	}
802 
803 	if (!pskb_expand_head(skb, 0, -delta, allocation))
804 		skb->truesize -= delta;
805 
806 	return skb;
807 }
808 
809 int netlink_unicast(struct sock *ssk, struct sk_buff *skb, u32 pid, int nonblock)
810 {
811 	struct sock *sk;
812 	int err;
813 	long timeo;
814 
815 	skb = netlink_trim(skb, gfp_any());
816 
817 	timeo = sock_sndtimeo(ssk, nonblock);
818 retry:
819 	sk = netlink_getsockbypid(ssk, pid);
820 	if (IS_ERR(sk)) {
821 		kfree_skb(skb);
822 		return PTR_ERR(sk);
823 	}
824 	err = netlink_attachskb(sk, skb, nonblock, timeo, ssk);
825 	if (err == 1)
826 		goto retry;
827 	if (err)
828 		return err;
829 
830 	return netlink_sendskb(sk, skb, ssk->sk_protocol);
831 }
832 
833 int netlink_has_listeners(struct sock *sk, unsigned int group)
834 {
835 	int res = 0;
836 
837 	BUG_ON(!(nlk_sk(sk)->flags & NETLINK_KERNEL_SOCKET));
838 	if (group - 1 < nl_table[sk->sk_protocol].groups)
839 		res = test_bit(group - 1, nl_table[sk->sk_protocol].listeners);
840 	return res;
841 }
842 EXPORT_SYMBOL_GPL(netlink_has_listeners);
843 
844 static __inline__ int netlink_broadcast_deliver(struct sock *sk, struct sk_buff *skb)
845 {
846 	struct netlink_sock *nlk = nlk_sk(sk);
847 
848 	if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf &&
849 	    !test_bit(0, &nlk->state)) {
850 		skb_set_owner_r(skb, sk);
851 		skb_queue_tail(&sk->sk_receive_queue, skb);
852 		sk->sk_data_ready(sk, skb->len);
853 		return atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf;
854 	}
855 	return -1;
856 }
857 
858 struct netlink_broadcast_data {
859 	struct sock *exclude_sk;
860 	u32 pid;
861 	u32 group;
862 	int failure;
863 	int congested;
864 	int delivered;
865 	gfp_t allocation;
866 	struct sk_buff *skb, *skb2;
867 };
868 
869 static inline int do_one_broadcast(struct sock *sk,
870 				   struct netlink_broadcast_data *p)
871 {
872 	struct netlink_sock *nlk = nlk_sk(sk);
873 	int val;
874 
875 	if (p->exclude_sk == sk)
876 		goto out;
877 
878 	if (nlk->pid == p->pid || p->group - 1 >= nlk->ngroups ||
879 	    !test_bit(p->group - 1, nlk->groups))
880 		goto out;
881 
882 	if (p->failure) {
883 		netlink_overrun(sk);
884 		goto out;
885 	}
886 
887 	sock_hold(sk);
888 	if (p->skb2 == NULL) {
889 		if (skb_shared(p->skb)) {
890 			p->skb2 = skb_clone(p->skb, p->allocation);
891 		} else {
892 			p->skb2 = skb_get(p->skb);
893 			/*
894 			 * skb ownership may have been set when
895 			 * delivered to a previous socket.
896 			 */
897 			skb_orphan(p->skb2);
898 		}
899 	}
900 	if (p->skb2 == NULL) {
901 		netlink_overrun(sk);
902 		/* Clone failed. Notify ALL listeners. */
903 		p->failure = 1;
904 	} else if ((val = netlink_broadcast_deliver(sk, p->skb2)) < 0) {
905 		netlink_overrun(sk);
906 	} else {
907 		p->congested |= val;
908 		p->delivered = 1;
909 		p->skb2 = NULL;
910 	}
911 	sock_put(sk);
912 
913 out:
914 	return 0;
915 }
916 
917 int netlink_broadcast(struct sock *ssk, struct sk_buff *skb, u32 pid,
918 		      u32 group, gfp_t allocation)
919 {
920 	struct netlink_broadcast_data info;
921 	struct hlist_node *node;
922 	struct sock *sk;
923 
924 	skb = netlink_trim(skb, allocation);
925 
926 	info.exclude_sk = ssk;
927 	info.pid = pid;
928 	info.group = group;
929 	info.failure = 0;
930 	info.congested = 0;
931 	info.delivered = 0;
932 	info.allocation = allocation;
933 	info.skb = skb;
934 	info.skb2 = NULL;
935 
936 	/* While we sleep in clone, do not allow to change socket list */
937 
938 	netlink_lock_table();
939 
940 	sk_for_each_bound(sk, node, &nl_table[ssk->sk_protocol].mc_list)
941 		do_one_broadcast(sk, &info);
942 
943 	kfree_skb(skb);
944 
945 	netlink_unlock_table();
946 
947 	if (info.skb2)
948 		kfree_skb(info.skb2);
949 
950 	if (info.delivered) {
951 		if (info.congested && (allocation & __GFP_WAIT))
952 			yield();
953 		return 0;
954 	}
955 	if (info.failure)
956 		return -ENOBUFS;
957 	return -ESRCH;
958 }
959 
960 struct netlink_set_err_data {
961 	struct sock *exclude_sk;
962 	u32 pid;
963 	u32 group;
964 	int code;
965 };
966 
967 static inline int do_one_set_err(struct sock *sk,
968 				 struct netlink_set_err_data *p)
969 {
970 	struct netlink_sock *nlk = nlk_sk(sk);
971 
972 	if (sk == p->exclude_sk)
973 		goto out;
974 
975 	if (nlk->pid == p->pid || p->group - 1 >= nlk->ngroups ||
976 	    !test_bit(p->group - 1, nlk->groups))
977 		goto out;
978 
979 	sk->sk_err = p->code;
980 	sk->sk_error_report(sk);
981 out:
982 	return 0;
983 }
984 
985 void netlink_set_err(struct sock *ssk, u32 pid, u32 group, int code)
986 {
987 	struct netlink_set_err_data info;
988 	struct hlist_node *node;
989 	struct sock *sk;
990 
991 	info.exclude_sk = ssk;
992 	info.pid = pid;
993 	info.group = group;
994 	info.code = code;
995 
996 	read_lock(&nl_table_lock);
997 
998 	sk_for_each_bound(sk, node, &nl_table[ssk->sk_protocol].mc_list)
999 		do_one_set_err(sk, &info);
1000 
1001 	read_unlock(&nl_table_lock);
1002 }
1003 
1004 static int netlink_setsockopt(struct socket *sock, int level, int optname,
1005                               char __user *optval, int optlen)
1006 {
1007 	struct sock *sk = sock->sk;
1008 	struct netlink_sock *nlk = nlk_sk(sk);
1009 	int val = 0, err;
1010 
1011 	if (level != SOL_NETLINK)
1012 		return -ENOPROTOOPT;
1013 
1014 	if (optlen >= sizeof(int) &&
1015 	    get_user(val, (int __user *)optval))
1016 		return -EFAULT;
1017 
1018 	switch (optname) {
1019 	case NETLINK_PKTINFO:
1020 		if (val)
1021 			nlk->flags |= NETLINK_RECV_PKTINFO;
1022 		else
1023 			nlk->flags &= ~NETLINK_RECV_PKTINFO;
1024 		err = 0;
1025 		break;
1026 	case NETLINK_ADD_MEMBERSHIP:
1027 	case NETLINK_DROP_MEMBERSHIP: {
1028 		unsigned int subscriptions;
1029 		int old, new = optname == NETLINK_ADD_MEMBERSHIP ? 1 : 0;
1030 
1031 		if (!netlink_capable(sock, NL_NONROOT_RECV))
1032 			return -EPERM;
1033 		if (nlk->groups == NULL) {
1034 			err = netlink_alloc_groups(sk);
1035 			if (err)
1036 				return err;
1037 		}
1038 		if (!val || val - 1 >= nlk->ngroups)
1039 			return -EINVAL;
1040 		netlink_table_grab();
1041 		old = test_bit(val - 1, nlk->groups);
1042 		subscriptions = nlk->subscriptions - old + new;
1043 		if (new)
1044 			__set_bit(val - 1, nlk->groups);
1045 		else
1046 			__clear_bit(val - 1, nlk->groups);
1047 		netlink_update_subscriptions(sk, subscriptions);
1048 		netlink_update_listeners(sk);
1049 		netlink_table_ungrab();
1050 		err = 0;
1051 		break;
1052 	}
1053 	default:
1054 		err = -ENOPROTOOPT;
1055 	}
1056 	return err;
1057 }
1058 
1059 static int netlink_getsockopt(struct socket *sock, int level, int optname,
1060                               char __user *optval, int __user *optlen)
1061 {
1062 	struct sock *sk = sock->sk;
1063 	struct netlink_sock *nlk = nlk_sk(sk);
1064 	int len, val, err;
1065 
1066 	if (level != SOL_NETLINK)
1067 		return -ENOPROTOOPT;
1068 
1069 	if (get_user(len, optlen))
1070 		return -EFAULT;
1071 	if (len < 0)
1072 		return -EINVAL;
1073 
1074 	switch (optname) {
1075 	case NETLINK_PKTINFO:
1076 		if (len < sizeof(int))
1077 			return -EINVAL;
1078 		len = sizeof(int);
1079 		val = nlk->flags & NETLINK_RECV_PKTINFO ? 1 : 0;
1080 		put_user(len, optlen);
1081 		put_user(val, optval);
1082 		err = 0;
1083 		break;
1084 	default:
1085 		err = -ENOPROTOOPT;
1086 	}
1087 	return err;
1088 }
1089 
1090 static void netlink_cmsg_recv_pktinfo(struct msghdr *msg, struct sk_buff *skb)
1091 {
1092 	struct nl_pktinfo info;
1093 
1094 	info.group = NETLINK_CB(skb).dst_group;
1095 	put_cmsg(msg, SOL_NETLINK, NETLINK_PKTINFO, sizeof(info), &info);
1096 }
1097 
1098 static inline void netlink_rcv_wake(struct sock *sk)
1099 {
1100 	struct netlink_sock *nlk = nlk_sk(sk);
1101 
1102 	if (skb_queue_empty(&sk->sk_receive_queue))
1103 		clear_bit(0, &nlk->state);
1104 	if (!test_bit(0, &nlk->state))
1105 		wake_up_interruptible(&nlk->wait);
1106 }
1107 
1108 static int netlink_sendmsg(struct kiocb *kiocb, struct socket *sock,
1109 			   struct msghdr *msg, size_t len)
1110 {
1111 	struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
1112 	struct sock *sk = sock->sk;
1113 	struct netlink_sock *nlk = nlk_sk(sk);
1114 	struct sockaddr_nl *addr=msg->msg_name;
1115 	u32 dst_pid;
1116 	u32 dst_group;
1117 	struct sk_buff *skb;
1118 	int err;
1119 	struct scm_cookie scm;
1120 
1121 	if (msg->msg_flags&MSG_OOB)
1122 		return -EOPNOTSUPP;
1123 
1124 	if (NULL == siocb->scm)
1125 		siocb->scm = &scm;
1126 	err = scm_send(sock, msg, siocb->scm);
1127 	if (err < 0)
1128 		return err;
1129 
1130 	if (msg->msg_namelen) {
1131 		if (addr->nl_family != AF_NETLINK)
1132 			return -EINVAL;
1133 		dst_pid = addr->nl_pid;
1134 		dst_group = ffs(addr->nl_groups);
1135 		if (dst_group && !netlink_capable(sock, NL_NONROOT_SEND))
1136 			return -EPERM;
1137 	} else {
1138 		dst_pid = nlk->dst_pid;
1139 		dst_group = nlk->dst_group;
1140 	}
1141 
1142 	if (!nlk->pid) {
1143 		err = netlink_autobind(sock);
1144 		if (err)
1145 			goto out;
1146 	}
1147 
1148 	err = -EMSGSIZE;
1149 	if (len > sk->sk_sndbuf - 32)
1150 		goto out;
1151 	err = -ENOBUFS;
1152 	skb = alloc_skb(len, GFP_KERNEL);
1153 	if (skb==NULL)
1154 		goto out;
1155 
1156 	NETLINK_CB(skb).pid	= nlk->pid;
1157 	NETLINK_CB(skb).dst_pid = dst_pid;
1158 	NETLINK_CB(skb).dst_group = dst_group;
1159 	NETLINK_CB(skb).loginuid = audit_get_loginuid(current->audit_context);
1160 	selinux_get_task_sid(current, &(NETLINK_CB(skb).sid));
1161 	memcpy(NETLINK_CREDS(skb), &siocb->scm->creds, sizeof(struct ucred));
1162 
1163 	/* What can I do? Netlink is asynchronous, so that
1164 	   we will have to save current capabilities to
1165 	   check them, when this message will be delivered
1166 	   to corresponding kernel module.   --ANK (980802)
1167 	 */
1168 
1169 	err = -EFAULT;
1170 	if (memcpy_fromiovec(skb_put(skb,len), msg->msg_iov, len)) {
1171 		kfree_skb(skb);
1172 		goto out;
1173 	}
1174 
1175 	err = security_netlink_send(sk, skb);
1176 	if (err) {
1177 		kfree_skb(skb);
1178 		goto out;
1179 	}
1180 
1181 	if (dst_group) {
1182 		atomic_inc(&skb->users);
1183 		netlink_broadcast(sk, skb, dst_pid, dst_group, GFP_KERNEL);
1184 	}
1185 	err = netlink_unicast(sk, skb, dst_pid, msg->msg_flags&MSG_DONTWAIT);
1186 
1187 out:
1188 	return err;
1189 }
1190 
1191 static int netlink_recvmsg(struct kiocb *kiocb, struct socket *sock,
1192 			   struct msghdr *msg, size_t len,
1193 			   int flags)
1194 {
1195 	struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
1196 	struct scm_cookie scm;
1197 	struct sock *sk = sock->sk;
1198 	struct netlink_sock *nlk = nlk_sk(sk);
1199 	int noblock = flags&MSG_DONTWAIT;
1200 	size_t copied;
1201 	struct sk_buff *skb;
1202 	int err;
1203 
1204 	if (flags&MSG_OOB)
1205 		return -EOPNOTSUPP;
1206 
1207 	copied = 0;
1208 
1209 	skb = skb_recv_datagram(sk,flags,noblock,&err);
1210 	if (skb==NULL)
1211 		goto out;
1212 
1213 	msg->msg_namelen = 0;
1214 
1215 	copied = skb->len;
1216 	if (len < copied) {
1217 		msg->msg_flags |= MSG_TRUNC;
1218 		copied = len;
1219 	}
1220 
1221 	skb->h.raw = skb->data;
1222 	err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
1223 
1224 	if (msg->msg_name) {
1225 		struct sockaddr_nl *addr = (struct sockaddr_nl*)msg->msg_name;
1226 		addr->nl_family = AF_NETLINK;
1227 		addr->nl_pad    = 0;
1228 		addr->nl_pid	= NETLINK_CB(skb).pid;
1229 		addr->nl_groups	= netlink_group_mask(NETLINK_CB(skb).dst_group);
1230 		msg->msg_namelen = sizeof(*addr);
1231 	}
1232 
1233 	if (nlk->flags & NETLINK_RECV_PKTINFO)
1234 		netlink_cmsg_recv_pktinfo(msg, skb);
1235 
1236 	if (NULL == siocb->scm) {
1237 		memset(&scm, 0, sizeof(scm));
1238 		siocb->scm = &scm;
1239 	}
1240 	siocb->scm->creds = *NETLINK_CREDS(skb);
1241 	skb_free_datagram(sk, skb);
1242 
1243 	if (nlk->cb && atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf / 2)
1244 		netlink_dump(sk);
1245 
1246 	scm_recv(sock, msg, siocb->scm, flags);
1247 
1248 out:
1249 	netlink_rcv_wake(sk);
1250 	return err ? : copied;
1251 }
1252 
1253 static void netlink_data_ready(struct sock *sk, int len)
1254 {
1255 	struct netlink_sock *nlk = nlk_sk(sk);
1256 
1257 	if (nlk->data_ready)
1258 		nlk->data_ready(sk, len);
1259 	netlink_rcv_wake(sk);
1260 }
1261 
1262 /*
1263  *	We export these functions to other modules. They provide a
1264  *	complete set of kernel non-blocking support for message
1265  *	queueing.
1266  */
1267 
1268 struct sock *
1269 netlink_kernel_create(int unit, unsigned int groups,
1270                       void (*input)(struct sock *sk, int len),
1271                       struct module *module)
1272 {
1273 	struct socket *sock;
1274 	struct sock *sk;
1275 	struct netlink_sock *nlk;
1276 	unsigned long *listeners = NULL;
1277 
1278 	if (!nl_table)
1279 		return NULL;
1280 
1281 	if (unit<0 || unit>=MAX_LINKS)
1282 		return NULL;
1283 
1284 	if (sock_create_lite(PF_NETLINK, SOCK_DGRAM, unit, &sock))
1285 		return NULL;
1286 
1287 	if (__netlink_create(sock, unit) < 0)
1288 		goto out_sock_release;
1289 
1290 	if (groups < 32)
1291 		groups = 32;
1292 
1293 	listeners = kzalloc(NLGRPSZ(groups), GFP_KERNEL);
1294 	if (!listeners)
1295 		goto out_sock_release;
1296 
1297 	sk = sock->sk;
1298 	sk->sk_data_ready = netlink_data_ready;
1299 	if (input)
1300 		nlk_sk(sk)->data_ready = input;
1301 
1302 	if (netlink_insert(sk, 0))
1303 		goto out_sock_release;
1304 
1305 	nlk = nlk_sk(sk);
1306 	nlk->flags |= NETLINK_KERNEL_SOCKET;
1307 
1308 	netlink_table_grab();
1309 	nl_table[unit].groups = groups;
1310 	nl_table[unit].listeners = listeners;
1311 	nl_table[unit].module = module;
1312 	nl_table[unit].registered = 1;
1313 	netlink_table_ungrab();
1314 
1315 	return sk;
1316 
1317 out_sock_release:
1318 	kfree(listeners);
1319 	sock_release(sock);
1320 	return NULL;
1321 }
1322 
1323 void netlink_set_nonroot(int protocol, unsigned int flags)
1324 {
1325 	if ((unsigned int)protocol < MAX_LINKS)
1326 		nl_table[protocol].nl_nonroot = flags;
1327 }
1328 
1329 static void netlink_destroy_callback(struct netlink_callback *cb)
1330 {
1331 	if (cb->skb)
1332 		kfree_skb(cb->skb);
1333 	kfree(cb);
1334 }
1335 
1336 /*
1337  * It looks a bit ugly.
1338  * It would be better to create kernel thread.
1339  */
1340 
1341 static int netlink_dump(struct sock *sk)
1342 {
1343 	struct netlink_sock *nlk = nlk_sk(sk);
1344 	struct netlink_callback *cb;
1345 	struct sk_buff *skb;
1346 	struct nlmsghdr *nlh;
1347 	int len;
1348 
1349 	skb = sock_rmalloc(sk, NLMSG_GOODSIZE, 0, GFP_KERNEL);
1350 	if (!skb)
1351 		return -ENOBUFS;
1352 
1353 	spin_lock(&nlk->cb_lock);
1354 
1355 	cb = nlk->cb;
1356 	if (cb == NULL) {
1357 		spin_unlock(&nlk->cb_lock);
1358 		kfree_skb(skb);
1359 		return -EINVAL;
1360 	}
1361 
1362 	len = cb->dump(skb, cb);
1363 
1364 	if (len > 0) {
1365 		spin_unlock(&nlk->cb_lock);
1366 		skb_queue_tail(&sk->sk_receive_queue, skb);
1367 		sk->sk_data_ready(sk, len);
1368 		return 0;
1369 	}
1370 
1371 	nlh = NLMSG_NEW_ANSWER(skb, cb, NLMSG_DONE, sizeof(len), NLM_F_MULTI);
1372 	memcpy(NLMSG_DATA(nlh), &len, sizeof(len));
1373 	skb_queue_tail(&sk->sk_receive_queue, skb);
1374 	sk->sk_data_ready(sk, skb->len);
1375 
1376 	if (cb->done)
1377 		cb->done(cb);
1378 	nlk->cb = NULL;
1379 	spin_unlock(&nlk->cb_lock);
1380 
1381 	netlink_destroy_callback(cb);
1382 	return 0;
1383 
1384 nlmsg_failure:
1385 	return -ENOBUFS;
1386 }
1387 
1388 int netlink_dump_start(struct sock *ssk, struct sk_buff *skb,
1389 		       struct nlmsghdr *nlh,
1390 		       int (*dump)(struct sk_buff *skb, struct netlink_callback*),
1391 		       int (*done)(struct netlink_callback*))
1392 {
1393 	struct netlink_callback *cb;
1394 	struct sock *sk;
1395 	struct netlink_sock *nlk;
1396 
1397 	cb = kmalloc(sizeof(*cb), GFP_KERNEL);
1398 	if (cb == NULL)
1399 		return -ENOBUFS;
1400 
1401 	memset(cb, 0, sizeof(*cb));
1402 	cb->dump = dump;
1403 	cb->done = done;
1404 	cb->nlh = nlh;
1405 	atomic_inc(&skb->users);
1406 	cb->skb = skb;
1407 
1408 	sk = netlink_lookup(ssk->sk_protocol, NETLINK_CB(skb).pid);
1409 	if (sk == NULL) {
1410 		netlink_destroy_callback(cb);
1411 		return -ECONNREFUSED;
1412 	}
1413 	nlk = nlk_sk(sk);
1414 	/* A dump is in progress... */
1415 	spin_lock(&nlk->cb_lock);
1416 	if (nlk->cb) {
1417 		spin_unlock(&nlk->cb_lock);
1418 		netlink_destroy_callback(cb);
1419 		sock_put(sk);
1420 		return -EBUSY;
1421 	}
1422 	nlk->cb = cb;
1423 	spin_unlock(&nlk->cb_lock);
1424 
1425 	netlink_dump(sk);
1426 	sock_put(sk);
1427 	return 0;
1428 }
1429 
1430 void netlink_ack(struct sk_buff *in_skb, struct nlmsghdr *nlh, int err)
1431 {
1432 	struct sk_buff *skb;
1433 	struct nlmsghdr *rep;
1434 	struct nlmsgerr *errmsg;
1435 	int size;
1436 
1437 	if (err == 0)
1438 		size = NLMSG_SPACE(sizeof(struct nlmsgerr));
1439 	else
1440 		size = NLMSG_SPACE(4 + NLMSG_ALIGN(nlh->nlmsg_len));
1441 
1442 	skb = alloc_skb(size, GFP_KERNEL);
1443 	if (!skb) {
1444 		struct sock *sk;
1445 
1446 		sk = netlink_lookup(in_skb->sk->sk_protocol,
1447 				    NETLINK_CB(in_skb).pid);
1448 		if (sk) {
1449 			sk->sk_err = ENOBUFS;
1450 			sk->sk_error_report(sk);
1451 			sock_put(sk);
1452 		}
1453 		return;
1454 	}
1455 
1456 	rep = __nlmsg_put(skb, NETLINK_CB(in_skb).pid, nlh->nlmsg_seq,
1457 			  NLMSG_ERROR, sizeof(struct nlmsgerr), 0);
1458 	errmsg = NLMSG_DATA(rep);
1459 	errmsg->error = err;
1460 	memcpy(&errmsg->msg, nlh, err ? nlh->nlmsg_len : sizeof(struct nlmsghdr));
1461 	netlink_unicast(in_skb->sk, skb, NETLINK_CB(in_skb).pid, MSG_DONTWAIT);
1462 }
1463 
1464 static int netlink_rcv_skb(struct sk_buff *skb, int (*cb)(struct sk_buff *,
1465 						     struct nlmsghdr *, int *))
1466 {
1467 	unsigned int total_len;
1468 	struct nlmsghdr *nlh;
1469 	int err;
1470 
1471 	while (skb->len >= nlmsg_total_size(0)) {
1472 		nlh = (struct nlmsghdr *) skb->data;
1473 
1474 		if (nlh->nlmsg_len < NLMSG_HDRLEN || skb->len < nlh->nlmsg_len)
1475 			return 0;
1476 
1477 		total_len = min(NLMSG_ALIGN(nlh->nlmsg_len), skb->len);
1478 
1479 		if (cb(skb, nlh, &err) < 0) {
1480 			/* Not an error, but we have to interrupt processing
1481 			 * here. Note: that in this case we do not pull
1482 			 * message from skb, it will be processed later.
1483 			 */
1484 			if (err == 0)
1485 				return -1;
1486 			netlink_ack(skb, nlh, err);
1487 		} else if (nlh->nlmsg_flags & NLM_F_ACK)
1488 			netlink_ack(skb, nlh, 0);
1489 
1490 		skb_pull(skb, total_len);
1491 	}
1492 
1493 	return 0;
1494 }
1495 
1496 /**
1497  * nelink_run_queue - Process netlink receive queue.
1498  * @sk: Netlink socket containing the queue
1499  * @qlen: Place to store queue length upon entry
1500  * @cb: Callback function invoked for each netlink message found
1501  *
1502  * Processes as much as there was in the queue upon entry and invokes
1503  * a callback function for each netlink message found. The callback
1504  * function may refuse a message by returning a negative error code
1505  * but setting the error pointer to 0 in which case this function
1506  * returns with a qlen != 0.
1507  *
1508  * qlen must be initialized to 0 before the initial entry, afterwards
1509  * the function may be called repeatedly until qlen reaches 0.
1510  */
1511 void netlink_run_queue(struct sock *sk, unsigned int *qlen,
1512 		       int (*cb)(struct sk_buff *, struct nlmsghdr *, int *))
1513 {
1514 	struct sk_buff *skb;
1515 
1516 	if (!*qlen || *qlen > skb_queue_len(&sk->sk_receive_queue))
1517 		*qlen = skb_queue_len(&sk->sk_receive_queue);
1518 
1519 	for (; *qlen; (*qlen)--) {
1520 		skb = skb_dequeue(&sk->sk_receive_queue);
1521 		if (netlink_rcv_skb(skb, cb)) {
1522 			if (skb->len)
1523 				skb_queue_head(&sk->sk_receive_queue, skb);
1524 			else {
1525 				kfree_skb(skb);
1526 				(*qlen)--;
1527 			}
1528 			break;
1529 		}
1530 
1531 		kfree_skb(skb);
1532 	}
1533 }
1534 
1535 /**
1536  * netlink_queue_skip - Skip netlink message while processing queue.
1537  * @nlh: Netlink message to be skipped
1538  * @skb: Socket buffer containing the netlink messages.
1539  *
1540  * Pulls the given netlink message off the socket buffer so the next
1541  * call to netlink_queue_run() will not reconsider the message.
1542  */
1543 void netlink_queue_skip(struct nlmsghdr *nlh, struct sk_buff *skb)
1544 {
1545 	int msglen = NLMSG_ALIGN(nlh->nlmsg_len);
1546 
1547 	if (msglen > skb->len)
1548 		msglen = skb->len;
1549 
1550 	skb_pull(skb, msglen);
1551 }
1552 
1553 #ifdef CONFIG_PROC_FS
1554 struct nl_seq_iter {
1555 	int link;
1556 	int hash_idx;
1557 };
1558 
1559 static struct sock *netlink_seq_socket_idx(struct seq_file *seq, loff_t pos)
1560 {
1561 	struct nl_seq_iter *iter = seq->private;
1562 	int i, j;
1563 	struct sock *s;
1564 	struct hlist_node *node;
1565 	loff_t off = 0;
1566 
1567 	for (i=0; i<MAX_LINKS; i++) {
1568 		struct nl_pid_hash *hash = &nl_table[i].hash;
1569 
1570 		for (j = 0; j <= hash->mask; j++) {
1571 			sk_for_each(s, node, &hash->table[j]) {
1572 				if (off == pos) {
1573 					iter->link = i;
1574 					iter->hash_idx = j;
1575 					return s;
1576 				}
1577 				++off;
1578 			}
1579 		}
1580 	}
1581 	return NULL;
1582 }
1583 
1584 static void *netlink_seq_start(struct seq_file *seq, loff_t *pos)
1585 {
1586 	read_lock(&nl_table_lock);
1587 	return *pos ? netlink_seq_socket_idx(seq, *pos - 1) : SEQ_START_TOKEN;
1588 }
1589 
1590 static void *netlink_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1591 {
1592 	struct sock *s;
1593 	struct nl_seq_iter *iter;
1594 	int i, j;
1595 
1596 	++*pos;
1597 
1598 	if (v == SEQ_START_TOKEN)
1599 		return netlink_seq_socket_idx(seq, 0);
1600 
1601 	s = sk_next(v);
1602 	if (s)
1603 		return s;
1604 
1605 	iter = seq->private;
1606 	i = iter->link;
1607 	j = iter->hash_idx + 1;
1608 
1609 	do {
1610 		struct nl_pid_hash *hash = &nl_table[i].hash;
1611 
1612 		for (; j <= hash->mask; j++) {
1613 			s = sk_head(&hash->table[j]);
1614 			if (s) {
1615 				iter->link = i;
1616 				iter->hash_idx = j;
1617 				return s;
1618 			}
1619 		}
1620 
1621 		j = 0;
1622 	} while (++i < MAX_LINKS);
1623 
1624 	return NULL;
1625 }
1626 
1627 static void netlink_seq_stop(struct seq_file *seq, void *v)
1628 {
1629 	read_unlock(&nl_table_lock);
1630 }
1631 
1632 
1633 static int netlink_seq_show(struct seq_file *seq, void *v)
1634 {
1635 	if (v == SEQ_START_TOKEN)
1636 		seq_puts(seq,
1637 			 "sk       Eth Pid    Groups   "
1638 			 "Rmem     Wmem     Dump     Locks\n");
1639 	else {
1640 		struct sock *s = v;
1641 		struct netlink_sock *nlk = nlk_sk(s);
1642 
1643 		seq_printf(seq, "%p %-3d %-6d %08x %-8d %-8d %p %d\n",
1644 			   s,
1645 			   s->sk_protocol,
1646 			   nlk->pid,
1647 			   nlk->groups ? (u32)nlk->groups[0] : 0,
1648 			   atomic_read(&s->sk_rmem_alloc),
1649 			   atomic_read(&s->sk_wmem_alloc),
1650 			   nlk->cb,
1651 			   atomic_read(&s->sk_refcnt)
1652 			);
1653 
1654 	}
1655 	return 0;
1656 }
1657 
1658 static struct seq_operations netlink_seq_ops = {
1659 	.start  = netlink_seq_start,
1660 	.next   = netlink_seq_next,
1661 	.stop   = netlink_seq_stop,
1662 	.show   = netlink_seq_show,
1663 };
1664 
1665 
1666 static int netlink_seq_open(struct inode *inode, struct file *file)
1667 {
1668 	struct seq_file *seq;
1669 	struct nl_seq_iter *iter;
1670 	int err;
1671 
1672 	iter = kmalloc(sizeof(*iter), GFP_KERNEL);
1673 	if (!iter)
1674 		return -ENOMEM;
1675 
1676 	err = seq_open(file, &netlink_seq_ops);
1677 	if (err) {
1678 		kfree(iter);
1679 		return err;
1680 	}
1681 
1682 	memset(iter, 0, sizeof(*iter));
1683 	seq = file->private_data;
1684 	seq->private = iter;
1685 	return 0;
1686 }
1687 
1688 static struct file_operations netlink_seq_fops = {
1689 	.owner		= THIS_MODULE,
1690 	.open		= netlink_seq_open,
1691 	.read		= seq_read,
1692 	.llseek		= seq_lseek,
1693 	.release	= seq_release_private,
1694 };
1695 
1696 #endif
1697 
1698 int netlink_register_notifier(struct notifier_block *nb)
1699 {
1700 	return atomic_notifier_chain_register(&netlink_chain, nb);
1701 }
1702 
1703 int netlink_unregister_notifier(struct notifier_block *nb)
1704 {
1705 	return atomic_notifier_chain_unregister(&netlink_chain, nb);
1706 }
1707 
1708 static const struct proto_ops netlink_ops = {
1709 	.family =	PF_NETLINK,
1710 	.owner =	THIS_MODULE,
1711 	.release =	netlink_release,
1712 	.bind =		netlink_bind,
1713 	.connect =	netlink_connect,
1714 	.socketpair =	sock_no_socketpair,
1715 	.accept =	sock_no_accept,
1716 	.getname =	netlink_getname,
1717 	.poll =		datagram_poll,
1718 	.ioctl =	sock_no_ioctl,
1719 	.listen =	sock_no_listen,
1720 	.shutdown =	sock_no_shutdown,
1721 	.setsockopt =	netlink_setsockopt,
1722 	.getsockopt =	netlink_getsockopt,
1723 	.sendmsg =	netlink_sendmsg,
1724 	.recvmsg =	netlink_recvmsg,
1725 	.mmap =		sock_no_mmap,
1726 	.sendpage =	sock_no_sendpage,
1727 };
1728 
1729 static struct net_proto_family netlink_family_ops = {
1730 	.family = PF_NETLINK,
1731 	.create = netlink_create,
1732 	.owner	= THIS_MODULE,	/* for consistency 8) */
1733 };
1734 
1735 extern void netlink_skb_parms_too_large(void);
1736 
1737 static int __init netlink_proto_init(void)
1738 {
1739 	struct sk_buff *dummy_skb;
1740 	int i;
1741 	unsigned long max;
1742 	unsigned int order;
1743 	int err = proto_register(&netlink_proto, 0);
1744 
1745 	if (err != 0)
1746 		goto out;
1747 
1748 	if (sizeof(struct netlink_skb_parms) > sizeof(dummy_skb->cb))
1749 		netlink_skb_parms_too_large();
1750 
1751 	nl_table = kmalloc(sizeof(*nl_table) * MAX_LINKS, GFP_KERNEL);
1752 	if (!nl_table) {
1753 enomem:
1754 		printk(KERN_CRIT "netlink_init: Cannot allocate nl_table\n");
1755 		return -ENOMEM;
1756 	}
1757 
1758 	memset(nl_table, 0, sizeof(*nl_table) * MAX_LINKS);
1759 
1760 	if (num_physpages >= (128 * 1024))
1761 		max = num_physpages >> (21 - PAGE_SHIFT);
1762 	else
1763 		max = num_physpages >> (23 - PAGE_SHIFT);
1764 
1765 	order = get_bitmask_order(max) - 1 + PAGE_SHIFT;
1766 	max = (1UL << order) / sizeof(struct hlist_head);
1767 	order = get_bitmask_order(max > UINT_MAX ? UINT_MAX : max) - 1;
1768 
1769 	for (i = 0; i < MAX_LINKS; i++) {
1770 		struct nl_pid_hash *hash = &nl_table[i].hash;
1771 
1772 		hash->table = nl_pid_hash_alloc(1 * sizeof(*hash->table));
1773 		if (!hash->table) {
1774 			while (i-- > 0)
1775 				nl_pid_hash_free(nl_table[i].hash.table,
1776 						 1 * sizeof(*hash->table));
1777 			kfree(nl_table);
1778 			goto enomem;
1779 		}
1780 		memset(hash->table, 0, 1 * sizeof(*hash->table));
1781 		hash->max_shift = order;
1782 		hash->shift = 0;
1783 		hash->mask = 0;
1784 		hash->rehash_time = jiffies;
1785 	}
1786 
1787 	sock_register(&netlink_family_ops);
1788 #ifdef CONFIG_PROC_FS
1789 	proc_net_fops_create("netlink", 0, &netlink_seq_fops);
1790 #endif
1791 	/* The netlink device handler may be needed early. */
1792 	rtnetlink_init();
1793 out:
1794 	return err;
1795 }
1796 
1797 core_initcall(netlink_proto_init);
1798 
1799 EXPORT_SYMBOL(netlink_ack);
1800 EXPORT_SYMBOL(netlink_run_queue);
1801 EXPORT_SYMBOL(netlink_queue_skip);
1802 EXPORT_SYMBOL(netlink_broadcast);
1803 EXPORT_SYMBOL(netlink_dump_start);
1804 EXPORT_SYMBOL(netlink_kernel_create);
1805 EXPORT_SYMBOL(netlink_register_notifier);
1806 EXPORT_SYMBOL(netlink_set_err);
1807 EXPORT_SYMBOL(netlink_set_nonroot);
1808 EXPORT_SYMBOL(netlink_unicast);
1809 EXPORT_SYMBOL(netlink_unregister_notifier);
1810 
1811