vserver 2.0 rc7
[linux-2.6.git] / net / netlink / af_netlink.c
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  *
17  */
18
19 #include <linux/config.h>
20 #include <linux/module.h>
21
22 #include <linux/kernel.h>
23 #include <linux/init.h>
24 #include <linux/signal.h>
25 #include <linux/sched.h>
26 #include <linux/errno.h>
27 #include <linux/string.h>
28 #include <linux/stat.h>
29 #include <linux/socket.h>
30 #include <linux/un.h>
31 #include <linux/fcntl.h>
32 #include <linux/termios.h>
33 #include <linux/sockios.h>
34 #include <linux/net.h>
35 #include <linux/fs.h>
36 #include <linux/slab.h>
37 #include <asm/uaccess.h>
38 #include <linux/skbuff.h>
39 #include <linux/netdevice.h>
40 #include <linux/rtnetlink.h>
41 #include <linux/proc_fs.h>
42 #include <linux/seq_file.h>
43 #include <linux/smp_lock.h>
44 #include <linux/notifier.h>
45 #include <linux/security.h>
46 #include <linux/jhash.h>
47 #include <linux/jiffies.h>
48 #include <linux/random.h>
49 #include <linux/bitops.h>
50 #include <linux/mm.h>
51 #include <linux/types.h>
52 #include <linux/audit.h>
53 #include <linux/vs_context.h>
54 #include <linux/vs_network.h>
55 #include <linux/vs_limit.h>
56
57 #include <net/sock.h>
58 #include <net/scm.h>
59
60 #define Nprintk(a...)
61
62 struct netlink_sock {
63         /* struct sock has to be the first member of netlink_sock */
64         struct sock             sk;
65         u32                     pid;
66         unsigned int            groups;
67         u32                     dst_pid;
68         unsigned int            dst_groups;
69         unsigned long           state;
70         wait_queue_head_t       wait;
71         struct netlink_callback *cb;
72         spinlock_t              cb_lock;
73         void                    (*data_ready)(struct sock *sk, int bytes);
74 };
75
76 static inline struct netlink_sock *nlk_sk(struct sock *sk)
77 {
78         return (struct netlink_sock *)sk;
79 }
80
81 struct nl_pid_hash {
82         struct hlist_head *table;
83         unsigned long rehash_time;
84
85         unsigned int mask;
86         unsigned int shift;
87
88         unsigned int entries;
89         unsigned int max_shift;
90
91         u32 rnd;
92 };
93
94 struct netlink_table {
95         struct nl_pid_hash hash;
96         struct hlist_head mc_list;
97         unsigned int nl_nonroot;
98 };
99
100 static struct netlink_table *nl_table;
101
102 static DECLARE_WAIT_QUEUE_HEAD(nl_table_wait);
103
104 static int netlink_dump(struct sock *sk);
105 static void netlink_destroy_callback(struct netlink_callback *cb);
106
107 static DEFINE_RWLOCK(nl_table_lock);
108 static atomic_t nl_table_users = ATOMIC_INIT(0);
109
110 static struct notifier_block *netlink_chain;
111
112 static struct hlist_head *nl_pid_hashfn(struct nl_pid_hash *hash, u32 pid)
113 {
114         return &hash->table[jhash_1word(pid, hash->rnd) & hash->mask];
115 }
116
117 static void netlink_sock_destruct(struct sock *sk)
118 {
119         skb_queue_purge(&sk->sk_receive_queue);
120
121         if (!sock_flag(sk, SOCK_DEAD)) {
122                 printk("Freeing alive netlink socket %p\n", sk);
123                 return;
124         }
125         BUG_TRAP(!atomic_read(&sk->sk_rmem_alloc));
126         BUG_TRAP(!atomic_read(&sk->sk_wmem_alloc));
127         BUG_TRAP(!nlk_sk(sk)->cb);
128 }
129
130 /* This lock without WQ_FLAG_EXCLUSIVE is good on UP and it is _very_ bad on SMP.
131  * Look, when several writers sleep and reader wakes them up, all but one
132  * immediately hit write lock and grab all the cpus. Exclusive sleep solves
133  * this, _but_ remember, it adds useless work on UP machines.
134  */
135
136 static void netlink_table_grab(void)
137 {
138         write_lock_bh(&nl_table_lock);
139
140         if (atomic_read(&nl_table_users)) {
141                 DECLARE_WAITQUEUE(wait, current);
142
143                 add_wait_queue_exclusive(&nl_table_wait, &wait);
144                 for(;;) {
145                         set_current_state(TASK_UNINTERRUPTIBLE);
146                         if (atomic_read(&nl_table_users) == 0)
147                                 break;
148                         write_unlock_bh(&nl_table_lock);
149                         schedule();
150                         write_lock_bh(&nl_table_lock);
151                 }
152
153                 __set_current_state(TASK_RUNNING);
154                 remove_wait_queue(&nl_table_wait, &wait);
155         }
156 }
157
158 static __inline__ void netlink_table_ungrab(void)
159 {
160         write_unlock_bh(&nl_table_lock);
161         wake_up(&nl_table_wait);
162 }
163
164 static __inline__ void
165 netlink_lock_table(void)
166 {
167         /* read_lock() synchronizes us to netlink_table_grab */
168
169         read_lock(&nl_table_lock);
170         atomic_inc(&nl_table_users);
171         read_unlock(&nl_table_lock);
172 }
173
174 static __inline__ void
175 netlink_unlock_table(void)
176 {
177         if (atomic_dec_and_test(&nl_table_users))
178                 wake_up(&nl_table_wait);
179 }
180
181 static __inline__ struct sock *netlink_lookup(int protocol, u32 pid)
182 {
183         struct nl_pid_hash *hash = &nl_table[protocol].hash;
184         struct hlist_head *head;
185         struct sock *sk;
186         struct hlist_node *node;
187
188         read_lock(&nl_table_lock);
189         head = nl_pid_hashfn(hash, pid);
190         sk_for_each(sk, node, head) {
191                 if (nlk_sk(sk)->pid == pid) {
192                         sock_hold(sk);
193                         goto found;
194                 }
195         }
196         sk = NULL;
197 found:
198         read_unlock(&nl_table_lock);
199         return sk;
200 }
201
202 static inline struct hlist_head *nl_pid_hash_alloc(size_t size)
203 {
204         if (size <= PAGE_SIZE)
205                 return kmalloc(size, GFP_ATOMIC);
206         else
207                 return (struct hlist_head *)
208                         __get_free_pages(GFP_ATOMIC, get_order(size));
209 }
210
211 static inline void nl_pid_hash_free(struct hlist_head *table, size_t size)
212 {
213         if (size <= PAGE_SIZE)
214                 kfree(table);
215         else
216                 free_pages((unsigned long)table, get_order(size));
217 }
218
219 static int nl_pid_hash_rehash(struct nl_pid_hash *hash, int grow)
220 {
221         unsigned int omask, mask, shift;
222         size_t osize, size;
223         struct hlist_head *otable, *table;
224         int i;
225
226         omask = mask = hash->mask;
227         osize = size = (mask + 1) * sizeof(*table);
228         shift = hash->shift;
229
230         if (grow) {
231                 if (++shift > hash->max_shift)
232                         return 0;
233                 mask = mask * 2 + 1;
234                 size *= 2;
235         }
236
237         table = nl_pid_hash_alloc(size);
238         if (!table)
239                 return 0;
240
241         memset(table, 0, size);
242         otable = hash->table;
243         hash->table = table;
244         hash->mask = mask;
245         hash->shift = shift;
246         get_random_bytes(&hash->rnd, sizeof(hash->rnd));
247
248         for (i = 0; i <= omask; i++) {
249                 struct sock *sk;
250                 struct hlist_node *node, *tmp;
251
252                 sk_for_each_safe(sk, node, tmp, &otable[i])
253                         __sk_add_node(sk, nl_pid_hashfn(hash, nlk_sk(sk)->pid));
254         }
255
256         nl_pid_hash_free(otable, osize);
257         hash->rehash_time = jiffies + 10 * 60 * HZ;
258         return 1;
259 }
260
261 static inline int nl_pid_hash_dilute(struct nl_pid_hash *hash, int len)
262 {
263         int avg = hash->entries >> hash->shift;
264
265         if (unlikely(avg > 1) && nl_pid_hash_rehash(hash, 1))
266                 return 1;
267
268         if (unlikely(len > avg) && time_after(jiffies, hash->rehash_time)) {
269                 nl_pid_hash_rehash(hash, 0);
270                 return 1;
271         }
272
273         return 0;
274 }
275
276 static struct proto_ops netlink_ops;
277
278 static int netlink_insert(struct sock *sk, u32 pid)
279 {
280         struct nl_pid_hash *hash = &nl_table[sk->sk_protocol].hash;
281         struct hlist_head *head;
282         int err = -EADDRINUSE;
283         struct sock *osk;
284         struct hlist_node *node;
285         int len;
286
287         netlink_table_grab();
288         head = nl_pid_hashfn(hash, pid);
289         len = 0;
290         sk_for_each(osk, node, head) {
291                 if (nlk_sk(osk)->pid == pid)
292                         break;
293                 len++;
294         }
295         if (node)
296                 goto err;
297
298         err = -EBUSY;
299         if (nlk_sk(sk)->pid)
300                 goto err;
301
302         err = -ENOMEM;
303         if (BITS_PER_LONG > 32 && unlikely(hash->entries >= UINT_MAX))
304                 goto err;
305
306         if (len && nl_pid_hash_dilute(hash, len))
307                 head = nl_pid_hashfn(hash, pid);
308         hash->entries++;
309         nlk_sk(sk)->pid = pid;
310         sk_add_node(sk, head);
311         err = 0;
312
313 err:
314         netlink_table_ungrab();
315         return err;
316 }
317
318 static void netlink_remove(struct sock *sk)
319 {
320         netlink_table_grab();
321         if (sk_del_node_init(sk))
322                 nl_table[sk->sk_protocol].hash.entries--;
323         if (nlk_sk(sk)->groups)
324                 __sk_del_bind_node(sk);
325         netlink_table_ungrab();
326 }
327
328 static struct proto netlink_proto = {
329         .name     = "NETLINK",
330         .owner    = THIS_MODULE,
331         .obj_size = sizeof(struct netlink_sock),
332 };
333
334 static int netlink_create(struct socket *sock, int protocol)
335 {
336         struct sock *sk;
337         struct netlink_sock *nlk;
338
339         sock->state = SS_UNCONNECTED;
340
341         if (sock->type != SOCK_RAW && sock->type != SOCK_DGRAM)
342                 return -ESOCKTNOSUPPORT;
343
344         if (protocol<0 || protocol >= MAX_LINKS)
345                 return -EPROTONOSUPPORT;
346
347         sock->ops = &netlink_ops;
348
349         sk = sk_alloc(PF_NETLINK, GFP_KERNEL, &netlink_proto, 1);
350         if (!sk)
351                 return -ENOMEM;
352
353         sock_init_data(sock, sk);
354
355         nlk = nlk_sk(sk);
356
357         spin_lock_init(&nlk->cb_lock);
358         init_waitqueue_head(&nlk->wait);
359         sk->sk_destruct = netlink_sock_destruct;
360
361         sk->sk_protocol = protocol;
362         return 0;
363 }
364
365 static int netlink_release(struct socket *sock)
366 {
367         struct sock *sk = sock->sk;
368         struct netlink_sock *nlk;
369
370         if (!sk)
371                 return 0;
372
373         netlink_remove(sk);
374         nlk = nlk_sk(sk);
375
376         spin_lock(&nlk->cb_lock);
377         if (nlk->cb) {
378                 nlk->cb->done(nlk->cb);
379                 netlink_destroy_callback(nlk->cb);
380                 nlk->cb = NULL;
381         }
382         spin_unlock(&nlk->cb_lock);
383
384         /* OK. Socket is unlinked, and, therefore,
385            no new packets will arrive */
386
387         sock_orphan(sk);
388         sock->sk = NULL;
389         wake_up_interruptible_all(&nlk->wait);
390
391         skb_queue_purge(&sk->sk_write_queue);
392
393         if (nlk->pid && !nlk->groups) {
394                 struct netlink_notify n = {
395                                                 .protocol = sk->sk_protocol,
396                                                 .pid = nlk->pid,
397                                           };
398                 notifier_call_chain(&netlink_chain, NETLINK_URELEASE, &n);
399         }       
400         
401         sock_put(sk);
402         return 0;
403 }
404
405 static int netlink_autobind(struct socket *sock)
406 {
407         struct sock *sk = sock->sk;
408         struct nl_pid_hash *hash = &nl_table[sk->sk_protocol].hash;
409         struct hlist_head *head;
410         struct sock *osk;
411         struct hlist_node *node;
412         s32 pid = current->pid;
413         int err;
414         static s32 rover = -4097;
415
416 retry:
417         cond_resched();
418         netlink_table_grab();
419         head = nl_pid_hashfn(hash, pid);
420         sk_for_each(osk, node, head) {
421                 if (nlk_sk(osk)->pid == pid) {
422                         /* Bind collision, search negative pid values. */
423                         pid = rover--;
424                         if (rover > -4097)
425                                 rover = -4097;
426                         netlink_table_ungrab();
427                         goto retry;
428                 }
429         }
430         netlink_table_ungrab();
431
432         err = netlink_insert(sk, pid);
433         if (err == -EADDRINUSE)
434                 goto retry;
435
436         /* If 2 threads race to autobind, that is fine.  */
437         if (err == -EBUSY)
438                 err = 0;
439
440         return err;
441 }
442
443 static inline int netlink_capable(struct socket *sock, unsigned int flag) 
444
445         return (nl_table[sock->sk->sk_protocol].nl_nonroot & flag) ||
446                capable(CAP_NET_ADMIN);
447
448
449 static int netlink_bind(struct socket *sock, struct sockaddr *addr, int addr_len)
450 {
451         struct sock *sk = sock->sk;
452         struct netlink_sock *nlk = nlk_sk(sk);
453         struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
454         int err;
455         
456         if (nladdr->nl_family != AF_NETLINK)
457                 return -EINVAL;
458
459         /* Only superuser is allowed to listen multicasts */
460         if (nladdr->nl_groups && !netlink_capable(sock, NL_NONROOT_RECV))
461                 return -EPERM;
462
463         if (nlk->pid) {
464                 if (nladdr->nl_pid != nlk->pid)
465                         return -EINVAL;
466         } else {
467                 err = nladdr->nl_pid ?
468                         netlink_insert(sk, nladdr->nl_pid) :
469                         netlink_autobind(sock);
470                 if (err)
471                         return err;
472         }
473
474         if (!nladdr->nl_groups && !nlk->groups)
475                 return 0;
476
477         netlink_table_grab();
478         if (nlk->groups && !nladdr->nl_groups)
479                 __sk_del_bind_node(sk);
480         else if (!nlk->groups && nladdr->nl_groups)
481                 sk_add_bind_node(sk, &nl_table[sk->sk_protocol].mc_list);
482         nlk->groups = nladdr->nl_groups;
483         netlink_table_ungrab();
484
485         return 0;
486 }
487
488 static int netlink_connect(struct socket *sock, struct sockaddr *addr,
489                            int alen, int flags)
490 {
491         int err = 0;
492         struct sock *sk = sock->sk;
493         struct netlink_sock *nlk = nlk_sk(sk);
494         struct sockaddr_nl *nladdr=(struct sockaddr_nl*)addr;
495
496         if (addr->sa_family == AF_UNSPEC) {
497                 sk->sk_state    = NETLINK_UNCONNECTED;
498                 nlk->dst_pid    = 0;
499                 nlk->dst_groups = 0;
500                 return 0;
501         }
502         if (addr->sa_family != AF_NETLINK)
503                 return -EINVAL;
504
505         /* Only superuser is allowed to send multicasts */
506         if (nladdr->nl_groups && !netlink_capable(sock, NL_NONROOT_SEND))
507                 return -EPERM;
508
509         if (!nlk->pid)
510                 err = netlink_autobind(sock);
511
512         if (err == 0) {
513                 sk->sk_state    = NETLINK_CONNECTED;
514                 nlk->dst_pid    = nladdr->nl_pid;
515                 nlk->dst_groups = nladdr->nl_groups;
516         }
517
518         return err;
519 }
520
521 static int netlink_getname(struct socket *sock, struct sockaddr *addr, int *addr_len, int peer)
522 {
523         struct sock *sk = sock->sk;
524         struct netlink_sock *nlk = nlk_sk(sk);
525         struct sockaddr_nl *nladdr=(struct sockaddr_nl *)addr;
526         
527         nladdr->nl_family = AF_NETLINK;
528         nladdr->nl_pad = 0;
529         *addr_len = sizeof(*nladdr);
530
531         if (peer) {
532                 nladdr->nl_pid = nlk->dst_pid;
533                 nladdr->nl_groups = nlk->dst_groups;
534         } else {
535                 nladdr->nl_pid = nlk->pid;
536                 nladdr->nl_groups = nlk->groups;
537         }
538         return 0;
539 }
540
541 static void netlink_overrun(struct sock *sk)
542 {
543         if (!test_and_set_bit(0, &nlk_sk(sk)->state)) {
544                 sk->sk_err = ENOBUFS;
545                 sk->sk_error_report(sk);
546         }
547 }
548
549 static struct sock *netlink_getsockbypid(struct sock *ssk, u32 pid)
550 {
551         int protocol = ssk->sk_protocol;
552         struct sock *sock;
553         struct netlink_sock *nlk;
554
555         sock = netlink_lookup(protocol, pid);
556         if (!sock)
557                 return ERR_PTR(-ECONNREFUSED);
558
559         /* Don't bother queuing skb if kernel socket has no input function */
560         nlk = nlk_sk(sock);
561         if ((nlk->pid == 0 && !nlk->data_ready) ||
562             (sock->sk_state == NETLINK_CONNECTED &&
563              nlk->dst_pid != nlk_sk(ssk)->pid)) {
564                 sock_put(sock);
565                 return ERR_PTR(-ECONNREFUSED);
566         }
567         return sock;
568 }
569
570 struct sock *netlink_getsockbyfilp(struct file *filp)
571 {
572         struct inode *inode = filp->f_dentry->d_inode;
573         struct sock *sock;
574
575         if (!S_ISSOCK(inode->i_mode))
576                 return ERR_PTR(-ENOTSOCK);
577
578         sock = SOCKET_I(inode)->sk;
579         if (sock->sk_family != AF_NETLINK)
580                 return ERR_PTR(-EINVAL);
581
582         sock_hold(sock);
583         return sock;
584 }
585
586 /*
587  * Attach a skb to a netlink socket.
588  * The caller must hold a reference to the destination socket. On error, the
589  * reference is dropped. The skb is not send to the destination, just all
590  * all error checks are performed and memory in the queue is reserved.
591  * Return values:
592  * < 0: error. skb freed, reference to sock dropped.
593  * 0: continue
594  * 1: repeat lookup - reference dropped while waiting for socket memory.
595  */
596 int netlink_attachskb(struct sock *sk, struct sk_buff *skb, int nonblock, long timeo)
597 {
598         struct netlink_sock *nlk;
599
600         nlk = nlk_sk(sk);
601
602         if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
603             test_bit(0, &nlk->state)) {
604                 DECLARE_WAITQUEUE(wait, current);
605                 if (!timeo) {
606                         if (!nlk->pid)
607                                 netlink_overrun(sk);
608                         sock_put(sk);
609                         kfree_skb(skb);
610                         return -EAGAIN;
611                 }
612
613                 __set_current_state(TASK_INTERRUPTIBLE);
614                 add_wait_queue(&nlk->wait, &wait);
615
616                 if ((atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
617                      test_bit(0, &nlk->state)) &&
618                     !sock_flag(sk, SOCK_DEAD))
619                         timeo = schedule_timeout(timeo);
620
621                 __set_current_state(TASK_RUNNING);
622                 remove_wait_queue(&nlk->wait, &wait);
623                 sock_put(sk);
624
625                 if (signal_pending(current)) {
626                         kfree_skb(skb);
627                         return sock_intr_errno(timeo);
628                 }
629                 return 1;
630         }
631         skb_set_owner_r(skb, sk);
632         return 0;
633 }
634
635 int netlink_sendskb(struct sock *sk, struct sk_buff *skb, int protocol)
636 {
637         struct netlink_sock *nlk;
638         int len = skb->len;
639
640         nlk = nlk_sk(sk);
641
642         skb_queue_tail(&sk->sk_receive_queue, skb);
643         sk->sk_data_ready(sk, len);
644         sock_put(sk);
645         return len;
646 }
647
648 void netlink_detachskb(struct sock *sk, struct sk_buff *skb)
649 {
650         kfree_skb(skb);
651         sock_put(sk);
652 }
653
654 static inline struct sk_buff *netlink_trim(struct sk_buff *skb, int allocation)
655 {
656         int delta;
657
658         skb_orphan(skb);
659
660         delta = skb->end - skb->tail;
661         if (delta * 2 < skb->truesize)
662                 return skb;
663
664         if (skb_shared(skb)) {
665                 struct sk_buff *nskb = skb_clone(skb, allocation);
666                 if (!nskb)
667                         return skb;
668                 kfree_skb(skb);
669                 skb = nskb;
670         }
671
672         if (!pskb_expand_head(skb, 0, -delta, allocation))
673                 skb->truesize -= delta;
674
675         return skb;
676 }
677
678 int netlink_unicast(struct sock *ssk, struct sk_buff *skb, u32 pid, int nonblock)
679 {
680         struct sock *sk;
681         int err;
682         long timeo;
683
684         skb = netlink_trim(skb, gfp_any());
685
686         timeo = sock_sndtimeo(ssk, nonblock);
687 retry:
688         sk = netlink_getsockbypid(ssk, pid);
689         if (IS_ERR(sk)) {
690                 kfree_skb(skb);
691                 return PTR_ERR(sk);
692         }
693         err = netlink_attachskb(sk, skb, nonblock, timeo);
694         if (err == 1)
695                 goto retry;
696         if (err)
697                 return err;
698
699         return netlink_sendskb(sk, skb, ssk->sk_protocol);
700 }
701
702 static __inline__ int netlink_broadcast_deliver(struct sock *sk, struct sk_buff *skb)
703 {
704         struct netlink_sock *nlk = nlk_sk(sk);
705
706         if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf &&
707             !test_bit(0, &nlk->state)) {
708                 skb_set_owner_r(skb, sk);
709                 skb_queue_tail(&sk->sk_receive_queue, skb);
710                 sk->sk_data_ready(sk, skb->len);
711                 return atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf;
712         }
713         return -1;
714 }
715
716 struct netlink_broadcast_data {
717         struct sock *exclude_sk;
718         u32 pid;
719         u32 group;
720         int failure;
721         int congested;
722         int delivered;
723         int allocation;
724         struct sk_buff *skb, *skb2;
725 };
726
727 static inline int do_one_broadcast(struct sock *sk,
728                                    struct netlink_broadcast_data *p)
729 {
730         struct netlink_sock *nlk = nlk_sk(sk);
731         int val;
732
733         if (p->exclude_sk == sk)
734                 goto out;
735
736         if (nlk->pid == p->pid || !(nlk->groups & p->group))
737                 goto out;
738
739         if (p->failure) {
740                 netlink_overrun(sk);
741                 goto out;
742         }
743
744         sock_hold(sk);
745         if (p->skb2 == NULL) {
746                 if (skb_shared(p->skb)) {
747                         p->skb2 = skb_clone(p->skb, p->allocation);
748                 } else {
749                         p->skb2 = skb_get(p->skb);
750                         /*
751                          * skb ownership may have been set when
752                          * delivered to a previous socket.
753                          */
754                         skb_orphan(p->skb2);
755                 }
756         }
757         if (p->skb2 == NULL) {
758                 netlink_overrun(sk);
759                 /* Clone failed. Notify ALL listeners. */
760                 p->failure = 1;
761         } else if ((val = netlink_broadcast_deliver(sk, p->skb2)) < 0) {
762                 netlink_overrun(sk);
763         } else {
764                 p->congested |= val;
765                 p->delivered = 1;
766                 p->skb2 = NULL;
767         }
768         sock_put(sk);
769
770 out:
771         return 0;
772 }
773
774 int netlink_broadcast(struct sock *ssk, struct sk_buff *skb, u32 pid,
775                       u32 group, int allocation)
776 {
777         struct netlink_broadcast_data info;
778         struct hlist_node *node;
779         struct sock *sk;
780
781         skb = netlink_trim(skb, allocation);
782
783         info.exclude_sk = ssk;
784         info.pid = pid;
785         info.group = group;
786         info.failure = 0;
787         info.congested = 0;
788         info.delivered = 0;
789         info.allocation = allocation;
790         info.skb = skb;
791         info.skb2 = NULL;
792
793         /* While we sleep in clone, do not allow to change socket list */
794
795         netlink_lock_table();
796
797         sk_for_each_bound(sk, node, &nl_table[ssk->sk_protocol].mc_list)
798                 do_one_broadcast(sk, &info);
799
800         kfree_skb(skb);
801
802         netlink_unlock_table();
803
804         if (info.skb2)
805                 kfree_skb(info.skb2);
806
807         if (info.delivered) {
808                 if (info.congested && (allocation & __GFP_WAIT))
809                         yield();
810                 return 0;
811         }
812         if (info.failure)
813                 return -ENOBUFS;
814         return -ESRCH;
815 }
816
817 struct netlink_set_err_data {
818         struct sock *exclude_sk;
819         u32 pid;
820         u32 group;
821         int code;
822 };
823
824 static inline int do_one_set_err(struct sock *sk,
825                                  struct netlink_set_err_data *p)
826 {
827         struct netlink_sock *nlk = nlk_sk(sk);
828
829         if (sk == p->exclude_sk)
830                 goto out;
831
832         if (nlk->pid == p->pid || !(nlk->groups & p->group))
833                 goto out;
834
835         sk->sk_err = p->code;
836         sk->sk_error_report(sk);
837 out:
838         return 0;
839 }
840
841 void netlink_set_err(struct sock *ssk, u32 pid, u32 group, int code)
842 {
843         struct netlink_set_err_data info;
844         struct hlist_node *node;
845         struct sock *sk;
846
847         info.exclude_sk = ssk;
848         info.pid = pid;
849         info.group = group;
850         info.code = code;
851
852         read_lock(&nl_table_lock);
853
854         sk_for_each_bound(sk, node, &nl_table[ssk->sk_protocol].mc_list)
855                 do_one_set_err(sk, &info);
856
857         read_unlock(&nl_table_lock);
858 }
859
860 static inline void netlink_rcv_wake(struct sock *sk)
861 {
862         struct netlink_sock *nlk = nlk_sk(sk);
863
864         if (!skb_queue_len(&sk->sk_receive_queue))
865                 clear_bit(0, &nlk->state);
866         if (!test_bit(0, &nlk->state))
867                 wake_up_interruptible(&nlk->wait);
868 }
869
870 static int netlink_sendmsg(struct kiocb *kiocb, struct socket *sock,
871                            struct msghdr *msg, size_t len)
872 {
873         struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
874         struct sock *sk = sock->sk;
875         struct netlink_sock *nlk = nlk_sk(sk);
876         struct sockaddr_nl *addr=msg->msg_name;
877         u32 dst_pid;
878         u32 dst_groups;
879         struct sk_buff *skb;
880         int err;
881         struct scm_cookie scm;
882
883         if (msg->msg_flags&MSG_OOB)
884                 return -EOPNOTSUPP;
885
886         if (NULL == siocb->scm)
887                 siocb->scm = &scm;
888         err = scm_send(sock, msg, siocb->scm);
889         if (err < 0)
890                 return err;
891
892         if (msg->msg_namelen) {
893                 if (addr->nl_family != AF_NETLINK)
894                         return -EINVAL;
895                 dst_pid = addr->nl_pid;
896                 dst_groups = addr->nl_groups;
897                 if (dst_groups && !netlink_capable(sock, NL_NONROOT_SEND))
898                         return -EPERM;
899         } else {
900                 dst_pid = nlk->dst_pid;
901                 dst_groups = nlk->dst_groups;
902         }
903
904         if (!nlk->pid) {
905                 err = netlink_autobind(sock);
906                 if (err)
907                         goto out;
908         }
909
910         err = -EMSGSIZE;
911         if (len > sk->sk_sndbuf - 32)
912                 goto out;
913         err = -ENOBUFS;
914         skb = alloc_skb(len, GFP_KERNEL);
915         if (skb==NULL)
916                 goto out;
917
918         NETLINK_CB(skb).pid     = nlk->pid;
919         NETLINK_CB(skb).groups  = nlk->groups;
920         NETLINK_CB(skb).dst_pid = dst_pid;
921         NETLINK_CB(skb).dst_groups = dst_groups;
922         NETLINK_CB(skb).loginuid = audit_get_loginuid(current->audit_context);
923         memcpy(NETLINK_CREDS(skb), &siocb->scm->creds, sizeof(struct ucred));
924
925         /* What can I do? Netlink is asynchronous, so that
926            we will have to save current capabilities to
927            check them, when this message will be delivered
928            to corresponding kernel module.   --ANK (980802)
929          */
930
931         err = -EFAULT;
932         if (memcpy_fromiovec(skb_put(skb,len), msg->msg_iov, len)) {
933                 kfree_skb(skb);
934                 goto out;
935         }
936
937         err = security_netlink_send(sk, skb);
938         if (err) {
939                 kfree_skb(skb);
940                 goto out;
941         }
942
943         if (dst_groups) {
944                 atomic_inc(&skb->users);
945                 netlink_broadcast(sk, skb, dst_pid, dst_groups, GFP_KERNEL);
946         }
947         err = netlink_unicast(sk, skb, dst_pid, msg->msg_flags&MSG_DONTWAIT);
948
949 out:
950         return err;
951 }
952
953 static int netlink_recvmsg(struct kiocb *kiocb, struct socket *sock,
954                            struct msghdr *msg, size_t len,
955                            int flags)
956 {
957         struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
958         struct scm_cookie scm;
959         struct sock *sk = sock->sk;
960         struct netlink_sock *nlk = nlk_sk(sk);
961         int noblock = flags&MSG_DONTWAIT;
962         size_t copied;
963         struct sk_buff *skb;
964         int err;
965
966         if (flags&MSG_OOB)
967                 return -EOPNOTSUPP;
968
969         copied = 0;
970
971         skb = skb_recv_datagram(sk,flags,noblock,&err);
972         if (skb==NULL)
973                 goto out;
974
975         msg->msg_namelen = 0;
976
977         copied = skb->len;
978         if (len < copied) {
979                 msg->msg_flags |= MSG_TRUNC;
980                 copied = len;
981         }
982
983         skb->h.raw = skb->data;
984         err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
985
986         if (msg->msg_name) {
987                 struct sockaddr_nl *addr = (struct sockaddr_nl*)msg->msg_name;
988                 addr->nl_family = AF_NETLINK;
989                 addr->nl_pad    = 0;
990                 addr->nl_pid    = NETLINK_CB(skb).pid;
991                 addr->nl_groups = NETLINK_CB(skb).dst_groups;
992                 msg->msg_namelen = sizeof(*addr);
993         }
994
995         if (NULL == siocb->scm) {
996                 memset(&scm, 0, sizeof(scm));
997                 siocb->scm = &scm;
998         }
999         siocb->scm->creds = *NETLINK_CREDS(skb);
1000         skb_free_datagram(sk, skb);
1001
1002         if (nlk->cb && atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf / 2)
1003                 netlink_dump(sk);
1004
1005         scm_recv(sock, msg, siocb->scm, flags);
1006
1007 out:
1008         netlink_rcv_wake(sk);
1009         return err ? : copied;
1010 }
1011
1012 static void netlink_data_ready(struct sock *sk, int len)
1013 {
1014         struct netlink_sock *nlk = nlk_sk(sk);
1015
1016         if (nlk->data_ready)
1017                 nlk->data_ready(sk, len);
1018         netlink_rcv_wake(sk);
1019 }
1020
1021 /*
1022  *      We export these functions to other modules. They provide a 
1023  *      complete set of kernel non-blocking support for message
1024  *      queueing.
1025  */
1026
1027 struct sock *
1028 netlink_kernel_create(int unit, void (*input)(struct sock *sk, int len))
1029 {
1030         struct socket *sock;
1031         struct sock *sk;
1032
1033         if (!nl_table)
1034                 return NULL;
1035
1036         if (unit<0 || unit>=MAX_LINKS)
1037                 return NULL;
1038
1039         if (sock_create_lite(PF_NETLINK, SOCK_DGRAM, unit, &sock))
1040                 return NULL;
1041
1042         if (netlink_create(sock, unit) < 0) {
1043                 sock_release(sock);
1044                 return NULL;
1045         }
1046         sk = sock->sk;
1047         sk->sk_data_ready = netlink_data_ready;
1048         if (input)
1049                 nlk_sk(sk)->data_ready = input;
1050
1051         if (netlink_insert(sk, 0)) {
1052                 sock_release(sock);
1053                 return NULL;
1054         }
1055         return sk;
1056 }
1057
1058 void netlink_set_nonroot(int protocol, unsigned int flags)
1059
1060         if ((unsigned int)protocol < MAX_LINKS) 
1061                 nl_table[protocol].nl_nonroot = flags;
1062
1063
1064 static void netlink_destroy_callback(struct netlink_callback *cb)
1065 {
1066         if (cb->skb)
1067                 kfree_skb(cb->skb);
1068         kfree(cb);
1069 }
1070
1071 /*
1072  * It looks a bit ugly.
1073  * It would be better to create kernel thread.
1074  */
1075
1076 static int netlink_dump(struct sock *sk)
1077 {
1078         struct netlink_sock *nlk = nlk_sk(sk);
1079         struct netlink_callback *cb;
1080         struct sk_buff *skb;
1081         struct nlmsghdr *nlh;
1082         int len;
1083         
1084         skb = sock_rmalloc(sk, NLMSG_GOODSIZE, 0, GFP_KERNEL);
1085         if (!skb)
1086                 return -ENOBUFS;
1087
1088         spin_lock(&nlk->cb_lock);
1089
1090         cb = nlk->cb;
1091         if (cb == NULL) {
1092                 spin_unlock(&nlk->cb_lock);
1093                 kfree_skb(skb);
1094                 return -EINVAL;
1095         }
1096
1097         len = cb->dump(skb, cb);
1098
1099         if (len > 0) {
1100                 spin_unlock(&nlk->cb_lock);
1101                 skb_queue_tail(&sk->sk_receive_queue, skb);
1102                 sk->sk_data_ready(sk, len);
1103                 return 0;
1104         }
1105
1106         nlh = __nlmsg_put(skb, NETLINK_CB(cb->skb).pid, cb->nlh->nlmsg_seq, NLMSG_DONE, sizeof(int));
1107         nlh->nlmsg_flags |= NLM_F_MULTI;
1108         memcpy(NLMSG_DATA(nlh), &len, sizeof(len));
1109         skb_queue_tail(&sk->sk_receive_queue, skb);
1110         sk->sk_data_ready(sk, skb->len);
1111
1112         cb->done(cb);
1113         nlk->cb = NULL;
1114         spin_unlock(&nlk->cb_lock);
1115
1116         netlink_destroy_callback(cb);
1117         return 0;
1118 }
1119
1120 int netlink_dump_start(struct sock *ssk, struct sk_buff *skb,
1121                        struct nlmsghdr *nlh,
1122                        int (*dump)(struct sk_buff *skb, struct netlink_callback*),
1123                        int (*done)(struct netlink_callback*))
1124 {
1125         struct netlink_callback *cb;
1126         struct sock *sk;
1127         struct netlink_sock *nlk;
1128
1129         cb = kmalloc(sizeof(*cb), GFP_KERNEL);
1130         if (cb == NULL)
1131                 return -ENOBUFS;
1132
1133         memset(cb, 0, sizeof(*cb));
1134         cb->dump = dump;
1135         cb->done = done;
1136         cb->nlh = nlh;
1137         atomic_inc(&skb->users);
1138         cb->skb = skb;
1139
1140         sk = netlink_lookup(ssk->sk_protocol, NETLINK_CB(skb).pid);
1141         if (sk == NULL) {
1142                 netlink_destroy_callback(cb);
1143                 return -ECONNREFUSED;
1144         }
1145         nlk = nlk_sk(sk);
1146         /* A dump is in progress... */
1147         spin_lock(&nlk->cb_lock);
1148         if (nlk->cb) {
1149                 spin_unlock(&nlk->cb_lock);
1150                 netlink_destroy_callback(cb);
1151                 sock_put(sk);
1152                 return -EBUSY;
1153         }
1154         nlk->cb = cb;
1155         spin_unlock(&nlk->cb_lock);
1156
1157         netlink_dump(sk);
1158         sock_put(sk);
1159         return 0;
1160 }
1161
1162 void netlink_ack(struct sk_buff *in_skb, struct nlmsghdr *nlh, int err)
1163 {
1164         struct sk_buff *skb;
1165         struct nlmsghdr *rep;
1166         struct nlmsgerr *errmsg;
1167         int size;
1168
1169         if (err == 0)
1170                 size = NLMSG_SPACE(sizeof(struct nlmsgerr));
1171         else
1172                 size = NLMSG_SPACE(4 + NLMSG_ALIGN(nlh->nlmsg_len));
1173
1174         skb = alloc_skb(size, GFP_KERNEL);
1175         if (!skb) {
1176                 struct sock *sk;
1177
1178                 sk = netlink_lookup(in_skb->sk->sk_protocol,
1179                                     NETLINK_CB(in_skb).pid);
1180                 if (sk) {
1181                         sk->sk_err = ENOBUFS;
1182                         sk->sk_error_report(sk);
1183                         sock_put(sk);
1184                 }
1185                 return;
1186         }
1187
1188         rep = __nlmsg_put(skb, NETLINK_CB(in_skb).pid, nlh->nlmsg_seq,
1189                           NLMSG_ERROR, sizeof(struct nlmsgerr));
1190         errmsg = NLMSG_DATA(rep);
1191         errmsg->error = err;
1192         memcpy(&errmsg->msg, nlh, err ? nlh->nlmsg_len : sizeof(struct nlmsghdr));
1193         netlink_unicast(in_skb->sk, skb, NETLINK_CB(in_skb).pid, MSG_DONTWAIT);
1194 }
1195
1196
1197 #ifdef CONFIG_PROC_FS
1198 struct nl_seq_iter {
1199         int link;
1200         int hash_idx;
1201 };
1202
1203 static struct sock *netlink_seq_socket_idx(struct seq_file *seq, loff_t pos)
1204 {
1205         struct nl_seq_iter *iter = seq->private;
1206         int i, j;
1207         struct sock *s;
1208         struct hlist_node *node;
1209         loff_t off = 0;
1210
1211         for (i=0; i<MAX_LINKS; i++) {
1212                 struct nl_pid_hash *hash = &nl_table[i].hash;
1213
1214                 for (j = 0; j <= hash->mask; j++) {
1215                         sk_for_each(s, node, &hash->table[j]) {
1216                                 if (off == pos) {
1217                                         iter->link = i;
1218                                         iter->hash_idx = j;
1219                                         return s;
1220                                 }
1221                                 ++off;
1222                         }
1223                 }
1224         }
1225         return NULL;
1226 }
1227
1228 static void *netlink_seq_start(struct seq_file *seq, loff_t *pos)
1229 {
1230         read_lock(&nl_table_lock);
1231         return *pos ? netlink_seq_socket_idx(seq, *pos - 1) : SEQ_START_TOKEN;
1232 }
1233
1234 static void *netlink_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1235 {
1236         struct sock *s;
1237         struct nl_seq_iter *iter;
1238         int i, j;
1239
1240         ++*pos;
1241
1242         if (v == SEQ_START_TOKEN)
1243                 return netlink_seq_socket_idx(seq, 0);
1244                 
1245         s = sk_next(v);
1246         if (s)
1247                 return s;
1248
1249         iter = seq->private;
1250         i = iter->link;
1251         j = iter->hash_idx + 1;
1252
1253         do {
1254                 struct nl_pid_hash *hash = &nl_table[i].hash;
1255
1256                 for (; j <= hash->mask; j++) {
1257                         s = sk_head(&hash->table[j]);
1258                         if (s) {
1259                                 iter->link = i;
1260                                 iter->hash_idx = j;
1261                                 return s;
1262                         }
1263                 }
1264
1265                 j = 0;
1266         } while (++i < MAX_LINKS);
1267
1268         return NULL;
1269 }
1270
1271 static void netlink_seq_stop(struct seq_file *seq, void *v)
1272 {
1273         read_unlock(&nl_table_lock);
1274 }
1275
1276
1277 static int netlink_seq_show(struct seq_file *seq, void *v)
1278 {
1279         if (v == SEQ_START_TOKEN)
1280                 seq_puts(seq,
1281                          "sk       Eth Pid    Groups   "
1282                          "Rmem     Wmem     Dump     Locks\n");
1283         else {
1284                 struct sock *s = v;
1285                 struct netlink_sock *nlk = nlk_sk(s);
1286
1287                 seq_printf(seq, "%p %-3d %-6d %08x %-8d %-8d %p %d\n",
1288                            s,
1289                            s->sk_protocol,
1290                            nlk->pid,
1291                            nlk->groups,
1292                            atomic_read(&s->sk_rmem_alloc),
1293                            atomic_read(&s->sk_wmem_alloc),
1294                            nlk->cb,
1295                            atomic_read(&s->sk_refcnt)
1296                         );
1297
1298         }
1299         return 0;
1300 }
1301
1302 static struct seq_operations netlink_seq_ops = {
1303         .start  = netlink_seq_start,
1304         .next   = netlink_seq_next,
1305         .stop   = netlink_seq_stop,
1306         .show   = netlink_seq_show,
1307 };
1308
1309
1310 static int netlink_seq_open(struct inode *inode, struct file *file)
1311 {
1312         struct seq_file *seq;
1313         struct nl_seq_iter *iter;
1314         int err;
1315
1316         iter = kmalloc(sizeof(*iter), GFP_KERNEL);
1317         if (!iter)
1318                 return -ENOMEM;
1319
1320         err = seq_open(file, &netlink_seq_ops);
1321         if (err) {
1322                 kfree(iter);
1323                 return err;
1324         }
1325
1326         memset(iter, 0, sizeof(*iter));
1327         seq = file->private_data;
1328         seq->private = iter;
1329         return 0;
1330 }
1331
1332 static struct file_operations netlink_seq_fops = {
1333         .owner          = THIS_MODULE,
1334         .open           = netlink_seq_open,
1335         .read           = seq_read,
1336         .llseek         = seq_lseek,
1337         .release        = seq_release_private,
1338 };
1339
1340 #endif
1341
1342 int netlink_register_notifier(struct notifier_block *nb)
1343 {
1344         return notifier_chain_register(&netlink_chain, nb);
1345 }
1346
1347 int netlink_unregister_notifier(struct notifier_block *nb)
1348 {
1349         return notifier_chain_unregister(&netlink_chain, nb);
1350 }
1351                 
1352 static struct proto_ops netlink_ops = {
1353         .family =       PF_NETLINK,
1354         .owner =        THIS_MODULE,
1355         .release =      netlink_release,
1356         .bind =         netlink_bind,
1357         .connect =      netlink_connect,
1358         .socketpair =   sock_no_socketpair,
1359         .accept =       sock_no_accept,
1360         .getname =      netlink_getname,
1361         .poll =         datagram_poll,
1362         .ioctl =        sock_no_ioctl,
1363         .listen =       sock_no_listen,
1364         .shutdown =     sock_no_shutdown,
1365         .setsockopt =   sock_no_setsockopt,
1366         .getsockopt =   sock_no_getsockopt,
1367         .sendmsg =      netlink_sendmsg,
1368         .recvmsg =      netlink_recvmsg,
1369         .mmap =         sock_no_mmap,
1370         .sendpage =     sock_no_sendpage,
1371 };
1372
1373 static struct net_proto_family netlink_family_ops = {
1374         .family = PF_NETLINK,
1375         .create = netlink_create,
1376         .owner  = THIS_MODULE,  /* for consistency 8) */
1377 };
1378
1379 extern void netlink_skb_parms_too_large(void);
1380
1381 static int __init netlink_proto_init(void)
1382 {
1383         struct sk_buff *dummy_skb;
1384         int i;
1385         unsigned long max;
1386         unsigned int order;
1387         int err = proto_register(&netlink_proto, 0);
1388
1389         if (err != 0)
1390                 goto out;
1391
1392         if (sizeof(struct netlink_skb_parms) > sizeof(dummy_skb->cb))
1393                 netlink_skb_parms_too_large();
1394
1395         nl_table = kmalloc(sizeof(*nl_table) * MAX_LINKS, GFP_KERNEL);
1396         if (!nl_table) {
1397 enomem:
1398                 printk(KERN_CRIT "netlink_init: Cannot allocate nl_table\n");
1399                 return -ENOMEM;
1400         }
1401
1402         memset(nl_table, 0, sizeof(*nl_table) * MAX_LINKS);
1403
1404         if (num_physpages >= (128 * 1024))
1405                 max = num_physpages >> (21 - PAGE_SHIFT);
1406         else
1407                 max = num_physpages >> (23 - PAGE_SHIFT);
1408
1409         order = get_bitmask_order(max) - 1 + PAGE_SHIFT;
1410         max = (1UL << order) / sizeof(struct hlist_head);
1411         order = get_bitmask_order(max > UINT_MAX ? UINT_MAX : max) - 1;
1412
1413         for (i = 0; i < MAX_LINKS; i++) {
1414                 struct nl_pid_hash *hash = &nl_table[i].hash;
1415
1416                 hash->table = nl_pid_hash_alloc(1 * sizeof(*hash->table));
1417                 if (!hash->table) {
1418                         while (i-- > 0)
1419                                 nl_pid_hash_free(nl_table[i].hash.table,
1420                                                  1 * sizeof(*hash->table));
1421                         kfree(nl_table);
1422                         goto enomem;
1423                 }
1424                 memset(hash->table, 0, 1 * sizeof(*hash->table));
1425                 hash->max_shift = order;
1426                 hash->shift = 0;
1427                 hash->mask = 0;
1428                 hash->rehash_time = jiffies;
1429         }
1430
1431         sock_register(&netlink_family_ops);
1432 #ifdef CONFIG_PROC_FS
1433         proc_net_fops_create("netlink", 0, &netlink_seq_fops);
1434 #endif
1435         /* The netlink device handler may be needed early. */ 
1436         rtnetlink_init();
1437 out:
1438         return err;
1439 }
1440
1441 static void __exit netlink_proto_exit(void)
1442 {
1443         sock_unregister(PF_NETLINK);
1444         proc_net_remove("netlink");
1445         kfree(nl_table);
1446         nl_table = NULL;
1447         proto_unregister(&netlink_proto);
1448 }
1449
1450 core_initcall(netlink_proto_init);
1451 module_exit(netlink_proto_exit);
1452
1453 MODULE_LICENSE("GPL");
1454
1455 MODULE_ALIAS_NETPROTO(PF_NETLINK);
1456
1457 EXPORT_SYMBOL(netlink_ack);
1458 EXPORT_SYMBOL(netlink_broadcast);
1459 EXPORT_SYMBOL(netlink_dump_start);
1460 EXPORT_SYMBOL(netlink_kernel_create);
1461 EXPORT_SYMBOL(netlink_register_notifier);
1462 EXPORT_SYMBOL(netlink_set_err);
1463 EXPORT_SYMBOL(netlink_set_nonroot);
1464 EXPORT_SYMBOL(netlink_unicast);
1465 EXPORT_SYMBOL(netlink_unregister_notifier);
1466