5baff8adff31239846d02dad8e7c81562d3cbfcb
[openafs.git] / src / rx / rx_rdwr.c
1  /*
2   * Copyright 2000, International Business Machines Corporation and others.
3   * All Rights Reserved.
4   * 
5   * This software has been released under the terms of the IBM Public
6   * License.  For details, see the LICENSE file in the top-level source
7   * directory or online at http://www.openafs.org/dl/license10.html
8   */
9
10 #include <afsconfig.h>
11 #ifdef KERNEL
12 #include "afs/param.h"
13 #else
14 #include <afs/param.h>
15 #endif
16
17 RCSID
18     ("$Header$");
19
20 #ifdef KERNEL
21 #ifndef UKERNEL
22 #ifdef RX_KERNEL_TRACE
23 #include "rx_kcommon.h"
24 #endif
25 #if defined(AFS_DARWIN_ENV) || defined(AFS_XBSD_ENV)
26 #include "afs/sysincludes.h"
27 #else
28 #include "h/types.h"
29 #include "h/time.h"
30 #include "h/stat.h"
31 #if defined(AFS_AIX_ENV) || defined(AFS_AUX_ENV) || defined(AFS_SUN5_ENV) 
32 #include "h/systm.h"
33 #endif
34 #ifdef  AFS_OSF_ENV
35 #include <net/net_globals.h>
36 #endif /* AFS_OSF_ENV */
37 #ifdef AFS_LINUX20_ENV
38 #include "h/socket.h"
39 #endif
40 #include "netinet/in.h"
41 #if defined(AFS_SGI_ENV)
42 #include "afs/sysincludes.h"
43 #endif
44 #endif
45 #include "afs/afs_args.h"
46 #include "afs/afs_osi.h"
47 #if     (defined(AFS_AUX_ENV) || defined(AFS_AIX_ENV))
48 #include "h/systm.h"
49 #endif
50 #else /* !UKERNEL */
51 #include "afs/sysincludes.h"
52 #endif /* !UKERNEL */
53 #ifdef RXDEBUG
54 #undef RXDEBUG                  /* turn off debugging */
55 #endif /* RXDEBUG */
56
57 #include "rx_kmutex.h"
58 #include "rx/rx_kernel.h"
59 #include "rx/rx_clock.h"
60 #include "rx/rx_queue.h"
61 #include "rx/rx.h"
62 #include "rx/rx_globals.h"
63 #include "afs/lock.h"
64 #include "afsint.h"
65 #ifdef  AFS_OSF_ENV
66 #undef kmem_alloc
67 #undef kmem_free
68 #undef mem_alloc
69 #undef mem_free
70 #undef register
71 #endif /* AFS_OSF_ENV */
72 #else /* KERNEL */
73 # include <sys/types.h>
74 #ifdef AFS_NT40_ENV
75 # include <winsock2.h>
76 #else /* !AFS_NT40_ENV */
77 # include <sys/socket.h>
78 # include <sys/file.h>
79 # include <netdb.h>
80 # include <netinet/in.h>
81 # include <sys/stat.h>
82 # include <sys/time.h>
83 #endif /* !AFS_NT40_ENV */
84 #include <string.h>
85 #ifdef HAVE_UNISTD_H
86 #include <unistd.h>
87 #endif
88 # include "rx_user.h"
89 # include "rx_clock.h"
90 # include "rx_queue.h"
91 # include "rx.h"
92 # include "rx_globals.h"
93 #endif /* KERNEL */
94
95 #ifdef RX_LOCKS_DB
96 /* rxdb_fileID is used to identify the lock location, along with line#. */
97 static int rxdb_fileID = RXDB_FILE_RX_RDWR;
98 #endif /* RX_LOCKS_DB */
99 /* rxi_ReadProc -- internal version.
100  *
101  * LOCKS USED -- called at netpri with rx global lock and call->lock held.
102  */
103 int
104 rxi_ReadProc(register struct rx_call *call, register char *buf,
105              register int nbytes)
106 {
107     register struct rx_packet *cp = call->currentPacket;
108     register struct rx_packet *rp;
109     register int requestCount;
110     register unsigned int t;
111
112 /* XXXX took out clock_NewTime from here.  Was it needed? */
113     requestCount = nbytes;
114
115     /* Free any packets from the last call to ReadvProc/WritevProc */
116     if (queue_IsNotEmpty(&call->iovq)) {
117         rxi_FreePackets(0, &call->iovq);
118     }
119
120     do {
121         if (call->nLeft == 0) {
122             /* Get next packet */
123             for (;;) {
124                 if (call->error || (call->mode != RX_MODE_RECEIVING)) {
125                     if (call->error) {
126                         return 0;
127                     }
128                     if (call->mode == RX_MODE_SENDING) {
129                         rxi_FlushWrite(call);
130                         continue;
131                     }
132                 }
133                 if (queue_IsNotEmpty(&call->rq)) {
134                     /* Check that next packet available is next in sequence */
135                     rp = queue_First(&call->rq, rx_packet);
136                     if (rp->header.seq == call->rnext) {
137                         afs_int32 error;
138                         register struct rx_connection *conn = call->conn;
139                         queue_Remove(rp);
140
141                         /* RXS_CheckPacket called to undo RXS_PreparePacket's
142                          * work.  It may reduce the length of the packet by up
143                          * to conn->maxTrailerSize, to reflect the length of the
144                          * data + the header. */
145                         if ((error =
146                              RXS_CheckPacket(conn->securityObject, call,
147                                              rp))) {
148                             /* Used to merely shut down the call, but now we 
149                              * shut down the whole connection since this may 
150                              * indicate an attempt to hijack it */
151
152                             MUTEX_EXIT(&call->lock);
153                             rxi_ConnectionError(conn, error);
154                             MUTEX_ENTER(&conn->conn_data_lock);
155                             rp = rxi_SendConnectionAbort(conn, rp, 0, 0);
156                             MUTEX_EXIT(&conn->conn_data_lock);
157                             rxi_FreePacket(rp);
158                             MUTEX_ENTER(&call->lock);
159
160                             return 0;
161                         }
162                         call->rnext++;
163                         cp = call->currentPacket = rp;
164                         call->curvec = 1;       /* 0th vec is always header */
165                         /* begin at the beginning [ more or less ], continue 
166                          * on until the end, then stop. */
167                         call->curpos =
168                             (char *)cp->wirevec[1].iov_base +
169                             call->conn->securityHeaderSize;
170                         call->curlen =
171                             cp->wirevec[1].iov_len -
172                             call->conn->securityHeaderSize;
173
174                         /* Notice that this code works correctly if the data
175                          * size is 0 (which it may be--no reply arguments from
176                          * server, for example).  This relies heavily on the
177                          * fact that the code below immediately frees the packet
178                          * (no yields, etc.).  If it didn't, this would be a
179                          * problem because a value of zero for call->nLeft
180                          * normally means that there is no read packet */
181                         call->nLeft = cp->length;
182                         hadd32(call->bytesRcvd, cp->length);
183
184                         /* Send a hard ack for every rxi_HardAckRate+1 packets
185                          * consumed. Otherwise schedule an event to send
186                          * the hard ack later on.
187                          */
188                         call->nHardAcks++;
189                         if (!(call->flags & RX_CALL_RECEIVE_DONE)) {
190                             if (call->nHardAcks > (u_short) rxi_HardAckRate) {
191                                 rxevent_Cancel(call->delayedAckEvent, call,
192                                                RX_CALL_REFCOUNT_DELAY);
193                                 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
194                             } else {
195                                 struct clock when, now;
196                                 clock_GetTime(&now);
197                                 when = now;
198                                 /* Delay to consolidate ack packets */
199                                 clock_Add(&when, &rx_hardAckDelay);
200                                 if (!call->delayedAckEvent
201                                     || clock_Gt(&call->delayedAckEvent->
202                                                 eventTime, &when)) {
203                                     rxevent_Cancel(call->delayedAckEvent,
204                                                    call,
205                                                    RX_CALL_REFCOUNT_DELAY);
206                                     CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
207                                     call->delayedAckEvent =
208                                       rxevent_PostNow(&when, &now,
209                                                      rxi_SendDelayedAck, call,
210                                                      0);
211                                 }
212                             }
213                         }
214                         break;
215                     }
216                 }
217
218 /*
219 MTUXXX  doesn't there need to be an "else" here ??? 
220 */
221                 /* Are there ever going to be any more packets? */
222                 if (call->flags & RX_CALL_RECEIVE_DONE) {
223                     return requestCount - nbytes;
224                 }
225                 /* Wait for in-sequence packet */
226                 call->flags |= RX_CALL_READER_WAIT;
227                 clock_NewTime();
228                 call->startWait = clock_Sec();
229                 while (call->flags & RX_CALL_READER_WAIT) {
230 #ifdef  RX_ENABLE_LOCKS
231                     CV_WAIT(&call->cv_rq, &call->lock);
232 #else
233                     osi_rxSleep(&call->rq);
234 #endif
235                 }
236
237                 call->startWait = 0;
238 #ifdef RX_ENABLE_LOCKS
239                 if (call->error) {
240                     return 0;
241                 }
242 #endif /* RX_ENABLE_LOCKS */
243             }
244         } else
245             /* assert(cp); */
246             /* MTUXXX  this should be replaced by some error-recovery code before shipping */
247             /* yes, the following block is allowed to be the ELSE clause (or not) */
248             /* It's possible for call->nLeft to be smaller than any particular
249              * iov_len.  Usually, recvmsg doesn't change the iov_len, since it
250              * reflects the size of the buffer.  We have to keep track of the
251              * number of bytes read in the length field of the packet struct.  On
252              * the final portion of a received packet, it's almost certain that
253              * call->nLeft will be smaller than the final buffer. */
254             while (nbytes && cp) {
255                 t = MIN((int)call->curlen, nbytes);
256                 t = MIN(t, (int)call->nLeft);
257                 memcpy(buf, call->curpos, t);
258                 buf += t;
259                 nbytes -= t;
260                 call->curpos += t;
261                 call->curlen -= t;
262                 call->nLeft -= t;
263
264                 if (!call->nLeft) {
265                     /* out of packet.  Get another one. */
266                     rxi_FreePacket(cp);
267                     cp = call->currentPacket = (struct rx_packet *)0;
268                 } else if (!call->curlen) {
269                     /* need to get another struct iov */
270                     if (++call->curvec >= cp->niovecs) {
271                         /* current packet is exhausted, get ready for another */
272                         /* don't worry about curvec and stuff, they get set somewhere else */
273                         rxi_FreePacket(cp);
274                         cp = call->currentPacket = (struct rx_packet *)0;
275                         call->nLeft = 0;
276                     } else {
277                         call->curpos =
278                             (char *)cp->wirevec[call->curvec].iov_base;
279                         call->curlen = cp->wirevec[call->curvec].iov_len;
280                     }
281                 }
282             }
283         if (!nbytes) {
284             /* user buffer is full, return */
285             return requestCount;
286         }
287
288     } while (nbytes);
289
290     return requestCount;
291 }
292
293 int
294 rx_ReadProc(struct rx_call *call, char *buf, int nbytes)
295 {
296     int bytes;
297     int tcurlen;
298     int tnLeft;
299     char *tcurpos;
300     SPLVAR;
301
302     /*
303      * Free any packets from the last call to ReadvProc/WritevProc.
304      * We do not need the lock because the receiver threads only
305      * touch the iovq when the RX_CALL_IOVEC_WAIT flag is set, and the
306      * RX_CALL_IOVEC_WAIT is always cleared before returning from
307      * ReadvProc/WritevProc.
308      */
309     if (!queue_IsEmpty(&call->iovq)) {
310         rxi_FreePackets(0, &call->iovq);
311     }
312
313     /*
314      * Most common case, all of the data is in the current iovec.
315      * We do not need the lock because this is the only thread that
316      * updates the curlen, curpos, nLeft fields.
317      *
318      * We are relying on nLeft being zero unless the call is in receive mode.
319      */
320     tcurlen = call->curlen;
321     tnLeft = call->nLeft;
322     if (!call->error && tcurlen > nbytes && tnLeft > nbytes) {
323         tcurpos = call->curpos;
324         memcpy(buf, tcurpos, nbytes);
325         call->curpos = tcurpos + nbytes;
326         call->curlen = tcurlen - nbytes;
327         call->nLeft = tnLeft - nbytes;
328
329         if (!call->nLeft) {
330             /* out of packet.  Get another one. */
331             NETPRI;
332             MUTEX_ENTER(&call->lock);
333             rxi_FreePacket(call->currentPacket);
334             call->currentPacket = (struct rx_packet *)0;
335             MUTEX_EXIT(&call->lock);
336             USERPRI;
337         }
338         return nbytes;
339     }
340
341     NETPRI;
342     MUTEX_ENTER(&call->lock);
343     bytes = rxi_ReadProc(call, buf, nbytes);
344     MUTEX_EXIT(&call->lock);
345     USERPRI;
346     return bytes;
347 }
348
349 /* Optimization for unmarshalling 32 bit integers */
350 int
351 rx_ReadProc32(struct rx_call *call, afs_int32 * value)
352 {
353     int bytes;
354     int tcurlen;
355     int tnLeft;
356     char *tcurpos;
357     SPLVAR;
358
359     /*
360      * Free any packets from the last call to ReadvProc/WritevProc.
361      * We do not need the lock because the receiver threads only
362      * touch the iovq when the RX_CALL_IOVEC_WAIT flag is set, and the
363      * RX_CALL_IOVEC_WAIT is always cleared before returning from
364      * ReadvProc/WritevProc.
365      */
366     if (!queue_IsEmpty(&call->iovq)) {
367         rxi_FreePackets(0, &call->iovq);
368     }
369
370     /*
371      * Most common case, all of the data is in the current iovec.
372      * We do not need the lock because this is the only thread that
373      * updates the curlen, curpos, nLeft fields.
374      *
375      * We are relying on nLeft being zero unless the call is in receive mode.
376      */
377     tcurlen = call->curlen;
378     tnLeft = call->nLeft;
379     if (!call->error && tcurlen >= sizeof(afs_int32)
380         && tnLeft >= sizeof(afs_int32)) {
381         tcurpos = call->curpos;
382         memcpy((char *)value, tcurpos, sizeof(afs_int32));
383         call->curpos = tcurpos + sizeof(afs_int32);
384         call->curlen = (u_short)(tcurlen - sizeof(afs_int32));
385         call->nLeft = (u_short)(tnLeft - sizeof(afs_int32));
386         if (!call->nLeft) {
387             /* out of packet.  Get another one. */
388             NETPRI;
389             MUTEX_ENTER(&call->lock);
390             rxi_FreePacket(call->currentPacket);
391             call->currentPacket = (struct rx_packet *)0;
392             MUTEX_EXIT(&call->lock);
393             USERPRI;
394         }
395         return sizeof(afs_int32);
396     }
397
398     NETPRI;
399     MUTEX_ENTER(&call->lock);
400     bytes = rxi_ReadProc(call, (char *)value, sizeof(afs_int32));
401     MUTEX_EXIT(&call->lock);
402     USERPRI;
403     return bytes;
404 }
405
406 /* rxi_FillReadVec
407  *
408  * Uses packets in the receive queue to fill in as much of the
409  * current iovec as possible. Does not block if it runs out
410  * of packets to complete the iovec. Return true if an ack packet
411  * was sent, otherwise return false */
412 int
413 rxi_FillReadVec(struct rx_call *call, afs_uint32 serial)
414 {
415     int didConsume = 0;
416     int didHardAck = 0;
417     register unsigned int t;
418     struct rx_packet *rp;
419     struct rx_packet *curp;
420     struct iovec *call_iov;
421     struct iovec *cur_iov = NULL;
422
423     curp = call->currentPacket;
424     if (curp) {
425         cur_iov = &curp->wirevec[call->curvec];
426     }
427     call_iov = &call->iov[call->iovNext];
428
429     while (!call->error && call->iovNBytes && call->iovNext < call->iovMax) {
430         if (call->nLeft == 0) {
431             /* Get next packet */
432             if (queue_IsNotEmpty(&call->rq)) {
433                 /* Check that next packet available is next in sequence */
434                 rp = queue_First(&call->rq, rx_packet);
435                 if (rp->header.seq == call->rnext) {
436                     afs_int32 error;
437                     register struct rx_connection *conn = call->conn;
438                     queue_Remove(rp);
439
440                     /* RXS_CheckPacket called to undo RXS_PreparePacket's
441                      * work.  It may reduce the length of the packet by up
442                      * to conn->maxTrailerSize, to reflect the length of the
443                      * data + the header. */
444                     if ((error =
445                          RXS_CheckPacket(conn->securityObject, call, rp))) {
446                         /* Used to merely shut down the call, but now we 
447                          * shut down the whole connection since this may 
448                          * indicate an attempt to hijack it */
449
450                         MUTEX_EXIT(&call->lock);
451                         rxi_ConnectionError(conn, error);
452                         MUTEX_ENTER(&conn->conn_data_lock);
453                         rp = rxi_SendConnectionAbort(conn, rp, 0, 0);
454                         MUTEX_EXIT(&conn->conn_data_lock);
455                         rxi_FreePacket(rp);
456                         MUTEX_ENTER(&call->lock);
457
458                         return 1;
459                     }
460                     call->rnext++;
461                     curp = call->currentPacket = rp;
462                     call->curvec = 1;   /* 0th vec is always header */
463                     cur_iov = &curp->wirevec[1];
464                     /* begin at the beginning [ more or less ], continue 
465                      * on until the end, then stop. */
466                     call->curpos =
467                         (char *)curp->wirevec[1].iov_base +
468                         call->conn->securityHeaderSize;
469                     call->curlen =
470                         curp->wirevec[1].iov_len -
471                         call->conn->securityHeaderSize;
472
473                     /* Notice that this code works correctly if the data
474                      * size is 0 (which it may be--no reply arguments from
475                      * server, for example).  This relies heavily on the
476                      * fact that the code below immediately frees the packet
477                      * (no yields, etc.).  If it didn't, this would be a
478                      * problem because a value of zero for call->nLeft
479                      * normally means that there is no read packet */
480                     call->nLeft = curp->length;
481                     hadd32(call->bytesRcvd, curp->length);
482
483                     /* Send a hard ack for every rxi_HardAckRate+1 packets
484                      * consumed. Otherwise schedule an event to send
485                      * the hard ack later on.
486                      */
487                     call->nHardAcks++;
488                     didConsume = 1;
489                     continue;
490                 }
491             }
492             break;
493         }
494
495         /* It's possible for call->nLeft to be smaller than any particular
496          * iov_len.  Usually, recvmsg doesn't change the iov_len, since it
497          * reflects the size of the buffer.  We have to keep track of the
498          * number of bytes read in the length field of the packet struct.  On
499          * the final portion of a received packet, it's almost certain that
500          * call->nLeft will be smaller than the final buffer. */
501         while (call->iovNBytes && call->iovNext < call->iovMax && curp) {
502
503             t = MIN((int)call->curlen, call->iovNBytes);
504             t = MIN(t, (int)call->nLeft);
505             call_iov->iov_base = call->curpos;
506             call_iov->iov_len = t;
507             call_iov++;
508             call->iovNext++;
509             call->iovNBytes -= t;
510             call->curpos += t;
511             call->curlen -= t;
512             call->nLeft -= t;
513
514             if (!call->nLeft) {
515                 /* out of packet.  Get another one. */
516                 queue_Append(&call->iovq, curp);
517                 curp = call->currentPacket = (struct rx_packet *)0;
518             } else if (!call->curlen) {
519                 /* need to get another struct iov */
520                 if (++call->curvec >= curp->niovecs) {
521                     /* current packet is exhausted, get ready for another */
522                     /* don't worry about curvec and stuff, they get set somewhere else */
523                     queue_Append(&call->iovq, curp);
524                     curp = call->currentPacket = (struct rx_packet *)0;
525                     call->nLeft = 0;
526                 } else {
527                     cur_iov++;
528                     call->curpos = (char *)cur_iov->iov_base;
529                     call->curlen = cur_iov->iov_len;
530                 }
531             }
532         }
533     }
534
535     /* If we consumed any packets then check whether we need to
536      * send a hard ack. */
537     if (didConsume && (!(call->flags & RX_CALL_RECEIVE_DONE))) {
538         if (call->nHardAcks > (u_short) rxi_HardAckRate) {
539             rxevent_Cancel(call->delayedAckEvent, call,
540                            RX_CALL_REFCOUNT_DELAY);
541             rxi_SendAck(call, 0, serial, RX_ACK_DELAY, 0);
542             didHardAck = 1;
543         } else {
544             struct clock when, now;
545             clock_GetTime(&now);
546             when = now;
547             /* Delay to consolidate ack packets */
548             clock_Add(&when, &rx_hardAckDelay);
549             if (!call->delayedAckEvent
550                 || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
551                 rxevent_Cancel(call->delayedAckEvent, call,
552                                RX_CALL_REFCOUNT_DELAY);
553                 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
554                 call->delayedAckEvent =
555                     rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
556             }
557         }
558     }
559     return didHardAck;
560 }
561
562
563 /* rxi_ReadvProc -- internal version.
564  *
565  * Fills in an iovec with pointers to the packet buffers. All packets
566  * except the last packet (new current packet) are moved to the iovq
567  * while the application is processing the data.
568  *
569  * LOCKS USED -- called at netpri with rx global lock and call->lock held.
570  */
571 int
572 rxi_ReadvProc(struct rx_call *call, struct iovec *iov, int *nio, int maxio,
573               int nbytes)
574 {
575     int requestCount;
576     int nextio;
577
578     requestCount = nbytes;
579     nextio = 0;
580
581     /* Free any packets from the last call to ReadvProc/WritevProc */
582     if (queue_IsNotEmpty(&call->iovq)) {
583         rxi_FreePackets(0, &call->iovq);
584     }
585
586     if (call->mode == RX_MODE_SENDING) {
587         rxi_FlushWrite(call);
588     }
589
590     if (call->error) {
591         return 0;
592     }
593
594     /* Get whatever data is currently available in the receive queue.
595      * If rxi_FillReadVec sends an ack packet then it is possible
596      * that we will receive more data while we drop the call lock
597      * to send the packet. Set the RX_CALL_IOVEC_WAIT flag
598      * here to avoid a race with the receive thread if we send
599      * hard acks in rxi_FillReadVec. */
600     call->flags |= RX_CALL_IOVEC_WAIT;
601     call->iovNBytes = nbytes;
602     call->iovMax = maxio;
603     call->iovNext = 0;
604     call->iov = iov;
605     rxi_FillReadVec(call, 0);
606
607     /* if we need more data then sleep until the receive thread has
608      * filled in the rest. */
609     if (!call->error && call->iovNBytes && call->iovNext < call->iovMax
610         && !(call->flags & RX_CALL_RECEIVE_DONE)) {
611         call->flags |= RX_CALL_READER_WAIT;
612         clock_NewTime();
613         call->startWait = clock_Sec();
614         while (call->flags & RX_CALL_READER_WAIT) {
615 #ifdef  RX_ENABLE_LOCKS
616             CV_WAIT(&call->cv_rq, &call->lock);
617 #else
618             osi_rxSleep(&call->rq);
619 #endif
620         }
621         call->startWait = 0;
622     }
623     call->flags &= ~RX_CALL_IOVEC_WAIT;
624 #ifdef RX_ENABLE_LOCKS
625     if (call->error) {
626         return 0;
627     }
628 #endif /* RX_ENABLE_LOCKS */
629
630     call->iov = NULL;
631     *nio = call->iovNext;
632     return nbytes - call->iovNBytes;
633 }
634
635 int
636 rx_ReadvProc(struct rx_call *call, struct iovec *iov, int *nio, int maxio,
637              int nbytes)
638 {
639     int bytes;
640     SPLVAR;
641
642     NETPRI;
643     MUTEX_ENTER(&call->lock);
644     bytes = rxi_ReadvProc(call, iov, nio, maxio, nbytes);
645     MUTEX_EXIT(&call->lock);
646     USERPRI;
647     return bytes;
648 }
649
650 /* rxi_WriteProc -- internal version.
651  *
652  * LOCKS USED -- called at netpri with rx global lock and call->lock held. */
653
654 int
655 rxi_WriteProc(register struct rx_call *call, register char *buf,
656               register int nbytes)
657 {
658     struct rx_connection *conn = call->conn;
659     register struct rx_packet *cp = call->currentPacket;
660     register unsigned int t;
661     int requestCount = nbytes;
662
663     /* Free any packets from the last call to ReadvProc/WritevProc */
664     if (queue_IsNotEmpty(&call->iovq)) {
665         rxi_FreePackets(0, &call->iovq);
666     }
667
668     if (call->mode != RX_MODE_SENDING) {
669         if ((conn->type == RX_SERVER_CONNECTION)
670             && (call->mode == RX_MODE_RECEIVING)) {
671             call->mode = RX_MODE_SENDING;
672             if (cp) {
673                 rxi_FreePacket(cp);
674                 cp = call->currentPacket = (struct rx_packet *)0;
675                 call->nLeft = 0;
676                 call->nFree = 0;
677             }
678         } else {
679             return 0;
680         }
681     }
682
683     /* Loop condition is checked at end, so that a write of 0 bytes
684      * will force a packet to be created--specially for the case where
685      * there are 0 bytes on the stream, but we must send a packet
686      * anyway. */
687     do {
688         if (call->nFree == 0) {
689             if (!call->error && cp) {
690 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
691                 /* Wait until TQ_BUSY is reset before adding any
692                  * packets to the transmit queue
693                  */
694                 while (call->flags & RX_CALL_TQ_BUSY) {
695                     call->flags |= RX_CALL_TQ_WAIT;
696 #ifdef RX_ENABLE_LOCKS
697                     CV_WAIT(&call->cv_tq, &call->lock);
698 #else /* RX_ENABLE_LOCKS */
699                     osi_rxSleep(&call->tq);
700 #endif /* RX_ENABLE_LOCKS */
701                 }
702 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
703                 clock_NewTime();        /* Bogus:  need new time package */
704                 /* The 0, below, specifies that it is not the last packet: 
705                  * there will be others. PrepareSendPacket may
706                  * alter the packet length by up to
707                  * conn->securityMaxTrailerSize */
708                 hadd32(call->bytesSent, cp->length);
709                 rxi_PrepareSendPacket(call, cp, 0);
710                 queue_Append(&call->tq, cp);
711                 cp = call->currentPacket = NULL;
712                 if (!
713                     (call->
714                      flags & (RX_CALL_FAST_RECOVER |
715                               RX_CALL_FAST_RECOVER_WAIT))) {
716                     rxi_Start(0, call, 0, 0);
717                 }
718             }
719             /* Wait for transmit window to open up */
720             while (!call->error
721                    && call->tnext + 1 > call->tfirst + (2 * call->twind)) {
722                 clock_NewTime();
723                 call->startWait = clock_Sec();
724
725 #ifdef  RX_ENABLE_LOCKS
726                 CV_WAIT(&call->cv_twind, &call->lock);
727 #else
728                 call->flags |= RX_CALL_WAIT_WINDOW_ALLOC;
729                 osi_rxSleep(&call->twind);
730 #endif
731
732                 call->startWait = 0;
733 #ifdef RX_ENABLE_LOCKS
734                 if (call->error) {
735                     return 0;
736                 }
737 #endif /* RX_ENABLE_LOCKS */
738             }
739             if ((cp = rxi_AllocSendPacket(call, nbytes))) {
740                 call->currentPacket = cp;
741                 call->nFree = cp->length;
742                 call->curvec = 1;       /* 0th vec is always header */
743                 /* begin at the beginning [ more or less ], continue 
744                  * on until the end, then stop. */
745                 call->curpos =
746                     (char *)cp->wirevec[1].iov_base +
747                     call->conn->securityHeaderSize;
748                 call->curlen =
749                     cp->wirevec[1].iov_len - call->conn->securityHeaderSize;
750             }
751             if (call->error) {
752                 if (cp) {
753                     rxi_FreePacket(cp);
754                     call->currentPacket = NULL;
755                 }
756                 return 0;
757             }
758         }
759
760         if (cp && (int)call->nFree < nbytes) {
761             /* Try to extend the current buffer */
762             register int len, mud;
763             len = cp->length;
764             mud = rx_MaxUserDataSize(call);
765             if (mud > len) {
766                 int want;
767                 want = MIN(nbytes - (int)call->nFree, mud - len);
768                 rxi_AllocDataBuf(cp, want, RX_PACKET_CLASS_SEND_CBUF);
769                 if (cp->length > (unsigned)mud)
770                     cp->length = mud;
771                 call->nFree += (cp->length - len);
772             }
773         }
774
775         /* If the remaining bytes fit in the buffer, then store them
776          * and return.  Don't ship a buffer that's full immediately to
777          * the peer--we don't know if it's the last buffer yet */
778
779         if (!cp) {
780             call->nFree = 0;
781         }
782
783         while (nbytes && call->nFree) {
784
785             t = MIN((int)call->curlen, nbytes);
786             t = MIN((int)call->nFree, t);
787             memcpy(call->curpos, buf, t);
788             buf += t;
789             nbytes -= t;
790             call->curpos += t;
791             call->curlen -= (u_short)t;
792             call->nFree -= (u_short)t;
793
794             if (!call->curlen) {
795                 /* need to get another struct iov */
796                 if (++call->curvec >= cp->niovecs) {
797                     /* current packet is full, extend or send it */
798                     call->nFree = 0;
799                 } else {
800                     call->curpos = (char *)cp->wirevec[call->curvec].iov_base;
801                     call->curlen = cp->wirevec[call->curvec].iov_len;
802                 }
803             }
804         }                       /* while bytes to send and room to send them */
805
806         /* might be out of space now */
807         if (!nbytes) {
808             return requestCount;
809         } else;                 /* more data to send, so get another packet and keep going */
810     } while (nbytes);
811
812     return requestCount - nbytes;
813 }
814
815 int
816 rx_WriteProc(struct rx_call *call, char *buf, int nbytes)
817 {
818     int bytes;
819     int tcurlen;
820     int tnFree;
821     char *tcurpos;
822     SPLVAR;
823
824     /*
825      * Free any packets from the last call to ReadvProc/WritevProc.
826      * We do not need the lock because the receiver threads only
827      * touch the iovq when the RX_CALL_IOVEC_WAIT flag is set, and the
828      * RX_CALL_IOVEC_WAIT is always cleared before returning from
829      * ReadvProc/WritevProc.
830      */
831     if (queue_IsNotEmpty(&call->iovq)) {
832         rxi_FreePackets(0, &call->iovq);
833     }
834
835     /*
836      * Most common case: all of the data fits in the current iovec.
837      * We do not need the lock because this is the only thread that
838      * updates the curlen, curpos, nFree fields.
839      *
840      * We are relying on nFree being zero unless the call is in send mode.
841      */
842     tcurlen = (int)call->curlen;
843     tnFree = (int)call->nFree;
844     if (!call->error && tcurlen >= nbytes && tnFree >= nbytes) {
845         tcurpos = call->curpos;
846         memcpy(tcurpos, buf, nbytes);
847         call->curpos = tcurpos + nbytes;
848         call->curlen = (u_short)(tcurlen - nbytes);
849         call->nFree = (u_short)(tnFree - nbytes);
850         return nbytes;
851     }
852
853     NETPRI;
854     MUTEX_ENTER(&call->lock);
855     bytes = rxi_WriteProc(call, buf, nbytes);
856     MUTEX_EXIT(&call->lock);
857     USERPRI;
858     return bytes;
859 }
860
861 /* Optimization for marshalling 32 bit arguments */
862 int
863 rx_WriteProc32(register struct rx_call *call, register afs_int32 * value)
864 {
865     int bytes;
866     int tcurlen;
867     int tnFree;
868     char *tcurpos;
869     SPLVAR;
870
871     /*
872      * Free any packets from the last call to ReadvProc/WritevProc.
873      * We do not need the lock because the receiver threads only
874      * touch the iovq when the RX_CALL_IOVEC_WAIT flag is set, and the
875      * RX_CALL_IOVEC_WAIT is always cleared before returning from
876      * ReadvProc/WritevProc.
877      */
878     if (queue_IsNotEmpty(&call->iovq)) {
879         rxi_FreePackets(0, &call->iovq);
880     }
881
882     /*
883      * Most common case: all of the data fits in the current iovec.
884      * We do not need the lock because this is the only thread that
885      * updates the curlen, curpos, nFree fields.
886      *
887      * We are relying on nFree being zero unless the call is in send mode.
888      */
889     tcurlen = call->curlen;
890     tnFree = call->nFree;
891     if (!call->error && tcurlen >= sizeof(afs_int32)
892         && tnFree >= sizeof(afs_int32)) {
893         tcurpos = call->curpos;
894         if (!((size_t)tcurpos & (sizeof(afs_int32) - 1))) {
895             *((afs_int32 *) (tcurpos)) = *value;
896         } else {
897             memcpy(tcurpos, (char *)value, sizeof(afs_int32));
898         }
899         call->curpos = tcurpos + sizeof(afs_int32);
900         call->curlen = (u_short)(tcurlen - sizeof(afs_int32));
901         call->nFree = (u_short)(tnFree - sizeof(afs_int32));
902         return sizeof(afs_int32);
903     }
904
905     NETPRI;
906     MUTEX_ENTER(&call->lock);
907     bytes = rxi_WriteProc(call, (char *)value, sizeof(afs_int32));
908     MUTEX_EXIT(&call->lock);
909     USERPRI;
910     return bytes;
911 }
912
913 /* rxi_WritevAlloc -- internal version.
914  *
915  * Fill in an iovec to point to data in packet buffers. The application
916  * calls rxi_WritevProc when the buffers are full.
917  *
918  * LOCKS USED -- called at netpri with rx global lock and call->lock held. */
919
920 int
921 rxi_WritevAlloc(struct rx_call *call, struct iovec *iov, int *nio, int maxio,
922                 int nbytes)
923 {
924     struct rx_connection *conn = call->conn;
925     struct rx_packet *cp = call->currentPacket;
926     int requestCount;
927     int nextio;
928     /* Temporary values, real work is done in rxi_WritevProc */
929     int tnFree;
930     int tcurvec;
931     char *tcurpos;
932     int tcurlen;
933
934     requestCount = nbytes;
935     nextio = 0;
936
937     /* Free any packets from the last call to ReadvProc/WritevProc */
938     if (queue_IsNotEmpty(&call->iovq)) {
939         rxi_FreePackets(0, &call->iovq);
940     }
941
942     if (call->mode != RX_MODE_SENDING) {
943         if ((conn->type == RX_SERVER_CONNECTION)
944             && (call->mode == RX_MODE_RECEIVING)) {
945             call->mode = RX_MODE_SENDING;
946             if (cp) {
947                 rxi_FreePacket(cp);
948                 cp = call->currentPacket = (struct rx_packet *)0;
949                 call->nLeft = 0;
950                 call->nFree = 0;
951             }
952         } else {
953             return 0;
954         }
955     }
956
957     /* Set up the iovec to point to data in packet buffers. */
958     tnFree = call->nFree;
959     tcurvec = call->curvec;
960     tcurpos = call->curpos;
961     tcurlen = call->curlen;
962     do {
963         register unsigned int t;
964
965         if (tnFree == 0) {
966             /* current packet is full, allocate a new one */
967             cp = rxi_AllocSendPacket(call, nbytes);
968             if (cp == NULL) {
969                 /* out of space, return what we have */
970                 *nio = nextio;
971                 return requestCount - nbytes;
972             }
973             queue_Append(&call->iovq, cp);
974             tnFree = cp->length;
975             tcurvec = 1;
976             tcurpos =
977                 (char *)cp->wirevec[1].iov_base +
978                 call->conn->securityHeaderSize;
979             tcurlen = cp->wirevec[1].iov_len - call->conn->securityHeaderSize;
980         }
981
982         if (tnFree < nbytes) {
983             /* try to extend the current packet */
984             register int len, mud;
985             len = cp->length;
986             mud = rx_MaxUserDataSize(call);
987             if (mud > len) {
988                 int want;
989                 want = MIN(nbytes - tnFree, mud - len);
990                 rxi_AllocDataBuf(cp, want, RX_PACKET_CLASS_SEND_CBUF);
991                 if (cp->length > (unsigned)mud)
992                     cp->length = mud;
993                 tnFree += (cp->length - len);
994                 if (cp == call->currentPacket) {
995                     call->nFree += (cp->length - len);
996                 }
997             }
998         }
999
1000         /* fill in the next entry in the iovec */
1001         t = MIN(tcurlen, nbytes);
1002         t = MIN(tnFree, t);
1003         iov[nextio].iov_base = tcurpos;
1004         iov[nextio].iov_len = t;
1005         nbytes -= t;
1006         tcurpos += t;
1007         tcurlen -= t;
1008         tnFree -= t;
1009         nextio++;
1010
1011         if (!tcurlen) {
1012             /* need to get another struct iov */
1013             if (++tcurvec >= cp->niovecs) {
1014                 /* current packet is full, extend it or move on to next packet */
1015                 tnFree = 0;
1016             } else {
1017                 tcurpos = (char *)cp->wirevec[tcurvec].iov_base;
1018                 tcurlen = cp->wirevec[tcurvec].iov_len;
1019             }
1020         }
1021     } while (nbytes && nextio < maxio);
1022     *nio = nextio;
1023     return requestCount - nbytes;
1024 }
1025
1026 int
1027 rx_WritevAlloc(struct rx_call *call, struct iovec *iov, int *nio, int maxio,
1028                int nbytes)
1029 {
1030     int bytes;
1031     SPLVAR;
1032
1033     NETPRI;
1034     MUTEX_ENTER(&call->lock);
1035     bytes = rxi_WritevAlloc(call, iov, nio, maxio, nbytes);
1036     MUTEX_EXIT(&call->lock);
1037     USERPRI;
1038     return bytes;
1039 }
1040
1041 /* rxi_WritevProc -- internal version.
1042  *
1043  * Send buffers allocated in rxi_WritevAlloc.
1044  *
1045  * LOCKS USED -- called at netpri with rx global lock and call->lock held. */
1046
1047 int
1048 rxi_WritevProc(struct rx_call *call, struct iovec *iov, int nio, int nbytes)
1049 {
1050     struct rx_packet *cp = call->currentPacket;
1051     int nextio;
1052     int requestCount;
1053     struct rx_queue tmpq;
1054
1055     requestCount = nbytes;
1056     nextio = 0;
1057
1058     if (call->mode != RX_MODE_SENDING) {
1059         call->error = RX_PROTOCOL_ERROR;
1060     }
1061 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1062     /* Wait until TQ_BUSY is reset before trying to move any
1063      * packets to the transmit queue.  */
1064     while (!call->error && call->flags & RX_CALL_TQ_BUSY) {
1065         call->flags |= RX_CALL_TQ_WAIT;
1066 #ifdef RX_ENABLE_LOCKS
1067         CV_WAIT(&call->cv_tq, &call->lock);
1068 #else /* RX_ENABLE_LOCKS */
1069         osi_rxSleep(&call->tq);
1070 #endif /* RX_ENABLE_LOCKS */
1071     }
1072 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1073
1074     if (call->error) {
1075         if (cp) {
1076             queue_Prepend(&call->iovq, cp);
1077             cp = call->currentPacket = NULL;
1078         }
1079         rxi_FreePackets(0, &call->iovq);
1080         return 0;
1081     }
1082
1083     /* Loop through the I/O vector adjusting packet pointers.
1084      * Place full packets back onto the iovq once they are ready
1085      * to send. Set RX_PROTOCOL_ERROR if any problems are found in
1086      * the iovec. We put the loop condition at the end to ensure that
1087      * a zero length write will push a short packet. */
1088     nextio = 0;
1089     queue_Init(&tmpq);
1090     do {
1091         if (call->nFree == 0 && cp) {
1092             clock_NewTime();    /* Bogus:  need new time package */
1093             /* The 0, below, specifies that it is not the last packet: 
1094              * there will be others. PrepareSendPacket may
1095              * alter the packet length by up to
1096              * conn->securityMaxTrailerSize */
1097             hadd32(call->bytesSent, cp->length);
1098             rxi_PrepareSendPacket(call, cp, 0);
1099             queue_Append(&tmpq, cp);
1100
1101             /* The head of the iovq is now the current packet */
1102             if (nbytes) {
1103                 if (queue_IsEmpty(&call->iovq)) {
1104                     call->error = RX_PROTOCOL_ERROR;
1105                     cp = call->currentPacket = NULL;
1106                     rxi_FreePackets(0, &tmpq);
1107                     return 0;
1108                 }
1109                 cp = queue_First(&call->iovq, rx_packet);
1110                 queue_Remove(cp);
1111                 call->currentPacket = cp;
1112                 call->nFree = cp->length;
1113                 call->curvec = 1;
1114                 call->curpos =
1115                     (char *)cp->wirevec[1].iov_base +
1116                     call->conn->securityHeaderSize;
1117                 call->curlen =
1118                     cp->wirevec[1].iov_len - call->conn->securityHeaderSize;
1119             }
1120         }
1121
1122         if (nbytes) {
1123             /* The next iovec should point to the current position */
1124             if (iov[nextio].iov_base != call->curpos
1125                 || iov[nextio].iov_len > (int)call->curlen) {
1126                 call->error = RX_PROTOCOL_ERROR;
1127                 if (cp) {
1128                     queue_Prepend(&tmpq, cp);
1129                     call->currentPacket = NULL;
1130                 }
1131                 rxi_FreePackets(0, &tmpq);
1132                 return 0;
1133             }
1134             nbytes -= iov[nextio].iov_len;
1135             call->curpos += iov[nextio].iov_len;
1136             call->curlen -= iov[nextio].iov_len;
1137             call->nFree -= iov[nextio].iov_len;
1138             nextio++;
1139             if (call->curlen == 0) {
1140                 if (++call->curvec > cp->niovecs) {
1141                     call->nFree = 0;
1142                 } else {
1143                     call->curpos = (char *)cp->wirevec[call->curvec].iov_base;
1144                     call->curlen = cp->wirevec[call->curvec].iov_len;
1145                 }
1146             }
1147         }
1148     } while (nbytes && nextio < nio);
1149
1150     /* Move the packets from the temporary queue onto the transmit queue.
1151      * We may end up with more than call->twind packets on the queue. */
1152     queue_SpliceAppend(&call->tq, &tmpq);
1153
1154     if (!(call->flags & (RX_CALL_FAST_RECOVER | RX_CALL_FAST_RECOVER_WAIT))) {
1155         rxi_Start(0, call, 0, 0);
1156     }
1157
1158     /* Wait for the length of the transmit queue to fall below call->twind */
1159     while (!call->error && call->tnext + 1 > call->tfirst + (2 * call->twind)) {
1160         clock_NewTime();
1161         call->startWait = clock_Sec();
1162 #ifdef  RX_ENABLE_LOCKS
1163         CV_WAIT(&call->cv_twind, &call->lock);
1164 #else
1165         call->flags |= RX_CALL_WAIT_WINDOW_ALLOC;
1166         osi_rxSleep(&call->twind);
1167 #endif
1168         call->startWait = 0;
1169     }
1170
1171     if (call->error) {
1172         if (cp) {
1173             rxi_FreePacket(cp);
1174             cp = call->currentPacket = NULL;
1175         }
1176         return 0;
1177     }
1178
1179     return requestCount - nbytes;
1180 }
1181
1182 int
1183 rx_WritevProc(struct rx_call *call, struct iovec *iov, int nio, int nbytes)
1184 {
1185     int bytes;
1186     SPLVAR;
1187
1188     NETPRI;
1189     MUTEX_ENTER(&call->lock);
1190     bytes = rxi_WritevProc(call, iov, nio, nbytes);
1191     MUTEX_EXIT(&call->lock);
1192     USERPRI;
1193     return bytes;
1194 }
1195
1196 /* Flush any buffered data to the stream, switch to read mode
1197  * (clients) or to EOF mode (servers) */
1198 void
1199 rxi_FlushWrite(register struct rx_call *call)
1200 {
1201     register struct rx_packet *cp = call->currentPacket;
1202
1203     /* Free any packets from the last call to ReadvProc/WritevProc */
1204     if (queue_IsNotEmpty(&call->iovq)) {
1205         rxi_FreePackets(0, &call->iovq);
1206     }
1207
1208     if (call->mode == RX_MODE_SENDING) {
1209
1210         call->mode =
1211             (call->conn->type ==
1212              RX_CLIENT_CONNECTION ? RX_MODE_RECEIVING : RX_MODE_EOF);
1213
1214 #ifdef RX_KERNEL_TRACE
1215         {
1216             int glockOwner = ISAFS_GLOCK();
1217             if (!glockOwner)
1218                 AFS_GLOCK();
1219             afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1220                        __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1221                        call);
1222             if (!glockOwner)
1223                 AFS_GUNLOCK();
1224         }
1225 #endif
1226
1227 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
1228         /* Wait until TQ_BUSY is reset before adding any
1229          * packets to the transmit queue
1230          */
1231         while (call->flags & RX_CALL_TQ_BUSY) {
1232             call->flags |= RX_CALL_TQ_WAIT;
1233 #ifdef RX_ENABLE_LOCKS
1234             CV_WAIT(&call->cv_tq, &call->lock);
1235 #else /* RX_ENABLE_LOCKS */
1236             osi_rxSleep(&call->tq);
1237 #endif /* RX_ENABLE_LOCKS */
1238         }
1239 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1240
1241         if (cp) {
1242             /* cp->length is only supposed to be the user's data */
1243             /* cp->length was already set to (then-current) 
1244              * MaxUserDataSize or less. */
1245             cp->length -= call->nFree;
1246             call->currentPacket = (struct rx_packet *)0;
1247             call->nFree = 0;
1248         } else {
1249             cp = rxi_AllocSendPacket(call, 0);
1250             if (!cp) {
1251                 /* Mode can no longer be MODE_SENDING */
1252                 return;
1253             }
1254             cp->length = 0;
1255             cp->niovecs = 2;    /* header + space for rxkad stuff */
1256             call->nFree = 0;
1257         }
1258
1259         /* The 1 specifies that this is the last packet */
1260         hadd32(call->bytesSent, cp->length);
1261         rxi_PrepareSendPacket(call, cp, 1);
1262         queue_Append(&call->tq, cp);
1263         if (!
1264             (call->
1265              flags & (RX_CALL_FAST_RECOVER | RX_CALL_FAST_RECOVER_WAIT))) {
1266             rxi_Start(0, call, 0, 0);
1267         }
1268     }
1269 }
1270
1271 /* Flush any buffered data to the stream, switch to read mode
1272  * (clients) or to EOF mode (servers) */
1273 void
1274 rx_FlushWrite(struct rx_call *call)
1275 {
1276     SPLVAR;
1277     NETPRI;
1278     MUTEX_ENTER(&call->lock);
1279     rxi_FlushWrite(call);
1280     MUTEX_EXIT(&call->lock);
1281     USERPRI;
1282 }