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