[PATCH] knfsd: SUNRPC: Don't set msg_name and msg_namelen when calling sock_recvmsg
[safe/jmp/linux-2.6] / net / sunrpc / svcsock.c
1 /*
2  * linux/net/sunrpc/svcsock.c
3  *
4  * These are the RPC server socket internals.
5  *
6  * The server scheduling algorithm does not always distribute the load
7  * evenly when servicing a single client. May need to modify the
8  * svc_sock_enqueue procedure...
9  *
10  * TCP support is largely untested and may be a little slow. The problem
11  * is that we currently do two separate recvfrom's, one for the 4-byte
12  * record length, and the second for the actual record. This could possibly
13  * be improved by always reading a minimum size of around 100 bytes and
14  * tucking any superfluous bytes away in a temporary store. Still, that
15  * leaves write requests out in the rain. An alternative may be to peek at
16  * the first skb in the queue, and if it matches the next TCP sequence
17  * number, to extract the record marker. Yuck.
18  *
19  * Copyright (C) 1995, 1996 Olaf Kirch <okir@monad.swb.de>
20  */
21
22 #include <linux/sched.h>
23 #include <linux/errno.h>
24 #include <linux/fcntl.h>
25 #include <linux/net.h>
26 #include <linux/in.h>
27 #include <linux/inet.h>
28 #include <linux/udp.h>
29 #include <linux/tcp.h>
30 #include <linux/unistd.h>
31 #include <linux/slab.h>
32 #include <linux/netdevice.h>
33 #include <linux/skbuff.h>
34 #include <linux/file.h>
35 #include <linux/freezer.h>
36 #include <net/sock.h>
37 #include <net/checksum.h>
38 #include <net/ip.h>
39 #include <net/tcp_states.h>
40 #include <asm/uaccess.h>
41 #include <asm/ioctls.h>
42
43 #include <linux/sunrpc/types.h>
44 #include <linux/sunrpc/xdr.h>
45 #include <linux/sunrpc/svcsock.h>
46 #include <linux/sunrpc/stats.h>
47
48 /* SMP locking strategy:
49  *
50  *      svc_pool->sp_lock protects most of the fields of that pool.
51  *      svc_serv->sv_lock protects sv_tempsocks, sv_permsocks, sv_tmpcnt.
52  *      when both need to be taken (rare), svc_serv->sv_lock is first.
53  *      BKL protects svc_serv->sv_nrthread.
54  *      svc_sock->sk_defer_lock protects the svc_sock->sk_deferred list
55  *      svc_sock->sk_flags.SK_BUSY prevents a svc_sock being enqueued multiply.
56  *
57  *      Some flags can be set to certain values at any time
58  *      providing that certain rules are followed:
59  *
60  *      SK_CONN, SK_DATA, can be set or cleared at any time.
61  *              after a set, svc_sock_enqueue must be called.
62  *              after a clear, the socket must be read/accepted
63  *               if this succeeds, it must be set again.
64  *      SK_CLOSE can set at any time. It is never cleared.
65  *      sk_inuse contains a bias of '1' until SK_DEAD is set.
66  *             so when sk_inuse hits zero, we know the socket is dead
67  *             and no-one is using it.
68  *      SK_DEAD can only be set while SK_BUSY is held which ensures
69  *             no other thread will be using the socket or will try to
70  *             set SK_DEAD.
71  *
72  */
73
74 #define RPCDBG_FACILITY RPCDBG_SVCSOCK
75
76
77 static struct svc_sock *svc_setup_socket(struct svc_serv *, struct socket *,
78                                          int *errp, int flags);
79 static void             svc_delete_socket(struct svc_sock *svsk);
80 static void             svc_udp_data_ready(struct sock *, int);
81 static int              svc_udp_recvfrom(struct svc_rqst *);
82 static int              svc_udp_sendto(struct svc_rqst *);
83
84 static struct svc_deferred_req *svc_deferred_dequeue(struct svc_sock *svsk);
85 static int svc_deferred_recv(struct svc_rqst *rqstp);
86 static struct cache_deferred_req *svc_defer(struct cache_req *req);
87
88 /* apparently the "standard" is that clients close
89  * idle connections after 5 minutes, servers after
90  * 6 minutes
91  *   http://www.connectathon.org/talks96/nfstcp.pdf
92  */
93 static int svc_conn_age_period = 6*60;
94
95 #ifdef CONFIG_DEBUG_LOCK_ALLOC
96 static struct lock_class_key svc_key[2];
97 static struct lock_class_key svc_slock_key[2];
98
99 static inline void svc_reclassify_socket(struct socket *sock)
100 {
101         struct sock *sk = sock->sk;
102         BUG_ON(sk->sk_lock.owner != NULL);
103         switch (sk->sk_family) {
104         case AF_INET:
105                 sock_lock_init_class_and_name(sk, "slock-AF_INET-NFSD",
106                     &svc_slock_key[0], "sk_lock-AF_INET-NFSD", &svc_key[0]);
107                 break;
108
109         case AF_INET6:
110                 sock_lock_init_class_and_name(sk, "slock-AF_INET6-NFSD",
111                     &svc_slock_key[1], "sk_lock-AF_INET6-NFSD", &svc_key[1]);
112                 break;
113
114         default:
115                 BUG();
116         }
117 }
118 #else
119 static inline void svc_reclassify_socket(struct socket *sock)
120 {
121 }
122 #endif
123
124 /*
125  * Queue up an idle server thread.  Must have pool->sp_lock held.
126  * Note: this is really a stack rather than a queue, so that we only
127  * use as many different threads as we need, and the rest don't pollute
128  * the cache.
129  */
130 static inline void
131 svc_thread_enqueue(struct svc_pool *pool, struct svc_rqst *rqstp)
132 {
133         list_add(&rqstp->rq_list, &pool->sp_threads);
134 }
135
136 /*
137  * Dequeue an nfsd thread.  Must have pool->sp_lock held.
138  */
139 static inline void
140 svc_thread_dequeue(struct svc_pool *pool, struct svc_rqst *rqstp)
141 {
142         list_del(&rqstp->rq_list);
143 }
144
145 /*
146  * Release an skbuff after use
147  */
148 static inline void
149 svc_release_skb(struct svc_rqst *rqstp)
150 {
151         struct sk_buff *skb = rqstp->rq_skbuff;
152         struct svc_deferred_req *dr = rqstp->rq_deferred;
153
154         if (skb) {
155                 rqstp->rq_skbuff = NULL;
156
157                 dprintk("svc: service %p, releasing skb %p\n", rqstp, skb);
158                 skb_free_datagram(rqstp->rq_sock->sk_sk, skb);
159         }
160         if (dr) {
161                 rqstp->rq_deferred = NULL;
162                 kfree(dr);
163         }
164 }
165
166 /*
167  * Any space to write?
168  */
169 static inline unsigned long
170 svc_sock_wspace(struct svc_sock *svsk)
171 {
172         int wspace;
173
174         if (svsk->sk_sock->type == SOCK_STREAM)
175                 wspace = sk_stream_wspace(svsk->sk_sk);
176         else
177                 wspace = sock_wspace(svsk->sk_sk);
178
179         return wspace;
180 }
181
182 /*
183  * Queue up a socket with data pending. If there are idle nfsd
184  * processes, wake 'em up.
185  *
186  */
187 static void
188 svc_sock_enqueue(struct svc_sock *svsk)
189 {
190         struct svc_serv *serv = svsk->sk_server;
191         struct svc_pool *pool;
192         struct svc_rqst *rqstp;
193         int cpu;
194
195         if (!(svsk->sk_flags &
196               ( (1<<SK_CONN)|(1<<SK_DATA)|(1<<SK_CLOSE)|(1<<SK_DEFERRED)) ))
197                 return;
198         if (test_bit(SK_DEAD, &svsk->sk_flags))
199                 return;
200
201         cpu = get_cpu();
202         pool = svc_pool_for_cpu(svsk->sk_server, cpu);
203         put_cpu();
204
205         spin_lock_bh(&pool->sp_lock);
206
207         if (!list_empty(&pool->sp_threads) &&
208             !list_empty(&pool->sp_sockets))
209                 printk(KERN_ERR
210                         "svc_sock_enqueue: threads and sockets both waiting??\n");
211
212         if (test_bit(SK_DEAD, &svsk->sk_flags)) {
213                 /* Don't enqueue dead sockets */
214                 dprintk("svc: socket %p is dead, not enqueued\n", svsk->sk_sk);
215                 goto out_unlock;
216         }
217
218         /* Mark socket as busy. It will remain in this state until the
219          * server has processed all pending data and put the socket back
220          * on the idle list.  We update SK_BUSY atomically because
221          * it also guards against trying to enqueue the svc_sock twice.
222          */
223         if (test_and_set_bit(SK_BUSY, &svsk->sk_flags)) {
224                 /* Don't enqueue socket while already enqueued */
225                 dprintk("svc: socket %p busy, not enqueued\n", svsk->sk_sk);
226                 goto out_unlock;
227         }
228         BUG_ON(svsk->sk_pool != NULL);
229         svsk->sk_pool = pool;
230
231         set_bit(SOCK_NOSPACE, &svsk->sk_sock->flags);
232         if (((atomic_read(&svsk->sk_reserved) + serv->sv_max_mesg)*2
233              > svc_sock_wspace(svsk))
234             && !test_bit(SK_CLOSE, &svsk->sk_flags)
235             && !test_bit(SK_CONN, &svsk->sk_flags)) {
236                 /* Don't enqueue while not enough space for reply */
237                 dprintk("svc: socket %p  no space, %d*2 > %ld, not enqueued\n",
238                         svsk->sk_sk, atomic_read(&svsk->sk_reserved)+serv->sv_max_mesg,
239                         svc_sock_wspace(svsk));
240                 svsk->sk_pool = NULL;
241                 clear_bit(SK_BUSY, &svsk->sk_flags);
242                 goto out_unlock;
243         }
244         clear_bit(SOCK_NOSPACE, &svsk->sk_sock->flags);
245
246
247         if (!list_empty(&pool->sp_threads)) {
248                 rqstp = list_entry(pool->sp_threads.next,
249                                    struct svc_rqst,
250                                    rq_list);
251                 dprintk("svc: socket %p served by daemon %p\n",
252                         svsk->sk_sk, rqstp);
253                 svc_thread_dequeue(pool, rqstp);
254                 if (rqstp->rq_sock)
255                         printk(KERN_ERR
256                                 "svc_sock_enqueue: server %p, rq_sock=%p!\n",
257                                 rqstp, rqstp->rq_sock);
258                 rqstp->rq_sock = svsk;
259                 atomic_inc(&svsk->sk_inuse);
260                 rqstp->rq_reserved = serv->sv_max_mesg;
261                 atomic_add(rqstp->rq_reserved, &svsk->sk_reserved);
262                 BUG_ON(svsk->sk_pool != pool);
263                 wake_up(&rqstp->rq_wait);
264         } else {
265                 dprintk("svc: socket %p put into queue\n", svsk->sk_sk);
266                 list_add_tail(&svsk->sk_ready, &pool->sp_sockets);
267                 BUG_ON(svsk->sk_pool != pool);
268         }
269
270 out_unlock:
271         spin_unlock_bh(&pool->sp_lock);
272 }
273
274 /*
275  * Dequeue the first socket.  Must be called with the pool->sp_lock held.
276  */
277 static inline struct svc_sock *
278 svc_sock_dequeue(struct svc_pool *pool)
279 {
280         struct svc_sock *svsk;
281
282         if (list_empty(&pool->sp_sockets))
283                 return NULL;
284
285         svsk = list_entry(pool->sp_sockets.next,
286                           struct svc_sock, sk_ready);
287         list_del_init(&svsk->sk_ready);
288
289         dprintk("svc: socket %p dequeued, inuse=%d\n",
290                 svsk->sk_sk, atomic_read(&svsk->sk_inuse));
291
292         return svsk;
293 }
294
295 /*
296  * Having read something from a socket, check whether it
297  * needs to be re-enqueued.
298  * Note: SK_DATA only gets cleared when a read-attempt finds
299  * no (or insufficient) data.
300  */
301 static inline void
302 svc_sock_received(struct svc_sock *svsk)
303 {
304         svsk->sk_pool = NULL;
305         clear_bit(SK_BUSY, &svsk->sk_flags);
306         svc_sock_enqueue(svsk);
307 }
308
309
310 /**
311  * svc_reserve - change the space reserved for the reply to a request.
312  * @rqstp:  The request in question
313  * @space: new max space to reserve
314  *
315  * Each request reserves some space on the output queue of the socket
316  * to make sure the reply fits.  This function reduces that reserved
317  * space to be the amount of space used already, plus @space.
318  *
319  */
320 void svc_reserve(struct svc_rqst *rqstp, int space)
321 {
322         space += rqstp->rq_res.head[0].iov_len;
323
324         if (space < rqstp->rq_reserved) {
325                 struct svc_sock *svsk = rqstp->rq_sock;
326                 atomic_sub((rqstp->rq_reserved - space), &svsk->sk_reserved);
327                 rqstp->rq_reserved = space;
328
329                 svc_sock_enqueue(svsk);
330         }
331 }
332
333 /*
334  * Release a socket after use.
335  */
336 static inline void
337 svc_sock_put(struct svc_sock *svsk)
338 {
339         if (atomic_dec_and_test(&svsk->sk_inuse)) {
340                 BUG_ON(! test_bit(SK_DEAD, &svsk->sk_flags));
341
342                 dprintk("svc: releasing dead socket\n");
343                 if (svsk->sk_sock->file)
344                         sockfd_put(svsk->sk_sock);
345                 else
346                         sock_release(svsk->sk_sock);
347                 if (svsk->sk_info_authunix != NULL)
348                         svcauth_unix_info_release(svsk->sk_info_authunix);
349                 kfree(svsk);
350         }
351 }
352
353 static void
354 svc_sock_release(struct svc_rqst *rqstp)
355 {
356         struct svc_sock *svsk = rqstp->rq_sock;
357
358         svc_release_skb(rqstp);
359
360         svc_free_res_pages(rqstp);
361         rqstp->rq_res.page_len = 0;
362         rqstp->rq_res.page_base = 0;
363
364
365         /* Reset response buffer and release
366          * the reservation.
367          * But first, check that enough space was reserved
368          * for the reply, otherwise we have a bug!
369          */
370         if ((rqstp->rq_res.len) >  rqstp->rq_reserved)
371                 printk(KERN_ERR "RPC request reserved %d but used %d\n",
372                        rqstp->rq_reserved,
373                        rqstp->rq_res.len);
374
375         rqstp->rq_res.head[0].iov_len = 0;
376         svc_reserve(rqstp, 0);
377         rqstp->rq_sock = NULL;
378
379         svc_sock_put(svsk);
380 }
381
382 /*
383  * External function to wake up a server waiting for data
384  * This really only makes sense for services like lockd
385  * which have exactly one thread anyway.
386  */
387 void
388 svc_wake_up(struct svc_serv *serv)
389 {
390         struct svc_rqst *rqstp;
391         unsigned int i;
392         struct svc_pool *pool;
393
394         for (i = 0; i < serv->sv_nrpools; i++) {
395                 pool = &serv->sv_pools[i];
396
397                 spin_lock_bh(&pool->sp_lock);
398                 if (!list_empty(&pool->sp_threads)) {
399                         rqstp = list_entry(pool->sp_threads.next,
400                                            struct svc_rqst,
401                                            rq_list);
402                         dprintk("svc: daemon %p woken up.\n", rqstp);
403                         /*
404                         svc_thread_dequeue(pool, rqstp);
405                         rqstp->rq_sock = NULL;
406                          */
407                         wake_up(&rqstp->rq_wait);
408                 }
409                 spin_unlock_bh(&pool->sp_lock);
410         }
411 }
412
413 /*
414  * Generic sendto routine
415  */
416 static int
417 svc_sendto(struct svc_rqst *rqstp, struct xdr_buf *xdr)
418 {
419         struct svc_sock *svsk = rqstp->rq_sock;
420         struct socket   *sock = svsk->sk_sock;
421         int             slen;
422         char            buffer[CMSG_SPACE(sizeof(struct in_pktinfo))];
423         struct cmsghdr *cmh = (struct cmsghdr *)buffer;
424         struct in_pktinfo *pki = (struct in_pktinfo *)CMSG_DATA(cmh);
425         int             len = 0;
426         int             result;
427         int             size;
428         struct page     **ppage = xdr->pages;
429         size_t          base = xdr->page_base;
430         unsigned int    pglen = xdr->page_len;
431         unsigned int    flags = MSG_MORE;
432
433         slen = xdr->len;
434
435         if (rqstp->rq_prot == IPPROTO_UDP) {
436                 /* set the source and destination */
437                 struct msghdr   msg;
438                 msg.msg_name    = &rqstp->rq_addr;
439                 msg.msg_namelen = sizeof(rqstp->rq_addr);
440                 msg.msg_iov     = NULL;
441                 msg.msg_iovlen  = 0;
442                 msg.msg_flags   = MSG_MORE;
443
444                 msg.msg_control = cmh;
445                 msg.msg_controllen = sizeof(buffer);
446                 cmh->cmsg_len = CMSG_LEN(sizeof(*pki));
447                 cmh->cmsg_level = SOL_IP;
448                 cmh->cmsg_type = IP_PKTINFO;
449                 pki->ipi_ifindex = 0;
450                 pki->ipi_spec_dst.s_addr = rqstp->rq_daddr;
451
452                 if (sock_sendmsg(sock, &msg, 0) < 0)
453                         goto out;
454         }
455
456         /* send head */
457         if (slen == xdr->head[0].iov_len)
458                 flags = 0;
459         len = kernel_sendpage(sock, rqstp->rq_respages[0], 0,
460                                   xdr->head[0].iov_len, flags);
461         if (len != xdr->head[0].iov_len)
462                 goto out;
463         slen -= xdr->head[0].iov_len;
464         if (slen == 0)
465                 goto out;
466
467         /* send page data */
468         size = PAGE_SIZE - base < pglen ? PAGE_SIZE - base : pglen;
469         while (pglen > 0) {
470                 if (slen == size)
471                         flags = 0;
472                 result = kernel_sendpage(sock, *ppage, base, size, flags);
473                 if (result > 0)
474                         len += result;
475                 if (result != size)
476                         goto out;
477                 slen -= size;
478                 pglen -= size;
479                 size = PAGE_SIZE < pglen ? PAGE_SIZE : pglen;
480                 base = 0;
481                 ppage++;
482         }
483         /* send tail */
484         if (xdr->tail[0].iov_len) {
485                 result = kernel_sendpage(sock, rqstp->rq_respages[0],
486                                              ((unsigned long)xdr->tail[0].iov_base)
487                                                 & (PAGE_SIZE-1),
488                                              xdr->tail[0].iov_len, 0);
489
490                 if (result > 0)
491                         len += result;
492         }
493 out:
494         dprintk("svc: socket %p sendto([%p %Zu... ], %d) = %d (addr %x)\n",
495                         rqstp->rq_sock, xdr->head[0].iov_base, xdr->head[0].iov_len, xdr->len, len,
496                 rqstp->rq_addr.sin_addr.s_addr);
497
498         return len;
499 }
500
501 /*
502  * Report socket names for nfsdfs
503  */
504 static int one_sock_name(char *buf, struct svc_sock *svsk)
505 {
506         int len;
507
508         switch(svsk->sk_sk->sk_family) {
509         case AF_INET:
510                 len = sprintf(buf, "ipv4 %s %u.%u.%u.%u %d\n",
511                               svsk->sk_sk->sk_protocol==IPPROTO_UDP?
512                               "udp" : "tcp",
513                               NIPQUAD(inet_sk(svsk->sk_sk)->rcv_saddr),
514                               inet_sk(svsk->sk_sk)->num);
515                 break;
516         default:
517                 len = sprintf(buf, "*unknown-%d*\n",
518                                svsk->sk_sk->sk_family);
519         }
520         return len;
521 }
522
523 int
524 svc_sock_names(char *buf, struct svc_serv *serv, char *toclose)
525 {
526         struct svc_sock *svsk, *closesk = NULL;
527         int len = 0;
528
529         if (!serv)
530                 return 0;
531         spin_lock_bh(&serv->sv_lock);
532         list_for_each_entry(svsk, &serv->sv_permsocks, sk_list) {
533                 int onelen = one_sock_name(buf+len, svsk);
534                 if (toclose && strcmp(toclose, buf+len) == 0)
535                         closesk = svsk;
536                 else
537                         len += onelen;
538         }
539         spin_unlock_bh(&serv->sv_lock);
540         if (closesk)
541                 /* Should unregister with portmap, but you cannot
542                  * unregister just one protocol...
543                  */
544                 svc_close_socket(closesk);
545         else if (toclose)
546                 return -ENOENT;
547         return len;
548 }
549 EXPORT_SYMBOL(svc_sock_names);
550
551 /*
552  * Check input queue length
553  */
554 static int
555 svc_recv_available(struct svc_sock *svsk)
556 {
557         struct socket   *sock = svsk->sk_sock;
558         int             avail, err;
559
560         err = kernel_sock_ioctl(sock, TIOCINQ, (unsigned long) &avail);
561
562         return (err >= 0)? avail : err;
563 }
564
565 /*
566  * Generic recvfrom routine.
567  */
568 static int
569 svc_recvfrom(struct svc_rqst *rqstp, struct kvec *iov, int nr, int buflen)
570 {
571         struct svc_sock *svsk = rqstp->rq_sock;
572         struct msghdr msg = {
573                 .msg_flags      = MSG_DONTWAIT,
574         };
575         int len;
576
577         len = kernel_recvmsg(svsk->sk_sock, &msg, iov, nr, buflen,
578                                 msg.msg_flags);
579
580         /* sock_recvmsg doesn't fill in the name/namelen, so we must..
581          */
582         memcpy(&rqstp->rq_addr, &svsk->sk_remote, svsk->sk_remotelen);
583         rqstp->rq_addrlen = svsk->sk_remotelen;
584
585         dprintk("svc: socket %p recvfrom(%p, %Zu) = %d\n",
586                 svsk, iov[0].iov_base, iov[0].iov_len, len);
587
588         return len;
589 }
590
591 /*
592  * Set socket snd and rcv buffer lengths
593  */
594 static inline void
595 svc_sock_setbufsize(struct socket *sock, unsigned int snd, unsigned int rcv)
596 {
597 #if 0
598         mm_segment_t    oldfs;
599         oldfs = get_fs(); set_fs(KERNEL_DS);
600         sock_setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
601                         (char*)&snd, sizeof(snd));
602         sock_setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
603                         (char*)&rcv, sizeof(rcv));
604 #else
605         /* sock_setsockopt limits use to sysctl_?mem_max,
606          * which isn't acceptable.  Until that is made conditional
607          * on not having CAP_SYS_RESOURCE or similar, we go direct...
608          * DaveM said I could!
609          */
610         lock_sock(sock->sk);
611         sock->sk->sk_sndbuf = snd * 2;
612         sock->sk->sk_rcvbuf = rcv * 2;
613         sock->sk->sk_userlocks |= SOCK_SNDBUF_LOCK|SOCK_RCVBUF_LOCK;
614         release_sock(sock->sk);
615 #endif
616 }
617 /*
618  * INET callback when data has been received on the socket.
619  */
620 static void
621 svc_udp_data_ready(struct sock *sk, int count)
622 {
623         struct svc_sock *svsk = (struct svc_sock *)sk->sk_user_data;
624
625         if (svsk) {
626                 dprintk("svc: socket %p(inet %p), count=%d, busy=%d\n",
627                         svsk, sk, count, test_bit(SK_BUSY, &svsk->sk_flags));
628                 set_bit(SK_DATA, &svsk->sk_flags);
629                 svc_sock_enqueue(svsk);
630         }
631         if (sk->sk_sleep && waitqueue_active(sk->sk_sleep))
632                 wake_up_interruptible(sk->sk_sleep);
633 }
634
635 /*
636  * INET callback when space is newly available on the socket.
637  */
638 static void
639 svc_write_space(struct sock *sk)
640 {
641         struct svc_sock *svsk = (struct svc_sock *)(sk->sk_user_data);
642
643         if (svsk) {
644                 dprintk("svc: socket %p(inet %p), write_space busy=%d\n",
645                         svsk, sk, test_bit(SK_BUSY, &svsk->sk_flags));
646                 svc_sock_enqueue(svsk);
647         }
648
649         if (sk->sk_sleep && waitqueue_active(sk->sk_sleep)) {
650                 dprintk("RPC svc_write_space: someone sleeping on %p\n",
651                        svsk);
652                 wake_up_interruptible(sk->sk_sleep);
653         }
654 }
655
656 /*
657  * Receive a datagram from a UDP socket.
658  */
659 static int
660 svc_udp_recvfrom(struct svc_rqst *rqstp)
661 {
662         struct svc_sock *svsk = rqstp->rq_sock;
663         struct svc_serv *serv = svsk->sk_server;
664         struct sk_buff  *skb;
665         int             err, len;
666
667         if (test_and_clear_bit(SK_CHNGBUF, &svsk->sk_flags))
668             /* udp sockets need large rcvbuf as all pending
669              * requests are still in that buffer.  sndbuf must
670              * also be large enough that there is enough space
671              * for one reply per thread.  We count all threads
672              * rather than threads in a particular pool, which
673              * provides an upper bound on the number of threads
674              * which will access the socket.
675              */
676             svc_sock_setbufsize(svsk->sk_sock,
677                                 (serv->sv_nrthreads+3) * serv->sv_max_mesg,
678                                 (serv->sv_nrthreads+3) * serv->sv_max_mesg);
679
680         if ((rqstp->rq_deferred = svc_deferred_dequeue(svsk))) {
681                 svc_sock_received(svsk);
682                 return svc_deferred_recv(rqstp);
683         }
684
685         if (test_bit(SK_CLOSE, &svsk->sk_flags)) {
686                 svc_delete_socket(svsk);
687                 return 0;
688         }
689
690         clear_bit(SK_DATA, &svsk->sk_flags);
691         while ((skb = skb_recv_datagram(svsk->sk_sk, 0, 1, &err)) == NULL) {
692                 if (err == -EAGAIN) {
693                         svc_sock_received(svsk);
694                         return err;
695                 }
696                 /* possibly an icmp error */
697                 dprintk("svc: recvfrom returned error %d\n", -err);
698         }
699         if (skb->tstamp.off_sec == 0) {
700                 struct timeval tv;
701
702                 tv.tv_sec = xtime.tv_sec;
703                 tv.tv_usec = xtime.tv_nsec / NSEC_PER_USEC;
704                 skb_set_timestamp(skb, &tv);
705                 /* Don't enable netstamp, sunrpc doesn't
706                    need that much accuracy */
707         }
708         skb_get_timestamp(skb, &svsk->sk_sk->sk_stamp);
709         set_bit(SK_DATA, &svsk->sk_flags); /* there may be more data... */
710
711         /*
712          * Maybe more packets - kick another thread ASAP.
713          */
714         svc_sock_received(svsk);
715
716         len  = skb->len - sizeof(struct udphdr);
717         rqstp->rq_arg.len = len;
718
719         rqstp->rq_prot        = IPPROTO_UDP;
720
721         /* Get sender address */
722         rqstp->rq_addr.sin_family = AF_INET;
723         rqstp->rq_addr.sin_port = skb->h.uh->source;
724         rqstp->rq_addr.sin_addr.s_addr = skb->nh.iph->saddr;
725         rqstp->rq_daddr = skb->nh.iph->daddr;
726
727         if (skb_is_nonlinear(skb)) {
728                 /* we have to copy */
729                 local_bh_disable();
730                 if (csum_partial_copy_to_xdr(&rqstp->rq_arg, skb)) {
731                         local_bh_enable();
732                         /* checksum error */
733                         skb_free_datagram(svsk->sk_sk, skb);
734                         return 0;
735                 }
736                 local_bh_enable();
737                 skb_free_datagram(svsk->sk_sk, skb);
738         } else {
739                 /* we can use it in-place */
740                 rqstp->rq_arg.head[0].iov_base = skb->data + sizeof(struct udphdr);
741                 rqstp->rq_arg.head[0].iov_len = len;
742                 if (skb_checksum_complete(skb)) {
743                         skb_free_datagram(svsk->sk_sk, skb);
744                         return 0;
745                 }
746                 rqstp->rq_skbuff = skb;
747         }
748
749         rqstp->rq_arg.page_base = 0;
750         if (len <= rqstp->rq_arg.head[0].iov_len) {
751                 rqstp->rq_arg.head[0].iov_len = len;
752                 rqstp->rq_arg.page_len = 0;
753                 rqstp->rq_respages = rqstp->rq_pages+1;
754         } else {
755                 rqstp->rq_arg.page_len = len - rqstp->rq_arg.head[0].iov_len;
756                 rqstp->rq_respages = rqstp->rq_pages + 1 +
757                         (rqstp->rq_arg.page_len + PAGE_SIZE - 1)/ PAGE_SIZE;
758         }
759
760         if (serv->sv_stats)
761                 serv->sv_stats->netudpcnt++;
762
763         return len;
764 }
765
766 static int
767 svc_udp_sendto(struct svc_rqst *rqstp)
768 {
769         int             error;
770
771         error = svc_sendto(rqstp, &rqstp->rq_res);
772         if (error == -ECONNREFUSED)
773                 /* ICMP error on earlier request. */
774                 error = svc_sendto(rqstp, &rqstp->rq_res);
775
776         return error;
777 }
778
779 static void
780 svc_udp_init(struct svc_sock *svsk)
781 {
782         svsk->sk_sk->sk_data_ready = svc_udp_data_ready;
783         svsk->sk_sk->sk_write_space = svc_write_space;
784         svsk->sk_recvfrom = svc_udp_recvfrom;
785         svsk->sk_sendto = svc_udp_sendto;
786
787         /* initialise setting must have enough space to
788          * receive and respond to one request.
789          * svc_udp_recvfrom will re-adjust if necessary
790          */
791         svc_sock_setbufsize(svsk->sk_sock,
792                             3 * svsk->sk_server->sv_max_mesg,
793                             3 * svsk->sk_server->sv_max_mesg);
794
795         set_bit(SK_DATA, &svsk->sk_flags); /* might have come in before data_ready set up */
796         set_bit(SK_CHNGBUF, &svsk->sk_flags);
797 }
798
799 /*
800  * A data_ready event on a listening socket means there's a connection
801  * pending. Do not use state_change as a substitute for it.
802  */
803 static void
804 svc_tcp_listen_data_ready(struct sock *sk, int count_unused)
805 {
806         struct svc_sock *svsk = (struct svc_sock *)sk->sk_user_data;
807
808         dprintk("svc: socket %p TCP (listen) state change %d\n",
809                 sk, sk->sk_state);
810
811         /*
812          * This callback may called twice when a new connection
813          * is established as a child socket inherits everything
814          * from a parent LISTEN socket.
815          * 1) data_ready method of the parent socket will be called
816          *    when one of child sockets become ESTABLISHED.
817          * 2) data_ready method of the child socket may be called
818          *    when it receives data before the socket is accepted.
819          * In case of 2, we should ignore it silently.
820          */
821         if (sk->sk_state == TCP_LISTEN) {
822                 if (svsk) {
823                         set_bit(SK_CONN, &svsk->sk_flags);
824                         svc_sock_enqueue(svsk);
825                 } else
826                         printk("svc: socket %p: no user data\n", sk);
827         }
828
829         if (sk->sk_sleep && waitqueue_active(sk->sk_sleep))
830                 wake_up_interruptible_all(sk->sk_sleep);
831 }
832
833 /*
834  * A state change on a connected socket means it's dying or dead.
835  */
836 static void
837 svc_tcp_state_change(struct sock *sk)
838 {
839         struct svc_sock *svsk = (struct svc_sock *)sk->sk_user_data;
840
841         dprintk("svc: socket %p TCP (connected) state change %d (svsk %p)\n",
842                 sk, sk->sk_state, sk->sk_user_data);
843
844         if (!svsk)
845                 printk("svc: socket %p: no user data\n", sk);
846         else {
847                 set_bit(SK_CLOSE, &svsk->sk_flags);
848                 svc_sock_enqueue(svsk);
849         }
850         if (sk->sk_sleep && waitqueue_active(sk->sk_sleep))
851                 wake_up_interruptible_all(sk->sk_sleep);
852 }
853
854 static void
855 svc_tcp_data_ready(struct sock *sk, int count)
856 {
857         struct svc_sock *svsk = (struct svc_sock *)sk->sk_user_data;
858
859         dprintk("svc: socket %p TCP data ready (svsk %p)\n",
860                 sk, sk->sk_user_data);
861         if (svsk) {
862                 set_bit(SK_DATA, &svsk->sk_flags);
863                 svc_sock_enqueue(svsk);
864         }
865         if (sk->sk_sleep && waitqueue_active(sk->sk_sleep))
866                 wake_up_interruptible(sk->sk_sleep);
867 }
868
869 /*
870  * Accept a TCP connection
871  */
872 static void
873 svc_tcp_accept(struct svc_sock *svsk)
874 {
875         struct sockaddr_in sin;
876         struct svc_serv *serv = svsk->sk_server;
877         struct socket   *sock = svsk->sk_sock;
878         struct socket   *newsock;
879         struct svc_sock *newsvsk;
880         int             err, slen;
881
882         dprintk("svc: tcp_accept %p sock %p\n", svsk, sock);
883         if (!sock)
884                 return;
885
886         clear_bit(SK_CONN, &svsk->sk_flags);
887         err = kernel_accept(sock, &newsock, O_NONBLOCK);
888         if (err < 0) {
889                 if (err == -ENOMEM)
890                         printk(KERN_WARNING "%s: no more sockets!\n",
891                                serv->sv_name);
892                 else if (err != -EAGAIN && net_ratelimit())
893                         printk(KERN_WARNING "%s: accept failed (err %d)!\n",
894                                    serv->sv_name, -err);
895                 return;
896         }
897
898         set_bit(SK_CONN, &svsk->sk_flags);
899         svc_sock_enqueue(svsk);
900
901         slen = sizeof(sin);
902         err = kernel_getpeername(newsock, (struct sockaddr *) &sin, &slen);
903         if (err < 0) {
904                 if (net_ratelimit())
905                         printk(KERN_WARNING "%s: peername failed (err %d)!\n",
906                                    serv->sv_name, -err);
907                 goto failed;            /* aborted connection or whatever */
908         }
909
910         /* Ideally, we would want to reject connections from unauthorized
911          * hosts here, but when we get encription, the IP of the host won't
912          * tell us anything. For now just warn about unpriv connections.
913          */
914         if (ntohs(sin.sin_port) >= 1024) {
915                 dprintk(KERN_WARNING
916                         "%s: connect from unprivileged port: %u.%u.%u.%u:%d\n",
917                         serv->sv_name,
918                         NIPQUAD(sin.sin_addr.s_addr), ntohs(sin.sin_port));
919         }
920
921         dprintk("%s: connect from %u.%u.%u.%u:%04x\n", serv->sv_name,
922                         NIPQUAD(sin.sin_addr.s_addr), ntohs(sin.sin_port));
923
924         /* make sure that a write doesn't block forever when
925          * low on memory
926          */
927         newsock->sk->sk_sndtimeo = HZ*30;
928
929         if (!(newsvsk = svc_setup_socket(serv, newsock, &err,
930                                  (SVC_SOCK_ANONYMOUS | SVC_SOCK_TEMPORARY))))
931                 goto failed;
932         memcpy(&newsvsk->sk_remote, &sin, slen);
933         newsvsk->sk_remotelen = slen;
934
935         svc_sock_received(newsvsk);
936
937         /* make sure that we don't have too many active connections.
938          * If we have, something must be dropped.
939          *
940          * There's no point in trying to do random drop here for
941          * DoS prevention. The NFS clients does 1 reconnect in 15
942          * seconds. An attacker can easily beat that.
943          *
944          * The only somewhat efficient mechanism would be if drop
945          * old connections from the same IP first. But right now
946          * we don't even record the client IP in svc_sock.
947          */
948         if (serv->sv_tmpcnt > (serv->sv_nrthreads+3)*20) {
949                 struct svc_sock *svsk = NULL;
950                 spin_lock_bh(&serv->sv_lock);
951                 if (!list_empty(&serv->sv_tempsocks)) {
952                         if (net_ratelimit()) {
953                                 /* Try to help the admin */
954                                 printk(KERN_NOTICE "%s: too many open TCP "
955                                         "sockets, consider increasing the "
956                                         "number of nfsd threads\n",
957                                                    serv->sv_name);
958                                 printk(KERN_NOTICE "%s: last TCP connect from "
959                                         "%u.%u.%u.%u:%d\n",
960                                         serv->sv_name,
961                                         NIPQUAD(sin.sin_addr.s_addr),
962                                         ntohs(sin.sin_port));
963                         }
964                         /*
965                          * Always select the oldest socket. It's not fair,
966                          * but so is life
967                          */
968                         svsk = list_entry(serv->sv_tempsocks.prev,
969                                           struct svc_sock,
970                                           sk_list);
971                         set_bit(SK_CLOSE, &svsk->sk_flags);
972                         atomic_inc(&svsk->sk_inuse);
973                 }
974                 spin_unlock_bh(&serv->sv_lock);
975
976                 if (svsk) {
977                         svc_sock_enqueue(svsk);
978                         svc_sock_put(svsk);
979                 }
980
981         }
982
983         if (serv->sv_stats)
984                 serv->sv_stats->nettcpconn++;
985
986         return;
987
988 failed:
989         sock_release(newsock);
990         return;
991 }
992
993 /*
994  * Receive data from a TCP socket.
995  */
996 static int
997 svc_tcp_recvfrom(struct svc_rqst *rqstp)
998 {
999         struct svc_sock *svsk = rqstp->rq_sock;
1000         struct svc_serv *serv = svsk->sk_server;
1001         int             len;
1002         struct kvec *vec;
1003         int pnum, vlen;
1004
1005         dprintk("svc: tcp_recv %p data %d conn %d close %d\n",
1006                 svsk, test_bit(SK_DATA, &svsk->sk_flags),
1007                 test_bit(SK_CONN, &svsk->sk_flags),
1008                 test_bit(SK_CLOSE, &svsk->sk_flags));
1009
1010         if ((rqstp->rq_deferred = svc_deferred_dequeue(svsk))) {
1011                 svc_sock_received(svsk);
1012                 return svc_deferred_recv(rqstp);
1013         }
1014
1015         if (test_bit(SK_CLOSE, &svsk->sk_flags)) {
1016                 svc_delete_socket(svsk);
1017                 return 0;
1018         }
1019
1020         if (svsk->sk_sk->sk_state == TCP_LISTEN) {
1021                 svc_tcp_accept(svsk);
1022                 svc_sock_received(svsk);
1023                 return 0;
1024         }
1025
1026         if (test_and_clear_bit(SK_CHNGBUF, &svsk->sk_flags))
1027                 /* sndbuf needs to have room for one request
1028                  * per thread, otherwise we can stall even when the
1029                  * network isn't a bottleneck.
1030                  *
1031                  * We count all threads rather than threads in a
1032                  * particular pool, which provides an upper bound
1033                  * on the number of threads which will access the socket.
1034                  *
1035                  * rcvbuf just needs to be able to hold a few requests.
1036                  * Normally they will be removed from the queue
1037                  * as soon a a complete request arrives.
1038                  */
1039                 svc_sock_setbufsize(svsk->sk_sock,
1040                                     (serv->sv_nrthreads+3) * serv->sv_max_mesg,
1041                                     3 * serv->sv_max_mesg);
1042
1043         clear_bit(SK_DATA, &svsk->sk_flags);
1044
1045         /* Receive data. If we haven't got the record length yet, get
1046          * the next four bytes. Otherwise try to gobble up as much as
1047          * possible up to the complete record length.
1048          */
1049         if (svsk->sk_tcplen < 4) {
1050                 unsigned long   want = 4 - svsk->sk_tcplen;
1051                 struct kvec     iov;
1052
1053                 iov.iov_base = ((char *) &svsk->sk_reclen) + svsk->sk_tcplen;
1054                 iov.iov_len  = want;
1055                 if ((len = svc_recvfrom(rqstp, &iov, 1, want)) < 0)
1056                         goto error;
1057                 svsk->sk_tcplen += len;
1058
1059                 if (len < want) {
1060                         dprintk("svc: short recvfrom while reading record length (%d of %lu)\n",
1061                                 len, want);
1062                         svc_sock_received(svsk);
1063                         return -EAGAIN; /* record header not complete */
1064                 }
1065
1066                 svsk->sk_reclen = ntohl(svsk->sk_reclen);
1067                 if (!(svsk->sk_reclen & 0x80000000)) {
1068                         /* FIXME: technically, a record can be fragmented,
1069                          *  and non-terminal fragments will not have the top
1070                          *  bit set in the fragment length header.
1071                          *  But apparently no known nfs clients send fragmented
1072                          *  records. */
1073                         if (net_ratelimit())
1074                                 printk(KERN_NOTICE "RPC: bad TCP reclen 0x%08lx"
1075                                        " (non-terminal)\n",
1076                                        (unsigned long) svsk->sk_reclen);
1077                         goto err_delete;
1078                 }
1079                 svsk->sk_reclen &= 0x7fffffff;
1080                 dprintk("svc: TCP record, %d bytes\n", svsk->sk_reclen);
1081                 if (svsk->sk_reclen > serv->sv_max_mesg) {
1082                         if (net_ratelimit())
1083                                 printk(KERN_NOTICE "RPC: bad TCP reclen 0x%08lx"
1084                                        " (large)\n",
1085                                        (unsigned long) svsk->sk_reclen);
1086                         goto err_delete;
1087                 }
1088         }
1089
1090         /* Check whether enough data is available */
1091         len = svc_recv_available(svsk);
1092         if (len < 0)
1093                 goto error;
1094
1095         if (len < svsk->sk_reclen) {
1096                 dprintk("svc: incomplete TCP record (%d of %d)\n",
1097                         len, svsk->sk_reclen);
1098                 svc_sock_received(svsk);
1099                 return -EAGAIN; /* record not complete */
1100         }
1101         len = svsk->sk_reclen;
1102         set_bit(SK_DATA, &svsk->sk_flags);
1103
1104         vec = rqstp->rq_vec;
1105         vec[0] = rqstp->rq_arg.head[0];
1106         vlen = PAGE_SIZE;
1107         pnum = 1;
1108         while (vlen < len) {
1109                 vec[pnum].iov_base = page_address(rqstp->rq_pages[pnum]);
1110                 vec[pnum].iov_len = PAGE_SIZE;
1111                 pnum++;
1112                 vlen += PAGE_SIZE;
1113         }
1114         rqstp->rq_respages = &rqstp->rq_pages[pnum];
1115
1116         /* Now receive data */
1117         len = svc_recvfrom(rqstp, vec, pnum, len);
1118         if (len < 0)
1119                 goto error;
1120
1121         dprintk("svc: TCP complete record (%d bytes)\n", len);
1122         rqstp->rq_arg.len = len;
1123         rqstp->rq_arg.page_base = 0;
1124         if (len <= rqstp->rq_arg.head[0].iov_len) {
1125                 rqstp->rq_arg.head[0].iov_len = len;
1126                 rqstp->rq_arg.page_len = 0;
1127         } else {
1128                 rqstp->rq_arg.page_len = len - rqstp->rq_arg.head[0].iov_len;
1129         }
1130
1131         rqstp->rq_skbuff      = NULL;
1132         rqstp->rq_prot        = IPPROTO_TCP;
1133
1134         /* Reset TCP read info */
1135         svsk->sk_reclen = 0;
1136         svsk->sk_tcplen = 0;
1137
1138         svc_sock_received(svsk);
1139         if (serv->sv_stats)
1140                 serv->sv_stats->nettcpcnt++;
1141
1142         return len;
1143
1144  err_delete:
1145         svc_delete_socket(svsk);
1146         return -EAGAIN;
1147
1148  error:
1149         if (len == -EAGAIN) {
1150                 dprintk("RPC: TCP recvfrom got EAGAIN\n");
1151                 svc_sock_received(svsk);
1152         } else {
1153                 printk(KERN_NOTICE "%s: recvfrom returned errno %d\n",
1154                                         svsk->sk_server->sv_name, -len);
1155                 goto err_delete;
1156         }
1157
1158         return len;
1159 }
1160
1161 /*
1162  * Send out data on TCP socket.
1163  */
1164 static int
1165 svc_tcp_sendto(struct svc_rqst *rqstp)
1166 {
1167         struct xdr_buf  *xbufp = &rqstp->rq_res;
1168         int sent;
1169         __be32 reclen;
1170
1171         /* Set up the first element of the reply kvec.
1172          * Any other kvecs that may be in use have been taken
1173          * care of by the server implementation itself.
1174          */
1175         reclen = htonl(0x80000000|((xbufp->len ) - 4));
1176         memcpy(xbufp->head[0].iov_base, &reclen, 4);
1177
1178         if (test_bit(SK_DEAD, &rqstp->rq_sock->sk_flags))
1179                 return -ENOTCONN;
1180
1181         sent = svc_sendto(rqstp, &rqstp->rq_res);
1182         if (sent != xbufp->len) {
1183                 printk(KERN_NOTICE "rpc-srv/tcp: %s: %s %d when sending %d bytes - shutting down socket\n",
1184                        rqstp->rq_sock->sk_server->sv_name,
1185                        (sent<0)?"got error":"sent only",
1186                        sent, xbufp->len);
1187                 set_bit(SK_CLOSE, &rqstp->rq_sock->sk_flags);
1188                 svc_sock_enqueue(rqstp->rq_sock);
1189                 sent = -EAGAIN;
1190         }
1191         return sent;
1192 }
1193
1194 static void
1195 svc_tcp_init(struct svc_sock *svsk)
1196 {
1197         struct sock     *sk = svsk->sk_sk;
1198         struct tcp_sock *tp = tcp_sk(sk);
1199
1200         svsk->sk_recvfrom = svc_tcp_recvfrom;
1201         svsk->sk_sendto = svc_tcp_sendto;
1202
1203         if (sk->sk_state == TCP_LISTEN) {
1204                 dprintk("setting up TCP socket for listening\n");
1205                 sk->sk_data_ready = svc_tcp_listen_data_ready;
1206                 set_bit(SK_CONN, &svsk->sk_flags);
1207         } else {
1208                 dprintk("setting up TCP socket for reading\n");
1209                 sk->sk_state_change = svc_tcp_state_change;
1210                 sk->sk_data_ready = svc_tcp_data_ready;
1211                 sk->sk_write_space = svc_write_space;
1212
1213                 svsk->sk_reclen = 0;
1214                 svsk->sk_tcplen = 0;
1215
1216                 tp->nonagle = 1;        /* disable Nagle's algorithm */
1217
1218                 /* initialise setting must have enough space to
1219                  * receive and respond to one request.
1220                  * svc_tcp_recvfrom will re-adjust if necessary
1221                  */
1222                 svc_sock_setbufsize(svsk->sk_sock,
1223                                     3 * svsk->sk_server->sv_max_mesg,
1224                                     3 * svsk->sk_server->sv_max_mesg);
1225
1226                 set_bit(SK_CHNGBUF, &svsk->sk_flags);
1227                 set_bit(SK_DATA, &svsk->sk_flags);
1228                 if (sk->sk_state != TCP_ESTABLISHED)
1229                         set_bit(SK_CLOSE, &svsk->sk_flags);
1230         }
1231 }
1232
1233 void
1234 svc_sock_update_bufs(struct svc_serv *serv)
1235 {
1236         /*
1237          * The number of server threads has changed. Update
1238          * rcvbuf and sndbuf accordingly on all sockets
1239          */
1240         struct list_head *le;
1241
1242         spin_lock_bh(&serv->sv_lock);
1243         list_for_each(le, &serv->sv_permsocks) {
1244                 struct svc_sock *svsk =
1245                         list_entry(le, struct svc_sock, sk_list);
1246                 set_bit(SK_CHNGBUF, &svsk->sk_flags);
1247         }
1248         list_for_each(le, &serv->sv_tempsocks) {
1249                 struct svc_sock *svsk =
1250                         list_entry(le, struct svc_sock, sk_list);
1251                 set_bit(SK_CHNGBUF, &svsk->sk_flags);
1252         }
1253         spin_unlock_bh(&serv->sv_lock);
1254 }
1255
1256 /*
1257  * Receive the next request on any socket.  This code is carefully
1258  * organised not to touch any cachelines in the shared svc_serv
1259  * structure, only cachelines in the local svc_pool.
1260  */
1261 int
1262 svc_recv(struct svc_rqst *rqstp, long timeout)
1263 {
1264         struct svc_sock         *svsk =NULL;
1265         struct svc_serv         *serv = rqstp->rq_server;
1266         struct svc_pool         *pool = rqstp->rq_pool;
1267         int                     len, i;
1268         int                     pages;
1269         struct xdr_buf          *arg;
1270         DECLARE_WAITQUEUE(wait, current);
1271
1272         dprintk("svc: server %p waiting for data (to = %ld)\n",
1273                 rqstp, timeout);
1274
1275         if (rqstp->rq_sock)
1276                 printk(KERN_ERR
1277                         "svc_recv: service %p, socket not NULL!\n",
1278                          rqstp);
1279         if (waitqueue_active(&rqstp->rq_wait))
1280                 printk(KERN_ERR
1281                         "svc_recv: service %p, wait queue active!\n",
1282                          rqstp);
1283
1284
1285         /* now allocate needed pages.  If we get a failure, sleep briefly */
1286         pages = (serv->sv_max_mesg + PAGE_SIZE) / PAGE_SIZE;
1287         for (i=0; i < pages ; i++)
1288                 while (rqstp->rq_pages[i] == NULL) {
1289                         struct page *p = alloc_page(GFP_KERNEL);
1290                         if (!p)
1291                                 schedule_timeout_uninterruptible(msecs_to_jiffies(500));
1292                         rqstp->rq_pages[i] = p;
1293                 }
1294         rqstp->rq_pages[i++] = NULL; /* this might be seen in nfs_read_actor */
1295         BUG_ON(pages >= RPCSVC_MAXPAGES);
1296
1297         /* Make arg->head point to first page and arg->pages point to rest */
1298         arg = &rqstp->rq_arg;
1299         arg->head[0].iov_base = page_address(rqstp->rq_pages[0]);
1300         arg->head[0].iov_len = PAGE_SIZE;
1301         arg->pages = rqstp->rq_pages + 1;
1302         arg->page_base = 0;
1303         /* save at least one page for response */
1304         arg->page_len = (pages-2)*PAGE_SIZE;
1305         arg->len = (pages-1)*PAGE_SIZE;
1306         arg->tail[0].iov_len = 0;
1307
1308         try_to_freeze();
1309         cond_resched();
1310         if (signalled())
1311                 return -EINTR;
1312
1313         spin_lock_bh(&pool->sp_lock);
1314         if ((svsk = svc_sock_dequeue(pool)) != NULL) {
1315                 rqstp->rq_sock = svsk;
1316                 atomic_inc(&svsk->sk_inuse);
1317                 rqstp->rq_reserved = serv->sv_max_mesg;
1318                 atomic_add(rqstp->rq_reserved, &svsk->sk_reserved);
1319         } else {
1320                 /* No data pending. Go to sleep */
1321                 svc_thread_enqueue(pool, rqstp);
1322
1323                 /*
1324                  * We have to be able to interrupt this wait
1325                  * to bring down the daemons ...
1326                  */
1327                 set_current_state(TASK_INTERRUPTIBLE);
1328                 add_wait_queue(&rqstp->rq_wait, &wait);
1329                 spin_unlock_bh(&pool->sp_lock);
1330
1331                 schedule_timeout(timeout);
1332
1333                 try_to_freeze();
1334
1335                 spin_lock_bh(&pool->sp_lock);
1336                 remove_wait_queue(&rqstp->rq_wait, &wait);
1337
1338                 if (!(svsk = rqstp->rq_sock)) {
1339                         svc_thread_dequeue(pool, rqstp);
1340                         spin_unlock_bh(&pool->sp_lock);
1341                         dprintk("svc: server %p, no data yet\n", rqstp);
1342                         return signalled()? -EINTR : -EAGAIN;
1343                 }
1344         }
1345         spin_unlock_bh(&pool->sp_lock);
1346
1347         dprintk("svc: server %p, pool %u, socket %p, inuse=%d\n",
1348                  rqstp, pool->sp_id, svsk, atomic_read(&svsk->sk_inuse));
1349         len = svsk->sk_recvfrom(rqstp);
1350         dprintk("svc: got len=%d\n", len);
1351
1352         /* No data, incomplete (TCP) read, or accept() */
1353         if (len == 0 || len == -EAGAIN) {
1354                 rqstp->rq_res.len = 0;
1355                 svc_sock_release(rqstp);
1356                 return -EAGAIN;
1357         }
1358         svsk->sk_lastrecv = get_seconds();
1359         clear_bit(SK_OLD, &svsk->sk_flags);
1360
1361         rqstp->rq_secure  = ntohs(rqstp->rq_addr.sin_port) < 1024;
1362         rqstp->rq_chandle.defer = svc_defer;
1363
1364         if (serv->sv_stats)
1365                 serv->sv_stats->netcnt++;
1366         return len;
1367 }
1368
1369 /*
1370  * Drop request
1371  */
1372 void
1373 svc_drop(struct svc_rqst *rqstp)
1374 {
1375         dprintk("svc: socket %p dropped request\n", rqstp->rq_sock);
1376         svc_sock_release(rqstp);
1377 }
1378
1379 /*
1380  * Return reply to client.
1381  */
1382 int
1383 svc_send(struct svc_rqst *rqstp)
1384 {
1385         struct svc_sock *svsk;
1386         int             len;
1387         struct xdr_buf  *xb;
1388
1389         if ((svsk = rqstp->rq_sock) == NULL) {
1390                 printk(KERN_WARNING "NULL socket pointer in %s:%d\n",
1391                                 __FILE__, __LINE__);
1392                 return -EFAULT;
1393         }
1394
1395         /* release the receive skb before sending the reply */
1396         svc_release_skb(rqstp);
1397
1398         /* calculate over-all length */
1399         xb = & rqstp->rq_res;
1400         xb->len = xb->head[0].iov_len +
1401                 xb->page_len +
1402                 xb->tail[0].iov_len;
1403
1404         /* Grab svsk->sk_mutex to serialize outgoing data. */
1405         mutex_lock(&svsk->sk_mutex);
1406         if (test_bit(SK_DEAD, &svsk->sk_flags))
1407                 len = -ENOTCONN;
1408         else
1409                 len = svsk->sk_sendto(rqstp);
1410         mutex_unlock(&svsk->sk_mutex);
1411         svc_sock_release(rqstp);
1412
1413         if (len == -ECONNREFUSED || len == -ENOTCONN || len == -EAGAIN)
1414                 return 0;
1415         return len;
1416 }
1417
1418 /*
1419  * Timer function to close old temporary sockets, using
1420  * a mark-and-sweep algorithm.
1421  */
1422 static void
1423 svc_age_temp_sockets(unsigned long closure)
1424 {
1425         struct svc_serv *serv = (struct svc_serv *)closure;
1426         struct svc_sock *svsk;
1427         struct list_head *le, *next;
1428         LIST_HEAD(to_be_aged);
1429
1430         dprintk("svc_age_temp_sockets\n");
1431
1432         if (!spin_trylock_bh(&serv->sv_lock)) {
1433                 /* busy, try again 1 sec later */
1434                 dprintk("svc_age_temp_sockets: busy\n");
1435                 mod_timer(&serv->sv_temptimer, jiffies + HZ);
1436                 return;
1437         }
1438
1439         list_for_each_safe(le, next, &serv->sv_tempsocks) {
1440                 svsk = list_entry(le, struct svc_sock, sk_list);
1441
1442                 if (!test_and_set_bit(SK_OLD, &svsk->sk_flags))
1443                         continue;
1444                 if (atomic_read(&svsk->sk_inuse) || test_bit(SK_BUSY, &svsk->sk_flags))
1445                         continue;
1446                 atomic_inc(&svsk->sk_inuse);
1447                 list_move(le, &to_be_aged);
1448                 set_bit(SK_CLOSE, &svsk->sk_flags);
1449                 set_bit(SK_DETACHED, &svsk->sk_flags);
1450         }
1451         spin_unlock_bh(&serv->sv_lock);
1452
1453         while (!list_empty(&to_be_aged)) {
1454                 le = to_be_aged.next;
1455                 /* fiddling the sk_list node is safe 'cos we're SK_DETACHED */
1456                 list_del_init(le);
1457                 svsk = list_entry(le, struct svc_sock, sk_list);
1458
1459                 dprintk("queuing svsk %p for closing, %lu seconds old\n",
1460                         svsk, get_seconds() - svsk->sk_lastrecv);
1461
1462                 /* a thread will dequeue and close it soon */
1463                 svc_sock_enqueue(svsk);
1464                 svc_sock_put(svsk);
1465         }
1466
1467         mod_timer(&serv->sv_temptimer, jiffies + svc_conn_age_period * HZ);
1468 }
1469
1470 /*
1471  * Initialize socket for RPC use and create svc_sock struct
1472  * XXX: May want to setsockopt SO_SNDBUF and SO_RCVBUF.
1473  */
1474 static struct svc_sock *svc_setup_socket(struct svc_serv *serv,
1475                                                 struct socket *sock,
1476                                                 int *errp, int flags)
1477 {
1478         struct svc_sock *svsk;
1479         struct sock     *inet;
1480         int             pmap_register = !(flags & SVC_SOCK_ANONYMOUS);
1481         int             is_temporary = flags & SVC_SOCK_TEMPORARY;
1482
1483         dprintk("svc: svc_setup_socket %p\n", sock);
1484         if (!(svsk = kzalloc(sizeof(*svsk), GFP_KERNEL))) {
1485                 *errp = -ENOMEM;
1486                 return NULL;
1487         }
1488
1489         inet = sock->sk;
1490
1491         /* Register socket with portmapper */
1492         if (*errp >= 0 && pmap_register)
1493                 *errp = svc_register(serv, inet->sk_protocol,
1494                                      ntohs(inet_sk(inet)->sport));
1495
1496         if (*errp < 0) {
1497                 kfree(svsk);
1498                 return NULL;
1499         }
1500
1501         set_bit(SK_BUSY, &svsk->sk_flags);
1502         inet->sk_user_data = svsk;
1503         svsk->sk_sock = sock;
1504         svsk->sk_sk = inet;
1505         svsk->sk_ostate = inet->sk_state_change;
1506         svsk->sk_odata = inet->sk_data_ready;
1507         svsk->sk_owspace = inet->sk_write_space;
1508         svsk->sk_server = serv;
1509         atomic_set(&svsk->sk_inuse, 1);
1510         svsk->sk_lastrecv = get_seconds();
1511         spin_lock_init(&svsk->sk_defer_lock);
1512         INIT_LIST_HEAD(&svsk->sk_deferred);
1513         INIT_LIST_HEAD(&svsk->sk_ready);
1514         mutex_init(&svsk->sk_mutex);
1515
1516         /* Initialize the socket */
1517         if (sock->type == SOCK_DGRAM)
1518                 svc_udp_init(svsk);
1519         else
1520                 svc_tcp_init(svsk);
1521
1522         spin_lock_bh(&serv->sv_lock);
1523         if (is_temporary) {
1524                 set_bit(SK_TEMP, &svsk->sk_flags);
1525                 list_add(&svsk->sk_list, &serv->sv_tempsocks);
1526                 serv->sv_tmpcnt++;
1527                 if (serv->sv_temptimer.function == NULL) {
1528                         /* setup timer to age temp sockets */
1529                         setup_timer(&serv->sv_temptimer, svc_age_temp_sockets,
1530                                         (unsigned long)serv);
1531                         mod_timer(&serv->sv_temptimer,
1532                                         jiffies + svc_conn_age_period * HZ);
1533                 }
1534         } else {
1535                 clear_bit(SK_TEMP, &svsk->sk_flags);
1536                 list_add(&svsk->sk_list, &serv->sv_permsocks);
1537         }
1538         spin_unlock_bh(&serv->sv_lock);
1539
1540         dprintk("svc: svc_setup_socket created %p (inet %p)\n",
1541                                 svsk, svsk->sk_sk);
1542
1543         return svsk;
1544 }
1545
1546 int svc_addsock(struct svc_serv *serv,
1547                 int fd,
1548                 char *name_return,
1549                 int *proto)
1550 {
1551         int err = 0;
1552         struct socket *so = sockfd_lookup(fd, &err);
1553         struct svc_sock *svsk = NULL;
1554
1555         if (!so)
1556                 return err;
1557         if (so->sk->sk_family != AF_INET)
1558                 err =  -EAFNOSUPPORT;
1559         else if (so->sk->sk_protocol != IPPROTO_TCP &&
1560             so->sk->sk_protocol != IPPROTO_UDP)
1561                 err =  -EPROTONOSUPPORT;
1562         else if (so->state > SS_UNCONNECTED)
1563                 err = -EISCONN;
1564         else {
1565                 svsk = svc_setup_socket(serv, so, &err, SVC_SOCK_DEFAULTS);
1566                 if (svsk) {
1567                         svc_sock_received(svsk);
1568                         err = 0;
1569                 }
1570         }
1571         if (err) {
1572                 sockfd_put(so);
1573                 return err;
1574         }
1575         if (proto) *proto = so->sk->sk_protocol;
1576         return one_sock_name(name_return, svsk);
1577 }
1578 EXPORT_SYMBOL_GPL(svc_addsock);
1579
1580 /*
1581  * Create socket for RPC service.
1582  */
1583 static int svc_create_socket(struct svc_serv *serv, int protocol,
1584                                 struct sockaddr_in *sin, int flags)
1585 {
1586         struct svc_sock *svsk;
1587         struct socket   *sock;
1588         int             error;
1589         int             type;
1590
1591         dprintk("svc: svc_create_socket(%s, %d, %u.%u.%u.%u:%d)\n",
1592                                 serv->sv_program->pg_name, protocol,
1593                                 NIPQUAD(sin->sin_addr.s_addr),
1594                                 ntohs(sin->sin_port));
1595
1596         if (protocol != IPPROTO_UDP && protocol != IPPROTO_TCP) {
1597                 printk(KERN_WARNING "svc: only UDP and TCP "
1598                                 "sockets supported\n");
1599                 return -EINVAL;
1600         }
1601         type = (protocol == IPPROTO_UDP)? SOCK_DGRAM : SOCK_STREAM;
1602
1603         if ((error = sock_create_kern(PF_INET, type, protocol, &sock)) < 0)
1604                 return error;
1605
1606         svc_reclassify_socket(sock);
1607
1608         if (type == SOCK_STREAM)
1609                 sock->sk->sk_reuse = 1; /* allow address reuse */
1610         error = kernel_bind(sock, (struct sockaddr *) sin,
1611                                         sizeof(*sin));
1612         if (error < 0)
1613                 goto bummer;
1614
1615         if (protocol == IPPROTO_TCP) {
1616                 if ((error = kernel_listen(sock, 64)) < 0)
1617                         goto bummer;
1618         }
1619
1620         if ((svsk = svc_setup_socket(serv, sock, &error, flags)) != NULL) {
1621                 svc_sock_received(svsk);
1622                 return ntohs(inet_sk(svsk->sk_sk)->sport);
1623         }
1624
1625 bummer:
1626         dprintk("svc: svc_create_socket error = %d\n", -error);
1627         sock_release(sock);
1628         return error;
1629 }
1630
1631 /*
1632  * Remove a dead socket
1633  */
1634 static void
1635 svc_delete_socket(struct svc_sock *svsk)
1636 {
1637         struct svc_serv *serv;
1638         struct sock     *sk;
1639
1640         dprintk("svc: svc_delete_socket(%p)\n", svsk);
1641
1642         serv = svsk->sk_server;
1643         sk = svsk->sk_sk;
1644
1645         sk->sk_state_change = svsk->sk_ostate;
1646         sk->sk_data_ready = svsk->sk_odata;
1647         sk->sk_write_space = svsk->sk_owspace;
1648
1649         spin_lock_bh(&serv->sv_lock);
1650
1651         if (!test_and_set_bit(SK_DETACHED, &svsk->sk_flags))
1652                 list_del_init(&svsk->sk_list);
1653         /*
1654          * We used to delete the svc_sock from whichever list
1655          * it's sk_ready node was on, but we don't actually
1656          * need to.  This is because the only time we're called
1657          * while still attached to a queue, the queue itself
1658          * is about to be destroyed (in svc_destroy).
1659          */
1660         if (!test_and_set_bit(SK_DEAD, &svsk->sk_flags)) {
1661                 BUG_ON(atomic_read(&svsk->sk_inuse)<2);
1662                 atomic_dec(&svsk->sk_inuse);
1663                 if (test_bit(SK_TEMP, &svsk->sk_flags))
1664                         serv->sv_tmpcnt--;
1665         }
1666
1667         spin_unlock_bh(&serv->sv_lock);
1668 }
1669
1670 void svc_close_socket(struct svc_sock *svsk)
1671 {
1672         set_bit(SK_CLOSE, &svsk->sk_flags);
1673         if (test_and_set_bit(SK_BUSY, &svsk->sk_flags))
1674                 /* someone else will have to effect the close */
1675                 return;
1676
1677         atomic_inc(&svsk->sk_inuse);
1678         svc_delete_socket(svsk);
1679         clear_bit(SK_BUSY, &svsk->sk_flags);
1680         svc_sock_put(svsk);
1681 }
1682
1683 /**
1684  * svc_makesock - Make a socket for nfsd and lockd
1685  * @serv: RPC server structure
1686  * @protocol: transport protocol to use
1687  * @port: port to use
1688  * @flags: requested socket characteristics
1689  *
1690  */
1691 int svc_makesock(struct svc_serv *serv, int protocol, unsigned short port,
1692                         int flags)
1693 {
1694         struct sockaddr_in sin = {
1695                 .sin_family             = AF_INET,
1696                 .sin_addr.s_addr        = INADDR_ANY,
1697                 .sin_port               = htons(port),
1698         };
1699
1700         dprintk("svc: creating socket proto = %d\n", protocol);
1701         return svc_create_socket(serv, protocol, &sin, flags);
1702 }
1703
1704 /*
1705  * Handle defer and revisit of requests
1706  */
1707
1708 static void svc_revisit(struct cache_deferred_req *dreq, int too_many)
1709 {
1710         struct svc_deferred_req *dr = container_of(dreq, struct svc_deferred_req, handle);
1711         struct svc_sock *svsk;
1712
1713         if (too_many) {
1714                 svc_sock_put(dr->svsk);
1715                 kfree(dr);
1716                 return;
1717         }
1718         dprintk("revisit queued\n");
1719         svsk = dr->svsk;
1720         dr->svsk = NULL;
1721         spin_lock_bh(&svsk->sk_defer_lock);
1722         list_add(&dr->handle.recent, &svsk->sk_deferred);
1723         spin_unlock_bh(&svsk->sk_defer_lock);
1724         set_bit(SK_DEFERRED, &svsk->sk_flags);
1725         svc_sock_enqueue(svsk);
1726         svc_sock_put(svsk);
1727 }
1728
1729 static struct cache_deferred_req *
1730 svc_defer(struct cache_req *req)
1731 {
1732         struct svc_rqst *rqstp = container_of(req, struct svc_rqst, rq_chandle);
1733         int size = sizeof(struct svc_deferred_req) + (rqstp->rq_arg.len);
1734         struct svc_deferred_req *dr;
1735
1736         if (rqstp->rq_arg.page_len)
1737                 return NULL; /* if more than a page, give up FIXME */
1738         if (rqstp->rq_deferred) {
1739                 dr = rqstp->rq_deferred;
1740                 rqstp->rq_deferred = NULL;
1741         } else {
1742                 int skip  = rqstp->rq_arg.len - rqstp->rq_arg.head[0].iov_len;
1743                 /* FIXME maybe discard if size too large */
1744                 dr = kmalloc(size, GFP_KERNEL);
1745                 if (dr == NULL)
1746                         return NULL;
1747
1748                 dr->handle.owner = rqstp->rq_server;
1749                 dr->prot = rqstp->rq_prot;
1750                 dr->addr = rqstp->rq_addr;
1751                 dr->daddr = rqstp->rq_daddr;
1752                 dr->argslen = rqstp->rq_arg.len >> 2;
1753                 memcpy(dr->args, rqstp->rq_arg.head[0].iov_base-skip, dr->argslen<<2);
1754         }
1755         atomic_inc(&rqstp->rq_sock->sk_inuse);
1756         dr->svsk = rqstp->rq_sock;
1757
1758         dr->handle.revisit = svc_revisit;
1759         return &dr->handle;
1760 }
1761
1762 /*
1763  * recv data from a deferred request into an active one
1764  */
1765 static int svc_deferred_recv(struct svc_rqst *rqstp)
1766 {
1767         struct svc_deferred_req *dr = rqstp->rq_deferred;
1768
1769         rqstp->rq_arg.head[0].iov_base = dr->args;
1770         rqstp->rq_arg.head[0].iov_len = dr->argslen<<2;
1771         rqstp->rq_arg.page_len = 0;
1772         rqstp->rq_arg.len = dr->argslen<<2;
1773         rqstp->rq_prot        = dr->prot;
1774         rqstp->rq_addr        = dr->addr;
1775         rqstp->rq_daddr       = dr->daddr;
1776         rqstp->rq_respages    = rqstp->rq_pages;
1777         return dr->argslen<<2;
1778 }
1779
1780
1781 static struct svc_deferred_req *svc_deferred_dequeue(struct svc_sock *svsk)
1782 {
1783         struct svc_deferred_req *dr = NULL;
1784
1785         if (!test_bit(SK_DEFERRED, &svsk->sk_flags))
1786                 return NULL;
1787         spin_lock_bh(&svsk->sk_defer_lock);
1788         clear_bit(SK_DEFERRED, &svsk->sk_flags);
1789         if (!list_empty(&svsk->sk_deferred)) {
1790                 dr = list_entry(svsk->sk_deferred.next,
1791                                 struct svc_deferred_req,
1792                                 handle.recent);
1793                 list_del_init(&dr->handle.recent);
1794                 set_bit(SK_DEFERRED, &svsk->sk_flags);
1795         }
1796         spin_unlock_bh(&svsk->sk_defer_lock);
1797         return dr;
1798 }