cleanup
[linux-2.4.21-pre4.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/version.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 <asm/uaccess.h>
38 #include <asm/ioctls.h>
39
40 #include <linux/sunrpc/types.h>
41 #include <linux/sunrpc/xdr.h>
42 #include <linux/sunrpc/svcsock.h>
43 #include <linux/sunrpc/stats.h>
44
45 /* SMP locking strategy:
46  *
47  *      svc_serv->sv_lock protects most stuff for that service.
48  *
49  *      Some flags can be set to certain values at any time
50  *      providing that certain rules are followed:
51  *
52  *      SK_BUSY  can be set to 0 at any time.  
53  *              svc_sock_enqueue must be called afterwards
54  *      SK_CONN, SK_DATA, can be set or cleared at any time.
55  *              after a set, svc_sock_enqueue must be called.   
56  *              after a clear, the socket must be read/accepted
57  *               if this succeeds, it must be set again.
58  *      SK_CLOSE can set at any time. It is never cleared.
59  *
60  */
61
62 #define RPCDBG_FACILITY RPCDBG_SVCSOCK
63
64
65 static struct svc_sock *svc_setup_socket(struct svc_serv *, struct socket *,
66                                          int *errp, int pmap_reg);
67 static void             svc_udp_data_ready(struct sock *, int);
68 static int              svc_udp_recvfrom(struct svc_rqst *);
69 static int              svc_udp_sendto(struct svc_rqst *);
70
71
72 /*
73  * Queue up an idle server thread.  Must have serv->sv_lock held.
74  * Note: this is really a stack rather than a queue, so that we only
75  * use as many different threads as we need, and the rest don't polute
76  * the cache.
77  */
78 static inline void
79 svc_serv_enqueue(struct svc_serv *serv, struct svc_rqst *rqstp)
80 {
81         list_add(&rqstp->rq_list, &serv->sv_threads);
82 }
83
84 /*
85  * Dequeue an nfsd thread.  Must have serv->sv_lock held.
86  */
87 static inline void
88 svc_serv_dequeue(struct svc_serv *serv, struct svc_rqst *rqstp)
89 {
90         list_del(&rqstp->rq_list);
91 }
92
93 /*
94  * Release an skbuff after use
95  */
96 static inline void
97 svc_release_skb(struct svc_rqst *rqstp)
98 {
99         struct sk_buff *skb = rqstp->rq_skbuff;
100
101         if (!skb)
102                 return;
103         rqstp->rq_skbuff = NULL;
104
105         dprintk("svc: service %p, releasing skb %p\n", rqstp, skb);
106         skb_free_datagram(rqstp->rq_sock->sk_sk, skb);
107 }
108
109 /*
110  * Queue up a socket with data pending. If there are idle nfsd
111  * processes, wake 'em up.
112  *
113  */
114 static void
115 svc_sock_enqueue(struct svc_sock *svsk)
116 {
117         struct svc_serv *serv = svsk->sk_server;
118         struct svc_rqst *rqstp;
119
120         if (!(svsk->sk_flags &
121               ( (1<<SK_CONN)|(1<<SK_DATA)|(1<<SK_CLOSE)) ))
122                 return;
123
124         spin_lock_bh(&serv->sv_lock);
125
126         if (!list_empty(&serv->sv_threads) && 
127             !list_empty(&serv->sv_sockets))
128                 printk(KERN_ERR
129                         "svc_sock_enqueue: threads and sockets both waiting??\n");
130
131         if (test_bit(SK_BUSY, &svsk->sk_flags)) {
132                 /* Don't enqueue socket while daemon is receiving */
133                 dprintk("svc: socket %p busy, not enqueued\n", svsk->sk_sk);
134                 goto out_unlock;
135         }
136
137         if (((svsk->sk_reserved + serv->sv_bufsz)*2
138              > sock_wspace(svsk->sk_sk))
139             && !test_bit(SK_CLOSE, &svsk->sk_flags)
140             && !test_bit(SK_CONN, &svsk->sk_flags)) {
141                 /* Don't enqueue while not enough space for reply */
142                 dprintk("svc: socket %p  no space, %d*2 > %ld, not enqueued\n",
143                         svsk->sk_sk, svsk->sk_reserved+serv->sv_bufsz,
144                         sock_wspace(svsk->sk_sk));
145                 goto out_unlock;
146         }
147
148         /* Mark socket as busy. It will remain in this state until the
149          * server has processed all pending data and put the socket back
150          * on the idle list.
151          */
152         set_bit(SK_BUSY, &svsk->sk_flags);
153
154         if (!list_empty(&serv->sv_threads)) {
155                 rqstp = list_entry(serv->sv_threads.next,
156                                    struct svc_rqst,
157                                    rq_list);
158                 dprintk("svc: socket %p served by daemon %p\n",
159                         svsk->sk_sk, rqstp);
160                 svc_serv_dequeue(serv, rqstp);
161                 if (rqstp->rq_sock)
162                         printk(KERN_ERR 
163                                 "svc_sock_enqueue: server %p, rq_sock=%p!\n",
164                                 rqstp, rqstp->rq_sock);
165                 rqstp->rq_sock = svsk;
166                 svsk->sk_inuse++;
167                 rqstp->rq_reserved = serv->sv_bufsz;
168                 svsk->sk_reserved += rqstp->rq_reserved;
169                 wake_up(&rqstp->rq_wait);
170         } else {
171                 dprintk("svc: socket %p put into queue\n", svsk->sk_sk);
172                 list_add_tail(&svsk->sk_ready, &serv->sv_sockets);
173                 set_bit(SK_QUED, &svsk->sk_flags);
174         }
175
176 out_unlock:
177         spin_unlock_bh(&serv->sv_lock);
178 }
179
180 /*
181  * Dequeue the first socket.  Must be called with the serv->sv_lock held.
182  */
183 static inline struct svc_sock *
184 svc_sock_dequeue(struct svc_serv *serv)
185 {
186         struct svc_sock *svsk;
187
188         if (list_empty(&serv->sv_sockets))
189                 return NULL;
190
191         svsk = list_entry(serv->sv_sockets.next,
192                           struct svc_sock, sk_ready);
193         list_del(&svsk->sk_ready);
194
195         dprintk("svc: socket %p dequeued, inuse=%d\n",
196                 svsk->sk_sk, svsk->sk_inuse);
197         clear_bit(SK_QUED, &svsk->sk_flags);
198
199         return svsk;
200 }
201
202 /*
203  * Having read something from a socket, check whether it
204  * needs to be re-enqueued.
205  * Note: SK_DATA only gets cleared when a read-attempt finds
206  * no (or insufficient) data.
207  */
208 static inline void
209 svc_sock_received(struct svc_sock *svsk)
210 {
211         clear_bit(SK_BUSY, &svsk->sk_flags);
212         svc_sock_enqueue(svsk);
213 }
214
215
216 /**
217  * svc_reserve - change the space reserved for the reply to a request.
218  * @rqstp:  The request in question
219  * @space: new max space to reserve
220  *
221  * Each request reserves some space on the output queue of the socket
222  * to make sure the reply fits.  This function reduces that reserved
223  * space to be the amount of space used already, plus @space.
224  *
225  */
226 void svc_reserve(struct svc_rqst *rqstp, int space)
227 {
228         space += rqstp->rq_resbuf.len<<2;
229
230         if (space < rqstp->rq_reserved) {
231                 struct svc_sock *svsk = rqstp->rq_sock;
232                 spin_lock_bh(&svsk->sk_server->sv_lock);
233                 svsk->sk_reserved -= (rqstp->rq_reserved - space);
234                 rqstp->rq_reserved = space;
235                 spin_unlock_bh(&svsk->sk_server->sv_lock);
236
237                 svc_sock_enqueue(svsk);
238         }
239 }
240
241 /*
242  * Release a socket after use.
243  */
244 static inline void
245 svc_sock_put(struct svc_sock *svsk)
246 {
247         struct svc_serv *serv = svsk->sk_server;
248
249         spin_lock_bh(&serv->sv_lock);
250         if (!--(svsk->sk_inuse) && test_bit(SK_DEAD, &svsk->sk_flags)) {
251                 spin_unlock_bh(&serv->sv_lock);
252                 dprintk("svc: releasing dead socket\n");
253                 sock_release(svsk->sk_sock);
254                 kfree(svsk);
255         }
256         else
257                 spin_unlock_bh(&serv->sv_lock);
258 }
259
260 static void
261 svc_sock_release(struct svc_rqst *rqstp)
262 {
263         struct svc_sock *svsk = rqstp->rq_sock;
264
265         svc_release_skb(rqstp);
266
267         /* Reset response buffer and release
268          * the reservation.
269          * But first, check that enough space was reserved
270          * for the reply, otherwise we have a bug!
271          */
272         if ((rqstp->rq_resbuf.len<<2) >  rqstp->rq_reserved)
273                 printk(KERN_ERR "RPC request reserved %d but used %d\n",
274                        rqstp->rq_reserved,
275                        rqstp->rq_resbuf.len<<2);
276
277         rqstp->rq_resbuf.buf = rqstp->rq_resbuf.base;
278         rqstp->rq_resbuf.len = 0;
279         svc_reserve(rqstp, 0);
280         rqstp->rq_sock = NULL;
281
282         svc_sock_put(svsk);
283 }
284
285 /*
286  * External function to wake up a server waiting for data
287  */
288 void
289 svc_wake_up(struct svc_serv *serv)
290 {
291         struct svc_rqst *rqstp;
292
293         spin_lock_bh(&serv->sv_lock);
294         if (!list_empty(&serv->sv_threads)) {
295                 rqstp = list_entry(serv->sv_threads.next,
296                                    struct svc_rqst,
297                                    rq_list);
298                 dprintk("svc: daemon %p woken up.\n", rqstp);
299                 /*
300                 svc_serv_dequeue(serv, rqstp);
301                 rqstp->rq_sock = NULL;
302                  */
303                 wake_up(&rqstp->rq_wait);
304         }
305         spin_unlock_bh(&serv->sv_lock);
306 }
307
308 /*
309  * Generic sendto routine
310  */
311 static int
312 svc_sendto(struct svc_rqst *rqstp, struct iovec *iov, int nr)
313 {
314         mm_segment_t    oldfs;
315         struct svc_sock *svsk = rqstp->rq_sock;
316         struct socket   *sock = svsk->sk_sock;
317         struct msghdr   msg;
318         int             i, buflen, len;
319
320         for (i = buflen = 0; i < nr; i++)
321                 buflen += iov[i].iov_len;
322
323         msg.msg_name    = &rqstp->rq_addr;
324         msg.msg_namelen = sizeof(rqstp->rq_addr);
325         msg.msg_iov     = iov;
326         msg.msg_iovlen  = nr;
327         msg.msg_control = NULL;
328         msg.msg_controllen = 0;
329
330         /* This was MSG_DONTWAIT, but I now want it to wait.
331          * The only thing that it would wait for is memory and
332          * if we are fairly low on memory, then we aren't likely
333          * to make much progress anyway.
334          * sk->sndtimeo is set to 30seconds just in case.
335          */
336         msg.msg_flags   = 0;
337
338         oldfs = get_fs(); set_fs(KERNEL_DS);
339         len = sock_sendmsg(sock, &msg, buflen);
340         set_fs(oldfs);
341
342         dprintk("svc: socket %p sendto([%p %Zu... ], %d, %d) = %d\n",
343                         rqstp->rq_sock, iov[0].iov_base, iov[0].iov_len, nr, buflen, len);
344
345         return len;
346 }
347
348 /*
349  * Check input queue length
350  */
351 static int
352 svc_recv_available(struct svc_sock *svsk)
353 {
354         mm_segment_t    oldfs;
355         struct socket   *sock = svsk->sk_sock;
356         int             avail, err;
357
358         oldfs = get_fs(); set_fs(KERNEL_DS);
359         err = sock->ops->ioctl(sock, TIOCINQ, (unsigned long) &avail);
360         set_fs(oldfs);
361
362         return (err >= 0)? avail : err;
363 }
364
365 /*
366  * Generic recvfrom routine.
367  */
368 static int
369 svc_recvfrom(struct svc_rqst *rqstp, struct iovec *iov, int nr, int buflen)
370 {
371         mm_segment_t    oldfs;
372         struct msghdr   msg;
373         struct socket   *sock;
374         int             len, alen;
375
376         rqstp->rq_addrlen = sizeof(rqstp->rq_addr);
377         sock = rqstp->rq_sock->sk_sock;
378
379         msg.msg_name    = &rqstp->rq_addr;
380         msg.msg_namelen = sizeof(rqstp->rq_addr);
381         msg.msg_iov     = iov;
382         msg.msg_iovlen  = nr;
383         msg.msg_control = NULL;
384         msg.msg_controllen = 0;
385
386         msg.msg_flags   = MSG_DONTWAIT;
387
388         oldfs = get_fs(); set_fs(KERNEL_DS);
389         len = sock_recvmsg(sock, &msg, buflen, MSG_DONTWAIT);
390         set_fs(oldfs);
391
392         /* sock_recvmsg doesn't fill in the name/namelen, so we must..
393          * possibly we should cache this in the svc_sock structure
394          * at accept time. FIXME
395          */
396         alen = sizeof(rqstp->rq_addr);
397         sock->ops->getname(sock, (struct sockaddr *)&rqstp->rq_addr, &alen, 1);
398
399         dprintk("svc: socket %p recvfrom(%p, %Zu) = %d\n",
400                 rqstp->rq_sock, iov[0].iov_base, iov[0].iov_len, len);
401
402         return len;
403 }
404
405 /*
406  * Set socket snd and rcv buffer lengths
407  */
408 static inline void
409 svc_sock_setbufsize(struct socket *sock, unsigned int snd, unsigned int rcv)
410 {
411 #if 0
412         mm_segment_t    oldfs;
413         oldfs = get_fs(); set_fs(KERNEL_DS);
414         sock_setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
415                         (char*)&snd, sizeof(snd));
416         sock_setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
417                         (char*)&rcv, sizeof(rcv));
418 #else
419         /* sock_setsockopt limits use to sysctl_?mem_max,
420          * which isn't acceptable.  Until that is made conditional
421          * on not having CAP_SYS_RESOURCE or similar, we go direct...
422          * DaveM said I could!
423          */
424         lock_sock(sock->sk);
425         sock->sk->sndbuf = snd * 2;
426         sock->sk->rcvbuf = rcv * 2;
427         sock->sk->userlocks |= SOCK_SNDBUF_LOCK|SOCK_RCVBUF_LOCK;
428         release_sock(sock->sk);
429 #endif
430 }
431 /*
432  * INET callback when data has been received on the socket.
433  */
434 static void
435 svc_udp_data_ready(struct sock *sk, int count)
436 {
437         struct svc_sock *svsk = (struct svc_sock *)(sk->user_data);
438
439         if (!svsk)
440                 goto out;
441         dprintk("svc: socket %p(inet %p), count=%d, busy=%d\n",
442                 svsk, sk, count, test_bit(SK_BUSY, &svsk->sk_flags));
443         set_bit(SK_DATA, &svsk->sk_flags);
444         svc_sock_enqueue(svsk);
445  out:
446         if (sk->sleep && waitqueue_active(sk->sleep))
447                 wake_up_interruptible(sk->sleep);
448 }
449
450 /*
451  * INET callback when space is newly available on the socket.
452  */
453 static void
454 svc_write_space(struct sock *sk)
455 {
456         struct svc_sock *svsk = (struct svc_sock *)(sk->user_data);
457
458         if (svsk) {
459                 dprintk("svc: socket %p(inet %p), write_space busy=%d\n",
460                         svsk, sk, test_bit(SK_BUSY, &svsk->sk_flags));
461                 svc_sock_enqueue(svsk);
462         }
463
464         if (sk->sleep && waitqueue_active(sk->sleep))
465                 wake_up_interruptible(sk->sleep);
466 }
467
468 /*
469  * Receive a datagram from a UDP socket.
470  */
471 static int
472 svc_udp_recvfrom(struct svc_rqst *rqstp)
473 {
474         struct svc_sock *svsk = rqstp->rq_sock;
475         struct svc_serv *serv = svsk->sk_server;
476         struct sk_buff  *skb;
477         u32             *data;
478         int             err, len;
479
480         if (test_and_clear_bit(SK_CHNGBUF, &svsk->sk_flags))
481                 /* udp sockets need large rcvbuf as all pending
482                  * requests are still in that buffer.  sndbuf must
483                  * also be large enough that there is enough space
484                  * for one reply per thread.
485                  */
486                 svc_sock_setbufsize(svsk->sk_sock,
487                                     (serv->sv_nrthreads+3)* serv->sv_bufsz,
488                                     (serv->sv_nrthreads+3)* serv->sv_bufsz);
489
490         clear_bit(SK_DATA, &svsk->sk_flags);
491         while ((skb = skb_recv_datagram(svsk->sk_sk, 0, 1, &err)) == NULL) {
492                 svc_sock_received(svsk);
493                 if (err == -EAGAIN)
494                         return err;
495                 /* possibly an icmp error */
496                 dprintk("svc: recvfrom returned error %d\n", -err);
497         }
498         set_bit(SK_DATA, &svsk->sk_flags); /* there may be more data... */
499
500         /* Sorry. */
501         if (skb_is_nonlinear(skb)) {
502                 if (skb_linearize(skb, GFP_KERNEL) != 0) {
503                         kfree_skb(skb);
504                         svc_sock_received(svsk);
505                         return 0;
506                 }
507         }
508
509         if (skb->ip_summed != CHECKSUM_UNNECESSARY) {
510                 if ((unsigned short)csum_fold(skb_checksum(skb, 0, skb->len, skb->csum))) {
511                         skb_free_datagram(svsk->sk_sk, skb);
512                         svc_sock_received(svsk);
513                         return 0;
514                 }
515         }
516
517
518         len  = skb->len - sizeof(struct udphdr);
519         data = (u32 *) (skb->data + sizeof(struct udphdr));
520
521         rqstp->rq_skbuff      = skb;
522         rqstp->rq_argbuf.base = data;
523         rqstp->rq_argbuf.buf  = data;
524         rqstp->rq_argbuf.len  = (len >> 2);
525         /* rqstp->rq_resbuf      = rqstp->rq_defbuf; */
526         rqstp->rq_prot        = IPPROTO_UDP;
527
528         /* Get sender address */
529         rqstp->rq_addr.sin_family = AF_INET;
530         rqstp->rq_addr.sin_port = skb->h.uh->source;
531         rqstp->rq_addr.sin_addr.s_addr = skb->nh.iph->saddr;
532
533         if (serv->sv_stats)
534                 serv->sv_stats->netudpcnt++;
535
536         /* One down, maybe more to go... */
537         svsk->sk_sk->stamp = skb->stamp;
538         svc_sock_received(svsk);
539
540         return len;
541 }
542
543 static int
544 svc_udp_sendto(struct svc_rqst *rqstp)
545 {
546         struct svc_buf  *bufp = &rqstp->rq_resbuf;
547         int             error;
548
549         /* Set up the first element of the reply iovec.
550          * Any other iovecs that may be in use have been taken
551          * care of by the server implementation itself.
552          */
553         /* bufp->base = bufp->area; */
554         bufp->iov[0].iov_base = bufp->base;
555         bufp->iov[0].iov_len  = bufp->len << 2;
556
557         error = svc_sendto(rqstp, bufp->iov, bufp->nriov);
558         if (error == -ECONNREFUSED)
559                 /* ICMP error on earlier request. */
560                 error = svc_sendto(rqstp, bufp->iov, bufp->nriov);
561
562         return error;
563 }
564
565 static int
566 svc_udp_init(struct svc_sock *svsk)
567 {
568         svsk->sk_sk->data_ready = svc_udp_data_ready;
569         svsk->sk_sk->write_space = svc_write_space;
570         svsk->sk_recvfrom = svc_udp_recvfrom;
571         svsk->sk_sendto = svc_udp_sendto;
572
573         /* initialise setting must have enough space to
574          * receive and respond to one request.  
575          * svc_udp_recvfrom will re-adjust if necessary
576          */
577         svc_sock_setbufsize(svsk->sk_sock,
578                             3 * svsk->sk_server->sv_bufsz,
579                             3 * svsk->sk_server->sv_bufsz);
580
581         set_bit(SK_CHNGBUF, &svsk->sk_flags);
582
583         return 0;
584 }
585
586 /*
587  * A data_ready event on a listening socket means there's a connection
588  * pending. Do not use state_change as a substitute for it.
589  */
590 static void
591 svc_tcp_listen_data_ready(struct sock *sk, int count_unused)
592 {
593         struct svc_sock *svsk;
594
595         dprintk("svc: socket %p TCP (listen) state change %d\n",
596                         sk, sk->state);
597
598         if  (sk->state != TCP_ESTABLISHED) {
599                 /* Aborted connection, SYN_RECV or whatever... */
600                 goto out;
601         }
602         if (!(svsk = (struct svc_sock *) sk->user_data)) {
603                 printk("svc: socket %p: no user data\n", sk);
604                 goto out;
605         }
606         set_bit(SK_CONN, &svsk->sk_flags);
607         svc_sock_enqueue(svsk);
608  out:
609         if (sk->sleep && waitqueue_active(sk->sleep))
610                 wake_up_interruptible_all(sk->sleep);
611 }
612
613 /*
614  * A state change on a connected socket means it's dying or dead.
615  */
616 static void
617 svc_tcp_state_change(struct sock *sk)
618 {
619         struct svc_sock *svsk;
620
621         dprintk("svc: socket %p TCP (connected) state change %d (svsk %p)\n",
622                         sk, sk->state, sk->user_data);
623
624         if (!(svsk = (struct svc_sock *) sk->user_data)) {
625                 printk("svc: socket %p: no user data\n", sk);
626                 goto out;
627         }
628         set_bit(SK_CLOSE, &svsk->sk_flags);
629         svc_sock_enqueue(svsk);
630  out:
631         if (sk->sleep && waitqueue_active(sk->sleep))
632                 wake_up_interruptible_all(sk->sleep);
633 }
634
635 static void
636 svc_tcp_data_ready(struct sock *sk, int count)
637 {
638         struct svc_sock *       svsk;
639
640         dprintk("svc: socket %p TCP data ready (svsk %p)\n",
641                         sk, sk->user_data);
642         if (!(svsk = (struct svc_sock *)(sk->user_data)))
643                 goto out;
644         set_bit(SK_DATA, &svsk->sk_flags);
645         svc_sock_enqueue(svsk);
646  out:
647         if (sk->sleep && waitqueue_active(sk->sleep))
648                 wake_up_interruptible(sk->sleep);
649 }
650
651 /*
652  * Accept a TCP connection
653  */
654 static void
655 svc_tcp_accept(struct svc_sock *svsk)
656 {
657         struct sockaddr_in sin;
658         struct svc_serv *serv = svsk->sk_server;
659         struct socket   *sock = svsk->sk_sock;
660         struct socket   *newsock;
661         struct proto_ops *ops;
662         struct svc_sock *newsvsk;
663         int             err, slen;
664
665         dprintk("svc: tcp_accept %p sock %p\n", svsk, sock);
666         if (!sock)
667                 return;
668
669         if (!(newsock = sock_alloc())) {
670                 printk(KERN_WARNING "%s: no more sockets!\n", serv->sv_name);
671                 return;
672         }
673         dprintk("svc: tcp_accept %p allocated\n", newsock);
674
675         newsock->type = sock->type;
676         newsock->ops = ops = sock->ops;
677
678         clear_bit(SK_CONN, &svsk->sk_flags);
679         if ((err = ops->accept(sock, newsock, O_NONBLOCK)) < 0) {
680                 if (err != -EAGAIN && net_ratelimit())
681                         printk(KERN_WARNING "%s: accept failed (err %d)!\n",
682                                    serv->sv_name, -err);
683                 goto failed;            /* aborted connection or whatever */
684         }
685         set_bit(SK_CONN, &svsk->sk_flags);
686         svc_sock_enqueue(svsk);
687
688         slen = sizeof(sin);
689         err = ops->getname(newsock, (struct sockaddr *) &sin, &slen, 1);
690         if (err < 0) {
691                 if (net_ratelimit())
692                         printk(KERN_WARNING "%s: peername failed (err %d)!\n",
693                                    serv->sv_name, -err);
694                 goto failed;            /* aborted connection or whatever */
695         }
696
697         /* Ideally, we would want to reject connections from unauthorized
698          * hosts here, but when we get encription, the IP of the host won't
699          * tell us anything. For now just warn about unpriv connections.
700          */
701         if (ntohs(sin.sin_port) >= 1024) {
702                 dprintk(KERN_WARNING
703                         "%s: connect from unprivileged port: %u.%u.%u.%u:%d\n",
704                         serv->sv_name, 
705                         NIPQUAD(sin.sin_addr.s_addr), ntohs(sin.sin_port));
706         }
707
708         dprintk("%s: connect from %u.%u.%u.%u:%04x\n", serv->sv_name,
709                         NIPQUAD(sin.sin_addr.s_addr), ntohs(sin.sin_port));
710
711         if (!(newsvsk = svc_setup_socket(serv, newsock, &err, 0)))
712                 goto failed;
713
714         /* make sure that a write doesn't block forever when
715          * low on memory
716          */
717         newsock->sk->sndtimeo = HZ*30;
718
719         /* Precharge. Data may have arrived on the socket before we
720          * installed the data_ready callback. 
721          */
722         set_bit(SK_DATA, &newsvsk->sk_flags);
723         svc_sock_enqueue(newsvsk);
724
725         /* make sure that we don't have too many active connections.
726          * If we have, something must be dropped.
727          * We randomly choose between newest and oldest (in terms
728          * of recent activity) and drop it.
729          */
730         if (serv->sv_tmpcnt > (serv->sv_nrthreads+3)*10) {
731                 struct svc_sock *svsk = NULL;
732                 spin_lock_bh(&serv->sv_lock);
733                 if (!list_empty(&serv->sv_tempsocks)) {
734                         if (net_random()&1)
735                                 svsk = list_entry(serv->sv_tempsocks.prev,
736                                                   struct svc_sock,
737                                                   sk_list);
738                         else
739                                 svsk = list_entry(serv->sv_tempsocks.next,
740                                                   struct svc_sock,
741                                                   sk_list);
742                         set_bit(SK_CLOSE, &svsk->sk_flags);
743                         svsk->sk_inuse ++;
744                 }
745                 spin_unlock_bh(&serv->sv_lock);
746
747                 if (svsk) {
748                         svc_sock_enqueue(svsk);
749                         svc_sock_put(svsk);
750                 }
751
752         }
753
754         if (serv->sv_stats)
755                 serv->sv_stats->nettcpconn++;
756
757         return;
758
759 failed:
760         sock_release(newsock);
761         return;
762 }
763
764 /*
765  * Receive data from a TCP socket.
766  */
767 static int
768 svc_tcp_recvfrom(struct svc_rqst *rqstp)
769 {
770         struct svc_sock *svsk = rqstp->rq_sock;
771         struct svc_serv *serv = svsk->sk_server;
772         struct svc_buf  *bufp = &rqstp->rq_argbuf;
773         int             len;
774
775         dprintk("svc: tcp_recv %p data %d conn %d close %d\n",
776                 svsk, test_bit(SK_DATA, &svsk->sk_flags),
777                 test_bit(SK_CONN, &svsk->sk_flags),
778                 test_bit(SK_CLOSE, &svsk->sk_flags));
779
780         if (test_bit(SK_CLOSE, &svsk->sk_flags)) {
781                 svc_delete_socket(svsk);
782                 return 0;
783         }
784
785         if (test_bit(SK_CONN, &svsk->sk_flags)) {
786                 svc_tcp_accept(svsk);
787                 svc_sock_received(svsk);
788                 return 0;
789         }
790
791         if (test_and_clear_bit(SK_CHNGBUF, &svsk->sk_flags))
792                 /* sndbuf needs to have room for one request
793                  * per thread, otherwise we can stall even when the
794                  * network isn't a bottleneck.
795                  * rcvbuf just needs to be able to hold a few requests.
796                  * Normally they will be removed from the queue 
797                  * as soon as a complete request arrives.
798                  */
799                 svc_sock_setbufsize(svsk->sk_sock,
800                                     (serv->sv_nrthreads+3) *
801                                     serv->sv_bufsz,
802                                     3 * serv->sv_bufsz);
803
804         clear_bit(SK_DATA, &svsk->sk_flags);
805
806         /* Receive data. If we haven't got the record length yet, get
807          * the next four bytes. Otherwise try to gobble up as much as
808          * possible up to the complete record length.
809          */
810         if (svsk->sk_tcplen < 4) {
811                 unsigned long   want = 4 - svsk->sk_tcplen;
812                 struct iovec    iov;
813
814                 iov.iov_base = ((char *) &svsk->sk_reclen) + svsk->sk_tcplen;
815                 iov.iov_len  = want;
816                 if ((len = svc_recvfrom(rqstp, &iov, 1, want)) < 0)
817                         goto error;
818                 svsk->sk_tcplen += len;
819                 if (len < want)
820                         return 0;
821
822                 svsk->sk_reclen = ntohl(svsk->sk_reclen);
823                 if (!(svsk->sk_reclen & 0x80000000)) {
824                         /* FIXME: technically, a record can be fragmented,
825                          *  and non-terminal fragments will not have the top
826                          *  bit set in the fragment length header.
827                          *  But apparently no known nfs clients send fragmented
828                          *  records. */
829                         printk(KERN_NOTICE "RPC: bad TCP reclen 0x%08lx (non-terminal)\n",
830                                (unsigned long) svsk->sk_reclen);
831                         goto err_delete;
832                 }
833                 svsk->sk_reclen &= 0x7fffffff;
834                 dprintk("svc: TCP record, %d bytes\n", svsk->sk_reclen);
835                 if (svsk->sk_reclen > (bufp->buflen<<2)) {
836                         printk(KERN_NOTICE "RPC: bad TCP reclen 0x%08lx (large)\n",
837                                (unsigned long) svsk->sk_reclen);
838                         goto err_delete;
839                 }
840         }
841
842         /* Check whether enough data is available */
843         len = svc_recv_available(svsk);
844         if (len < 0)
845                 goto error;
846
847         if (len < svsk->sk_reclen) {
848                 dprintk("svc: incomplete TCP record (%d of %d)\n",
849                         len, svsk->sk_reclen);
850                 svc_sock_received(svsk);
851                 return -EAGAIN; /* record not complete */
852         }
853         set_bit(SK_DATA, &svsk->sk_flags);
854
855         /* Frob argbuf */
856         bufp->iov[0].iov_base += 4;
857         bufp->iov[0].iov_len  -= 4;
858
859         /* Now receive data */
860         len = svc_recvfrom(rqstp, bufp->iov, bufp->nriov, svsk->sk_reclen);
861         if (len < 0)
862                 goto error;
863
864         dprintk("svc: TCP complete record (%d bytes)\n", len);
865
866         /* Position reply write pointer immediately after
867          * record length */
868         rqstp->rq_resbuf.buf += 1;
869         rqstp->rq_resbuf.len  = 1;
870
871         rqstp->rq_skbuff      = 0;
872         rqstp->rq_argbuf.buf += 1;
873         rqstp->rq_argbuf.len  = (len >> 2);
874         rqstp->rq_prot        = IPPROTO_TCP;
875
876         /* Reset TCP read info */
877         svsk->sk_reclen = 0;
878         svsk->sk_tcplen = 0;
879
880         svc_sock_received(svsk);
881         if (serv->sv_stats)
882                 serv->sv_stats->nettcpcnt++;
883
884         return len;
885
886  err_delete:
887         svc_delete_socket(svsk);
888         return -EAGAIN;
889
890  error:
891         if (len == -EAGAIN) {
892                 dprintk("RPC: TCP recvfrom got EAGAIN\n");
893                 svc_sock_received(svsk);
894         } else {
895                 printk(KERN_NOTICE "%s: recvfrom returned errno %d\n",
896                                         svsk->sk_server->sv_name, -len);
897                 svc_sock_received(svsk);
898         }
899
900         return len;
901 }
902
903 /*
904  * Send out data on TCP socket.
905  */
906 static int
907 svc_tcp_sendto(struct svc_rqst *rqstp)
908 {
909         struct svc_buf  *bufp = &rqstp->rq_resbuf;
910         int sent;
911
912         /* Set up the first element of the reply iovec.
913          * Any other iovecs that may be in use have been taken
914          * care of by the server implementation itself.
915          */
916         bufp->iov[0].iov_base = bufp->base;
917         bufp->iov[0].iov_len  = bufp->len << 2;
918         bufp->base[0] = htonl(0x80000000|((bufp->len << 2) - 4));
919
920         sent = svc_sendto(rqstp, bufp->iov, bufp->nriov);
921         if (sent != bufp->len<<2) {
922                 printk(KERN_NOTICE "rpc-srv/tcp: %s: sent only %d bytes of %d - shutting down socket\n",
923                        rqstp->rq_sock->sk_server->sv_name,
924                        sent, bufp->len << 2);
925                 svc_delete_socket(rqstp->rq_sock);
926                 sent = -EAGAIN;
927         }
928         return sent;
929 }
930
931 static int
932 svc_tcp_init(struct svc_sock *svsk)
933 {
934         struct sock     *sk = svsk->sk_sk;
935
936         svsk->sk_recvfrom = svc_tcp_recvfrom;
937         svsk->sk_sendto = svc_tcp_sendto;
938
939         if (sk->state == TCP_LISTEN) {
940                 dprintk("setting up TCP socket for listening\n");
941                 sk->data_ready = svc_tcp_listen_data_ready;
942         } else {
943                 dprintk("setting up TCP socket for reading\n");
944                 sk->state_change = svc_tcp_state_change;
945                 sk->data_ready = svc_tcp_data_ready;
946                 sk->write_space = svc_write_space;
947
948                 svsk->sk_reclen = 0;
949                 svsk->sk_tcplen = 0;
950
951                 /* initialise setting must have enough space to
952                  * receive and respond to one request.  
953                  * svc_tcp_recvfrom will re-adjust if necessary
954                  */
955                 svc_sock_setbufsize(svsk->sk_sock,
956                                     3 * svsk->sk_server->sv_bufsz,
957                                     3 * svsk->sk_server->sv_bufsz);
958
959                 set_bit(SK_CHNGBUF, &svsk->sk_flags);
960         }
961
962         return 0;
963 }
964
965 void
966 svc_sock_update_bufs(struct svc_serv *serv)
967 {
968         /*
969          * The number of server threads has changed. 
970          * flag all socket to the snd/rcv buffer sizes
971          * updated.
972          * We don't just do it, as the locking is rather
973          * awkward at this point
974          */
975         struct list_head *le;
976
977         spin_lock_bh(&serv->sv_lock);
978         list_for_each(le, &serv->sv_permsocks) {
979                 struct svc_sock *svsk = 
980                         list_entry(le, struct svc_sock, sk_list);
981                 set_bit(SK_CHNGBUF, &svsk->sk_flags);
982         }
983         list_for_each(le, &serv->sv_tempsocks) {
984                 struct svc_sock *svsk =
985                         list_entry(le, struct svc_sock, sk_list);
986                 set_bit(SK_CHNGBUF, &svsk->sk_flags);
987         }
988         spin_unlock_bh(&serv->sv_lock);
989 }
990
991 /*
992  * Receive the next request on any socket.
993  */
994 int
995 svc_recv(struct svc_serv *serv, struct svc_rqst *rqstp, long timeout)
996 {
997         struct svc_sock         *svsk =NULL;
998         int                     len;
999         DECLARE_WAITQUEUE(wait, current);
1000
1001         dprintk("svc: server %p waiting for data (to = %ld)\n",
1002                 rqstp, timeout);
1003
1004         if (rqstp->rq_sock)
1005                 printk(KERN_ERR 
1006                         "svc_recv: service %p, socket not NULL!\n",
1007                          rqstp);
1008         if (waitqueue_active(&rqstp->rq_wait))
1009                 printk(KERN_ERR 
1010                         "svc_recv: service %p, wait queue active!\n",
1011                          rqstp);
1012
1013         /* Initialize the buffers */
1014         rqstp->rq_argbuf = rqstp->rq_defbuf;
1015         rqstp->rq_resbuf = rqstp->rq_defbuf;
1016
1017         if (signalled())
1018                 return -EINTR;
1019
1020         spin_lock_bh(&serv->sv_lock);
1021         if (!list_empty(&serv->sv_tempsocks)) {
1022                 svsk = list_entry(serv->sv_tempsocks.next,
1023                                   struct svc_sock, sk_list);
1024                 /* apparently the "standard" is that clients close
1025                  * idle connections after 5 minutes, servers after
1026                  * 6 minutes
1027                  *   http://www.connectathon.org/talks96/nfstcp.pdf 
1028                  */
1029                 if (CURRENT_TIME - svsk->sk_lastrecv < 6*60
1030                     || test_bit(SK_BUSY, &svsk->sk_flags))
1031                         svsk = NULL;
1032         }
1033         if (svsk) {
1034                 set_bit(SK_BUSY, &svsk->sk_flags);
1035                 set_bit(SK_CLOSE, &svsk->sk_flags);
1036                 rqstp->rq_sock = svsk;
1037                 svsk->sk_inuse++;
1038         } else if ((svsk = svc_sock_dequeue(serv)) != NULL) {
1039                 rqstp->rq_sock = svsk;
1040                 svsk->sk_inuse++;
1041                 rqstp->rq_reserved = serv->sv_bufsz;    
1042                 svsk->sk_reserved += rqstp->rq_reserved;
1043         } else {
1044                 /* No data pending. Go to sleep */
1045                 svc_serv_enqueue(serv, rqstp);
1046
1047                 /*
1048                  * We have to be able to interrupt this wait
1049                  * to bring down the daemons ...
1050                  */
1051                 set_current_state(TASK_INTERRUPTIBLE);
1052                 add_wait_queue(&rqstp->rq_wait, &wait);
1053                 spin_unlock_bh(&serv->sv_lock);
1054
1055                 schedule_timeout(timeout);
1056
1057                 spin_lock_bh(&serv->sv_lock);
1058                 remove_wait_queue(&rqstp->rq_wait, &wait);
1059
1060                 if (!(svsk = rqstp->rq_sock)) {
1061                         svc_serv_dequeue(serv, rqstp);
1062                         spin_unlock_bh(&serv->sv_lock);
1063                         dprintk("svc: server %p, no data yet\n", rqstp);
1064                         return signalled()? -EINTR : -EAGAIN;
1065                 }
1066         }
1067         spin_unlock_bh(&serv->sv_lock);
1068
1069         dprintk("svc: server %p, socket %p, inuse=%d\n",
1070                  rqstp, svsk, svsk->sk_inuse);
1071         len = svsk->sk_recvfrom(rqstp);
1072         dprintk("svc: got len=%d\n", len);
1073
1074         /* No data, incomplete (TCP) read, or accept() */
1075         if (len == 0 || len == -EAGAIN) {
1076                 svc_sock_release(rqstp);
1077                 return -EAGAIN;
1078         }
1079         svsk->sk_lastrecv = CURRENT_TIME;
1080         if (test_bit(SK_TEMP, &svsk->sk_flags)) {
1081                 /* push active sockets to end of list */
1082                 spin_lock_bh(&serv->sv_lock);
1083                 list_del(&svsk->sk_list);
1084                 list_add_tail(&svsk->sk_list, &serv->sv_tempsocks);
1085                 spin_unlock_bh(&serv->sv_lock);
1086         }
1087
1088         rqstp->rq_secure  = ntohs(rqstp->rq_addr.sin_port) < 1024;
1089         rqstp->rq_userset = 0;
1090         rqstp->rq_verfed  = 0;
1091
1092         svc_getlong(&rqstp->rq_argbuf, rqstp->rq_xid);
1093         svc_putlong(&rqstp->rq_resbuf, rqstp->rq_xid);
1094
1095         /* Assume that the reply consists of a single buffer. */
1096         rqstp->rq_resbuf.nriov = 1;
1097
1098         if (serv->sv_stats)
1099                 serv->sv_stats->netcnt++;
1100         return len;
1101 }
1102
1103 /* 
1104  * Drop request
1105  */
1106 void
1107 svc_drop(struct svc_rqst *rqstp)
1108 {
1109         dprintk("svc: socket %p dropped request\n", rqstp->rq_sock);
1110         svc_sock_release(rqstp);
1111 }
1112
1113 /*
1114  * Return reply to client.
1115  */
1116 int
1117 svc_send(struct svc_rqst *rqstp)
1118 {
1119         struct svc_sock *svsk;
1120         int             len;
1121
1122         if ((svsk = rqstp->rq_sock) == NULL) {
1123                 printk(KERN_WARNING "NULL socket pointer in %s:%d\n",
1124                                 __FILE__, __LINE__);
1125                 return -EFAULT;
1126         }
1127
1128         /* release the receive skb before sending the reply */
1129         svc_release_skb(rqstp);
1130
1131         len = svsk->sk_sendto(rqstp);
1132         svc_sock_release(rqstp);
1133
1134         if (len == -ECONNREFUSED || len == -ENOTCONN || len == -EAGAIN)
1135                 return 0;
1136         return len;
1137 }
1138
1139 /*
1140  * Initialize socket for RPC use and create svc_sock struct
1141  * XXX: May want to setsockopt SO_SNDBUF and SO_RCVBUF.
1142  */
1143 static struct svc_sock *
1144 svc_setup_socket(struct svc_serv *serv, struct socket *sock,
1145                                         int *errp, int pmap_register)
1146 {
1147         struct svc_sock *svsk;
1148         struct sock     *inet;
1149
1150         dprintk("svc: svc_setup_socket %p\n", sock);
1151         if (!(svsk = kmalloc(sizeof(*svsk), GFP_KERNEL))) {
1152                 *errp = -ENOMEM;
1153                 return NULL;
1154         }
1155         memset(svsk, 0, sizeof(*svsk));
1156
1157         inet = sock->sk;
1158         inet->user_data = svsk;
1159         svsk->sk_sock = sock;
1160         svsk->sk_sk = inet;
1161         svsk->sk_ostate = inet->state_change;
1162         svsk->sk_odata = inet->data_ready;
1163         svsk->sk_owspace = inet->write_space;
1164         svsk->sk_server = serv;
1165         svsk->sk_lastrecv = CURRENT_TIME;
1166
1167         /* Initialize the socket */
1168         if (sock->type == SOCK_DGRAM)
1169                 *errp = svc_udp_init(svsk);
1170         else
1171                 *errp = svc_tcp_init(svsk);
1172 if (svsk->sk_sk == NULL)
1173         printk(KERN_WARNING "svsk->sk_sk == NULL after svc_prot_init!\n");
1174
1175         /* Register socket with portmapper */
1176         if (*errp >= 0 && pmap_register)
1177                 *errp = svc_register(serv, inet->protocol, ntohs(inet->sport));
1178
1179         if (*errp < 0) {
1180                 inet->user_data = NULL;
1181                 kfree(svsk);
1182                 return NULL;
1183         }
1184
1185
1186         spin_lock_bh(&serv->sv_lock);
1187         if (!pmap_register) {
1188                 set_bit(SK_TEMP, &svsk->sk_flags);
1189                 list_add(&svsk->sk_list, &serv->sv_tempsocks);
1190                 serv->sv_tmpcnt++;
1191         } else {
1192                 clear_bit(SK_TEMP, &svsk->sk_flags);
1193                 list_add(&svsk->sk_list, &serv->sv_permsocks);
1194         }
1195         spin_unlock_bh(&serv->sv_lock);
1196
1197         dprintk("svc: svc_setup_socket created %p (inet %p)\n",
1198                                 svsk, svsk->sk_sk);
1199         return svsk;
1200 }
1201
1202 /*
1203  * Create socket for RPC service.
1204  */
1205 static int
1206 svc_create_socket(struct svc_serv *serv, int protocol, struct sockaddr_in *sin)
1207 {
1208         struct svc_sock *svsk;
1209         struct socket   *sock;
1210         int             error;
1211         int             type;
1212
1213         dprintk("svc: svc_create_socket(%s, %d, %u.%u.%u.%u:%d)\n",
1214                                 serv->sv_program->pg_name, protocol,
1215                                 NIPQUAD(sin->sin_addr.s_addr),
1216                                 ntohs(sin->sin_port));
1217
1218         if (protocol != IPPROTO_UDP && protocol != IPPROTO_TCP) {
1219                 printk(KERN_WARNING "svc: only UDP and TCP "
1220                                 "sockets supported\n");
1221                 return -EINVAL;
1222         }
1223         type = (protocol == IPPROTO_UDP)? SOCK_DGRAM : SOCK_STREAM;
1224
1225         if ((error = sock_create(PF_INET, type, protocol, &sock)) < 0)
1226                 return error;
1227
1228         if (sin != NULL) {
1229                 sock->sk->reuse = 1; /* allow address reuse */
1230                 error = sock->ops->bind(sock, (struct sockaddr *) sin,
1231                                                 sizeof(*sin));
1232                 if (error < 0)
1233                         goto bummer;
1234         }
1235
1236         if (protocol == IPPROTO_TCP) {
1237                 if ((error = sock->ops->listen(sock, 64)) < 0)
1238                         goto bummer;
1239         }
1240
1241         if ((svsk = svc_setup_socket(serv, sock, &error, 1)) != NULL)
1242                 return 0;
1243
1244 bummer:
1245         dprintk("svc: svc_create_socket error = %d\n", -error);
1246         sock_release(sock);
1247         return error;
1248 }
1249
1250 /*
1251  * Remove a dead socket
1252  */
1253 void
1254 svc_delete_socket(struct svc_sock *svsk)
1255 {
1256         struct svc_serv *serv;
1257         struct sock     *sk;
1258
1259         dprintk("svc: svc_delete_socket(%p)\n", svsk);
1260
1261         serv = svsk->sk_server;
1262         sk = svsk->sk_sk;
1263
1264         sk->state_change = svsk->sk_ostate;
1265         sk->data_ready = svsk->sk_odata;
1266         sk->write_space = svsk->sk_owspace;
1267
1268         spin_lock_bh(&serv->sv_lock);
1269
1270         list_del(&svsk->sk_list);
1271         if (test_bit(SK_TEMP, &svsk->sk_flags))
1272                 serv->sv_tmpcnt--;
1273         if (test_bit(SK_QUED, &svsk->sk_flags))
1274                 list_del(&svsk->sk_ready);
1275
1276
1277         set_bit(SK_DEAD, &svsk->sk_flags);
1278
1279         if (!svsk->sk_inuse) {
1280                 spin_unlock_bh(&serv->sv_lock);
1281                 sock_release(svsk->sk_sock);
1282                 kfree(svsk);
1283         } else {
1284                 spin_unlock_bh(&serv->sv_lock);
1285                 dprintk(KERN_NOTICE "svc: server socket destroy delayed\n");
1286                 /* svsk->sk_server = NULL; */
1287         }
1288 }
1289
1290 /*
1291  * Make a socket for nfsd and lockd
1292  */
1293 int
1294 svc_makesock(struct svc_serv *serv, int protocol, unsigned short port)
1295 {
1296         struct sockaddr_in      sin;
1297
1298         dprintk("svc: creating socket proto = %d\n", protocol);
1299         sin.sin_family      = AF_INET;
1300         sin.sin_addr.s_addr = INADDR_ANY;
1301         sin.sin_port        = htons(port);
1302         return svc_create_socket(serv, protocol, &sin);
1303 }
1304