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