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