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