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