netlink: implement memory mapped recvmsg()
[firefly-linux-kernel-4.4.55.git] / net / netlink / af_netlink.c
1 /*
2  * NETLINK      Kernel-user communication protocol.
3  *
4  *              Authors:        Alan Cox <alan@lxorguk.ukuu.org.uk>
5  *                              Alexey Kuznetsov <kuznet@ms2.inr.ac.ru>
6  *
7  *              This program is free software; you can redistribute it and/or
8  *              modify it under the terms of the GNU General Public License
9  *              as published by the Free Software Foundation; either version
10  *              2 of the License, or (at your option) any later version.
11  *
12  * Tue Jun 26 14:36:48 MEST 2001 Herbert "herp" Rosmanith
13  *                               added netlink_proto_exit
14  * Tue Jan 22 18:32:44 BRST 2002 Arnaldo C. de Melo <acme@conectiva.com.br>
15  *                               use nlk_sk, as sk->protinfo is on a diet 8)
16  * Fri Jul 22 19:51:12 MEST 2005 Harald Welte <laforge@gnumonks.org>
17  *                               - inc module use count of module that owns
18  *                                 the kernel socket in case userspace opens
19  *                                 socket of same protocol
20  *                               - remove all module support, since netlink is
21  *                                 mandatory if CONFIG_NET=y these days
22  */
23
24 #include <linux/module.h>
25
26 #include <linux/capability.h>
27 #include <linux/kernel.h>
28 #include <linux/init.h>
29 #include <linux/signal.h>
30 #include <linux/sched.h>
31 #include <linux/errno.h>
32 #include <linux/string.h>
33 #include <linux/stat.h>
34 #include <linux/socket.h>
35 #include <linux/un.h>
36 #include <linux/fcntl.h>
37 #include <linux/termios.h>
38 #include <linux/sockios.h>
39 #include <linux/net.h>
40 #include <linux/fs.h>
41 #include <linux/slab.h>
42 #include <asm/uaccess.h>
43 #include <linux/skbuff.h>
44 #include <linux/netdevice.h>
45 #include <linux/rtnetlink.h>
46 #include <linux/proc_fs.h>
47 #include <linux/seq_file.h>
48 #include <linux/notifier.h>
49 #include <linux/security.h>
50 #include <linux/jhash.h>
51 #include <linux/jiffies.h>
52 #include <linux/random.h>
53 #include <linux/bitops.h>
54 #include <linux/mm.h>
55 #include <linux/types.h>
56 #include <linux/audit.h>
57 #include <linux/mutex.h>
58 #include <linux/vmalloc.h>
59 #include <asm/cacheflush.h>
60
61 #include <net/net_namespace.h>
62 #include <net/sock.h>
63 #include <net/scm.h>
64 #include <net/netlink.h>
65
66 #include "af_netlink.h"
67
68 struct listeners {
69         struct rcu_head         rcu;
70         unsigned long           masks[0];
71 };
72
73 /* state bits */
74 #define NETLINK_CONGESTED       0x0
75
76 /* flags */
77 #define NETLINK_KERNEL_SOCKET   0x1
78 #define NETLINK_RECV_PKTINFO    0x2
79 #define NETLINK_BROADCAST_SEND_ERROR    0x4
80 #define NETLINK_RECV_NO_ENOBUFS 0x8
81
82 static inline int netlink_is_kernel(struct sock *sk)
83 {
84         return nlk_sk(sk)->flags & NETLINK_KERNEL_SOCKET;
85 }
86
87 struct netlink_table *nl_table;
88 EXPORT_SYMBOL_GPL(nl_table);
89
90 static DECLARE_WAIT_QUEUE_HEAD(nl_table_wait);
91
92 static int netlink_dump(struct sock *sk);
93 static void netlink_skb_destructor(struct sk_buff *skb);
94
95 DEFINE_RWLOCK(nl_table_lock);
96 EXPORT_SYMBOL_GPL(nl_table_lock);
97 static atomic_t nl_table_users = ATOMIC_INIT(0);
98
99 #define nl_deref_protected(X) rcu_dereference_protected(X, lockdep_is_held(&nl_table_lock));
100
101 static ATOMIC_NOTIFIER_HEAD(netlink_chain);
102
103 static inline u32 netlink_group_mask(u32 group)
104 {
105         return group ? 1 << (group - 1) : 0;
106 }
107
108 static inline struct hlist_head *nl_portid_hashfn(struct nl_portid_hash *hash, u32 portid)
109 {
110         return &hash->table[jhash_1word(portid, hash->rnd) & hash->mask];
111 }
112
113 #ifdef CONFIG_NETLINK_MMAP
114 static bool netlink_skb_is_mmaped(const struct sk_buff *skb)
115 {
116         return NETLINK_CB(skb).flags & NETLINK_SKB_MMAPED;
117 }
118
119 static bool netlink_rx_is_mmaped(struct sock *sk)
120 {
121         return nlk_sk(sk)->rx_ring.pg_vec != NULL;
122 }
123
124 static bool netlink_tx_is_mmaped(struct sock *sk)
125 {
126         return nlk_sk(sk)->tx_ring.pg_vec != NULL;
127 }
128
129 static __pure struct page *pgvec_to_page(const void *addr)
130 {
131         if (is_vmalloc_addr(addr))
132                 return vmalloc_to_page(addr);
133         else
134                 return virt_to_page(addr);
135 }
136
137 static void free_pg_vec(void **pg_vec, unsigned int order, unsigned int len)
138 {
139         unsigned int i;
140
141         for (i = 0; i < len; i++) {
142                 if (pg_vec[i] != NULL) {
143                         if (is_vmalloc_addr(pg_vec[i]))
144                                 vfree(pg_vec[i]);
145                         else
146                                 free_pages((unsigned long)pg_vec[i], order);
147                 }
148         }
149         kfree(pg_vec);
150 }
151
152 static void *alloc_one_pg_vec_page(unsigned long order)
153 {
154         void *buffer;
155         gfp_t gfp_flags = GFP_KERNEL | __GFP_COMP | __GFP_ZERO |
156                           __GFP_NOWARN | __GFP_NORETRY;
157
158         buffer = (void *)__get_free_pages(gfp_flags, order);
159         if (buffer != NULL)
160                 return buffer;
161
162         buffer = vzalloc((1 << order) * PAGE_SIZE);
163         if (buffer != NULL)
164                 return buffer;
165
166         gfp_flags &= ~__GFP_NORETRY;
167         return (void *)__get_free_pages(gfp_flags, order);
168 }
169
170 static void **alloc_pg_vec(struct netlink_sock *nlk,
171                            struct nl_mmap_req *req, unsigned int order)
172 {
173         unsigned int block_nr = req->nm_block_nr;
174         unsigned int i;
175         void **pg_vec, *ptr;
176
177         pg_vec = kcalloc(block_nr, sizeof(void *), GFP_KERNEL);
178         if (pg_vec == NULL)
179                 return NULL;
180
181         for (i = 0; i < block_nr; i++) {
182                 pg_vec[i] = ptr = alloc_one_pg_vec_page(order);
183                 if (pg_vec[i] == NULL)
184                         goto err1;
185         }
186
187         return pg_vec;
188 err1:
189         free_pg_vec(pg_vec, order, block_nr);
190         return NULL;
191 }
192
193 static int netlink_set_ring(struct sock *sk, struct nl_mmap_req *req,
194                             bool closing, bool tx_ring)
195 {
196         struct netlink_sock *nlk = nlk_sk(sk);
197         struct netlink_ring *ring;
198         struct sk_buff_head *queue;
199         void **pg_vec = NULL;
200         unsigned int order = 0;
201         int err;
202
203         ring  = tx_ring ? &nlk->tx_ring : &nlk->rx_ring;
204         queue = tx_ring ? &sk->sk_write_queue : &sk->sk_receive_queue;
205
206         if (!closing) {
207                 if (atomic_read(&nlk->mapped))
208                         return -EBUSY;
209                 if (atomic_read(&ring->pending))
210                         return -EBUSY;
211         }
212
213         if (req->nm_block_nr) {
214                 if (ring->pg_vec != NULL)
215                         return -EBUSY;
216
217                 if ((int)req->nm_block_size <= 0)
218                         return -EINVAL;
219                 if (!IS_ALIGNED(req->nm_block_size, PAGE_SIZE))
220                         return -EINVAL;
221                 if (req->nm_frame_size < NL_MMAP_HDRLEN)
222                         return -EINVAL;
223                 if (!IS_ALIGNED(req->nm_frame_size, NL_MMAP_MSG_ALIGNMENT))
224                         return -EINVAL;
225
226                 ring->frames_per_block = req->nm_block_size /
227                                          req->nm_frame_size;
228                 if (ring->frames_per_block == 0)
229                         return -EINVAL;
230                 if (ring->frames_per_block * req->nm_block_nr !=
231                     req->nm_frame_nr)
232                         return -EINVAL;
233
234                 order = get_order(req->nm_block_size);
235                 pg_vec = alloc_pg_vec(nlk, req, order);
236                 if (pg_vec == NULL)
237                         return -ENOMEM;
238         } else {
239                 if (req->nm_frame_nr)
240                         return -EINVAL;
241         }
242
243         err = -EBUSY;
244         mutex_lock(&nlk->pg_vec_lock);
245         if (closing || atomic_read(&nlk->mapped) == 0) {
246                 err = 0;
247                 spin_lock_bh(&queue->lock);
248
249                 ring->frame_max         = req->nm_frame_nr - 1;
250                 ring->head              = 0;
251                 ring->frame_size        = req->nm_frame_size;
252                 ring->pg_vec_pages      = req->nm_block_size / PAGE_SIZE;
253
254                 swap(ring->pg_vec_len, req->nm_block_nr);
255                 swap(ring->pg_vec_order, order);
256                 swap(ring->pg_vec, pg_vec);
257
258                 __skb_queue_purge(queue);
259                 spin_unlock_bh(&queue->lock);
260
261                 WARN_ON(atomic_read(&nlk->mapped));
262         }
263         mutex_unlock(&nlk->pg_vec_lock);
264
265         if (pg_vec)
266                 free_pg_vec(pg_vec, order, req->nm_block_nr);
267         return err;
268 }
269
270 static void netlink_mm_open(struct vm_area_struct *vma)
271 {
272         struct file *file = vma->vm_file;
273         struct socket *sock = file->private_data;
274         struct sock *sk = sock->sk;
275
276         if (sk)
277                 atomic_inc(&nlk_sk(sk)->mapped);
278 }
279
280 static void netlink_mm_close(struct vm_area_struct *vma)
281 {
282         struct file *file = vma->vm_file;
283         struct socket *sock = file->private_data;
284         struct sock *sk = sock->sk;
285
286         if (sk)
287                 atomic_dec(&nlk_sk(sk)->mapped);
288 }
289
290 static const struct vm_operations_struct netlink_mmap_ops = {
291         .open   = netlink_mm_open,
292         .close  = netlink_mm_close,
293 };
294
295 static int netlink_mmap(struct file *file, struct socket *sock,
296                         struct vm_area_struct *vma)
297 {
298         struct sock *sk = sock->sk;
299         struct netlink_sock *nlk = nlk_sk(sk);
300         struct netlink_ring *ring;
301         unsigned long start, size, expected;
302         unsigned int i;
303         int err = -EINVAL;
304
305         if (vma->vm_pgoff)
306                 return -EINVAL;
307
308         mutex_lock(&nlk->pg_vec_lock);
309
310         expected = 0;
311         for (ring = &nlk->rx_ring; ring <= &nlk->tx_ring; ring++) {
312                 if (ring->pg_vec == NULL)
313                         continue;
314                 expected += ring->pg_vec_len * ring->pg_vec_pages * PAGE_SIZE;
315         }
316
317         if (expected == 0)
318                 goto out;
319
320         size = vma->vm_end - vma->vm_start;
321         if (size != expected)
322                 goto out;
323
324         start = vma->vm_start;
325         for (ring = &nlk->rx_ring; ring <= &nlk->tx_ring; ring++) {
326                 if (ring->pg_vec == NULL)
327                         continue;
328
329                 for (i = 0; i < ring->pg_vec_len; i++) {
330                         struct page *page;
331                         void *kaddr = ring->pg_vec[i];
332                         unsigned int pg_num;
333
334                         for (pg_num = 0; pg_num < ring->pg_vec_pages; pg_num++) {
335                                 page = pgvec_to_page(kaddr);
336                                 err = vm_insert_page(vma, start, page);
337                                 if (err < 0)
338                                         goto out;
339                                 start += PAGE_SIZE;
340                                 kaddr += PAGE_SIZE;
341                         }
342                 }
343         }
344
345         atomic_inc(&nlk->mapped);
346         vma->vm_ops = &netlink_mmap_ops;
347         err = 0;
348 out:
349         mutex_unlock(&nlk->pg_vec_lock);
350         return 0;
351 }
352
353 static void netlink_frame_flush_dcache(const struct nl_mmap_hdr *hdr)
354 {
355 #if ARCH_IMPLEMENTS_FLUSH_DCACHE_PAGE == 1
356         struct page *p_start, *p_end;
357
358         /* First page is flushed through netlink_{get,set}_status */
359         p_start = pgvec_to_page(hdr + PAGE_SIZE);
360         p_end   = pgvec_to_page((void *)hdr + NL_MMAP_MSG_HDRLEN + hdr->nm_len - 1);
361         while (p_start <= p_end) {
362                 flush_dcache_page(p_start);
363                 p_start++;
364         }
365 #endif
366 }
367
368 static enum nl_mmap_status netlink_get_status(const struct nl_mmap_hdr *hdr)
369 {
370         smp_rmb();
371         flush_dcache_page(pgvec_to_page(hdr));
372         return hdr->nm_status;
373 }
374
375 static void netlink_set_status(struct nl_mmap_hdr *hdr,
376                                enum nl_mmap_status status)
377 {
378         hdr->nm_status = status;
379         flush_dcache_page(pgvec_to_page(hdr));
380         smp_wmb();
381 }
382
383 static struct nl_mmap_hdr *
384 __netlink_lookup_frame(const struct netlink_ring *ring, unsigned int pos)
385 {
386         unsigned int pg_vec_pos, frame_off;
387
388         pg_vec_pos = pos / ring->frames_per_block;
389         frame_off  = pos % ring->frames_per_block;
390
391         return ring->pg_vec[pg_vec_pos] + (frame_off * ring->frame_size);
392 }
393
394 static struct nl_mmap_hdr *
395 netlink_lookup_frame(const struct netlink_ring *ring, unsigned int pos,
396                      enum nl_mmap_status status)
397 {
398         struct nl_mmap_hdr *hdr;
399
400         hdr = __netlink_lookup_frame(ring, pos);
401         if (netlink_get_status(hdr) != status)
402                 return NULL;
403
404         return hdr;
405 }
406
407 static struct nl_mmap_hdr *
408 netlink_current_frame(const struct netlink_ring *ring,
409                       enum nl_mmap_status status)
410 {
411         return netlink_lookup_frame(ring, ring->head, status);
412 }
413
414 static struct nl_mmap_hdr *
415 netlink_previous_frame(const struct netlink_ring *ring,
416                        enum nl_mmap_status status)
417 {
418         unsigned int prev;
419
420         prev = ring->head ? ring->head - 1 : ring->frame_max;
421         return netlink_lookup_frame(ring, prev, status);
422 }
423
424 static void netlink_increment_head(struct netlink_ring *ring)
425 {
426         ring->head = ring->head != ring->frame_max ? ring->head + 1 : 0;
427 }
428
429 static void netlink_forward_ring(struct netlink_ring *ring)
430 {
431         unsigned int head = ring->head, pos = head;
432         const struct nl_mmap_hdr *hdr;
433
434         do {
435                 hdr = __netlink_lookup_frame(ring, pos);
436                 if (hdr->nm_status == NL_MMAP_STATUS_UNUSED)
437                         break;
438                 if (hdr->nm_status != NL_MMAP_STATUS_SKIP)
439                         break;
440                 netlink_increment_head(ring);
441         } while (ring->head != head);
442 }
443
444 static unsigned int netlink_poll(struct file *file, struct socket *sock,
445                                  poll_table *wait)
446 {
447         struct sock *sk = sock->sk;
448         struct netlink_sock *nlk = nlk_sk(sk);
449         unsigned int mask;
450
451         if (nlk->cb != NULL && nlk->rx_ring.pg_vec != NULL)
452                 netlink_dump(sk);
453
454         mask = datagram_poll(file, sock, wait);
455
456         spin_lock_bh(&sk->sk_receive_queue.lock);
457         if (nlk->rx_ring.pg_vec) {
458                 netlink_forward_ring(&nlk->rx_ring);
459                 if (!netlink_previous_frame(&nlk->rx_ring, NL_MMAP_STATUS_UNUSED))
460                         mask |= POLLIN | POLLRDNORM;
461         }
462         spin_unlock_bh(&sk->sk_receive_queue.lock);
463
464         spin_lock_bh(&sk->sk_write_queue.lock);
465         if (nlk->tx_ring.pg_vec) {
466                 if (netlink_current_frame(&nlk->tx_ring, NL_MMAP_STATUS_UNUSED))
467                         mask |= POLLOUT | POLLWRNORM;
468         }
469         spin_unlock_bh(&sk->sk_write_queue.lock);
470
471         return mask;
472 }
473
474 static struct nl_mmap_hdr *netlink_mmap_hdr(struct sk_buff *skb)
475 {
476         return (struct nl_mmap_hdr *)(skb->head - NL_MMAP_HDRLEN);
477 }
478
479 static void netlink_ring_setup_skb(struct sk_buff *skb, struct sock *sk,
480                                    struct netlink_ring *ring,
481                                    struct nl_mmap_hdr *hdr)
482 {
483         unsigned int size;
484         void *data;
485
486         size = ring->frame_size - NL_MMAP_HDRLEN;
487         data = (void *)hdr + NL_MMAP_HDRLEN;
488
489         skb->head       = data;
490         skb->data       = data;
491         skb_reset_tail_pointer(skb);
492         skb->end        = skb->tail + size;
493         skb->len        = 0;
494
495         skb->destructor = netlink_skb_destructor;
496         NETLINK_CB(skb).flags |= NETLINK_SKB_MMAPED;
497         NETLINK_CB(skb).sk = sk;
498 }
499
500 static int netlink_mmap_sendmsg(struct sock *sk, struct msghdr *msg,
501                                 u32 dst_portid, u32 dst_group,
502                                 struct sock_iocb *siocb)
503 {
504         struct netlink_sock *nlk = nlk_sk(sk);
505         struct netlink_ring *ring;
506         struct nl_mmap_hdr *hdr;
507         struct sk_buff *skb;
508         unsigned int maxlen;
509         bool excl = true;
510         int err = 0, len = 0;
511
512         /* Netlink messages are validated by the receiver before processing.
513          * In order to avoid userspace changing the contents of the message
514          * after validation, the socket and the ring may only be used by a
515          * single process, otherwise we fall back to copying.
516          */
517         if (atomic_long_read(&sk->sk_socket->file->f_count) > 2 ||
518             atomic_read(&nlk->mapped) > 1)
519                 excl = false;
520
521         mutex_lock(&nlk->pg_vec_lock);
522
523         ring   = &nlk->tx_ring;
524         maxlen = ring->frame_size - NL_MMAP_HDRLEN;
525
526         do {
527                 hdr = netlink_current_frame(ring, NL_MMAP_STATUS_VALID);
528                 if (hdr == NULL) {
529                         if (!(msg->msg_flags & MSG_DONTWAIT) &&
530                             atomic_read(&nlk->tx_ring.pending))
531                                 schedule();
532                         continue;
533                 }
534                 if (hdr->nm_len > maxlen) {
535                         err = -EINVAL;
536                         goto out;
537                 }
538
539                 netlink_frame_flush_dcache(hdr);
540
541                 if (likely(dst_portid == 0 && dst_group == 0 && excl)) {
542                         skb = alloc_skb_head(GFP_KERNEL);
543                         if (skb == NULL) {
544                                 err = -ENOBUFS;
545                                 goto out;
546                         }
547                         sock_hold(sk);
548                         netlink_ring_setup_skb(skb, sk, ring, hdr);
549                         NETLINK_CB(skb).flags |= NETLINK_SKB_TX;
550                         __skb_put(skb, hdr->nm_len);
551                         netlink_set_status(hdr, NL_MMAP_STATUS_RESERVED);
552                         atomic_inc(&ring->pending);
553                 } else {
554                         skb = alloc_skb(hdr->nm_len, GFP_KERNEL);
555                         if (skb == NULL) {
556                                 err = -ENOBUFS;
557                                 goto out;
558                         }
559                         __skb_put(skb, hdr->nm_len);
560                         memcpy(skb->data, (void *)hdr + NL_MMAP_HDRLEN, hdr->nm_len);
561                         netlink_set_status(hdr, NL_MMAP_STATUS_UNUSED);
562                 }
563
564                 netlink_increment_head(ring);
565
566                 NETLINK_CB(skb).portid    = nlk->portid;
567                 NETLINK_CB(skb).dst_group = dst_group;
568                 NETLINK_CB(skb).creds     = siocb->scm->creds;
569
570                 err = security_netlink_send(sk, skb);
571                 if (err) {
572                         kfree_skb(skb);
573                         goto out;
574                 }
575
576                 if (unlikely(dst_group)) {
577                         atomic_inc(&skb->users);
578                         netlink_broadcast(sk, skb, dst_portid, dst_group,
579                                           GFP_KERNEL);
580                 }
581                 err = netlink_unicast(sk, skb, dst_portid,
582                                       msg->msg_flags & MSG_DONTWAIT);
583                 if (err < 0)
584                         goto out;
585                 len += err;
586
587         } while (hdr != NULL ||
588                  (!(msg->msg_flags & MSG_DONTWAIT) &&
589                   atomic_read(&nlk->tx_ring.pending)));
590
591         if (len > 0)
592                 err = len;
593 out:
594         mutex_unlock(&nlk->pg_vec_lock);
595         return err;
596 }
597
598 static void netlink_queue_mmaped_skb(struct sock *sk, struct sk_buff *skb)
599 {
600         struct nl_mmap_hdr *hdr;
601
602         hdr = netlink_mmap_hdr(skb);
603         hdr->nm_len     = skb->len;
604         hdr->nm_group   = NETLINK_CB(skb).dst_group;
605         hdr->nm_pid     = NETLINK_CB(skb).creds.pid;
606         hdr->nm_uid     = NETLINK_CB(skb).creds.uid;
607         hdr->nm_gid     = NETLINK_CB(skb).creds.gid;
608         netlink_frame_flush_dcache(hdr);
609         netlink_set_status(hdr, NL_MMAP_STATUS_VALID);
610
611         NETLINK_CB(skb).flags |= NETLINK_SKB_DELIVERED;
612         kfree_skb(skb);
613 }
614
615 static void netlink_ring_set_copied(struct sock *sk, struct sk_buff *skb)
616 {
617         struct netlink_sock *nlk = nlk_sk(sk);
618         struct netlink_ring *ring = &nlk->rx_ring;
619         struct nl_mmap_hdr *hdr;
620
621         spin_lock_bh(&sk->sk_receive_queue.lock);
622         hdr = netlink_current_frame(ring, NL_MMAP_STATUS_UNUSED);
623         if (hdr == NULL) {
624                 spin_unlock_bh(&sk->sk_receive_queue.lock);
625                 kfree_skb(skb);
626                 sk->sk_err = ENOBUFS;
627                 sk->sk_error_report(sk);
628                 return;
629         }
630         netlink_increment_head(ring);
631         __skb_queue_tail(&sk->sk_receive_queue, skb);
632         spin_unlock_bh(&sk->sk_receive_queue.lock);
633
634         hdr->nm_len     = skb->len;
635         hdr->nm_group   = NETLINK_CB(skb).dst_group;
636         hdr->nm_pid     = NETLINK_CB(skb).creds.pid;
637         hdr->nm_uid     = NETLINK_CB(skb).creds.uid;
638         hdr->nm_gid     = NETLINK_CB(skb).creds.gid;
639         netlink_set_status(hdr, NL_MMAP_STATUS_COPY);
640 }
641
642 #else /* CONFIG_NETLINK_MMAP */
643 #define netlink_skb_is_mmaped(skb)      false
644 #define netlink_rx_is_mmaped(sk)        false
645 #define netlink_tx_is_mmaped(sk)        false
646 #define netlink_mmap                    sock_no_mmap
647 #define netlink_poll                    datagram_poll
648 #define netlink_mmap_sendmsg(sk, msg, dst_portid, dst_group, siocb)     0
649 #endif /* CONFIG_NETLINK_MMAP */
650
651 static void netlink_destroy_callback(struct netlink_callback *cb)
652 {
653         kfree_skb(cb->skb);
654         kfree(cb);
655 }
656
657 static void netlink_consume_callback(struct netlink_callback *cb)
658 {
659         consume_skb(cb->skb);
660         kfree(cb);
661 }
662
663 static void netlink_skb_destructor(struct sk_buff *skb)
664 {
665 #ifdef CONFIG_NETLINK_MMAP
666         struct nl_mmap_hdr *hdr;
667         struct netlink_ring *ring;
668         struct sock *sk;
669
670         /* If a packet from the kernel to userspace was freed because of an
671          * error without being delivered to userspace, the kernel must reset
672          * the status. In the direction userspace to kernel, the status is
673          * always reset here after the packet was processed and freed.
674          */
675         if (netlink_skb_is_mmaped(skb)) {
676                 hdr = netlink_mmap_hdr(skb);
677                 sk = NETLINK_CB(skb).sk;
678
679                 if (NETLINK_CB(skb).flags & NETLINK_SKB_TX) {
680                         netlink_set_status(hdr, NL_MMAP_STATUS_UNUSED);
681                         ring = &nlk_sk(sk)->tx_ring;
682                 } else {
683                         if (!(NETLINK_CB(skb).flags & NETLINK_SKB_DELIVERED)) {
684                                 hdr->nm_len = 0;
685                                 netlink_set_status(hdr, NL_MMAP_STATUS_VALID);
686                         }
687                         ring = &nlk_sk(sk)->rx_ring;
688                 }
689
690                 WARN_ON(atomic_read(&ring->pending) == 0);
691                 atomic_dec(&ring->pending);
692                 sock_put(sk);
693
694                 skb->data = NULL;
695         }
696 #endif
697         if (skb->sk != NULL)
698                 sock_rfree(skb);
699 }
700
701 static void netlink_skb_set_owner_r(struct sk_buff *skb, struct sock *sk)
702 {
703         WARN_ON(skb->sk != NULL);
704         skb->sk = sk;
705         skb->destructor = netlink_skb_destructor;
706         atomic_add(skb->truesize, &sk->sk_rmem_alloc);
707         sk_mem_charge(sk, skb->truesize);
708 }
709
710 static void netlink_sock_destruct(struct sock *sk)
711 {
712         struct netlink_sock *nlk = nlk_sk(sk);
713
714         if (nlk->cb) {
715                 if (nlk->cb->done)
716                         nlk->cb->done(nlk->cb);
717
718                 module_put(nlk->cb->module);
719                 netlink_destroy_callback(nlk->cb);
720         }
721
722         skb_queue_purge(&sk->sk_receive_queue);
723 #ifdef CONFIG_NETLINK_MMAP
724         if (1) {
725                 struct nl_mmap_req req;
726
727                 memset(&req, 0, sizeof(req));
728                 if (nlk->rx_ring.pg_vec)
729                         netlink_set_ring(sk, &req, true, false);
730                 memset(&req, 0, sizeof(req));
731                 if (nlk->tx_ring.pg_vec)
732                         netlink_set_ring(sk, &req, true, true);
733         }
734 #endif /* CONFIG_NETLINK_MMAP */
735
736         if (!sock_flag(sk, SOCK_DEAD)) {
737                 printk(KERN_ERR "Freeing alive netlink socket %p\n", sk);
738                 return;
739         }
740
741         WARN_ON(atomic_read(&sk->sk_rmem_alloc));
742         WARN_ON(atomic_read(&sk->sk_wmem_alloc));
743         WARN_ON(nlk_sk(sk)->groups);
744 }
745
746 /* This lock without WQ_FLAG_EXCLUSIVE is good on UP and it is _very_ bad on
747  * SMP. Look, when several writers sleep and reader wakes them up, all but one
748  * immediately hit write lock and grab all the cpus. Exclusive sleep solves
749  * this, _but_ remember, it adds useless work on UP machines.
750  */
751
752 void netlink_table_grab(void)
753         __acquires(nl_table_lock)
754 {
755         might_sleep();
756
757         write_lock_irq(&nl_table_lock);
758
759         if (atomic_read(&nl_table_users)) {
760                 DECLARE_WAITQUEUE(wait, current);
761
762                 add_wait_queue_exclusive(&nl_table_wait, &wait);
763                 for (;;) {
764                         set_current_state(TASK_UNINTERRUPTIBLE);
765                         if (atomic_read(&nl_table_users) == 0)
766                                 break;
767                         write_unlock_irq(&nl_table_lock);
768                         schedule();
769                         write_lock_irq(&nl_table_lock);
770                 }
771
772                 __set_current_state(TASK_RUNNING);
773                 remove_wait_queue(&nl_table_wait, &wait);
774         }
775 }
776
777 void netlink_table_ungrab(void)
778         __releases(nl_table_lock)
779 {
780         write_unlock_irq(&nl_table_lock);
781         wake_up(&nl_table_wait);
782 }
783
784 static inline void
785 netlink_lock_table(void)
786 {
787         /* read_lock() synchronizes us to netlink_table_grab */
788
789         read_lock(&nl_table_lock);
790         atomic_inc(&nl_table_users);
791         read_unlock(&nl_table_lock);
792 }
793
794 static inline void
795 netlink_unlock_table(void)
796 {
797         if (atomic_dec_and_test(&nl_table_users))
798                 wake_up(&nl_table_wait);
799 }
800
801 static struct sock *netlink_lookup(struct net *net, int protocol, u32 portid)
802 {
803         struct nl_portid_hash *hash = &nl_table[protocol].hash;
804         struct hlist_head *head;
805         struct sock *sk;
806
807         read_lock(&nl_table_lock);
808         head = nl_portid_hashfn(hash, portid);
809         sk_for_each(sk, head) {
810                 if (net_eq(sock_net(sk), net) && (nlk_sk(sk)->portid == portid)) {
811                         sock_hold(sk);
812                         goto found;
813                 }
814         }
815         sk = NULL;
816 found:
817         read_unlock(&nl_table_lock);
818         return sk;
819 }
820
821 static struct hlist_head *nl_portid_hash_zalloc(size_t size)
822 {
823         if (size <= PAGE_SIZE)
824                 return kzalloc(size, GFP_ATOMIC);
825         else
826                 return (struct hlist_head *)
827                         __get_free_pages(GFP_ATOMIC | __GFP_ZERO,
828                                          get_order(size));
829 }
830
831 static void nl_portid_hash_free(struct hlist_head *table, size_t size)
832 {
833         if (size <= PAGE_SIZE)
834                 kfree(table);
835         else
836                 free_pages((unsigned long)table, get_order(size));
837 }
838
839 static int nl_portid_hash_rehash(struct nl_portid_hash *hash, int grow)
840 {
841         unsigned int omask, mask, shift;
842         size_t osize, size;
843         struct hlist_head *otable, *table;
844         int i;
845
846         omask = mask = hash->mask;
847         osize = size = (mask + 1) * sizeof(*table);
848         shift = hash->shift;
849
850         if (grow) {
851                 if (++shift > hash->max_shift)
852                         return 0;
853                 mask = mask * 2 + 1;
854                 size *= 2;
855         }
856
857         table = nl_portid_hash_zalloc(size);
858         if (!table)
859                 return 0;
860
861         otable = hash->table;
862         hash->table = table;
863         hash->mask = mask;
864         hash->shift = shift;
865         get_random_bytes(&hash->rnd, sizeof(hash->rnd));
866
867         for (i = 0; i <= omask; i++) {
868                 struct sock *sk;
869                 struct hlist_node *tmp;
870
871                 sk_for_each_safe(sk, tmp, &otable[i])
872                         __sk_add_node(sk, nl_portid_hashfn(hash, nlk_sk(sk)->portid));
873         }
874
875         nl_portid_hash_free(otable, osize);
876         hash->rehash_time = jiffies + 10 * 60 * HZ;
877         return 1;
878 }
879
880 static inline int nl_portid_hash_dilute(struct nl_portid_hash *hash, int len)
881 {
882         int avg = hash->entries >> hash->shift;
883
884         if (unlikely(avg > 1) && nl_portid_hash_rehash(hash, 1))
885                 return 1;
886
887         if (unlikely(len > avg) && time_after(jiffies, hash->rehash_time)) {
888                 nl_portid_hash_rehash(hash, 0);
889                 return 1;
890         }
891
892         return 0;
893 }
894
895 static const struct proto_ops netlink_ops;
896
897 static void
898 netlink_update_listeners(struct sock *sk)
899 {
900         struct netlink_table *tbl = &nl_table[sk->sk_protocol];
901         unsigned long mask;
902         unsigned int i;
903         struct listeners *listeners;
904
905         listeners = nl_deref_protected(tbl->listeners);
906         if (!listeners)
907                 return;
908
909         for (i = 0; i < NLGRPLONGS(tbl->groups); i++) {
910                 mask = 0;
911                 sk_for_each_bound(sk, &tbl->mc_list) {
912                         if (i < NLGRPLONGS(nlk_sk(sk)->ngroups))
913                                 mask |= nlk_sk(sk)->groups[i];
914                 }
915                 listeners->masks[i] = mask;
916         }
917         /* this function is only called with the netlink table "grabbed", which
918          * makes sure updates are visible before bind or setsockopt return. */
919 }
920
921 static int netlink_insert(struct sock *sk, struct net *net, u32 portid)
922 {
923         struct nl_portid_hash *hash = &nl_table[sk->sk_protocol].hash;
924         struct hlist_head *head;
925         int err = -EADDRINUSE;
926         struct sock *osk;
927         int len;
928
929         netlink_table_grab();
930         head = nl_portid_hashfn(hash, portid);
931         len = 0;
932         sk_for_each(osk, head) {
933                 if (net_eq(sock_net(osk), net) && (nlk_sk(osk)->portid == portid))
934                         break;
935                 len++;
936         }
937         if (osk)
938                 goto err;
939
940         err = -EBUSY;
941         if (nlk_sk(sk)->portid)
942                 goto err;
943
944         err = -ENOMEM;
945         if (BITS_PER_LONG > 32 && unlikely(hash->entries >= UINT_MAX))
946                 goto err;
947
948         if (len && nl_portid_hash_dilute(hash, len))
949                 head = nl_portid_hashfn(hash, portid);
950         hash->entries++;
951         nlk_sk(sk)->portid = portid;
952         sk_add_node(sk, head);
953         err = 0;
954
955 err:
956         netlink_table_ungrab();
957         return err;
958 }
959
960 static void netlink_remove(struct sock *sk)
961 {
962         netlink_table_grab();
963         if (sk_del_node_init(sk))
964                 nl_table[sk->sk_protocol].hash.entries--;
965         if (nlk_sk(sk)->subscriptions)
966                 __sk_del_bind_node(sk);
967         netlink_table_ungrab();
968 }
969
970 static struct proto netlink_proto = {
971         .name     = "NETLINK",
972         .owner    = THIS_MODULE,
973         .obj_size = sizeof(struct netlink_sock),
974 };
975
976 static int __netlink_create(struct net *net, struct socket *sock,
977                             struct mutex *cb_mutex, int protocol)
978 {
979         struct sock *sk;
980         struct netlink_sock *nlk;
981
982         sock->ops = &netlink_ops;
983
984         sk = sk_alloc(net, PF_NETLINK, GFP_KERNEL, &netlink_proto);
985         if (!sk)
986                 return -ENOMEM;
987
988         sock_init_data(sock, sk);
989
990         nlk = nlk_sk(sk);
991         if (cb_mutex) {
992                 nlk->cb_mutex = cb_mutex;
993         } else {
994                 nlk->cb_mutex = &nlk->cb_def_mutex;
995                 mutex_init(nlk->cb_mutex);
996         }
997         init_waitqueue_head(&nlk->wait);
998 #ifdef CONFIG_NETLINK_MMAP
999         mutex_init(&nlk->pg_vec_lock);
1000 #endif
1001
1002         sk->sk_destruct = netlink_sock_destruct;
1003         sk->sk_protocol = protocol;
1004         return 0;
1005 }
1006
1007 static int netlink_create(struct net *net, struct socket *sock, int protocol,
1008                           int kern)
1009 {
1010         struct module *module = NULL;
1011         struct mutex *cb_mutex;
1012         struct netlink_sock *nlk;
1013         void (*bind)(int group);
1014         int err = 0;
1015
1016         sock->state = SS_UNCONNECTED;
1017
1018         if (sock->type != SOCK_RAW && sock->type != SOCK_DGRAM)
1019                 return -ESOCKTNOSUPPORT;
1020
1021         if (protocol < 0 || protocol >= MAX_LINKS)
1022                 return -EPROTONOSUPPORT;
1023
1024         netlink_lock_table();
1025 #ifdef CONFIG_MODULES
1026         if (!nl_table[protocol].registered) {
1027                 netlink_unlock_table();
1028                 request_module("net-pf-%d-proto-%d", PF_NETLINK, protocol);
1029                 netlink_lock_table();
1030         }
1031 #endif
1032         if (nl_table[protocol].registered &&
1033             try_module_get(nl_table[protocol].module))
1034                 module = nl_table[protocol].module;
1035         else
1036                 err = -EPROTONOSUPPORT;
1037         cb_mutex = nl_table[protocol].cb_mutex;
1038         bind = nl_table[protocol].bind;
1039         netlink_unlock_table();
1040
1041         if (err < 0)
1042                 goto out;
1043
1044         err = __netlink_create(net, sock, cb_mutex, protocol);
1045         if (err < 0)
1046                 goto out_module;
1047
1048         local_bh_disable();
1049         sock_prot_inuse_add(net, &netlink_proto, 1);
1050         local_bh_enable();
1051
1052         nlk = nlk_sk(sock->sk);
1053         nlk->module = module;
1054         nlk->netlink_bind = bind;
1055 out:
1056         return err;
1057
1058 out_module:
1059         module_put(module);
1060         goto out;
1061 }
1062
1063 static int netlink_release(struct socket *sock)
1064 {
1065         struct sock *sk = sock->sk;
1066         struct netlink_sock *nlk;
1067
1068         if (!sk)
1069                 return 0;
1070
1071         netlink_remove(sk);
1072         sock_orphan(sk);
1073         nlk = nlk_sk(sk);
1074
1075         /*
1076          * OK. Socket is unlinked, any packets that arrive now
1077          * will be purged.
1078          */
1079
1080         sock->sk = NULL;
1081         wake_up_interruptible_all(&nlk->wait);
1082
1083         skb_queue_purge(&sk->sk_write_queue);
1084
1085         if (nlk->portid) {
1086                 struct netlink_notify n = {
1087                                                 .net = sock_net(sk),
1088                                                 .protocol = sk->sk_protocol,
1089                                                 .portid = nlk->portid,
1090                                           };
1091                 atomic_notifier_call_chain(&netlink_chain,
1092                                 NETLINK_URELEASE, &n);
1093         }
1094
1095         module_put(nlk->module);
1096
1097         netlink_table_grab();
1098         if (netlink_is_kernel(sk)) {
1099                 BUG_ON(nl_table[sk->sk_protocol].registered == 0);
1100                 if (--nl_table[sk->sk_protocol].registered == 0) {
1101                         struct listeners *old;
1102
1103                         old = nl_deref_protected(nl_table[sk->sk_protocol].listeners);
1104                         RCU_INIT_POINTER(nl_table[sk->sk_protocol].listeners, NULL);
1105                         kfree_rcu(old, rcu);
1106                         nl_table[sk->sk_protocol].module = NULL;
1107                         nl_table[sk->sk_protocol].bind = NULL;
1108                         nl_table[sk->sk_protocol].flags = 0;
1109                         nl_table[sk->sk_protocol].registered = 0;
1110                 }
1111         } else if (nlk->subscriptions) {
1112                 netlink_update_listeners(sk);
1113         }
1114         netlink_table_ungrab();
1115
1116         kfree(nlk->groups);
1117         nlk->groups = NULL;
1118
1119         local_bh_disable();
1120         sock_prot_inuse_add(sock_net(sk), &netlink_proto, -1);
1121         local_bh_enable();
1122         sock_put(sk);
1123         return 0;
1124 }
1125
1126 static int netlink_autobind(struct socket *sock)
1127 {
1128         struct sock *sk = sock->sk;
1129         struct net *net = sock_net(sk);
1130         struct nl_portid_hash *hash = &nl_table[sk->sk_protocol].hash;
1131         struct hlist_head *head;
1132         struct sock *osk;
1133         s32 portid = task_tgid_vnr(current);
1134         int err;
1135         static s32 rover = -4097;
1136
1137 retry:
1138         cond_resched();
1139         netlink_table_grab();
1140         head = nl_portid_hashfn(hash, portid);
1141         sk_for_each(osk, head) {
1142                 if (!net_eq(sock_net(osk), net))
1143                         continue;
1144                 if (nlk_sk(osk)->portid == portid) {
1145                         /* Bind collision, search negative portid values. */
1146                         portid = rover--;
1147                         if (rover > -4097)
1148                                 rover = -4097;
1149                         netlink_table_ungrab();
1150                         goto retry;
1151                 }
1152         }
1153         netlink_table_ungrab();
1154
1155         err = netlink_insert(sk, net, portid);
1156         if (err == -EADDRINUSE)
1157                 goto retry;
1158
1159         /* If 2 threads race to autobind, that is fine.  */
1160         if (err == -EBUSY)
1161                 err = 0;
1162
1163         return err;
1164 }
1165
1166 static inline int netlink_capable(const struct socket *sock, unsigned int flag)
1167 {
1168         return (nl_table[sock->sk->sk_protocol].flags & flag) ||
1169                 ns_capable(sock_net(sock->sk)->user_ns, CAP_NET_ADMIN);
1170 }
1171
1172 static void
1173 netlink_update_subscriptions(struct sock *sk, unsigned int subscriptions)
1174 {
1175         struct netlink_sock *nlk = nlk_sk(sk);
1176
1177         if (nlk->subscriptions && !subscriptions)
1178                 __sk_del_bind_node(sk);
1179         else if (!nlk->subscriptions && subscriptions)
1180                 sk_add_bind_node(sk, &nl_table[sk->sk_protocol].mc_list);
1181         nlk->subscriptions = subscriptions;
1182 }
1183
1184 static int netlink_realloc_groups(struct sock *sk)
1185 {
1186         struct netlink_sock *nlk = nlk_sk(sk);
1187         unsigned int groups;
1188         unsigned long *new_groups;
1189         int err = 0;
1190
1191         netlink_table_grab();
1192
1193         groups = nl_table[sk->sk_protocol].groups;
1194         if (!nl_table[sk->sk_protocol].registered) {
1195                 err = -ENOENT;
1196                 goto out_unlock;
1197         }
1198
1199         if (nlk->ngroups >= groups)
1200                 goto out_unlock;
1201
1202         new_groups = krealloc(nlk->groups, NLGRPSZ(groups), GFP_ATOMIC);
1203         if (new_groups == NULL) {
1204                 err = -ENOMEM;
1205                 goto out_unlock;
1206         }
1207         memset((char *)new_groups + NLGRPSZ(nlk->ngroups), 0,
1208                NLGRPSZ(groups) - NLGRPSZ(nlk->ngroups));
1209
1210         nlk->groups = new_groups;
1211         nlk->ngroups = groups;
1212  out_unlock:
1213         netlink_table_ungrab();
1214         return err;
1215 }
1216
1217 static int netlink_bind(struct socket *sock, struct sockaddr *addr,
1218                         int addr_len)
1219 {
1220         struct sock *sk = sock->sk;
1221         struct net *net = sock_net(sk);
1222         struct netlink_sock *nlk = nlk_sk(sk);
1223         struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
1224         int err;
1225
1226         if (addr_len < sizeof(struct sockaddr_nl))
1227                 return -EINVAL;
1228
1229         if (nladdr->nl_family != AF_NETLINK)
1230                 return -EINVAL;
1231
1232         /* Only superuser is allowed to listen multicasts */
1233         if (nladdr->nl_groups) {
1234                 if (!netlink_capable(sock, NL_CFG_F_NONROOT_RECV))
1235                         return -EPERM;
1236                 err = netlink_realloc_groups(sk);
1237                 if (err)
1238                         return err;
1239         }
1240
1241         if (nlk->portid) {
1242                 if (nladdr->nl_pid != nlk->portid)
1243                         return -EINVAL;
1244         } else {
1245                 err = nladdr->nl_pid ?
1246                         netlink_insert(sk, net, nladdr->nl_pid) :
1247                         netlink_autobind(sock);
1248                 if (err)
1249                         return err;
1250         }
1251
1252         if (!nladdr->nl_groups && (nlk->groups == NULL || !(u32)nlk->groups[0]))
1253                 return 0;
1254
1255         netlink_table_grab();
1256         netlink_update_subscriptions(sk, nlk->subscriptions +
1257                                          hweight32(nladdr->nl_groups) -
1258                                          hweight32(nlk->groups[0]));
1259         nlk->groups[0] = (nlk->groups[0] & ~0xffffffffUL) | nladdr->nl_groups;
1260         netlink_update_listeners(sk);
1261         netlink_table_ungrab();
1262
1263         if (nlk->netlink_bind && nlk->groups[0]) {
1264                 int i;
1265
1266                 for (i=0; i<nlk->ngroups; i++) {
1267                         if (test_bit(i, nlk->groups))
1268                                 nlk->netlink_bind(i);
1269                 }
1270         }
1271
1272         return 0;
1273 }
1274
1275 static int netlink_connect(struct socket *sock, struct sockaddr *addr,
1276                            int alen, int flags)
1277 {
1278         int err = 0;
1279         struct sock *sk = sock->sk;
1280         struct netlink_sock *nlk = nlk_sk(sk);
1281         struct sockaddr_nl *nladdr = (struct sockaddr_nl *)addr;
1282
1283         if (alen < sizeof(addr->sa_family))
1284                 return -EINVAL;
1285
1286         if (addr->sa_family == AF_UNSPEC) {
1287                 sk->sk_state    = NETLINK_UNCONNECTED;
1288                 nlk->dst_portid = 0;
1289                 nlk->dst_group  = 0;
1290                 return 0;
1291         }
1292         if (addr->sa_family != AF_NETLINK)
1293                 return -EINVAL;
1294
1295         /* Only superuser is allowed to send multicasts */
1296         if (nladdr->nl_groups && !netlink_capable(sock, NL_CFG_F_NONROOT_SEND))
1297                 return -EPERM;
1298
1299         if (!nlk->portid)
1300                 err = netlink_autobind(sock);
1301
1302         if (err == 0) {
1303                 sk->sk_state    = NETLINK_CONNECTED;
1304                 nlk->dst_portid = nladdr->nl_pid;
1305                 nlk->dst_group  = ffs(nladdr->nl_groups);
1306         }
1307
1308         return err;
1309 }
1310
1311 static int netlink_getname(struct socket *sock, struct sockaddr *addr,
1312                            int *addr_len, int peer)
1313 {
1314         struct sock *sk = sock->sk;
1315         struct netlink_sock *nlk = nlk_sk(sk);
1316         DECLARE_SOCKADDR(struct sockaddr_nl *, nladdr, addr);
1317
1318         nladdr->nl_family = AF_NETLINK;
1319         nladdr->nl_pad = 0;
1320         *addr_len = sizeof(*nladdr);
1321
1322         if (peer) {
1323                 nladdr->nl_pid = nlk->dst_portid;
1324                 nladdr->nl_groups = netlink_group_mask(nlk->dst_group);
1325         } else {
1326                 nladdr->nl_pid = nlk->portid;
1327                 nladdr->nl_groups = nlk->groups ? nlk->groups[0] : 0;
1328         }
1329         return 0;
1330 }
1331
1332 static void netlink_overrun(struct sock *sk)
1333 {
1334         struct netlink_sock *nlk = nlk_sk(sk);
1335
1336         if (!(nlk->flags & NETLINK_RECV_NO_ENOBUFS)) {
1337                 if (!test_and_set_bit(NETLINK_CONGESTED, &nlk_sk(sk)->state)) {
1338                         sk->sk_err = ENOBUFS;
1339                         sk->sk_error_report(sk);
1340                 }
1341         }
1342         atomic_inc(&sk->sk_drops);
1343 }
1344
1345 static struct sock *netlink_getsockbyportid(struct sock *ssk, u32 portid)
1346 {
1347         struct sock *sock;
1348         struct netlink_sock *nlk;
1349
1350         sock = netlink_lookup(sock_net(ssk), ssk->sk_protocol, portid);
1351         if (!sock)
1352                 return ERR_PTR(-ECONNREFUSED);
1353
1354         /* Don't bother queuing skb if kernel socket has no input function */
1355         nlk = nlk_sk(sock);
1356         if (sock->sk_state == NETLINK_CONNECTED &&
1357             nlk->dst_portid != nlk_sk(ssk)->portid) {
1358                 sock_put(sock);
1359                 return ERR_PTR(-ECONNREFUSED);
1360         }
1361         return sock;
1362 }
1363
1364 struct sock *netlink_getsockbyfilp(struct file *filp)
1365 {
1366         struct inode *inode = file_inode(filp);
1367         struct sock *sock;
1368
1369         if (!S_ISSOCK(inode->i_mode))
1370                 return ERR_PTR(-ENOTSOCK);
1371
1372         sock = SOCKET_I(inode)->sk;
1373         if (sock->sk_family != AF_NETLINK)
1374                 return ERR_PTR(-EINVAL);
1375
1376         sock_hold(sock);
1377         return sock;
1378 }
1379
1380 /*
1381  * Attach a skb to a netlink socket.
1382  * The caller must hold a reference to the destination socket. On error, the
1383  * reference is dropped. The skb is not send to the destination, just all
1384  * all error checks are performed and memory in the queue is reserved.
1385  * Return values:
1386  * < 0: error. skb freed, reference to sock dropped.
1387  * 0: continue
1388  * 1: repeat lookup - reference dropped while waiting for socket memory.
1389  */
1390 int netlink_attachskb(struct sock *sk, struct sk_buff *skb,
1391                       long *timeo, struct sock *ssk)
1392 {
1393         struct netlink_sock *nlk;
1394
1395         nlk = nlk_sk(sk);
1396
1397         if ((atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
1398              test_bit(NETLINK_CONGESTED, &nlk->state)) &&
1399             !netlink_skb_is_mmaped(skb)) {
1400                 DECLARE_WAITQUEUE(wait, current);
1401                 if (!*timeo) {
1402                         if (!ssk || netlink_is_kernel(ssk))
1403                                 netlink_overrun(sk);
1404                         sock_put(sk);
1405                         kfree_skb(skb);
1406                         return -EAGAIN;
1407                 }
1408
1409                 __set_current_state(TASK_INTERRUPTIBLE);
1410                 add_wait_queue(&nlk->wait, &wait);
1411
1412                 if ((atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf ||
1413                      test_bit(NETLINK_CONGESTED, &nlk->state)) &&
1414                     !sock_flag(sk, SOCK_DEAD))
1415                         *timeo = schedule_timeout(*timeo);
1416
1417                 __set_current_state(TASK_RUNNING);
1418                 remove_wait_queue(&nlk->wait, &wait);
1419                 sock_put(sk);
1420
1421                 if (signal_pending(current)) {
1422                         kfree_skb(skb);
1423                         return sock_intr_errno(*timeo);
1424                 }
1425                 return 1;
1426         }
1427         netlink_skb_set_owner_r(skb, sk);
1428         return 0;
1429 }
1430
1431 static int __netlink_sendskb(struct sock *sk, struct sk_buff *skb)
1432 {
1433         int len = skb->len;
1434
1435 #ifdef CONFIG_NETLINK_MMAP
1436         if (netlink_skb_is_mmaped(skb))
1437                 netlink_queue_mmaped_skb(sk, skb);
1438         else if (netlink_rx_is_mmaped(sk))
1439                 netlink_ring_set_copied(sk, skb);
1440         else
1441 #endif /* CONFIG_NETLINK_MMAP */
1442                 skb_queue_tail(&sk->sk_receive_queue, skb);
1443         sk->sk_data_ready(sk, len);
1444         return len;
1445 }
1446
1447 int netlink_sendskb(struct sock *sk, struct sk_buff *skb)
1448 {
1449         int len = __netlink_sendskb(sk, skb);
1450
1451         sock_put(sk);
1452         return len;
1453 }
1454
1455 void netlink_detachskb(struct sock *sk, struct sk_buff *skb)
1456 {
1457         kfree_skb(skb);
1458         sock_put(sk);
1459 }
1460
1461 static struct sk_buff *netlink_trim(struct sk_buff *skb, gfp_t allocation)
1462 {
1463         int delta;
1464
1465         WARN_ON(skb->sk != NULL);
1466         if (netlink_skb_is_mmaped(skb))
1467                 return skb;
1468
1469         delta = skb->end - skb->tail;
1470         if (delta * 2 < skb->truesize)
1471                 return skb;
1472
1473         if (skb_shared(skb)) {
1474                 struct sk_buff *nskb = skb_clone(skb, allocation);
1475                 if (!nskb)
1476                         return skb;
1477                 consume_skb(skb);
1478                 skb = nskb;
1479         }
1480
1481         if (!pskb_expand_head(skb, 0, -delta, allocation))
1482                 skb->truesize -= delta;
1483
1484         return skb;
1485 }
1486
1487 static void netlink_rcv_wake(struct sock *sk)
1488 {
1489         struct netlink_sock *nlk = nlk_sk(sk);
1490
1491         if (skb_queue_empty(&sk->sk_receive_queue))
1492                 clear_bit(NETLINK_CONGESTED, &nlk->state);
1493         if (!test_bit(NETLINK_CONGESTED, &nlk->state))
1494                 wake_up_interruptible(&nlk->wait);
1495 }
1496
1497 static int netlink_unicast_kernel(struct sock *sk, struct sk_buff *skb,
1498                                   struct sock *ssk)
1499 {
1500         int ret;
1501         struct netlink_sock *nlk = nlk_sk(sk);
1502
1503         ret = -ECONNREFUSED;
1504         if (nlk->netlink_rcv != NULL) {
1505                 ret = skb->len;
1506                 netlink_skb_set_owner_r(skb, sk);
1507                 NETLINK_CB(skb).sk = ssk;
1508                 nlk->netlink_rcv(skb);
1509                 consume_skb(skb);
1510         } else {
1511                 kfree_skb(skb);
1512         }
1513         sock_put(sk);
1514         return ret;
1515 }
1516
1517 int netlink_unicast(struct sock *ssk, struct sk_buff *skb,
1518                     u32 portid, int nonblock)
1519 {
1520         struct sock *sk;
1521         int err;
1522         long timeo;
1523
1524         skb = netlink_trim(skb, gfp_any());
1525
1526         timeo = sock_sndtimeo(ssk, nonblock);
1527 retry:
1528         sk = netlink_getsockbyportid(ssk, portid);
1529         if (IS_ERR(sk)) {
1530                 kfree_skb(skb);
1531                 return PTR_ERR(sk);
1532         }
1533         if (netlink_is_kernel(sk))
1534                 return netlink_unicast_kernel(sk, skb, ssk);
1535
1536         if (sk_filter(sk, skb)) {
1537                 err = skb->len;
1538                 kfree_skb(skb);
1539                 sock_put(sk);
1540                 return err;
1541         }
1542
1543         err = netlink_attachskb(sk, skb, &timeo, ssk);
1544         if (err == 1)
1545                 goto retry;
1546         if (err)
1547                 return err;
1548
1549         return netlink_sendskb(sk, skb);
1550 }
1551 EXPORT_SYMBOL(netlink_unicast);
1552
1553 struct sk_buff *netlink_alloc_skb(struct sock *ssk, unsigned int size,
1554                                   u32 dst_portid, gfp_t gfp_mask)
1555 {
1556 #ifdef CONFIG_NETLINK_MMAP
1557         struct sock *sk = NULL;
1558         struct sk_buff *skb;
1559         struct netlink_ring *ring;
1560         struct nl_mmap_hdr *hdr;
1561         unsigned int maxlen;
1562
1563         sk = netlink_getsockbyportid(ssk, dst_portid);
1564         if (IS_ERR(sk))
1565                 goto out;
1566
1567         ring = &nlk_sk(sk)->rx_ring;
1568         /* fast-path without atomic ops for common case: non-mmaped receiver */
1569         if (ring->pg_vec == NULL)
1570                 goto out_put;
1571
1572         skb = alloc_skb_head(gfp_mask);
1573         if (skb == NULL)
1574                 goto err1;
1575
1576         spin_lock_bh(&sk->sk_receive_queue.lock);
1577         /* check again under lock */
1578         if (ring->pg_vec == NULL)
1579                 goto out_free;
1580
1581         maxlen = ring->frame_size - NL_MMAP_HDRLEN;
1582         if (maxlen < size)
1583                 goto out_free;
1584
1585         netlink_forward_ring(ring);
1586         hdr = netlink_current_frame(ring, NL_MMAP_STATUS_UNUSED);
1587         if (hdr == NULL)
1588                 goto err2;
1589         netlink_ring_setup_skb(skb, sk, ring, hdr);
1590         netlink_set_status(hdr, NL_MMAP_STATUS_RESERVED);
1591         atomic_inc(&ring->pending);
1592         netlink_increment_head(ring);
1593
1594         spin_unlock_bh(&sk->sk_receive_queue.lock);
1595         return skb;
1596
1597 err2:
1598         kfree_skb(skb);
1599         spin_unlock_bh(&sk->sk_receive_queue.lock);
1600 err1:
1601         sock_put(sk);
1602         return NULL;
1603
1604 out_free:
1605         kfree_skb(skb);
1606         spin_unlock_bh(&sk->sk_receive_queue.lock);
1607 out_put:
1608         sock_put(sk);
1609 out:
1610 #endif
1611         return alloc_skb(size, gfp_mask);
1612 }
1613 EXPORT_SYMBOL_GPL(netlink_alloc_skb);
1614
1615 int netlink_has_listeners(struct sock *sk, unsigned int group)
1616 {
1617         int res = 0;
1618         struct listeners *listeners;
1619
1620         BUG_ON(!netlink_is_kernel(sk));
1621
1622         rcu_read_lock();
1623         listeners = rcu_dereference(nl_table[sk->sk_protocol].listeners);
1624
1625         if (listeners && group - 1 < nl_table[sk->sk_protocol].groups)
1626                 res = test_bit(group - 1, listeners->masks);
1627
1628         rcu_read_unlock();
1629
1630         return res;
1631 }
1632 EXPORT_SYMBOL_GPL(netlink_has_listeners);
1633
1634 static int netlink_broadcast_deliver(struct sock *sk, struct sk_buff *skb)
1635 {
1636         struct netlink_sock *nlk = nlk_sk(sk);
1637
1638         if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf &&
1639             !test_bit(NETLINK_CONGESTED, &nlk->state)) {
1640                 netlink_skb_set_owner_r(skb, sk);
1641                 __netlink_sendskb(sk, skb);
1642                 return atomic_read(&sk->sk_rmem_alloc) > (sk->sk_rcvbuf >> 1);
1643         }
1644         return -1;
1645 }
1646
1647 struct netlink_broadcast_data {
1648         struct sock *exclude_sk;
1649         struct net *net;
1650         u32 portid;
1651         u32 group;
1652         int failure;
1653         int delivery_failure;
1654         int congested;
1655         int delivered;
1656         gfp_t allocation;
1657         struct sk_buff *skb, *skb2;
1658         int (*tx_filter)(struct sock *dsk, struct sk_buff *skb, void *data);
1659         void *tx_data;
1660 };
1661
1662 static int do_one_broadcast(struct sock *sk,
1663                                    struct netlink_broadcast_data *p)
1664 {
1665         struct netlink_sock *nlk = nlk_sk(sk);
1666         int val;
1667
1668         if (p->exclude_sk == sk)
1669                 goto out;
1670
1671         if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
1672             !test_bit(p->group - 1, nlk->groups))
1673                 goto out;
1674
1675         if (!net_eq(sock_net(sk), p->net))
1676                 goto out;
1677
1678         if (p->failure) {
1679                 netlink_overrun(sk);
1680                 goto out;
1681         }
1682
1683         sock_hold(sk);
1684         if (p->skb2 == NULL) {
1685                 if (skb_shared(p->skb)) {
1686                         p->skb2 = skb_clone(p->skb, p->allocation);
1687                 } else {
1688                         p->skb2 = skb_get(p->skb);
1689                         /*
1690                          * skb ownership may have been set when
1691                          * delivered to a previous socket.
1692                          */
1693                         skb_orphan(p->skb2);
1694                 }
1695         }
1696         if (p->skb2 == NULL) {
1697                 netlink_overrun(sk);
1698                 /* Clone failed. Notify ALL listeners. */
1699                 p->failure = 1;
1700                 if (nlk->flags & NETLINK_BROADCAST_SEND_ERROR)
1701                         p->delivery_failure = 1;
1702         } else if (p->tx_filter && p->tx_filter(sk, p->skb2, p->tx_data)) {
1703                 kfree_skb(p->skb2);
1704                 p->skb2 = NULL;
1705         } else if (sk_filter(sk, p->skb2)) {
1706                 kfree_skb(p->skb2);
1707                 p->skb2 = NULL;
1708         } else if ((val = netlink_broadcast_deliver(sk, p->skb2)) < 0) {
1709                 netlink_overrun(sk);
1710                 if (nlk->flags & NETLINK_BROADCAST_SEND_ERROR)
1711                         p->delivery_failure = 1;
1712         } else {
1713                 p->congested |= val;
1714                 p->delivered = 1;
1715                 p->skb2 = NULL;
1716         }
1717         sock_put(sk);
1718
1719 out:
1720         return 0;
1721 }
1722
1723 int netlink_broadcast_filtered(struct sock *ssk, struct sk_buff *skb, u32 portid,
1724         u32 group, gfp_t allocation,
1725         int (*filter)(struct sock *dsk, struct sk_buff *skb, void *data),
1726         void *filter_data)
1727 {
1728         struct net *net = sock_net(ssk);
1729         struct netlink_broadcast_data info;
1730         struct sock *sk;
1731
1732         skb = netlink_trim(skb, allocation);
1733
1734         info.exclude_sk = ssk;
1735         info.net = net;
1736         info.portid = portid;
1737         info.group = group;
1738         info.failure = 0;
1739         info.delivery_failure = 0;
1740         info.congested = 0;
1741         info.delivered = 0;
1742         info.allocation = allocation;
1743         info.skb = skb;
1744         info.skb2 = NULL;
1745         info.tx_filter = filter;
1746         info.tx_data = filter_data;
1747
1748         /* While we sleep in clone, do not allow to change socket list */
1749
1750         netlink_lock_table();
1751
1752         sk_for_each_bound(sk, &nl_table[ssk->sk_protocol].mc_list)
1753                 do_one_broadcast(sk, &info);
1754
1755         consume_skb(skb);
1756
1757         netlink_unlock_table();
1758
1759         if (info.delivery_failure) {
1760                 kfree_skb(info.skb2);
1761                 return -ENOBUFS;
1762         }
1763         consume_skb(info.skb2);
1764
1765         if (info.delivered) {
1766                 if (info.congested && (allocation & __GFP_WAIT))
1767                         yield();
1768                 return 0;
1769         }
1770         return -ESRCH;
1771 }
1772 EXPORT_SYMBOL(netlink_broadcast_filtered);
1773
1774 int netlink_broadcast(struct sock *ssk, struct sk_buff *skb, u32 portid,
1775                       u32 group, gfp_t allocation)
1776 {
1777         return netlink_broadcast_filtered(ssk, skb, portid, group, allocation,
1778                 NULL, NULL);
1779 }
1780 EXPORT_SYMBOL(netlink_broadcast);
1781
1782 struct netlink_set_err_data {
1783         struct sock *exclude_sk;
1784         u32 portid;
1785         u32 group;
1786         int code;
1787 };
1788
1789 static int do_one_set_err(struct sock *sk, struct netlink_set_err_data *p)
1790 {
1791         struct netlink_sock *nlk = nlk_sk(sk);
1792         int ret = 0;
1793
1794         if (sk == p->exclude_sk)
1795                 goto out;
1796
1797         if (!net_eq(sock_net(sk), sock_net(p->exclude_sk)))
1798                 goto out;
1799
1800         if (nlk->portid == p->portid || p->group - 1 >= nlk->ngroups ||
1801             !test_bit(p->group - 1, nlk->groups))
1802                 goto out;
1803
1804         if (p->code == ENOBUFS && nlk->flags & NETLINK_RECV_NO_ENOBUFS) {
1805                 ret = 1;
1806                 goto out;
1807         }
1808
1809         sk->sk_err = p->code;
1810         sk->sk_error_report(sk);
1811 out:
1812         return ret;
1813 }
1814
1815 /**
1816  * netlink_set_err - report error to broadcast listeners
1817  * @ssk: the kernel netlink socket, as returned by netlink_kernel_create()
1818  * @portid: the PORTID of a process that we want to skip (if any)
1819  * @groups: the broadcast group that will notice the error
1820  * @code: error code, must be negative (as usual in kernelspace)
1821  *
1822  * This function returns the number of broadcast listeners that have set the
1823  * NETLINK_RECV_NO_ENOBUFS socket option.
1824  */
1825 int netlink_set_err(struct sock *ssk, u32 portid, u32 group, int code)
1826 {
1827         struct netlink_set_err_data info;
1828         struct sock *sk;
1829         int ret = 0;
1830
1831         info.exclude_sk = ssk;
1832         info.portid = portid;
1833         info.group = group;
1834         /* sk->sk_err wants a positive error value */
1835         info.code = -code;
1836
1837         read_lock(&nl_table_lock);
1838
1839         sk_for_each_bound(sk, &nl_table[ssk->sk_protocol].mc_list)
1840                 ret += do_one_set_err(sk, &info);
1841
1842         read_unlock(&nl_table_lock);
1843         return ret;
1844 }
1845 EXPORT_SYMBOL(netlink_set_err);
1846
1847 /* must be called with netlink table grabbed */
1848 static void netlink_update_socket_mc(struct netlink_sock *nlk,
1849                                      unsigned int group,
1850                                      int is_new)
1851 {
1852         int old, new = !!is_new, subscriptions;
1853
1854         old = test_bit(group - 1, nlk->groups);
1855         subscriptions = nlk->subscriptions - old + new;
1856         if (new)
1857                 __set_bit(group - 1, nlk->groups);
1858         else
1859                 __clear_bit(group - 1, nlk->groups);
1860         netlink_update_subscriptions(&nlk->sk, subscriptions);
1861         netlink_update_listeners(&nlk->sk);
1862 }
1863
1864 static int netlink_setsockopt(struct socket *sock, int level, int optname,
1865                               char __user *optval, unsigned int optlen)
1866 {
1867         struct sock *sk = sock->sk;
1868         struct netlink_sock *nlk = nlk_sk(sk);
1869         unsigned int val = 0;
1870         int err;
1871
1872         if (level != SOL_NETLINK)
1873                 return -ENOPROTOOPT;
1874
1875         if (optname != NETLINK_RX_RING && optname != NETLINK_TX_RING &&
1876             optlen >= sizeof(int) &&
1877             get_user(val, (unsigned int __user *)optval))
1878                 return -EFAULT;
1879
1880         switch (optname) {
1881         case NETLINK_PKTINFO:
1882                 if (val)
1883                         nlk->flags |= NETLINK_RECV_PKTINFO;
1884                 else
1885                         nlk->flags &= ~NETLINK_RECV_PKTINFO;
1886                 err = 0;
1887                 break;
1888         case NETLINK_ADD_MEMBERSHIP:
1889         case NETLINK_DROP_MEMBERSHIP: {
1890                 if (!netlink_capable(sock, NL_CFG_F_NONROOT_RECV))
1891                         return -EPERM;
1892                 err = netlink_realloc_groups(sk);
1893                 if (err)
1894                         return err;
1895                 if (!val || val - 1 >= nlk->ngroups)
1896                         return -EINVAL;
1897                 netlink_table_grab();
1898                 netlink_update_socket_mc(nlk, val,
1899                                          optname == NETLINK_ADD_MEMBERSHIP);
1900                 netlink_table_ungrab();
1901
1902                 if (nlk->netlink_bind)
1903                         nlk->netlink_bind(val);
1904
1905                 err = 0;
1906                 break;
1907         }
1908         case NETLINK_BROADCAST_ERROR:
1909                 if (val)
1910                         nlk->flags |= NETLINK_BROADCAST_SEND_ERROR;
1911                 else
1912                         nlk->flags &= ~NETLINK_BROADCAST_SEND_ERROR;
1913                 err = 0;
1914                 break;
1915         case NETLINK_NO_ENOBUFS:
1916                 if (val) {
1917                         nlk->flags |= NETLINK_RECV_NO_ENOBUFS;
1918                         clear_bit(NETLINK_CONGESTED, &nlk->state);
1919                         wake_up_interruptible(&nlk->wait);
1920                 } else {
1921                         nlk->flags &= ~NETLINK_RECV_NO_ENOBUFS;
1922                 }
1923                 err = 0;
1924                 break;
1925 #ifdef CONFIG_NETLINK_MMAP
1926         case NETLINK_RX_RING:
1927         case NETLINK_TX_RING: {
1928                 struct nl_mmap_req req;
1929
1930                 /* Rings might consume more memory than queue limits, require
1931                  * CAP_NET_ADMIN.
1932                  */
1933                 if (!capable(CAP_NET_ADMIN))
1934                         return -EPERM;
1935                 if (optlen < sizeof(req))
1936                         return -EINVAL;
1937                 if (copy_from_user(&req, optval, sizeof(req)))
1938                         return -EFAULT;
1939                 err = netlink_set_ring(sk, &req, false,
1940                                        optname == NETLINK_TX_RING);
1941                 break;
1942         }
1943 #endif /* CONFIG_NETLINK_MMAP */
1944         default:
1945                 err = -ENOPROTOOPT;
1946         }
1947         return err;
1948 }
1949
1950 static int netlink_getsockopt(struct socket *sock, int level, int optname,
1951                               char __user *optval, int __user *optlen)
1952 {
1953         struct sock *sk = sock->sk;
1954         struct netlink_sock *nlk = nlk_sk(sk);
1955         int len, val, err;
1956
1957         if (level != SOL_NETLINK)
1958                 return -ENOPROTOOPT;
1959
1960         if (get_user(len, optlen))
1961                 return -EFAULT;
1962         if (len < 0)
1963                 return -EINVAL;
1964
1965         switch (optname) {
1966         case NETLINK_PKTINFO:
1967                 if (len < sizeof(int))
1968                         return -EINVAL;
1969                 len = sizeof(int);
1970                 val = nlk->flags & NETLINK_RECV_PKTINFO ? 1 : 0;
1971                 if (put_user(len, optlen) ||
1972                     put_user(val, optval))
1973                         return -EFAULT;
1974                 err = 0;
1975                 break;
1976         case NETLINK_BROADCAST_ERROR:
1977                 if (len < sizeof(int))
1978                         return -EINVAL;
1979                 len = sizeof(int);
1980                 val = nlk->flags & NETLINK_BROADCAST_SEND_ERROR ? 1 : 0;
1981                 if (put_user(len, optlen) ||
1982                     put_user(val, optval))
1983                         return -EFAULT;
1984                 err = 0;
1985                 break;
1986         case NETLINK_NO_ENOBUFS:
1987                 if (len < sizeof(int))
1988                         return -EINVAL;
1989                 len = sizeof(int);
1990                 val = nlk->flags & NETLINK_RECV_NO_ENOBUFS ? 1 : 0;
1991                 if (put_user(len, optlen) ||
1992                     put_user(val, optval))
1993                         return -EFAULT;
1994                 err = 0;
1995                 break;
1996         default:
1997                 err = -ENOPROTOOPT;
1998         }
1999         return err;
2000 }
2001
2002 static void netlink_cmsg_recv_pktinfo(struct msghdr *msg, struct sk_buff *skb)
2003 {
2004         struct nl_pktinfo info;
2005
2006         info.group = NETLINK_CB(skb).dst_group;
2007         put_cmsg(msg, SOL_NETLINK, NETLINK_PKTINFO, sizeof(info), &info);
2008 }
2009
2010 static int netlink_sendmsg(struct kiocb *kiocb, struct socket *sock,
2011                            struct msghdr *msg, size_t len)
2012 {
2013         struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
2014         struct sock *sk = sock->sk;
2015         struct netlink_sock *nlk = nlk_sk(sk);
2016         struct sockaddr_nl *addr = msg->msg_name;
2017         u32 dst_portid;
2018         u32 dst_group;
2019         struct sk_buff *skb;
2020         int err;
2021         struct scm_cookie scm;
2022
2023         if (msg->msg_flags&MSG_OOB)
2024                 return -EOPNOTSUPP;
2025
2026         if (NULL == siocb->scm)
2027                 siocb->scm = &scm;
2028
2029         err = scm_send(sock, msg, siocb->scm, true);
2030         if (err < 0)
2031                 return err;
2032
2033         if (msg->msg_namelen) {
2034                 err = -EINVAL;
2035                 if (addr->nl_family != AF_NETLINK)
2036                         goto out;
2037                 dst_portid = addr->nl_pid;
2038                 dst_group = ffs(addr->nl_groups);
2039                 err =  -EPERM;
2040                 if ((dst_group || dst_portid) &&
2041                     !netlink_capable(sock, NL_CFG_F_NONROOT_SEND))
2042                         goto out;
2043         } else {
2044                 dst_portid = nlk->dst_portid;
2045                 dst_group = nlk->dst_group;
2046         }
2047
2048         if (!nlk->portid) {
2049                 err = netlink_autobind(sock);
2050                 if (err)
2051                         goto out;
2052         }
2053
2054         if (netlink_tx_is_mmaped(sk) &&
2055             msg->msg_iov->iov_base == NULL) {
2056                 err = netlink_mmap_sendmsg(sk, msg, dst_portid, dst_group,
2057                                            siocb);
2058                 goto out;
2059         }
2060
2061         err = -EMSGSIZE;
2062         if (len > sk->sk_sndbuf - 32)
2063                 goto out;
2064         err = -ENOBUFS;
2065         skb = alloc_skb(len, GFP_KERNEL);
2066         if (skb == NULL)
2067                 goto out;
2068
2069         NETLINK_CB(skb).portid  = nlk->portid;
2070         NETLINK_CB(skb).dst_group = dst_group;
2071         NETLINK_CB(skb).creds   = siocb->scm->creds;
2072
2073         err = -EFAULT;
2074         if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) {
2075                 kfree_skb(skb);
2076                 goto out;
2077         }
2078
2079         err = security_netlink_send(sk, skb);
2080         if (err) {
2081                 kfree_skb(skb);
2082                 goto out;
2083         }
2084
2085         if (dst_group) {
2086                 atomic_inc(&skb->users);
2087                 netlink_broadcast(sk, skb, dst_portid, dst_group, GFP_KERNEL);
2088         }
2089         err = netlink_unicast(sk, skb, dst_portid, msg->msg_flags&MSG_DONTWAIT);
2090
2091 out:
2092         scm_destroy(siocb->scm);
2093         return err;
2094 }
2095
2096 static int netlink_recvmsg(struct kiocb *kiocb, struct socket *sock,
2097                            struct msghdr *msg, size_t len,
2098                            int flags)
2099 {
2100         struct sock_iocb *siocb = kiocb_to_siocb(kiocb);
2101         struct scm_cookie scm;
2102         struct sock *sk = sock->sk;
2103         struct netlink_sock *nlk = nlk_sk(sk);
2104         int noblock = flags&MSG_DONTWAIT;
2105         size_t copied;
2106         struct sk_buff *skb, *data_skb;
2107         int err, ret;
2108
2109         if (flags&MSG_OOB)
2110                 return -EOPNOTSUPP;
2111
2112         copied = 0;
2113
2114         skb = skb_recv_datagram(sk, flags, noblock, &err);
2115         if (skb == NULL)
2116                 goto out;
2117
2118         data_skb = skb;
2119
2120 #ifdef CONFIG_COMPAT_NETLINK_MESSAGES
2121         if (unlikely(skb_shinfo(skb)->frag_list)) {
2122                 /*
2123                  * If this skb has a frag_list, then here that means that we
2124                  * will have to use the frag_list skb's data for compat tasks
2125                  * and the regular skb's data for normal (non-compat) tasks.
2126                  *
2127                  * If we need to send the compat skb, assign it to the
2128                  * 'data_skb' variable so that it will be used below for data
2129                  * copying. We keep 'skb' for everything else, including
2130                  * freeing both later.
2131                  */
2132                 if (flags & MSG_CMSG_COMPAT)
2133                         data_skb = skb_shinfo(skb)->frag_list;
2134         }
2135 #endif
2136
2137         msg->msg_namelen = 0;
2138
2139         copied = data_skb->len;
2140         if (len < copied) {
2141                 msg->msg_flags |= MSG_TRUNC;
2142                 copied = len;
2143         }
2144
2145         skb_reset_transport_header(data_skb);
2146         err = skb_copy_datagram_iovec(data_skb, 0, msg->msg_iov, copied);
2147
2148         if (msg->msg_name) {
2149                 struct sockaddr_nl *addr = (struct sockaddr_nl *)msg->msg_name;
2150                 addr->nl_family = AF_NETLINK;
2151                 addr->nl_pad    = 0;
2152                 addr->nl_pid    = NETLINK_CB(skb).portid;
2153                 addr->nl_groups = netlink_group_mask(NETLINK_CB(skb).dst_group);
2154                 msg->msg_namelen = sizeof(*addr);
2155         }
2156
2157         if (nlk->flags & NETLINK_RECV_PKTINFO)
2158                 netlink_cmsg_recv_pktinfo(msg, skb);
2159
2160         if (NULL == siocb->scm) {
2161                 memset(&scm, 0, sizeof(scm));
2162                 siocb->scm = &scm;
2163         }
2164         siocb->scm->creds = *NETLINK_CREDS(skb);
2165         if (flags & MSG_TRUNC)
2166                 copied = data_skb->len;
2167
2168         skb_free_datagram(sk, skb);
2169
2170         if (nlk->cb && atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf / 2) {
2171                 ret = netlink_dump(sk);
2172                 if (ret) {
2173                         sk->sk_err = ret;
2174                         sk->sk_error_report(sk);
2175                 }
2176         }
2177
2178         scm_recv(sock, msg, siocb->scm, flags);
2179 out:
2180         netlink_rcv_wake(sk);
2181         return err ? : copied;
2182 }
2183
2184 static void netlink_data_ready(struct sock *sk, int len)
2185 {
2186         BUG();
2187 }
2188
2189 /*
2190  *      We export these functions to other modules. They provide a
2191  *      complete set of kernel non-blocking support for message
2192  *      queueing.
2193  */
2194
2195 struct sock *
2196 __netlink_kernel_create(struct net *net, int unit, struct module *module,
2197                         struct netlink_kernel_cfg *cfg)
2198 {
2199         struct socket *sock;
2200         struct sock *sk;
2201         struct netlink_sock *nlk;
2202         struct listeners *listeners = NULL;
2203         struct mutex *cb_mutex = cfg ? cfg->cb_mutex : NULL;
2204         unsigned int groups;
2205
2206         BUG_ON(!nl_table);
2207
2208         if (unit < 0 || unit >= MAX_LINKS)
2209                 return NULL;
2210
2211         if (sock_create_lite(PF_NETLINK, SOCK_DGRAM, unit, &sock))
2212                 return NULL;
2213
2214         /*
2215          * We have to just have a reference on the net from sk, but don't
2216          * get_net it. Besides, we cannot get and then put the net here.
2217          * So we create one inside init_net and the move it to net.
2218          */
2219
2220         if (__netlink_create(&init_net, sock, cb_mutex, unit) < 0)
2221                 goto out_sock_release_nosk;
2222
2223         sk = sock->sk;
2224         sk_change_net(sk, net);
2225
2226         if (!cfg || cfg->groups < 32)
2227                 groups = 32;
2228         else
2229                 groups = cfg->groups;
2230
2231         listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
2232         if (!listeners)
2233                 goto out_sock_release;
2234
2235         sk->sk_data_ready = netlink_data_ready;
2236         if (cfg && cfg->input)
2237                 nlk_sk(sk)->netlink_rcv = cfg->input;
2238
2239         if (netlink_insert(sk, net, 0))
2240                 goto out_sock_release;
2241
2242         nlk = nlk_sk(sk);
2243         nlk->flags |= NETLINK_KERNEL_SOCKET;
2244
2245         netlink_table_grab();
2246         if (!nl_table[unit].registered) {
2247                 nl_table[unit].groups = groups;
2248                 rcu_assign_pointer(nl_table[unit].listeners, listeners);
2249                 nl_table[unit].cb_mutex = cb_mutex;
2250                 nl_table[unit].module = module;
2251                 if (cfg) {
2252                         nl_table[unit].bind = cfg->bind;
2253                         nl_table[unit].flags = cfg->flags;
2254                 }
2255                 nl_table[unit].registered = 1;
2256         } else {
2257                 kfree(listeners);
2258                 nl_table[unit].registered++;
2259         }
2260         netlink_table_ungrab();
2261         return sk;
2262
2263 out_sock_release:
2264         kfree(listeners);
2265         netlink_kernel_release(sk);
2266         return NULL;
2267
2268 out_sock_release_nosk:
2269         sock_release(sock);
2270         return NULL;
2271 }
2272 EXPORT_SYMBOL(__netlink_kernel_create);
2273
2274 void
2275 netlink_kernel_release(struct sock *sk)
2276 {
2277         sk_release_kernel(sk);
2278 }
2279 EXPORT_SYMBOL(netlink_kernel_release);
2280
2281 int __netlink_change_ngroups(struct sock *sk, unsigned int groups)
2282 {
2283         struct listeners *new, *old;
2284         struct netlink_table *tbl = &nl_table[sk->sk_protocol];
2285
2286         if (groups < 32)
2287                 groups = 32;
2288
2289         if (NLGRPSZ(tbl->groups) < NLGRPSZ(groups)) {
2290                 new = kzalloc(sizeof(*new) + NLGRPSZ(groups), GFP_ATOMIC);
2291                 if (!new)
2292                         return -ENOMEM;
2293                 old = nl_deref_protected(tbl->listeners);
2294                 memcpy(new->masks, old->masks, NLGRPSZ(tbl->groups));
2295                 rcu_assign_pointer(tbl->listeners, new);
2296
2297                 kfree_rcu(old, rcu);
2298         }
2299         tbl->groups = groups;
2300
2301         return 0;
2302 }
2303
2304 /**
2305  * netlink_change_ngroups - change number of multicast groups
2306  *
2307  * This changes the number of multicast groups that are available
2308  * on a certain netlink family. Note that it is not possible to
2309  * change the number of groups to below 32. Also note that it does
2310  * not implicitly call netlink_clear_multicast_users() when the
2311  * number of groups is reduced.
2312  *
2313  * @sk: The kernel netlink socket, as returned by netlink_kernel_create().
2314  * @groups: The new number of groups.
2315  */
2316 int netlink_change_ngroups(struct sock *sk, unsigned int groups)
2317 {
2318         int err;
2319
2320         netlink_table_grab();
2321         err = __netlink_change_ngroups(sk, groups);
2322         netlink_table_ungrab();
2323
2324         return err;
2325 }
2326
2327 void __netlink_clear_multicast_users(struct sock *ksk, unsigned int group)
2328 {
2329         struct sock *sk;
2330         struct netlink_table *tbl = &nl_table[ksk->sk_protocol];
2331
2332         sk_for_each_bound(sk, &tbl->mc_list)
2333                 netlink_update_socket_mc(nlk_sk(sk), group, 0);
2334 }
2335
2336 /**
2337  * netlink_clear_multicast_users - kick off multicast listeners
2338  *
2339  * This function removes all listeners from the given group.
2340  * @ksk: The kernel netlink socket, as returned by
2341  *      netlink_kernel_create().
2342  * @group: The multicast group to clear.
2343  */
2344 void netlink_clear_multicast_users(struct sock *ksk, unsigned int group)
2345 {
2346         netlink_table_grab();
2347         __netlink_clear_multicast_users(ksk, group);
2348         netlink_table_ungrab();
2349 }
2350
2351 struct nlmsghdr *
2352 __nlmsg_put(struct sk_buff *skb, u32 portid, u32 seq, int type, int len, int flags)
2353 {
2354         struct nlmsghdr *nlh;
2355         int size = nlmsg_msg_size(len);
2356
2357         nlh = (struct nlmsghdr*)skb_put(skb, NLMSG_ALIGN(size));
2358         nlh->nlmsg_type = type;
2359         nlh->nlmsg_len = size;
2360         nlh->nlmsg_flags = flags;
2361         nlh->nlmsg_pid = portid;
2362         nlh->nlmsg_seq = seq;
2363         if (!__builtin_constant_p(size) || NLMSG_ALIGN(size) - size != 0)
2364                 memset(nlmsg_data(nlh) + len, 0, NLMSG_ALIGN(size) - size);
2365         return nlh;
2366 }
2367 EXPORT_SYMBOL(__nlmsg_put);
2368
2369 /*
2370  * It looks a bit ugly.
2371  * It would be better to create kernel thread.
2372  */
2373
2374 static int netlink_dump(struct sock *sk)
2375 {
2376         struct netlink_sock *nlk = nlk_sk(sk);
2377         struct netlink_callback *cb;
2378         struct sk_buff *skb = NULL;
2379         struct nlmsghdr *nlh;
2380         int len, err = -ENOBUFS;
2381         int alloc_size;
2382
2383         mutex_lock(nlk->cb_mutex);
2384
2385         cb = nlk->cb;
2386         if (cb == NULL) {
2387                 err = -EINVAL;
2388                 goto errout_skb;
2389         }
2390
2391         alloc_size = max_t(int, cb->min_dump_alloc, NLMSG_GOODSIZE);
2392
2393         if (!netlink_rx_is_mmaped(sk) &&
2394             atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf)
2395                 goto errout_skb;
2396         skb = netlink_alloc_skb(sk, alloc_size, nlk->portid, GFP_KERNEL);
2397         if (!skb)
2398                 goto errout_skb;
2399         netlink_skb_set_owner_r(skb, sk);
2400
2401         len = cb->dump(skb, cb);
2402
2403         if (len > 0) {
2404                 mutex_unlock(nlk->cb_mutex);
2405
2406                 if (sk_filter(sk, skb))
2407                         kfree_skb(skb);
2408                 else
2409                         __netlink_sendskb(sk, skb);
2410                 return 0;
2411         }
2412
2413         nlh = nlmsg_put_answer(skb, cb, NLMSG_DONE, sizeof(len), NLM_F_MULTI);
2414         if (!nlh)
2415                 goto errout_skb;
2416
2417         nl_dump_check_consistent(cb, nlh);
2418
2419         memcpy(nlmsg_data(nlh), &len, sizeof(len));
2420
2421         if (sk_filter(sk, skb))
2422                 kfree_skb(skb);
2423         else
2424                 __netlink_sendskb(sk, skb);
2425
2426         if (cb->done)
2427                 cb->done(cb);
2428         nlk->cb = NULL;
2429         mutex_unlock(nlk->cb_mutex);
2430
2431         module_put(cb->module);
2432         netlink_consume_callback(cb);
2433         return 0;
2434
2435 errout_skb:
2436         mutex_unlock(nlk->cb_mutex);
2437         kfree_skb(skb);
2438         return err;
2439 }
2440
2441 int __netlink_dump_start(struct sock *ssk, struct sk_buff *skb,
2442                          const struct nlmsghdr *nlh,
2443                          struct netlink_dump_control *control)
2444 {
2445         struct netlink_callback *cb;
2446         struct sock *sk;
2447         struct netlink_sock *nlk;
2448         int ret;
2449
2450         cb = kzalloc(sizeof(*cb), GFP_KERNEL);
2451         if (cb == NULL)
2452                 return -ENOBUFS;
2453
2454         /* Memory mapped dump requests need to be copied to avoid looping
2455          * on the pending state in netlink_mmap_sendmsg() while the CB hold
2456          * a reference to the skb.
2457          */
2458         if (netlink_skb_is_mmaped(skb)) {
2459                 skb = skb_copy(skb, GFP_KERNEL);
2460                 if (skb == NULL) {
2461                         kfree(cb);
2462                         return -ENOBUFS;
2463                 }
2464         } else
2465                 atomic_inc(&skb->users);
2466
2467         cb->dump = control->dump;
2468         cb->done = control->done;
2469         cb->nlh = nlh;
2470         cb->data = control->data;
2471         cb->module = control->module;
2472         cb->min_dump_alloc = control->min_dump_alloc;
2473         atomic_inc(&skb->users);
2474         cb->skb = skb;
2475
2476         sk = netlink_lookup(sock_net(ssk), ssk->sk_protocol, NETLINK_CB(skb).portid);
2477         if (sk == NULL) {
2478                 netlink_destroy_callback(cb);
2479                 return -ECONNREFUSED;
2480         }
2481         nlk = nlk_sk(sk);
2482
2483         mutex_lock(nlk->cb_mutex);
2484         /* A dump is in progress... */
2485         if (nlk->cb) {
2486                 mutex_unlock(nlk->cb_mutex);
2487                 netlink_destroy_callback(cb);
2488                 ret = -EBUSY;
2489                 goto out;
2490         }
2491         /* add reference of module which cb->dump belongs to */
2492         if (!try_module_get(cb->module)) {
2493                 mutex_unlock(nlk->cb_mutex);
2494                 netlink_destroy_callback(cb);
2495                 ret = -EPROTONOSUPPORT;
2496                 goto out;
2497         }
2498
2499         nlk->cb = cb;
2500         mutex_unlock(nlk->cb_mutex);
2501
2502         ret = netlink_dump(sk);
2503 out:
2504         sock_put(sk);
2505
2506         if (ret)
2507                 return ret;
2508
2509         /* We successfully started a dump, by returning -EINTR we
2510          * signal not to send ACK even if it was requested.
2511          */
2512         return -EINTR;
2513 }
2514 EXPORT_SYMBOL(__netlink_dump_start);
2515
2516 void netlink_ack(struct sk_buff *in_skb, struct nlmsghdr *nlh, int err)
2517 {
2518         struct sk_buff *skb;
2519         struct nlmsghdr *rep;
2520         struct nlmsgerr *errmsg;
2521         size_t payload = sizeof(*errmsg);
2522
2523         /* error messages get the original request appened */
2524         if (err)
2525                 payload += nlmsg_len(nlh);
2526
2527         skb = netlink_alloc_skb(in_skb->sk, nlmsg_total_size(payload),
2528                                 NETLINK_CB(in_skb).portid, GFP_KERNEL);
2529         if (!skb) {
2530                 struct sock *sk;
2531
2532                 sk = netlink_lookup(sock_net(in_skb->sk),
2533                                     in_skb->sk->sk_protocol,
2534                                     NETLINK_CB(in_skb).portid);
2535                 if (sk) {
2536                         sk->sk_err = ENOBUFS;
2537                         sk->sk_error_report(sk);
2538                         sock_put(sk);
2539                 }
2540                 return;
2541         }
2542
2543         rep = __nlmsg_put(skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq,
2544                           NLMSG_ERROR, payload, 0);
2545         errmsg = nlmsg_data(rep);
2546         errmsg->error = err;
2547         memcpy(&errmsg->msg, nlh, err ? nlh->nlmsg_len : sizeof(*nlh));
2548         netlink_unicast(in_skb->sk, skb, NETLINK_CB(in_skb).portid, MSG_DONTWAIT);
2549 }
2550 EXPORT_SYMBOL(netlink_ack);
2551
2552 int netlink_rcv_skb(struct sk_buff *skb, int (*cb)(struct sk_buff *,
2553                                                      struct nlmsghdr *))
2554 {
2555         struct nlmsghdr *nlh;
2556         int err;
2557
2558         while (skb->len >= nlmsg_total_size(0)) {
2559                 int msglen;
2560
2561                 nlh = nlmsg_hdr(skb);
2562                 err = 0;
2563
2564                 if (nlh->nlmsg_len < NLMSG_HDRLEN || skb->len < nlh->nlmsg_len)
2565                         return 0;
2566
2567                 /* Only requests are handled by the kernel */
2568                 if (!(nlh->nlmsg_flags & NLM_F_REQUEST))
2569                         goto ack;
2570
2571                 /* Skip control messages */
2572                 if (nlh->nlmsg_type < NLMSG_MIN_TYPE)
2573                         goto ack;
2574
2575                 err = cb(skb, nlh);
2576                 if (err == -EINTR)
2577                         goto skip;
2578
2579 ack:
2580                 if (nlh->nlmsg_flags & NLM_F_ACK || err)
2581                         netlink_ack(skb, nlh, err);
2582
2583 skip:
2584                 msglen = NLMSG_ALIGN(nlh->nlmsg_len);
2585                 if (msglen > skb->len)
2586                         msglen = skb->len;
2587                 skb_pull(skb, msglen);
2588         }
2589
2590         return 0;
2591 }
2592 EXPORT_SYMBOL(netlink_rcv_skb);
2593
2594 /**
2595  * nlmsg_notify - send a notification netlink message
2596  * @sk: netlink socket to use
2597  * @skb: notification message
2598  * @portid: destination netlink portid for reports or 0
2599  * @group: destination multicast group or 0
2600  * @report: 1 to report back, 0 to disable
2601  * @flags: allocation flags
2602  */
2603 int nlmsg_notify(struct sock *sk, struct sk_buff *skb, u32 portid,
2604                  unsigned int group, int report, gfp_t flags)
2605 {
2606         int err = 0;
2607
2608         if (group) {
2609                 int exclude_portid = 0;
2610
2611                 if (report) {
2612                         atomic_inc(&skb->users);
2613                         exclude_portid = portid;
2614                 }
2615
2616                 /* errors reported via destination sk->sk_err, but propagate
2617                  * delivery errors if NETLINK_BROADCAST_ERROR flag is set */
2618                 err = nlmsg_multicast(sk, skb, exclude_portid, group, flags);
2619         }
2620
2621         if (report) {
2622                 int err2;
2623
2624                 err2 = nlmsg_unicast(sk, skb, portid);
2625                 if (!err || err == -ESRCH)
2626                         err = err2;
2627         }
2628
2629         return err;
2630 }
2631 EXPORT_SYMBOL(nlmsg_notify);
2632
2633 #ifdef CONFIG_PROC_FS
2634 struct nl_seq_iter {
2635         struct seq_net_private p;
2636         int link;
2637         int hash_idx;
2638 };
2639
2640 static struct sock *netlink_seq_socket_idx(struct seq_file *seq, loff_t pos)
2641 {
2642         struct nl_seq_iter *iter = seq->private;
2643         int i, j;
2644         struct sock *s;
2645         loff_t off = 0;
2646
2647         for (i = 0; i < MAX_LINKS; i++) {
2648                 struct nl_portid_hash *hash = &nl_table[i].hash;
2649
2650                 for (j = 0; j <= hash->mask; j++) {
2651                         sk_for_each(s, &hash->table[j]) {
2652                                 if (sock_net(s) != seq_file_net(seq))
2653                                         continue;
2654                                 if (off == pos) {
2655                                         iter->link = i;
2656                                         iter->hash_idx = j;
2657                                         return s;
2658                                 }
2659                                 ++off;
2660                         }
2661                 }
2662         }
2663         return NULL;
2664 }
2665
2666 static void *netlink_seq_start(struct seq_file *seq, loff_t *pos)
2667         __acquires(nl_table_lock)
2668 {
2669         read_lock(&nl_table_lock);
2670         return *pos ? netlink_seq_socket_idx(seq, *pos - 1) : SEQ_START_TOKEN;
2671 }
2672
2673 static void *netlink_seq_next(struct seq_file *seq, void *v, loff_t *pos)
2674 {
2675         struct sock *s;
2676         struct nl_seq_iter *iter;
2677         int i, j;
2678
2679         ++*pos;
2680
2681         if (v == SEQ_START_TOKEN)
2682                 return netlink_seq_socket_idx(seq, 0);
2683
2684         iter = seq->private;
2685         s = v;
2686         do {
2687                 s = sk_next(s);
2688         } while (s && sock_net(s) != seq_file_net(seq));
2689         if (s)
2690                 return s;
2691
2692         i = iter->link;
2693         j = iter->hash_idx + 1;
2694
2695         do {
2696                 struct nl_portid_hash *hash = &nl_table[i].hash;
2697
2698                 for (; j <= hash->mask; j++) {
2699                         s = sk_head(&hash->table[j]);
2700                         while (s && sock_net(s) != seq_file_net(seq))
2701                                 s = sk_next(s);
2702                         if (s) {
2703                                 iter->link = i;
2704                                 iter->hash_idx = j;
2705                                 return s;
2706                         }
2707                 }
2708
2709                 j = 0;
2710         } while (++i < MAX_LINKS);
2711
2712         return NULL;
2713 }
2714
2715 static void netlink_seq_stop(struct seq_file *seq, void *v)
2716         __releases(nl_table_lock)
2717 {
2718         read_unlock(&nl_table_lock);
2719 }
2720
2721
2722 static int netlink_seq_show(struct seq_file *seq, void *v)
2723 {
2724         if (v == SEQ_START_TOKEN) {
2725                 seq_puts(seq,
2726                          "sk       Eth Pid    Groups   "
2727                          "Rmem     Wmem     Dump     Locks     Drops     Inode\n");
2728         } else {
2729                 struct sock *s = v;
2730                 struct netlink_sock *nlk = nlk_sk(s);
2731
2732                 seq_printf(seq, "%pK %-3d %-6u %08x %-8d %-8d %pK %-8d %-8d %-8lu\n",
2733                            s,
2734                            s->sk_protocol,
2735                            nlk->portid,
2736                            nlk->groups ? (u32)nlk->groups[0] : 0,
2737                            sk_rmem_alloc_get(s),
2738                            sk_wmem_alloc_get(s),
2739                            nlk->cb,
2740                            atomic_read(&s->sk_refcnt),
2741                            atomic_read(&s->sk_drops),
2742                            sock_i_ino(s)
2743                         );
2744
2745         }
2746         return 0;
2747 }
2748
2749 static const struct seq_operations netlink_seq_ops = {
2750         .start  = netlink_seq_start,
2751         .next   = netlink_seq_next,
2752         .stop   = netlink_seq_stop,
2753         .show   = netlink_seq_show,
2754 };
2755
2756
2757 static int netlink_seq_open(struct inode *inode, struct file *file)
2758 {
2759         return seq_open_net(inode, file, &netlink_seq_ops,
2760                                 sizeof(struct nl_seq_iter));
2761 }
2762
2763 static const struct file_operations netlink_seq_fops = {
2764         .owner          = THIS_MODULE,
2765         .open           = netlink_seq_open,
2766         .read           = seq_read,
2767         .llseek         = seq_lseek,
2768         .release        = seq_release_net,
2769 };
2770
2771 #endif
2772
2773 int netlink_register_notifier(struct notifier_block *nb)
2774 {
2775         return atomic_notifier_chain_register(&netlink_chain, nb);
2776 }
2777 EXPORT_SYMBOL(netlink_register_notifier);
2778
2779 int netlink_unregister_notifier(struct notifier_block *nb)
2780 {
2781         return atomic_notifier_chain_unregister(&netlink_chain, nb);
2782 }
2783 EXPORT_SYMBOL(netlink_unregister_notifier);
2784
2785 static const struct proto_ops netlink_ops = {
2786         .family =       PF_NETLINK,
2787         .owner =        THIS_MODULE,
2788         .release =      netlink_release,
2789         .bind =         netlink_bind,
2790         .connect =      netlink_connect,
2791         .socketpair =   sock_no_socketpair,
2792         .accept =       sock_no_accept,
2793         .getname =      netlink_getname,
2794         .poll =         netlink_poll,
2795         .ioctl =        sock_no_ioctl,
2796         .listen =       sock_no_listen,
2797         .shutdown =     sock_no_shutdown,
2798         .setsockopt =   netlink_setsockopt,
2799         .getsockopt =   netlink_getsockopt,
2800         .sendmsg =      netlink_sendmsg,
2801         .recvmsg =      netlink_recvmsg,
2802         .mmap =         netlink_mmap,
2803         .sendpage =     sock_no_sendpage,
2804 };
2805
2806 static const struct net_proto_family netlink_family_ops = {
2807         .family = PF_NETLINK,
2808         .create = netlink_create,
2809         .owner  = THIS_MODULE,  /* for consistency 8) */
2810 };
2811
2812 static int __net_init netlink_net_init(struct net *net)
2813 {
2814 #ifdef CONFIG_PROC_FS
2815         if (!proc_create("netlink", 0, net->proc_net, &netlink_seq_fops))
2816                 return -ENOMEM;
2817 #endif
2818         return 0;
2819 }
2820
2821 static void __net_exit netlink_net_exit(struct net *net)
2822 {
2823 #ifdef CONFIG_PROC_FS
2824         remove_proc_entry("netlink", net->proc_net);
2825 #endif
2826 }
2827
2828 static void __init netlink_add_usersock_entry(void)
2829 {
2830         struct listeners *listeners;
2831         int groups = 32;
2832
2833         listeners = kzalloc(sizeof(*listeners) + NLGRPSZ(groups), GFP_KERNEL);
2834         if (!listeners)
2835                 panic("netlink_add_usersock_entry: Cannot allocate listeners\n");
2836
2837         netlink_table_grab();
2838
2839         nl_table[NETLINK_USERSOCK].groups = groups;
2840         rcu_assign_pointer(nl_table[NETLINK_USERSOCK].listeners, listeners);
2841         nl_table[NETLINK_USERSOCK].module = THIS_MODULE;
2842         nl_table[NETLINK_USERSOCK].registered = 1;
2843         nl_table[NETLINK_USERSOCK].flags = NL_CFG_F_NONROOT_SEND;
2844
2845         netlink_table_ungrab();
2846 }
2847
2848 static struct pernet_operations __net_initdata netlink_net_ops = {
2849         .init = netlink_net_init,
2850         .exit = netlink_net_exit,
2851 };
2852
2853 static int __init netlink_proto_init(void)
2854 {
2855         int i;
2856         unsigned long limit;
2857         unsigned int order;
2858         int err = proto_register(&netlink_proto, 0);
2859
2860         if (err != 0)
2861                 goto out;
2862
2863         BUILD_BUG_ON(sizeof(struct netlink_skb_parms) > FIELD_SIZEOF(struct sk_buff, cb));
2864
2865         nl_table = kcalloc(MAX_LINKS, sizeof(*nl_table), GFP_KERNEL);
2866         if (!nl_table)
2867                 goto panic;
2868
2869         if (totalram_pages >= (128 * 1024))
2870                 limit = totalram_pages >> (21 - PAGE_SHIFT);
2871         else
2872                 limit = totalram_pages >> (23 - PAGE_SHIFT);
2873
2874         order = get_bitmask_order(limit) - 1 + PAGE_SHIFT;
2875         limit = (1UL << order) / sizeof(struct hlist_head);
2876         order = get_bitmask_order(min(limit, (unsigned long)UINT_MAX)) - 1;
2877
2878         for (i = 0; i < MAX_LINKS; i++) {
2879                 struct nl_portid_hash *hash = &nl_table[i].hash;
2880
2881                 hash->table = nl_portid_hash_zalloc(1 * sizeof(*hash->table));
2882                 if (!hash->table) {
2883                         while (i-- > 0)
2884                                 nl_portid_hash_free(nl_table[i].hash.table,
2885                                                  1 * sizeof(*hash->table));
2886                         kfree(nl_table);
2887                         goto panic;
2888                 }
2889                 hash->max_shift = order;
2890                 hash->shift = 0;
2891                 hash->mask = 0;
2892                 hash->rehash_time = jiffies;
2893         }
2894
2895         netlink_add_usersock_entry();
2896
2897         sock_register(&netlink_family_ops);
2898         register_pernet_subsys(&netlink_net_ops);
2899         /* The netlink device handler may be needed early. */
2900         rtnetlink_init();
2901 out:
2902         return err;
2903 panic:
2904         panic("netlink_init: Cannot allocate nl_table\n");
2905 }
2906
2907 core_initcall(netlink_proto_init);