a832c21424dde5fb069cf2a663bc6f4b1eb815eb
[openafs.git] / src / rx / rx.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 /* RX:  Extended Remote Procedure Call */
11
12 #include <afsconfig.h>
13 #include <afs/param.h>
14
15 #ifdef KERNEL
16 # include "afs/sysincludes.h"
17 # include "afsincludes.h"
18 # ifndef UKERNEL
19 #  include "h/types.h"
20 #  include "h/time.h"
21 #  include "h/stat.h"
22 #  ifdef AFS_LINUX20_ENV
23 #   include "h/socket.h"
24 #  endif
25 #  include "netinet/in.h"
26 #  ifdef AFS_SUN5_ENV
27 #   include "netinet/ip6.h"
28 #   include "inet/common.h"
29 #   include "inet/ip.h"
30 #   include "inet/ip_ire.h"
31 #  endif
32 #  include "afs/afs_args.h"
33 #  include "afs/afs_osi.h"
34 #  ifdef RX_KERNEL_TRACE
35 #   include "rx_kcommon.h"
36 #  endif
37 #  if   defined(AFS_AIX_ENV)
38 #   include "h/systm.h"
39 #  endif
40 #  ifdef RXDEBUG
41 #   undef RXDEBUG                       /* turn off debugging */
42 #  endif /* RXDEBUG */
43 #  if defined(AFS_SGI_ENV)
44 #   include "sys/debug.h"
45 #  endif
46 # else /* !UKERNEL */
47 #  include "afs/sysincludes.h"
48 #  include "afsincludes.h"
49 # endif /* !UKERNEL */
50 # include "afs/lock.h"
51 # include "rx_kmutex.h"
52 # include "rx_kernel.h"
53 # define        AFSOP_STOP_RXCALLBACK   210     /* Stop CALLBACK process */
54 # define        AFSOP_STOP_AFS          211     /* Stop AFS process */
55 # define        AFSOP_STOP_BKG          212     /* Stop BKG process */
56 extern afs_int32 afs_termState;
57 # ifdef AFS_AIX41_ENV
58 #  include "sys/lockl.h"
59 #  include "sys/lock_def.h"
60 # endif /* AFS_AIX41_ENV */
61 # include "afs/rxgen_consts.h"
62 #else /* KERNEL */
63 # include <roken.h>
64
65 # ifdef AFS_NT40_ENV
66 #  include <afs/afsutil.h>
67 #  include <WINNT\afsreg.h>
68 # endif
69
70 # include "rx_user.h"
71 #endif /* KERNEL */
72
73 #include "rx.h"
74 #include "rx_clock.h"
75 #include "rx_queue.h"
76 #include "rx_atomic.h"
77 #include "rx_globals.h"
78 #include "rx_trace.h"
79 #include "rx_internal.h"
80 #include "rx_stats.h"
81 #include "rx_event.h"
82
83 #include "rx_conn.h"
84 #include "rx_call.h"
85 #include "rx_packet.h"
86
87 #include <afs/rxgen_consts.h>
88
89 #ifndef KERNEL
90 #ifdef AFS_PTHREAD_ENV
91 #ifndef AFS_NT40_ENV
92 int (*registerProgram) (pid_t, char *) = 0;
93 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
94 #endif
95 #else
96 int (*registerProgram) (PROCESS, char *) = 0;
97 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
98 #endif
99 #endif
100
101 /* Local static routines */
102 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
103 static void rxi_ComputeRoundTripTime(struct rx_packet *, struct rx_ackPacket *,
104                                      struct rx_call *, struct rx_peer *,
105                                      struct clock *);
106 static void rxi_Resend(struct rxevent *event, void *arg0, void *arg1,
107                        int istack);
108 static void rxi_SendDelayedAck(struct rxevent *event, void *call,
109                                void *dummy, int dummy2);
110 static void rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1,
111                                      void *dummy, int dummy2);
112 static void rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1,
113                                      void *unused, int unused2);
114 static void rxi_ReapConnections(struct rxevent *unused, void *unused1,
115                                 void *unused2, int unused3);
116
117 #ifdef RX_ENABLE_LOCKS
118 static void rxi_SetAcksInTransmitQueue(struct rx_call *call);
119 #endif
120
121 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
122 struct rx_tq_debug {
123     rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
124     rx_atomic_t rxi_start_in_error;
125 } rx_tq_debug;
126 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
127
128 /* Constant delay time before sending an acknowledge of the last packet
129  * received.  This is to avoid sending an extra acknowledge when the
130  * client is about to make another call, anyway, or the server is
131  * about to respond.
132  *
133  * The lastAckDelay may not exceeed 400ms without causing peers to
134  * unecessarily timeout.
135  */
136 struct clock rx_lastAckDelay = {0, 400000};
137
138 /* Constant delay time before sending a soft ack when none was requested.
139  * This is to make sure we send soft acks before the sender times out,
140  * Normally we wait and send a hard ack when the receiver consumes the packet
141  *
142  * This value has been 100ms in all shipping versions of OpenAFS. Changing it
143  * will require changes to the peer's RTT calculations.
144  */
145 struct clock rx_softAckDelay = {0, 100000};
146
147 /*
148  * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
149  * currently allocated within rx.  This number is used to allocate the
150  * memory required to return the statistics when queried.
151  * Protected by the rx_rpc_stats mutex.
152  */
153
154 static unsigned int rxi_rpc_peer_stat_cnt;
155
156 /*
157  * rxi_rpc_process_stat_cnt counts the total number of local process stat
158  * structures currently allocated within rx.  The number is used to allocate
159  * the memory required to return the statistics when queried.
160  * Protected by the rx_rpc_stats mutex.
161  */
162
163 static unsigned int rxi_rpc_process_stat_cnt;
164
165 /*
166  * rxi_busyChannelError is a boolean.  It indicates whether or not RX_CALL_BUSY
167  * errors should be reported to the application when a call channel appears busy
168  * (inferred from the receipt of RX_PACKET_TYPE_BUSY packets on the channel),
169  * and there are other call channels in the connection that are not busy.
170  * If 0, we do not return errors upon receiving busy packets; we just keep
171  * trying on the same call channel until we hit a timeout.
172  */
173 static afs_int32 rxi_busyChannelError = 0;
174
175 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
176 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
177
178 #if !defined(offsetof)
179 #include <stddef.h>             /* for definition of offsetof() */
180 #endif
181
182 #ifdef RX_ENABLE_LOCKS
183 afs_kmutex_t rx_atomic_mutex;
184 #endif
185
186 /* Forward prototypes */
187 static struct rx_call * rxi_NewCall(struct rx_connection *, int);
188
189 static_inline void
190 putConnection (struct rx_connection *conn) {
191     MUTEX_ENTER(&rx_refcnt_mutex);
192     conn->refCount--;
193     MUTEX_EXIT(&rx_refcnt_mutex);
194 }
195
196 #ifdef AFS_PTHREAD_ENV
197
198 /*
199  * Use procedural initialization of mutexes/condition variables
200  * to ease NT porting
201  */
202
203 extern afs_kmutex_t rx_quota_mutex;
204 extern afs_kmutex_t rx_pthread_mutex;
205 extern afs_kmutex_t rx_packets_mutex;
206 extern afs_kmutex_t rx_refcnt_mutex;
207 extern afs_kmutex_t des_init_mutex;
208 extern afs_kmutex_t des_random_mutex;
209 extern afs_kmutex_t rx_clock_mutex;
210 extern afs_kmutex_t rxi_connCacheMutex;
211 extern afs_kmutex_t event_handler_mutex;
212 extern afs_kmutex_t listener_mutex;
213 extern afs_kmutex_t rx_if_init_mutex;
214 extern afs_kmutex_t rx_if_mutex;
215
216 extern afs_kcondvar_t rx_event_handler_cond;
217 extern afs_kcondvar_t rx_listener_cond;
218
219 static afs_kmutex_t epoch_mutex;
220 static afs_kmutex_t rx_init_mutex;
221 static afs_kmutex_t rx_debug_mutex;
222 static afs_kmutex_t rx_rpc_stats;
223
224 static void
225 rxi_InitPthread(void)
226 {
227     MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
228     MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
229     MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
230     MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
231     MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
232     MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
233     MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
234     MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
235     MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
236     MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
237     MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
238     MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
239     MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
240     MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
241     MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
242
243     CV_INIT(&rx_event_handler_cond, "evhand", CV_DEFAULT, 0);
244     CV_INIT(&rx_listener_cond, "rxlisten", CV_DEFAULT, 0);
245
246     osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
247     osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
248
249     MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
250     MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
251 #ifdef  RX_ENABLE_LOCKS
252 #ifdef RX_LOCKS_DB
253     rxdb_init();
254 #endif /* RX_LOCKS_DB */
255     MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
256     MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
257                0);
258     CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
259             0);
260     MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
261                0);
262     MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
263                0);
264     MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
265     MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
266 #endif /* RX_ENABLE_LOCKS */
267 }
268
269 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
270 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
271 /*
272  * The rx_stats_mutex mutex protects the following global variables:
273  * rxi_lowConnRefCount
274  * rxi_lowPeerRefCount
275  * rxi_nCalls
276  * rxi_Alloccnt
277  * rxi_Allocsize
278  * rx_tq_debug
279  * rx_stats
280  */
281
282 /*
283  * The rx_quota_mutex mutex protects the following global variables:
284  * rxi_dataQuota
285  * rxi_minDeficit
286  * rxi_availProcs
287  * rxi_totalMin
288  */
289
290 /*
291  * The rx_freePktQ_lock protects the following global variables:
292  * rx_nFreePackets
293  */
294
295 /*
296  * The rx_packets_mutex mutex protects the following global variables:
297  * rx_nPackets
298  * rx_TSFPQLocalMax
299  * rx_TSFPQGlobSize
300  * rx_TSFPQMaxProcs
301  */
302
303 /*
304  * The rx_pthread_mutex mutex protects the following global variables:
305  * rxi_fcfs_thread_num
306  */
307 #else
308 #define INIT_PTHREAD_LOCKS
309 #endif
310
311
312 /* Variables for handling the minProcs implementation.  availProcs gives the
313  * number of threads available in the pool at this moment (not counting dudes
314  * executing right now).  totalMin gives the total number of procs required
315  * for handling all minProcs requests.  minDeficit is a dynamic variable
316  * tracking the # of procs required to satisfy all of the remaining minProcs
317  * demands.
318  * For fine grain locking to work, the quota check and the reservation of
319  * a server thread has to come while rxi_availProcs and rxi_minDeficit
320  * are locked. To this end, the code has been modified under #ifdef
321  * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
322  * same time. A new function, ReturnToServerPool() returns the allocation.
323  *
324  * A call can be on several queue's (but only one at a time). When
325  * rxi_ResetCall wants to remove the call from a queue, it has to ensure
326  * that no one else is touching the queue. To this end, we store the address
327  * of the queue lock in the call structure (under the call lock) when we
328  * put the call on a queue, and we clear the call_queue_lock when the
329  * call is removed from a queue (once the call lock has been obtained).
330  * This allows rxi_ResetCall to safely synchronize with others wishing
331  * to manipulate the queue.
332  */
333
334 #if defined(RX_ENABLE_LOCKS)
335 static afs_kmutex_t rx_rpc_stats;
336 #endif
337
338 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
339 ** pretty good that the next packet coming in is from the same connection
340 ** as the last packet, since we're send multiple packets in a transmit window.
341 */
342 struct rx_connection *rxLastConn = 0;
343
344 #ifdef RX_ENABLE_LOCKS
345 /* The locking hierarchy for rx fine grain locking is composed of these
346  * tiers:
347  *
348  * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
349  * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
350  * call->lock - locks call data fields.
351  * These are independent of each other:
352  *      rx_freeCallQueue_lock
353  *      rxi_keyCreate_lock
354  * rx_serverPool_lock
355  * freeSQEList_lock
356  *
357  * serverQueueEntry->lock
358  * rx_peerHashTable_lock - locked under rx_connHashTable_lock
359  * rx_rpc_stats
360  * peer->lock - locks peer data fields.
361  * conn_data_lock - that more than one thread is not updating a conn data
362  *                  field at the same time.
363  * rx_freePktQ_lock
364  *
365  * lowest level:
366  *      multi_handle->lock
367  *      rxevent_lock
368  *      rx_packets_mutex
369  *      rx_stats_mutex
370  *      rx_refcnt_mutex
371  *      rx_atomic_mutex
372  *
373  * Do we need a lock to protect the peer field in the conn structure?
374  *      conn->peer was previously a constant for all intents and so has no
375  *      lock protecting this field. The multihomed client delta introduced
376  *      a RX code change : change the peer field in the connection structure
377  *      to that remote interface from which the last packet for this
378  *      connection was sent out. This may become an issue if further changes
379  *      are made.
380  */
381 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
382 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
383 #ifdef RX_LOCKS_DB
384 /* rxdb_fileID is used to identify the lock location, along with line#. */
385 static int rxdb_fileID = RXDB_FILE_RX;
386 #endif /* RX_LOCKS_DB */
387 #else /* RX_ENABLE_LOCKS */
388 #define SET_CALL_QUEUE_LOCK(C, L)
389 #define CLEAR_CALL_QUEUE_LOCK(C)
390 #endif /* RX_ENABLE_LOCKS */
391 struct rx_serverQueueEntry *rx_waitForPacket = 0;
392 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
393
394 /* ------------Exported Interfaces------------- */
395
396 /* This function allows rxkad to set the epoch to a suitably random number
397  * which rx_NewConnection will use in the future.  The principle purpose is to
398  * get rxnull connections to use the same epoch as the rxkad connections do, at
399  * least once the first rxkad connection is established.  This is important now
400  * that the host/port addresses aren't used in FindConnection: the uniqueness
401  * of epoch/cid matters and the start time won't do. */
402
403 #ifdef AFS_PTHREAD_ENV
404 /*
405  * This mutex protects the following global variables:
406  * rx_epoch
407  */
408
409 #define LOCK_EPOCH MUTEX_ENTER(&epoch_mutex)
410 #define UNLOCK_EPOCH MUTEX_EXIT(&epoch_mutex)
411 #else
412 #define LOCK_EPOCH
413 #define UNLOCK_EPOCH
414 #endif /* AFS_PTHREAD_ENV */
415
416 void
417 rx_SetEpoch(afs_uint32 epoch)
418 {
419     LOCK_EPOCH;
420     rx_epoch = epoch;
421     UNLOCK_EPOCH;
422 }
423
424 /* Initialize rx.  A port number may be mentioned, in which case this
425  * becomes the default port number for any service installed later.
426  * If 0 is provided for the port number, a random port will be chosen
427  * by the kernel.  Whether this will ever overlap anything in
428  * /etc/services is anybody's guess...  Returns 0 on success, -1 on
429  * error. */
430 #ifndef AFS_NT40_ENV
431 static
432 #endif
433 int rxinit_status = 1;
434 #ifdef AFS_PTHREAD_ENV
435 /*
436  * This mutex protects the following global variables:
437  * rxinit_status
438  */
439
440 #define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
441 #define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
442 #else
443 #define LOCK_RX_INIT
444 #define UNLOCK_RX_INIT
445 #endif
446
447 int
448 rx_InitHost(u_int host, u_int port)
449 {
450 #ifdef KERNEL
451     osi_timeval_t tv;
452 #else /* KERNEL */
453     struct timeval tv;
454 #endif /* KERNEL */
455     char *htable, *ptable;
456     int tmp_status;
457
458     SPLVAR;
459
460     INIT_PTHREAD_LOCKS;
461     LOCK_RX_INIT;
462     if (rxinit_status == 0) {
463         tmp_status = rxinit_status;
464         UNLOCK_RX_INIT;
465         return tmp_status;      /* Already started; return previous error code. */
466     }
467 #ifdef RXDEBUG
468     rxi_DebugInit();
469 #endif
470 #ifdef AFS_NT40_ENV
471     if (afs_winsockInit() < 0)
472         return -1;
473 #endif
474
475 #ifndef KERNEL
476     /*
477      * Initialize anything necessary to provide a non-premptive threading
478      * environment.
479      */
480     rxi_InitializeThreadSupport();
481 #endif
482
483     /* Allocate and initialize a socket for client and perhaps server
484      * connections. */
485
486     rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
487     if (rx_socket == OSI_NULLSOCKET) {
488         UNLOCK_RX_INIT;
489         return RX_ADDRINUSE;
490     }
491 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
492 #ifdef RX_LOCKS_DB
493     rxdb_init();
494 #endif /* RX_LOCKS_DB */
495     MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
496     MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
497     MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
498     MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
499     MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
500     MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
501     MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
502     MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
503     MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
504                0);
505     CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
506             0);
507     MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
508                0);
509     MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
510                0);
511     MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
512 #if defined(AFS_HPUX110_ENV)
513     if (!uniprocessor)
514         rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
515 #endif /* AFS_HPUX110_ENV */
516 #endif /* RX_ENABLE_LOCKS && KERNEL */
517
518     rxi_nCalls = 0;
519     rx_connDeadTime = 12;
520     rx_tranquil = 0;            /* reset flag */
521     rxi_ResetStatistics();
522     htable = (char *)
523         osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
524     PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *));     /* XXXXX */
525     memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
526     ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
527     PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *));   /* XXXXX */
528     memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
529
530     /* Malloc up a bunch of packets & buffers */
531     rx_nFreePackets = 0;
532     queue_Init(&rx_freePacketQueue);
533     rxi_NeedMorePackets = FALSE;
534     rx_nPackets = 0;    /* rx_nPackets is managed by rxi_MorePackets* */
535
536     /* enforce a minimum number of allocated packets */
537     if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
538         rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
539
540     /* allocate the initial free packet pool */
541 #ifdef RX_ENABLE_TSFPQ
542     rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
543 #else /* RX_ENABLE_TSFPQ */
544     rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2);        /* fudge */
545 #endif /* RX_ENABLE_TSFPQ */
546     rx_CheckPackets();
547
548     NETPRI;
549
550     clock_Init();
551
552 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
553     tv.tv_sec = clock_now.sec;
554     tv.tv_usec = clock_now.usec;
555     srand((unsigned int)tv.tv_usec);
556 #else
557     osi_GetTime(&tv);
558 #endif
559     if (port) {
560         rx_port = port;
561     } else {
562 #if defined(KERNEL) && !defined(UKERNEL)
563         /* Really, this should never happen in a real kernel */
564         rx_port = 0;
565 #else
566         struct sockaddr_in addr;
567 #ifdef AFS_NT40_ENV
568         int addrlen = sizeof(addr);
569 #else
570         socklen_t addrlen = sizeof(addr);
571 #endif
572         if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
573             rx_Finalize();
574             return -1;
575         }
576         rx_port = addr.sin_port;
577 #endif
578     }
579     rx_stats.minRtt.sec = 9999999;
580 #ifdef  KERNEL
581     rx_SetEpoch(tv.tv_sec | 0x80000000);
582 #else
583     rx_SetEpoch(tv.tv_sec);     /* Start time of this package, rxkad
584                                  * will provide a randomer value. */
585 #endif
586     MUTEX_ENTER(&rx_quota_mutex);
587     rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
588     MUTEX_EXIT(&rx_quota_mutex);
589     /* *Slightly* random start time for the cid.  This is just to help
590      * out with the hashing function at the peer */
591     rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
592     rx_connHashTable = (struct rx_connection **)htable;
593     rx_peerHashTable = (struct rx_peer **)ptable;
594
595     rx_hardAckDelay.sec = 0;
596     rx_hardAckDelay.usec = 100000;      /* 100 milliseconds */
597
598     rxevent_Init(20, rxi_ReScheduleEvents);
599
600     /* Initialize various global queues */
601     queue_Init(&rx_idleServerQueue);
602     queue_Init(&rx_incomingCallQueue);
603     queue_Init(&rx_freeCallQueue);
604
605 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
606     /* Initialize our list of usable IP addresses. */
607     rx_GetIFInfo();
608 #endif
609
610 #if defined(RXK_LISTENER_ENV) || !defined(KERNEL)
611     /* Start listener process (exact function is dependent on the
612      * implementation environment--kernel or user space) */
613     rxi_StartListener();
614 #endif
615
616     USERPRI;
617     tmp_status = rxinit_status = 0;
618     UNLOCK_RX_INIT;
619     return tmp_status;
620 }
621
622 int
623 rx_Init(u_int port)
624 {
625     return rx_InitHost(htonl(INADDR_ANY), port);
626 }
627
628 /* RTT Timer
629  * ---------
630  *
631  * The rxi_rto functions implement a TCP (RFC2988) style algorithm for
632  * maintaing the round trip timer.
633  *
634  */
635
636 /*!
637  * Start a new RTT timer for a given call and packet.
638  *
639  * There must be no resendEvent already listed for this call, otherwise this
640  * will leak events - intended for internal use within the RTO code only
641  *
642  * @param[in] call
643  *      the RX call to start the timer for
644  * @param[in] lastPacket
645  *      a flag indicating whether the last packet has been sent or not
646  *
647  * @pre call must be locked before calling this function
648  *
649  */
650 static_inline void
651 rxi_rto_startTimer(struct rx_call *call, int lastPacket, int istack)
652 {
653     struct clock now, retryTime;
654
655     clock_GetTime(&now);
656     retryTime = now;
657
658     clock_Add(&retryTime, &call->rto);
659
660     /* If we're sending the last packet, and we're the client, then the server
661      * may wait for an additional 400ms before returning the ACK, wait for it
662      * rather than hitting a timeout */
663     if (lastPacket && call->conn->type == RX_CLIENT_CONNECTION)
664         clock_Addmsec(&retryTime, 400);
665
666     CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
667     call->resendEvent = rxevent_Post(&retryTime, &now, rxi_Resend,
668                                      call, NULL, istack);
669 }
670
671 /*!
672  * Cancel an RTT timer for a given call.
673  *
674  *
675  * @param[in] call
676  *      the RX call to cancel the timer for
677  *
678  * @pre call must be locked before calling this function
679  *
680  */
681
682 static_inline void
683 rxi_rto_cancel(struct rx_call *call)
684 {
685     rxevent_Cancel(&call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
686 }
687
688 /*!
689  * Tell the RTO timer that we have sent a packet.
690  *
691  * If the timer isn't already running, then start it. If the timer is running,
692  * then do nothing.
693  *
694  * @param[in] call
695  *      the RX call that the packet has been sent on
696  * @param[in] lastPacket
697  *      A flag which is true if this is the last packet for the call
698  *
699  * @pre The call must be locked before calling this function
700  *
701  */
702
703 static_inline void
704 rxi_rto_packet_sent(struct rx_call *call, int lastPacket, int istack)
705 {
706     if (call->resendEvent)
707         return;
708
709     rxi_rto_startTimer(call, lastPacket, istack);
710 }
711
712 /*!
713  * Tell the RTO timer that we have received an new ACK message
714  *
715  * This function should be called whenever a call receives an ACK that
716  * acknowledges new packets. Whatever happens, we stop the current timer.
717  * If there are unacked packets in the queue which have been sent, then
718  * we restart the timer from now. Otherwise, we leave it stopped.
719  *
720  * @param[in] call
721  *      the RX call that the ACK has been received on
722  */
723
724 static_inline void
725 rxi_rto_packet_acked(struct rx_call *call, int istack)
726 {
727     struct rx_packet *p, *nxp;
728
729     rxi_rto_cancel(call);
730
731     if (queue_IsEmpty(&call->tq))
732         return;
733
734     for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
735         if (p->header.seq > call->tfirst + call->twind)
736             return;
737
738         if (!(p->flags & RX_PKTFLAG_ACKED) && p->flags & RX_PKTFLAG_SENT) {
739             rxi_rto_startTimer(call, p->header.flags & RX_LAST_PACKET, istack);
740             return;
741         }
742     }
743 }
744
745
746 /**
747  * Set an initial round trip timeout for a peer connection
748  *
749  * @param[in] secs The timeout to set in seconds
750  */
751
752 void
753 rx_rto_setPeerTimeoutSecs(struct rx_peer *peer, int secs) {
754     peer->rtt = secs * 8000;
755 }
756
757 /**
758  * Enables or disables the busy call channel error (RX_CALL_BUSY).
759  *
760  * @param[in] onoff Non-zero to enable busy call channel errors.
761  *
762  * @pre Neither rx_Init nor rx_InitHost have been called yet
763  */
764 void
765 rx_SetBusyChannelError(afs_int32 onoff)
766 {
767     osi_Assert(rxinit_status != 0);
768     rxi_busyChannelError = onoff ? 1 : 0;
769 }
770
771 /**
772  * Set a delayed ack event on the specified call for the given time
773  *
774  * @param[in] call - the call on which to set the event
775  * @param[in] offset - the delay from now after which the event fires
776  */
777 void
778 rxi_PostDelayedAckEvent(struct rx_call *call, struct clock *offset)
779 {
780     struct clock now, when;
781
782     clock_GetTime(&now);
783     when = now;
784     clock_Add(&when, offset);
785
786     if (!call->delayedAckEvent
787         || clock_Gt(&call->delayedAckTime, &when)) {
788
789         rxevent_Cancel(&call->delayedAckEvent, call,
790                        RX_CALL_REFCOUNT_DELAY);
791         CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
792
793         call->delayedAckEvent = rxevent_Post(&when, &now,
794                                              rxi_SendDelayedAck,
795                                              call, NULL, 0);
796         call->delayedAckTime = when;
797     }
798 }
799
800 /* called with unincremented nRequestsRunning to see if it is OK to start
801  * a new thread in this service.  Could be "no" for two reasons: over the
802  * max quota, or would prevent others from reaching their min quota.
803  */
804 #ifdef RX_ENABLE_LOCKS
805 /* This verion of QuotaOK reserves quota if it's ok while the
806  * rx_serverPool_lock is held.  Return quota using ReturnToServerPool().
807  */
808 static int
809 QuotaOK(struct rx_service *aservice)
810 {
811     /* check if over max quota */
812     if (aservice->nRequestsRunning >= aservice->maxProcs) {
813         return 0;
814     }
815
816     /* under min quota, we're OK */
817     /* otherwise, can use only if there are enough to allow everyone
818      * to go to their min quota after this guy starts.
819      */
820
821     MUTEX_ENTER(&rx_quota_mutex);
822     if ((aservice->nRequestsRunning < aservice->minProcs)
823         || (rxi_availProcs > rxi_minDeficit)) {
824         aservice->nRequestsRunning++;
825         /* just started call in minProcs pool, need fewer to maintain
826          * guarantee */
827         if (aservice->nRequestsRunning <= aservice->minProcs)
828             rxi_minDeficit--;
829         rxi_availProcs--;
830         MUTEX_EXIT(&rx_quota_mutex);
831         return 1;
832     }
833     MUTEX_EXIT(&rx_quota_mutex);
834
835     return 0;
836 }
837
838 static void
839 ReturnToServerPool(struct rx_service *aservice)
840 {
841     aservice->nRequestsRunning--;
842     MUTEX_ENTER(&rx_quota_mutex);
843     if (aservice->nRequestsRunning < aservice->minProcs)
844         rxi_minDeficit++;
845     rxi_availProcs++;
846     MUTEX_EXIT(&rx_quota_mutex);
847 }
848
849 #else /* RX_ENABLE_LOCKS */
850 static int
851 QuotaOK(struct rx_service *aservice)
852 {
853     int rc = 0;
854     /* under min quota, we're OK */
855     if (aservice->nRequestsRunning < aservice->minProcs)
856         return 1;
857
858     /* check if over max quota */
859     if (aservice->nRequestsRunning >= aservice->maxProcs)
860         return 0;
861
862     /* otherwise, can use only if there are enough to allow everyone
863      * to go to their min quota after this guy starts.
864      */
865     MUTEX_ENTER(&rx_quota_mutex);
866     if (rxi_availProcs > rxi_minDeficit)
867         rc = 1;
868     MUTEX_EXIT(&rx_quota_mutex);
869     return rc;
870 }
871 #endif /* RX_ENABLE_LOCKS */
872
873 #ifndef KERNEL
874 /* Called by rx_StartServer to start up lwp's to service calls.
875    NExistingProcs gives the number of procs already existing, and which
876    therefore needn't be created. */
877 static void
878 rxi_StartServerProcs(int nExistingProcs)
879 {
880     struct rx_service *service;
881     int i;
882     int maxdiff = 0;
883     int nProcs = 0;
884
885     /* For each service, reserve N processes, where N is the "minimum"
886      * number of processes that MUST be able to execute a request in parallel,
887      * at any time, for that process.  Also compute the maximum difference
888      * between any service's maximum number of processes that can run
889      * (i.e. the maximum number that ever will be run, and a guarantee
890      * that this number will run if other services aren't running), and its
891      * minimum number.  The result is the extra number of processes that
892      * we need in order to provide the latter guarantee */
893     for (i = 0; i < RX_MAX_SERVICES; i++) {
894         int diff;
895         service = rx_services[i];
896         if (service == (struct rx_service *)0)
897             break;
898         nProcs += service->minProcs;
899         diff = service->maxProcs - service->minProcs;
900         if (diff > maxdiff)
901             maxdiff = diff;
902     }
903     nProcs += maxdiff;          /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
904     nProcs -= nExistingProcs;   /* Subtract the number of procs that were previously created for use as server procs */
905     for (i = 0; i < nProcs; i++) {
906         rxi_StartServerProc(rx_ServerProc, rx_stackSize);
907     }
908 }
909 #endif /* KERNEL */
910
911 #ifdef AFS_NT40_ENV
912 /* This routine is only required on Windows */
913 void
914 rx_StartClientThread(void)
915 {
916 #ifdef AFS_PTHREAD_ENV
917     pthread_t pid;
918     pid = pthread_self();
919 #endif /* AFS_PTHREAD_ENV */
920 }
921 #endif /* AFS_NT40_ENV */
922
923 /* This routine must be called if any services are exported.  If the
924  * donateMe flag is set, the calling process is donated to the server
925  * process pool */
926 void
927 rx_StartServer(int donateMe)
928 {
929     struct rx_service *service;
930     int i;
931     SPLVAR;
932     clock_NewTime();
933
934     NETPRI;
935     /* Start server processes, if necessary (exact function is dependent
936      * on the implementation environment--kernel or user space).  DonateMe
937      * will be 1 if there is 1 pre-existing proc, i.e. this one.  In this
938      * case, one less new proc will be created rx_StartServerProcs.
939      */
940     rxi_StartServerProcs(donateMe);
941
942     /* count up the # of threads in minProcs, and add set the min deficit to
943      * be that value, too.
944      */
945     for (i = 0; i < RX_MAX_SERVICES; i++) {
946         service = rx_services[i];
947         if (service == (struct rx_service *)0)
948             break;
949         MUTEX_ENTER(&rx_quota_mutex);
950         rxi_totalMin += service->minProcs;
951         /* below works even if a thread is running, since minDeficit would
952          * still have been decremented and later re-incremented.
953          */
954         rxi_minDeficit += service->minProcs;
955         MUTEX_EXIT(&rx_quota_mutex);
956     }
957
958     /* Turn on reaping of idle server connections */
959     rxi_ReapConnections(NULL, NULL, NULL, 0);
960
961     USERPRI;
962
963     if (donateMe) {
964 #ifndef AFS_NT40_ENV
965 #ifndef KERNEL
966         char name[32];
967         static int nProcs;
968 #ifdef AFS_PTHREAD_ENV
969         pid_t pid;
970         pid = afs_pointer_to_int(pthread_self());
971 #else /* AFS_PTHREAD_ENV */
972         PROCESS pid;
973         LWP_CurrentProcess(&pid);
974 #endif /* AFS_PTHREAD_ENV */
975
976         sprintf(name, "srv_%d", ++nProcs);
977         if (registerProgram)
978             (*registerProgram) (pid, name);
979 #endif /* KERNEL */
980 #endif /* AFS_NT40_ENV */
981         rx_ServerProc(NULL);    /* Never returns */
982     }
983 #ifdef RX_ENABLE_TSFPQ
984     /* no use leaving packets around in this thread's local queue if
985      * it isn't getting donated to the server thread pool.
986      */
987     rxi_FlushLocalPacketsTSFPQ();
988 #endif /* RX_ENABLE_TSFPQ */
989     return;
990 }
991
992 /* Create a new client connection to the specified service, using the
993  * specified security object to implement the security model for this
994  * connection. */
995 struct rx_connection *
996 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
997                  struct rx_securityClass *securityObject,
998                  int serviceSecurityIndex)
999 {
1000     int hashindex, i;
1001     afs_int32 cid;
1002     struct rx_connection *conn;
1003
1004     SPLVAR;
1005
1006     clock_NewTime();
1007     dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
1008          "serviceSecurityIndex %d)\n",
1009          ntohl(shost), ntohs(sport), sservice, securityObject,
1010          serviceSecurityIndex));
1011
1012     /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
1013      * the case of kmem_alloc? */
1014     conn = rxi_AllocConnection();
1015 #ifdef  RX_ENABLE_LOCKS
1016     MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
1017     MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
1018     CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
1019 #endif
1020     NETPRI;
1021     MUTEX_ENTER(&rx_connHashTable_lock);
1022     cid = (rx_nextCid += RX_MAXCALLS);
1023     conn->type = RX_CLIENT_CONNECTION;
1024     conn->cid = cid;
1025     conn->epoch = rx_epoch;
1026     conn->peer = rxi_FindPeer(shost, sport, 0, 1);
1027     conn->serviceId = sservice;
1028     conn->securityObject = securityObject;
1029     conn->securityData = (void *) 0;
1030     conn->securityIndex = serviceSecurityIndex;
1031     rx_SetConnDeadTime(conn, rx_connDeadTime);
1032     rx_SetConnSecondsUntilNatPing(conn, 0);
1033     conn->ackRate = RX_FAST_ACK_RATE;
1034     conn->nSpecific = 0;
1035     conn->specific = NULL;
1036     conn->challengeEvent = NULL;
1037     conn->delayedAbortEvent = NULL;
1038     conn->abortCount = 0;
1039     conn->error = 0;
1040     for (i = 0; i < RX_MAXCALLS; i++) {
1041         conn->twind[i] = rx_initSendWindow;
1042         conn->rwind[i] = rx_initReceiveWindow;
1043         conn->lastBusy[i] = 0;
1044     }
1045
1046     RXS_NewConnection(securityObject, conn);
1047     hashindex =
1048         CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
1049
1050     conn->refCount++;           /* no lock required since only this thread knows... */
1051     conn->next = rx_connHashTable[hashindex];
1052     rx_connHashTable[hashindex] = conn;
1053     if (rx_stats_active)
1054         rx_atomic_inc(&rx_stats.nClientConns);
1055     MUTEX_EXIT(&rx_connHashTable_lock);
1056     USERPRI;
1057     return conn;
1058 }
1059
1060 /**
1061  * Ensure a connection's timeout values are valid.
1062  *
1063  * @param[in] conn The connection to check
1064  *
1065  * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
1066  *       unless idleDeadTime and/or hardDeadTime are not set
1067  * @internal
1068  */
1069 static void
1070 rxi_CheckConnTimeouts(struct rx_connection *conn)
1071 {
1072     /* a connection's timeouts must have the relationship
1073      * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
1074      * total loss of network to a peer may cause an idle timeout instead of a
1075      * dead timeout, simply because the idle timeout gets hit first. Also set
1076      * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
1077     /* this logic is slightly complicated by the fact that
1078      * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
1079      */
1080     conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
1081     if (conn->idleDeadTime) {
1082         conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
1083     }
1084     if (conn->hardDeadTime) {
1085         if (conn->idleDeadTime) {
1086             conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
1087         } else {
1088             conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
1089         }
1090     }
1091 }
1092
1093 void
1094 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
1095 {
1096     /* The idea is to set the dead time to a value that allows several
1097      * keepalives to be dropped without timing out the connection. */
1098     conn->secondsUntilDead = seconds;
1099     rxi_CheckConnTimeouts(conn);
1100     conn->secondsUntilPing = conn->secondsUntilDead / 6;
1101 }
1102
1103 void
1104 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
1105 {
1106     conn->hardDeadTime = seconds;
1107     rxi_CheckConnTimeouts(conn);
1108 }
1109
1110 void
1111 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
1112 {
1113     conn->idleDeadTime = seconds;
1114     conn->idleDeadDetection = (seconds ? 1 : 0);
1115     rxi_CheckConnTimeouts(conn);
1116 }
1117
1118 int rxi_lowPeerRefCount = 0;
1119 int rxi_lowConnRefCount = 0;
1120
1121 /*
1122  * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
1123  * NOTE: must not be called with rx_connHashTable_lock held.
1124  */
1125 static void
1126 rxi_CleanupConnection(struct rx_connection *conn)
1127 {
1128     /* Notify the service exporter, if requested, that this connection
1129      * is being destroyed */
1130     if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
1131         (*conn->service->destroyConnProc) (conn);
1132
1133     /* Notify the security module that this connection is being destroyed */
1134     RXS_DestroyConnection(conn->securityObject, conn);
1135
1136     /* If this is the last connection using the rx_peer struct, set its
1137      * idle time to now. rxi_ReapConnections will reap it if it's still
1138      * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
1139      */
1140     MUTEX_ENTER(&rx_peerHashTable_lock);
1141     if (conn->peer->refCount < 2) {
1142         conn->peer->idleWhen = clock_Sec();
1143         if (conn->peer->refCount < 1) {
1144             conn->peer->refCount = 1;
1145             if (rx_stats_active) {
1146                 MUTEX_ENTER(&rx_stats_mutex);
1147                 rxi_lowPeerRefCount++;
1148                 MUTEX_EXIT(&rx_stats_mutex);
1149             }
1150         }
1151     }
1152     conn->peer->refCount--;
1153     MUTEX_EXIT(&rx_peerHashTable_lock);
1154
1155     if (rx_stats_active)
1156     {
1157         if (conn->type == RX_SERVER_CONNECTION)
1158             rx_atomic_dec(&rx_stats.nServerConns);
1159         else
1160             rx_atomic_dec(&rx_stats.nClientConns);
1161     }
1162 #ifndef KERNEL
1163     if (conn->specific) {
1164         int i;
1165         for (i = 0; i < conn->nSpecific; i++) {
1166             if (conn->specific[i] && rxi_keyCreate_destructor[i])
1167                 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
1168             conn->specific[i] = NULL;
1169         }
1170         free(conn->specific);
1171     }
1172     conn->specific = NULL;
1173     conn->nSpecific = 0;
1174 #endif /* !KERNEL */
1175
1176     MUTEX_DESTROY(&conn->conn_call_lock);
1177     MUTEX_DESTROY(&conn->conn_data_lock);
1178     CV_DESTROY(&conn->conn_call_cv);
1179
1180     rxi_FreeConnection(conn);
1181 }
1182
1183 /* Destroy the specified connection */
1184 void
1185 rxi_DestroyConnection(struct rx_connection *conn)
1186 {
1187     MUTEX_ENTER(&rx_connHashTable_lock);
1188     rxi_DestroyConnectionNoLock(conn);
1189     /* conn should be at the head of the cleanup list */
1190     if (conn == rx_connCleanup_list) {
1191         rx_connCleanup_list = rx_connCleanup_list->next;
1192         MUTEX_EXIT(&rx_connHashTable_lock);
1193         rxi_CleanupConnection(conn);
1194     }
1195 #ifdef RX_ENABLE_LOCKS
1196     else {
1197         MUTEX_EXIT(&rx_connHashTable_lock);
1198     }
1199 #endif /* RX_ENABLE_LOCKS */
1200 }
1201
1202 static void
1203 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1204 {
1205     struct rx_connection **conn_ptr;
1206     int havecalls = 0;
1207     struct rx_packet *packet;
1208     int i;
1209     SPLVAR;
1210
1211     clock_NewTime();
1212
1213     NETPRI;
1214     MUTEX_ENTER(&conn->conn_data_lock);
1215     MUTEX_ENTER(&rx_refcnt_mutex);
1216     if (conn->refCount > 0)
1217         conn->refCount--;
1218     else {
1219         if (rx_stats_active) {
1220             MUTEX_ENTER(&rx_stats_mutex);
1221             rxi_lowConnRefCount++;
1222             MUTEX_EXIT(&rx_stats_mutex);
1223         }
1224     }
1225
1226     if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1227         /* Busy; wait till the last guy before proceeding */
1228         MUTEX_EXIT(&rx_refcnt_mutex);
1229         MUTEX_EXIT(&conn->conn_data_lock);
1230         USERPRI;
1231         return;
1232     }
1233
1234     /* If the client previously called rx_NewCall, but it is still
1235      * waiting, treat this as a running call, and wait to destroy the
1236      * connection later when the call completes. */
1237     if ((conn->type == RX_CLIENT_CONNECTION)
1238         && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1239         conn->flags |= RX_CONN_DESTROY_ME;
1240         MUTEX_EXIT(&conn->conn_data_lock);
1241         USERPRI;
1242         return;
1243     }
1244     MUTEX_EXIT(&rx_refcnt_mutex);
1245     MUTEX_EXIT(&conn->conn_data_lock);
1246
1247     /* Check for extant references to this connection */
1248     MUTEX_ENTER(&conn->conn_call_lock);
1249     for (i = 0; i < RX_MAXCALLS; i++) {
1250         struct rx_call *call = conn->call[i];
1251         if (call) {
1252             havecalls = 1;
1253             if (conn->type == RX_CLIENT_CONNECTION) {
1254                 MUTEX_ENTER(&call->lock);
1255                 if (call->delayedAckEvent) {
1256                     /* Push the final acknowledgment out now--there
1257                      * won't be a subsequent call to acknowledge the
1258                      * last reply packets */
1259                     rxevent_Cancel(&call->delayedAckEvent, call,
1260                                    RX_CALL_REFCOUNT_DELAY);
1261                     if (call->state == RX_STATE_PRECALL
1262                         || call->state == RX_STATE_ACTIVE) {
1263                         rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1264                     } else {
1265                         rxi_AckAll(NULL, call, 0);
1266                     }
1267                 }
1268                 MUTEX_EXIT(&call->lock);
1269             }
1270         }
1271     }
1272     MUTEX_EXIT(&conn->conn_call_lock);
1273
1274 #ifdef RX_ENABLE_LOCKS
1275     if (!havecalls) {
1276         if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1277             MUTEX_EXIT(&conn->conn_data_lock);
1278         } else {
1279             /* Someone is accessing a packet right now. */
1280             havecalls = 1;
1281         }
1282     }
1283 #endif /* RX_ENABLE_LOCKS */
1284
1285     if (havecalls) {
1286         /* Don't destroy the connection if there are any call
1287          * structures still in use */
1288         MUTEX_ENTER(&conn->conn_data_lock);
1289         conn->flags |= RX_CONN_DESTROY_ME;
1290         MUTEX_EXIT(&conn->conn_data_lock);
1291         USERPRI;
1292         return;
1293     }
1294
1295     if (conn->natKeepAliveEvent) {
1296         rxi_NatKeepAliveOff(conn);
1297     }
1298
1299     if (conn->delayedAbortEvent) {
1300         rxevent_Cancel(&conn->delayedAbortEvent, NULL, 0);
1301         packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1302         if (packet) {
1303             MUTEX_ENTER(&conn->conn_data_lock);
1304             rxi_SendConnectionAbort(conn, packet, 0, 1);
1305             MUTEX_EXIT(&conn->conn_data_lock);
1306             rxi_FreePacket(packet);
1307         }
1308     }
1309
1310     /* Remove from connection hash table before proceeding */
1311     conn_ptr =
1312         &rx_connHashTable[CONN_HASH
1313                           (peer->host, peer->port, conn->cid, conn->epoch,
1314                            conn->type)];
1315     for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1316         if (*conn_ptr == conn) {
1317             *conn_ptr = conn->next;
1318             break;
1319         }
1320     }
1321     /* if the conn that we are destroying was the last connection, then we
1322      * clear rxLastConn as well */
1323     if (rxLastConn == conn)
1324         rxLastConn = 0;
1325
1326     /* Make sure the connection is completely reset before deleting it. */
1327     /* get rid of pending events that could zap us later */
1328     rxevent_Cancel(&conn->challengeEvent, NULL, 0);
1329     rxevent_Cancel(&conn->checkReachEvent, NULL, 0);
1330     rxevent_Cancel(&conn->natKeepAliveEvent, NULL, 0);
1331
1332     /* Add the connection to the list of destroyed connections that
1333      * need to be cleaned up. This is necessary to avoid deadlocks
1334      * in the routines we call to inform others that this connection is
1335      * being destroyed. */
1336     conn->next = rx_connCleanup_list;
1337     rx_connCleanup_list = conn;
1338 }
1339
1340 /* Externally available version */
1341 void
1342 rx_DestroyConnection(struct rx_connection *conn)
1343 {
1344     SPLVAR;
1345
1346     NETPRI;
1347     rxi_DestroyConnection(conn);
1348     USERPRI;
1349 }
1350
1351 void
1352 rx_GetConnection(struct rx_connection *conn)
1353 {
1354     SPLVAR;
1355
1356     NETPRI;
1357     MUTEX_ENTER(&rx_refcnt_mutex);
1358     conn->refCount++;
1359     MUTEX_EXIT(&rx_refcnt_mutex);
1360     USERPRI;
1361 }
1362
1363 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
1364 /* Wait for the transmit queue to no longer be busy.
1365  * requires the call->lock to be held */
1366 void
1367 rxi_WaitforTQBusy(struct rx_call *call) {
1368     while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1369         call->flags |= RX_CALL_TQ_WAIT;
1370         call->tqWaiters++;
1371 #ifdef RX_ENABLE_LOCKS
1372         osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1373         CV_WAIT(&call->cv_tq, &call->lock);
1374 #else /* RX_ENABLE_LOCKS */
1375         osi_rxSleep(&call->tq);
1376 #endif /* RX_ENABLE_LOCKS */
1377         call->tqWaiters--;
1378         if (call->tqWaiters == 0) {
1379             call->flags &= ~RX_CALL_TQ_WAIT;
1380         }
1381     }
1382 }
1383 #endif
1384
1385 static void
1386 rxi_WakeUpTransmitQueue(struct rx_call *call)
1387 {
1388     if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1389         dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
1390              call, call->tqWaiters, call->flags));
1391 #ifdef RX_ENABLE_LOCKS
1392         osirx_AssertMine(&call->lock, "rxi_Start start");
1393         CV_BROADCAST(&call->cv_tq);
1394 #else /* RX_ENABLE_LOCKS */
1395         osi_rxWakeup(&call->tq);
1396 #endif /* RX_ENABLE_LOCKS */
1397     }
1398 }
1399
1400 /* Start a new rx remote procedure call, on the specified connection.
1401  * If wait is set to 1, wait for a free call channel; otherwise return
1402  * 0.  Maxtime gives the maximum number of seconds this call may take,
1403  * after rx_NewCall returns.  After this time interval, a call to any
1404  * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1405  * For fine grain locking, we hold the conn_call_lock in order to
1406  * to ensure that we don't get signalle after we found a call in an active
1407  * state and before we go to sleep.
1408  */
1409 struct rx_call *
1410 rx_NewCall(struct rx_connection *conn)
1411 {
1412     int i, wait, ignoreBusy = 1;
1413     struct rx_call *call;
1414     struct clock queueTime;
1415     afs_uint32 leastBusy = 0;
1416     SPLVAR;
1417
1418     clock_NewTime();
1419     dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1420
1421     NETPRI;
1422     clock_GetTime(&queueTime);
1423     /*
1424      * Check if there are others waiting for a new call.
1425      * If so, let them go first to avoid starving them.
1426      * This is a fairly simple scheme, and might not be
1427      * a complete solution for large numbers of waiters.
1428      *
1429      * makeCallWaiters keeps track of the number of
1430      * threads waiting to make calls and the
1431      * RX_CONN_MAKECALL_WAITING flag bit is used to
1432      * indicate that there are indeed calls waiting.
1433      * The flag is set when the waiter is incremented.
1434      * It is only cleared when makeCallWaiters is 0.
1435      * This prevents us from accidently destroying the
1436      * connection while it is potentially about to be used.
1437      */
1438     MUTEX_ENTER(&conn->conn_call_lock);
1439     MUTEX_ENTER(&conn->conn_data_lock);
1440     while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1441         conn->flags |= RX_CONN_MAKECALL_WAITING;
1442         conn->makeCallWaiters++;
1443         MUTEX_EXIT(&conn->conn_data_lock);
1444
1445 #ifdef  RX_ENABLE_LOCKS
1446         CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1447 #else
1448         osi_rxSleep(conn);
1449 #endif
1450         MUTEX_ENTER(&conn->conn_data_lock);
1451         conn->makeCallWaiters--;
1452         if (conn->makeCallWaiters == 0)
1453             conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1454     }
1455
1456     /* We are now the active thread in rx_NewCall */
1457     conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1458     MUTEX_EXIT(&conn->conn_data_lock);
1459
1460     for (;;) {
1461         wait = 1;
1462
1463         for (i = 0; i < RX_MAXCALLS; i++) {
1464             call = conn->call[i];
1465             if (call) {
1466                 if (!ignoreBusy && conn->lastBusy[i] != leastBusy) {
1467                     /* we're not ignoring busy call slots; only look at the
1468                      * call slot that is the "least" busy */
1469                     continue;
1470                 }
1471
1472                 if (call->state == RX_STATE_DALLY) {
1473                     MUTEX_ENTER(&call->lock);
1474                     if (call->state == RX_STATE_DALLY) {
1475                         if (ignoreBusy && conn->lastBusy[i]) {
1476                             /* if we're ignoring busy call slots, skip any ones that
1477                              * have lastBusy set */
1478                             if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1479                                 leastBusy = conn->lastBusy[i];
1480                             }
1481                             MUTEX_EXIT(&call->lock);
1482                             continue;
1483                         }
1484
1485                         /*
1486                          * We are setting the state to RX_STATE_RESET to
1487                          * ensure that no one else will attempt to use this
1488                          * call once we drop the conn->conn_call_lock and
1489                          * call->lock.  We must drop the conn->conn_call_lock
1490                          * before calling rxi_ResetCall because the process
1491                          * of clearing the transmit queue can block for an
1492                          * extended period of time.  If we block while holding
1493                          * the conn->conn_call_lock, then all rx_EndCall
1494                          * processing will block as well.  This has a detrimental
1495                          * effect on overall system performance.
1496                          */
1497                         call->state = RX_STATE_RESET;
1498                         CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1499                         (*call->callNumber)++;
1500                         MUTEX_EXIT(&conn->conn_call_lock);
1501                         CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1502                         rxi_ResetCall(call, 0);
1503                         if (MUTEX_TRYENTER(&conn->conn_call_lock))
1504                             break;
1505
1506                         /*
1507                          * If we failed to be able to safely obtain the
1508                          * conn->conn_call_lock we will have to drop the
1509                          * call->lock to avoid a deadlock.  When the call->lock
1510                          * is released the state of the call can change.  If it
1511                          * is no longer RX_STATE_RESET then some other thread is
1512                          * using the call.
1513                          */
1514                         MUTEX_EXIT(&call->lock);
1515                         MUTEX_ENTER(&conn->conn_call_lock);
1516                         MUTEX_ENTER(&call->lock);
1517
1518                         if (call->state == RX_STATE_RESET)
1519                             break;
1520
1521                         /*
1522                          * If we get here it means that after dropping
1523                          * the conn->conn_call_lock and call->lock that
1524                          * the call is no longer ours.  If we can't find
1525                          * a free call in the remaining slots we should
1526                          * not go immediately to RX_CONN_MAKECALL_WAITING
1527                          * because by dropping the conn->conn_call_lock
1528                          * we have given up synchronization with rx_EndCall.
1529                          * Instead, cycle through one more time to see if
1530                          * we can find a call that can call our own.
1531                          */
1532                         CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1533                         wait = 0;
1534                     }
1535                     MUTEX_EXIT(&call->lock);
1536                 }
1537             } else {
1538                 if (ignoreBusy && conn->lastBusy[i]) {
1539                     /* if we're ignoring busy call slots, skip any ones that
1540                      * have lastBusy set */
1541                     if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1542                         leastBusy = conn->lastBusy[i];
1543                     }
1544                     continue;
1545                 }
1546
1547                 /* rxi_NewCall returns with mutex locked */
1548                 call = rxi_NewCall(conn, i);
1549                 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1550                 break;
1551             }
1552         }
1553         if (i < RX_MAXCALLS) {
1554             conn->lastBusy[i] = 0;
1555             call->flags &= ~RX_CALL_PEER_BUSY;
1556             break;
1557         }
1558         if (!wait)
1559             continue;
1560         if (leastBusy && ignoreBusy) {
1561             /* we didn't find a useable call slot, but we did see at least one
1562              * 'busy' slot; look again and only use a slot with the 'least
1563              * busy time */
1564             ignoreBusy = 0;
1565             continue;
1566         }
1567
1568         MUTEX_ENTER(&conn->conn_data_lock);
1569         conn->flags |= RX_CONN_MAKECALL_WAITING;
1570         conn->makeCallWaiters++;
1571         MUTEX_EXIT(&conn->conn_data_lock);
1572
1573 #ifdef  RX_ENABLE_LOCKS
1574         CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1575 #else
1576         osi_rxSleep(conn);
1577 #endif
1578         MUTEX_ENTER(&conn->conn_data_lock);
1579         conn->makeCallWaiters--;
1580         if (conn->makeCallWaiters == 0)
1581             conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1582         MUTEX_EXIT(&conn->conn_data_lock);
1583     }
1584     /* Client is initially in send mode */
1585     call->state = RX_STATE_ACTIVE;
1586     call->error = conn->error;
1587     if (call->error)
1588         call->mode = RX_MODE_ERROR;
1589     else
1590         call->mode = RX_MODE_SENDING;
1591
1592     /* remember start time for call in case we have hard dead time limit */
1593     call->queueTime = queueTime;
1594     clock_GetTime(&call->startTime);
1595     hzero(call->bytesSent);
1596     hzero(call->bytesRcvd);
1597
1598     /* Turn on busy protocol. */
1599     rxi_KeepAliveOn(call);
1600
1601     /* Attempt MTU discovery */
1602     rxi_GrowMTUOn(call);
1603
1604     /*
1605      * We are no longer the active thread in rx_NewCall
1606      */
1607     MUTEX_ENTER(&conn->conn_data_lock);
1608     conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1609     MUTEX_EXIT(&conn->conn_data_lock);
1610
1611     /*
1612      * Wake up anyone else who might be giving us a chance to
1613      * run (see code above that avoids resource starvation).
1614      */
1615 #ifdef  RX_ENABLE_LOCKS
1616     CV_BROADCAST(&conn->conn_call_cv);
1617 #else
1618     osi_rxWakeup(conn);
1619 #endif
1620     MUTEX_EXIT(&conn->conn_call_lock);
1621
1622 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
1623     if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1624         osi_Panic("rx_NewCall call about to be used without an empty tq");
1625     }
1626 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1627
1628     MUTEX_EXIT(&call->lock);
1629     USERPRI;
1630
1631     dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1632     return call;
1633 }
1634
1635 static int
1636 rxi_HasActiveCalls(struct rx_connection *aconn)
1637 {
1638     int i;
1639     struct rx_call *tcall;
1640     SPLVAR;
1641
1642     NETPRI;
1643     for (i = 0; i < RX_MAXCALLS; i++) {
1644         if ((tcall = aconn->call[i])) {
1645             if ((tcall->state == RX_STATE_ACTIVE)
1646                 || (tcall->state == RX_STATE_PRECALL)) {
1647                 USERPRI;
1648                 return 1;
1649             }
1650         }
1651     }
1652     USERPRI;
1653     return 0;
1654 }
1655
1656 int
1657 rxi_GetCallNumberVector(struct rx_connection *aconn,
1658                         afs_int32 * aint32s)
1659 {
1660     int i;
1661     struct rx_call *tcall;
1662     SPLVAR;
1663
1664     NETPRI;
1665     MUTEX_ENTER(&aconn->conn_call_lock);
1666     for (i = 0; i < RX_MAXCALLS; i++) {
1667         if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1668             aint32s[i] = aconn->callNumber[i] + 1;
1669         else
1670             aint32s[i] = aconn->callNumber[i];
1671     }
1672     MUTEX_EXIT(&aconn->conn_call_lock);
1673     USERPRI;
1674     return 0;
1675 }
1676
1677 int
1678 rxi_SetCallNumberVector(struct rx_connection *aconn,
1679                         afs_int32 * aint32s)
1680 {
1681     int i;
1682     struct rx_call *tcall;
1683     SPLVAR;
1684
1685     NETPRI;
1686     MUTEX_ENTER(&aconn->conn_call_lock);
1687     for (i = 0; i < RX_MAXCALLS; i++) {
1688         if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1689             aconn->callNumber[i] = aint32s[i] - 1;
1690         else
1691             aconn->callNumber[i] = aint32s[i];
1692     }
1693     MUTEX_EXIT(&aconn->conn_call_lock);
1694     USERPRI;
1695     return 0;
1696 }
1697
1698 /* Advertise a new service.  A service is named locally by a UDP port
1699  * number plus a 16-bit service id.  Returns (struct rx_service *) 0
1700  * on a failure.
1701  *
1702      char *serviceName;  Name for identification purposes (e.g. the
1703                          service name might be used for probing for
1704                          statistics) */
1705 struct rx_service *
1706 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1707                   char *serviceName, struct rx_securityClass **securityObjects,
1708                   int nSecurityObjects,
1709                   afs_int32(*serviceProc) (struct rx_call * acall))
1710 {
1711     osi_socket socket = OSI_NULLSOCKET;
1712     struct rx_service *tservice;
1713     int i;
1714     SPLVAR;
1715
1716     clock_NewTime();
1717
1718     if (serviceId == 0) {
1719         (osi_Msg
1720          "rx_NewService:  service id for service %s is not non-zero.\n",
1721          serviceName);
1722         return 0;
1723     }
1724     if (port == 0) {
1725         if (rx_port == 0) {
1726             (osi_Msg
1727              "rx_NewService: A non-zero port must be specified on this call if a non-zero port was not provided at Rx initialization (service %s).\n",
1728              serviceName);
1729             return 0;
1730         }
1731         port = rx_port;
1732         socket = rx_socket;
1733     }
1734
1735     tservice = rxi_AllocService();
1736     NETPRI;
1737
1738 #ifdef  RX_ENABLE_LOCKS
1739     MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1740 #endif
1741
1742     for (i = 0; i < RX_MAX_SERVICES; i++) {
1743         struct rx_service *service = rx_services[i];
1744         if (service) {
1745             if (port == service->servicePort && host == service->serviceHost) {
1746                 if (service->serviceId == serviceId) {
1747                     /* The identical service has already been
1748                      * installed; if the caller was intending to
1749                      * change the security classes used by this
1750                      * service, he/she loses. */
1751                     (osi_Msg
1752                      "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1753                      serviceName, serviceId, service->serviceName);
1754                     USERPRI;
1755                     rxi_FreeService(tservice);
1756                     return service;
1757                 }
1758                 /* Different service, same port: re-use the socket
1759                  * which is bound to the same port */
1760                 socket = service->socket;
1761             }
1762         } else {
1763             if (socket == OSI_NULLSOCKET) {
1764                 /* If we don't already have a socket (from another
1765                  * service on same port) get a new one */
1766                 socket = rxi_GetHostUDPSocket(host, port);
1767                 if (socket == OSI_NULLSOCKET) {
1768                     USERPRI;
1769                     rxi_FreeService(tservice);
1770                     return 0;
1771                 }
1772             }
1773             service = tservice;
1774             service->socket = socket;
1775             service->serviceHost = host;
1776             service->servicePort = port;
1777             service->serviceId = serviceId;
1778             service->serviceName = serviceName;
1779             service->nSecurityObjects = nSecurityObjects;
1780             service->securityObjects = securityObjects;
1781             service->minProcs = 0;
1782             service->maxProcs = 1;
1783             service->idleDeadTime = 60;
1784             service->idleDeadErr = 0;
1785             service->connDeadTime = rx_connDeadTime;
1786             service->executeRequestProc = serviceProc;
1787             service->checkReach = 0;
1788             service->nSpecific = 0;
1789             service->specific = NULL;
1790             rx_services[i] = service;   /* not visible until now */
1791             USERPRI;
1792             return service;
1793         }
1794     }
1795     USERPRI;
1796     rxi_FreeService(tservice);
1797     (osi_Msg "rx_NewService: cannot support > %d services\n",
1798      RX_MAX_SERVICES);
1799     return 0;
1800 }
1801
1802 /* Set configuration options for all of a service's security objects */
1803
1804 afs_int32
1805 rx_SetSecurityConfiguration(struct rx_service *service,
1806                             rx_securityConfigVariables type,
1807                             void *value)
1808 {
1809     int i;
1810     for (i = 0; i<service->nSecurityObjects; i++) {
1811         if (service->securityObjects[i]) {
1812             RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1813                                  value, NULL);
1814         }
1815     }
1816     return 0;
1817 }
1818
1819 struct rx_service *
1820 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1821               struct rx_securityClass **securityObjects, int nSecurityObjects,
1822               afs_int32(*serviceProc) (struct rx_call * acall))
1823 {
1824     return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1825 }
1826
1827 /* Generic request processing loop. This routine should be called
1828  * by the implementation dependent rx_ServerProc. If socketp is
1829  * non-null, it will be set to the file descriptor that this thread
1830  * is now listening on. If socketp is null, this routine will never
1831  * returns. */
1832 void
1833 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1834 {
1835     struct rx_call *call;
1836     afs_int32 code;
1837     struct rx_service *tservice = NULL;
1838
1839     for (;;) {
1840         if (newcall) {
1841             call = newcall;
1842             newcall = NULL;
1843         } else {
1844             call = rx_GetCall(threadID, tservice, socketp);
1845             if (socketp && *socketp != OSI_NULLSOCKET) {
1846                 /* We are now a listener thread */
1847                 return;
1848             }
1849         }
1850
1851 #ifdef  KERNEL
1852         if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1853 #ifdef RX_ENABLE_LOCKS
1854             AFS_GLOCK();
1855 #endif /* RX_ENABLE_LOCKS */
1856             afs_termState = AFSOP_STOP_AFS;
1857             afs_osi_Wakeup(&afs_termState);
1858 #ifdef RX_ENABLE_LOCKS
1859             AFS_GUNLOCK();
1860 #endif /* RX_ENABLE_LOCKS */
1861             return;
1862         }
1863 #endif
1864
1865         /* if server is restarting( typically smooth shutdown) then do not
1866          * allow any new calls.
1867          */
1868
1869         if (rx_tranquil && (call != NULL)) {
1870             SPLVAR;
1871
1872             NETPRI;
1873             MUTEX_ENTER(&call->lock);
1874
1875             rxi_CallError(call, RX_RESTARTING);
1876             rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1877
1878             MUTEX_EXIT(&call->lock);
1879             USERPRI;
1880             continue;
1881         }
1882
1883         tservice = call->conn->service;
1884
1885         if (tservice->beforeProc)
1886             (*tservice->beforeProc) (call);
1887
1888         code = tservice->executeRequestProc(call);
1889
1890         if (tservice->afterProc)
1891             (*tservice->afterProc) (call, code);
1892
1893         rx_EndCall(call, code);
1894
1895         if (tservice->postProc)
1896             (*tservice->postProc) (code);
1897
1898         if (rx_stats_active) {
1899             MUTEX_ENTER(&rx_stats_mutex);
1900             rxi_nCalls++;
1901             MUTEX_EXIT(&rx_stats_mutex);
1902         }
1903     }
1904 }
1905
1906
1907 void
1908 rx_WakeupServerProcs(void)
1909 {
1910     struct rx_serverQueueEntry *np, *tqp;
1911     SPLVAR;
1912
1913     NETPRI;
1914     MUTEX_ENTER(&rx_serverPool_lock);
1915
1916 #ifdef RX_ENABLE_LOCKS
1917     if (rx_waitForPacket)
1918         CV_BROADCAST(&rx_waitForPacket->cv);
1919 #else /* RX_ENABLE_LOCKS */
1920     if (rx_waitForPacket)
1921         osi_rxWakeup(rx_waitForPacket);
1922 #endif /* RX_ENABLE_LOCKS */
1923     MUTEX_ENTER(&freeSQEList_lock);
1924     for (np = rx_FreeSQEList; np; np = tqp) {
1925         tqp = *(struct rx_serverQueueEntry **)np;
1926 #ifdef RX_ENABLE_LOCKS
1927         CV_BROADCAST(&np->cv);
1928 #else /* RX_ENABLE_LOCKS */
1929         osi_rxWakeup(np);
1930 #endif /* RX_ENABLE_LOCKS */
1931     }
1932     MUTEX_EXIT(&freeSQEList_lock);
1933     for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1934 #ifdef RX_ENABLE_LOCKS
1935         CV_BROADCAST(&np->cv);
1936 #else /* RX_ENABLE_LOCKS */
1937         osi_rxWakeup(np);
1938 #endif /* RX_ENABLE_LOCKS */
1939     }
1940     MUTEX_EXIT(&rx_serverPool_lock);
1941     USERPRI;
1942 }
1943
1944 /* meltdown:
1945  * One thing that seems to happen is that all the server threads get
1946  * tied up on some empty or slow call, and then a whole bunch of calls
1947  * arrive at once, using up the packet pool, so now there are more
1948  * empty calls.  The most critical resources here are server threads
1949  * and the free packet pool.  The "doreclaim" code seems to help in
1950  * general.  I think that eventually we arrive in this state: there
1951  * are lots of pending calls which do have all their packets present,
1952  * so they won't be reclaimed, are multi-packet calls, so they won't
1953  * be scheduled until later, and thus are tying up most of the free
1954  * packet pool for a very long time.
1955  * future options:
1956  * 1.  schedule multi-packet calls if all the packets are present.
1957  * Probably CPU-bound operation, useful to return packets to pool.
1958  * Do what if there is a full window, but the last packet isn't here?
1959  * 3.  preserve one thread which *only* runs "best" calls, otherwise
1960  * it sleeps and waits for that type of call.
1961  * 4.  Don't necessarily reserve a whole window for each thread.  In fact,
1962  * the current dataquota business is badly broken.  The quota isn't adjusted
1963  * to reflect how many packets are presently queued for a running call.
1964  * So, when we schedule a queued call with a full window of packets queued
1965  * up for it, that *should* free up a window full of packets for other 2d-class
1966  * calls to be able to use from the packet pool.  But it doesn't.
1967  *
1968  * NB.  Most of the time, this code doesn't run -- since idle server threads
1969  * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1970  * as a new call arrives.
1971  */
1972 /* Sleep until a call arrives.  Returns a pointer to the call, ready
1973  * for an rx_Read. */
1974 #ifdef RX_ENABLE_LOCKS
1975 struct rx_call *
1976 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1977 {
1978     struct rx_serverQueueEntry *sq;
1979     struct rx_call *call = (struct rx_call *)0;
1980     struct rx_service *service = NULL;
1981
1982     MUTEX_ENTER(&freeSQEList_lock);
1983
1984     if ((sq = rx_FreeSQEList)) {
1985         rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1986         MUTEX_EXIT(&freeSQEList_lock);
1987     } else {                    /* otherwise allocate a new one and return that */
1988         MUTEX_EXIT(&freeSQEList_lock);
1989         sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1990         MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1991         CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1992     }
1993
1994     MUTEX_ENTER(&rx_serverPool_lock);
1995     if (cur_service != NULL) {
1996         ReturnToServerPool(cur_service);
1997     }
1998     while (1) {
1999         if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
2000             struct rx_call *tcall, *ncall, *choice2 = NULL;
2001
2002             /* Scan for eligible incoming calls.  A call is not eligible
2003              * if the maximum number of calls for its service type are
2004              * already executing */
2005             /* One thread will process calls FCFS (to prevent starvation),
2006              * while the other threads may run ahead looking for calls which
2007              * have all their input data available immediately.  This helps
2008              * keep threads from blocking, waiting for data from the client. */
2009             for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
2010                 service = tcall->conn->service;
2011                 if (!QuotaOK(service)) {
2012                     continue;
2013                 }
2014                 MUTEX_ENTER(&rx_pthread_mutex);
2015                 if (tno == rxi_fcfs_thread_num
2016                         || queue_IsLast(&rx_incomingCallQueue, tcall)) {
2017                     MUTEX_EXIT(&rx_pthread_mutex);
2018                     /* If we're the fcfs thread , then  we'll just use
2019                      * this call. If we haven't been able to find an optimal
2020                      * choice, and we're at the end of the list, then use a
2021                      * 2d choice if one has been identified.  Otherwise... */
2022                     call = (choice2 ? choice2 : tcall);
2023                     service = call->conn->service;
2024                 } else {
2025                     MUTEX_EXIT(&rx_pthread_mutex);
2026                     if (!queue_IsEmpty(&tcall->rq)) {
2027                         struct rx_packet *rp;
2028                         rp = queue_First(&tcall->rq, rx_packet);
2029                         if (rp->header.seq == 1) {
2030                             if (!meltdown_1pkt
2031                                 || (rp->header.flags & RX_LAST_PACKET)) {
2032                                 call = tcall;
2033                             } else if (rxi_2dchoice && !choice2
2034                                        && !(tcall->flags & RX_CALL_CLEARED)
2035                                        && (tcall->rprev > rxi_HardAckRate)) {
2036                                 choice2 = tcall;
2037                             } else
2038                                 rxi_md2cnt++;
2039                         }
2040                     }
2041                 }
2042                 if (call) {
2043                     break;
2044                 } else {
2045                     ReturnToServerPool(service);
2046                 }
2047             }
2048         }
2049
2050         if (call) {
2051             queue_Remove(call);
2052             MUTEX_EXIT(&rx_serverPool_lock);
2053             MUTEX_ENTER(&call->lock);
2054
2055             if (call->flags & RX_CALL_WAIT_PROC) {
2056                 call->flags &= ~RX_CALL_WAIT_PROC;
2057                 rx_atomic_dec(&rx_nWaiting);
2058             }
2059
2060             if (call->state != RX_STATE_PRECALL || call->error) {
2061                 MUTEX_EXIT(&call->lock);
2062                 MUTEX_ENTER(&rx_serverPool_lock);
2063                 ReturnToServerPool(service);
2064                 call = NULL;
2065                 continue;
2066             }
2067
2068             if (queue_IsEmpty(&call->rq)
2069                 || queue_First(&call->rq, rx_packet)->header.seq != 1)
2070                 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2071
2072             CLEAR_CALL_QUEUE_LOCK(call);
2073             break;
2074         } else {
2075             /* If there are no eligible incoming calls, add this process
2076              * to the idle server queue, to wait for one */
2077             sq->newcall = 0;
2078             sq->tno = tno;
2079             if (socketp) {
2080                 *socketp = OSI_NULLSOCKET;
2081             }
2082             sq->socketp = socketp;
2083             queue_Append(&rx_idleServerQueue, sq);
2084 #ifndef AFS_AIX41_ENV
2085             rx_waitForPacket = sq;
2086 #else
2087             rx_waitingForPacket = sq;
2088 #endif /* AFS_AIX41_ENV */
2089             do {
2090                 CV_WAIT(&sq->cv, &rx_serverPool_lock);
2091 #ifdef  KERNEL
2092                 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2093                     MUTEX_EXIT(&rx_serverPool_lock);
2094                     return (struct rx_call *)0;
2095                 }
2096 #endif
2097             } while (!(call = sq->newcall)
2098                      && !(socketp && *socketp != OSI_NULLSOCKET));
2099             MUTEX_EXIT(&rx_serverPool_lock);
2100             if (call) {
2101                 MUTEX_ENTER(&call->lock);
2102             }
2103             break;
2104         }
2105     }
2106
2107     MUTEX_ENTER(&freeSQEList_lock);
2108     *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2109     rx_FreeSQEList = sq;
2110     MUTEX_EXIT(&freeSQEList_lock);
2111
2112     if (call) {
2113         clock_GetTime(&call->startTime);
2114         call->state = RX_STATE_ACTIVE;
2115         call->mode = RX_MODE_RECEIVING;
2116 #ifdef RX_KERNEL_TRACE
2117         if (ICL_SETACTIVE(afs_iclSetp)) {
2118             int glockOwner = ISAFS_GLOCK();
2119             if (!glockOwner)
2120                 AFS_GLOCK();
2121             afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2122                        __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2123                        call);
2124             if (!glockOwner)
2125                 AFS_GUNLOCK();
2126         }
2127 #endif
2128
2129         rxi_calltrace(RX_CALL_START, call);
2130         dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
2131              call->conn->service->servicePort, call->conn->service->serviceId,
2132              call));
2133
2134         MUTEX_EXIT(&call->lock);
2135         CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
2136     } else {
2137         dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2138     }
2139
2140     return call;
2141 }
2142 #else /* RX_ENABLE_LOCKS */
2143 struct rx_call *
2144 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2145 {
2146     struct rx_serverQueueEntry *sq;
2147     struct rx_call *call = (struct rx_call *)0, *choice2;
2148     struct rx_service *service = NULL;
2149     SPLVAR;
2150
2151     NETPRI;
2152     MUTEX_ENTER(&freeSQEList_lock);
2153
2154     if ((sq = rx_FreeSQEList)) {
2155         rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
2156         MUTEX_EXIT(&freeSQEList_lock);
2157     } else {                    /* otherwise allocate a new one and return that */
2158         MUTEX_EXIT(&freeSQEList_lock);
2159         sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2160         MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2161         CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2162     }
2163     MUTEX_ENTER(&sq->lock);
2164
2165     if (cur_service != NULL) {
2166         cur_service->nRequestsRunning--;
2167         MUTEX_ENTER(&rx_quota_mutex);
2168         if (cur_service->nRequestsRunning < cur_service->minProcs)
2169             rxi_minDeficit++;
2170         rxi_availProcs++;
2171         MUTEX_EXIT(&rx_quota_mutex);
2172     }
2173     if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
2174         struct rx_call *tcall, *ncall;
2175         /* Scan for eligible incoming calls.  A call is not eligible
2176          * if the maximum number of calls for its service type are
2177          * already executing */
2178         /* One thread will process calls FCFS (to prevent starvation),
2179          * while the other threads may run ahead looking for calls which
2180          * have all their input data available immediately.  This helps
2181          * keep threads from blocking, waiting for data from the client. */
2182         choice2 = (struct rx_call *)0;
2183         for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
2184             service = tcall->conn->service;
2185             if (QuotaOK(service)) {
2186                 MUTEX_ENTER(&rx_pthread_mutex);
2187                 if (tno == rxi_fcfs_thread_num
2188                     || !tcall->queue_item_header.next) {
2189                     MUTEX_EXIT(&rx_pthread_mutex);
2190                     /* If we're the fcfs thread, then  we'll just use
2191                      * this call. If we haven't been able to find an optimal
2192                      * choice, and we're at the end of the list, then use a
2193                      * 2d choice if one has been identified.  Otherwise... */
2194                     call = (choice2 ? choice2 : tcall);
2195                     service = call->conn->service;
2196                 } else {
2197                     MUTEX_EXIT(&rx_pthread_mutex);
2198                     if (!queue_IsEmpty(&tcall->rq)) {
2199                         struct rx_packet *rp;
2200                         rp = queue_First(&tcall->rq, rx_packet);
2201                         if (rp->header.seq == 1
2202                             && (!meltdown_1pkt
2203                                 || (rp->header.flags & RX_LAST_PACKET))) {
2204                             call = tcall;
2205                         } else if (rxi_2dchoice && !choice2
2206                                    && !(tcall->flags & RX_CALL_CLEARED)
2207                                    && (tcall->rprev > rxi_HardAckRate)) {
2208                             choice2 = tcall;
2209                         } else
2210                             rxi_md2cnt++;
2211                     }
2212                 }
2213             }
2214             if (call)
2215                 break;
2216         }
2217     }
2218
2219     if (call) {
2220         queue_Remove(call);
2221         /* we can't schedule a call if there's no data!!! */
2222         /* send an ack if there's no data, if we're missing the
2223          * first packet, or we're missing something between first
2224          * and last -- there's a "hole" in the incoming data. */
2225         if (queue_IsEmpty(&call->rq)
2226             || queue_First(&call->rq, rx_packet)->header.seq != 1
2227             || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
2228             rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2229
2230         call->flags &= (~RX_CALL_WAIT_PROC);
2231         service->nRequestsRunning++;
2232         /* just started call in minProcs pool, need fewer to maintain
2233          * guarantee */
2234         MUTEX_ENTER(&rx_quota_mutex);
2235         if (service->nRequestsRunning <= service->minProcs)
2236             rxi_minDeficit--;
2237         rxi_availProcs--;
2238         MUTEX_EXIT(&rx_quota_mutex);
2239         rx_atomic_dec(&rx_nWaiting);
2240         /* MUTEX_EXIT(&call->lock); */
2241     } else {
2242         /* If there are no eligible incoming calls, add this process
2243          * to the idle server queue, to wait for one */
2244         sq->newcall = 0;
2245         if (socketp) {
2246             *socketp = OSI_NULLSOCKET;
2247         }
2248         sq->socketp = socketp;
2249         queue_Append(&rx_idleServerQueue, sq);
2250         do {
2251             osi_rxSleep(sq);
2252 #ifdef  KERNEL
2253             if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2254                 USERPRI;
2255                 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2256                 return (struct rx_call *)0;
2257             }
2258 #endif
2259         } while (!(call = sq->newcall)
2260                  && !(socketp && *socketp != OSI_NULLSOCKET));
2261     }
2262     MUTEX_EXIT(&sq->lock);
2263
2264     MUTEX_ENTER(&freeSQEList_lock);
2265     *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2266     rx_FreeSQEList = sq;
2267     MUTEX_EXIT(&freeSQEList_lock);
2268
2269     if (call) {
2270         clock_GetTime(&call->startTime);
2271         call->state = RX_STATE_ACTIVE;
2272         call->mode = RX_MODE_RECEIVING;
2273 #ifdef RX_KERNEL_TRACE
2274         if (ICL_SETACTIVE(afs_iclSetp)) {
2275             int glockOwner = ISAFS_GLOCK();
2276             if (!glockOwner)
2277                 AFS_GLOCK();
2278             afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2279                        __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2280                        call);
2281             if (!glockOwner)
2282                 AFS_GUNLOCK();
2283         }
2284 #endif
2285
2286         rxi_calltrace(RX_CALL_START, call);
2287         dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2288              call->conn->service->servicePort, call->conn->service->serviceId,
2289              call));
2290     } else {
2291         dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2292     }
2293
2294     USERPRI;
2295
2296     return call;
2297 }
2298 #endif /* RX_ENABLE_LOCKS */
2299
2300
2301
2302 /* Establish a procedure to be called when a packet arrives for a
2303  * call.  This routine will be called at most once after each call,
2304  * and will also be called if there is an error condition on the or
2305  * the call is complete.  Used by multi rx to build a selection
2306  * function which determines which of several calls is likely to be a
2307  * good one to read from.
2308  * NOTE: the way this is currently implemented it is probably only a
2309  * good idea to (1) use it immediately after a newcall (clients only)
2310  * and (2) only use it once.  Other uses currently void your warranty
2311  */
2312 void
2313 rx_SetArrivalProc(struct rx_call *call,
2314                   void (*proc) (struct rx_call * call,
2315                                         void * mh,
2316                                         int index),
2317                   void * handle, int arg)
2318 {
2319     call->arrivalProc = proc;
2320     call->arrivalProcHandle = handle;
2321     call->arrivalProcArg = arg;
2322 }
2323
2324 /* Call is finished (possibly prematurely).  Return rc to the peer, if
2325  * appropriate, and return the final error code from the conversation
2326  * to the caller */
2327
2328 afs_int32
2329 rx_EndCall(struct rx_call *call, afs_int32 rc)
2330 {
2331     struct rx_connection *conn = call->conn;
2332     afs_int32 error;
2333     SPLVAR;
2334
2335     dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2336           call, rc, call->error, call->abortCode));
2337
2338     NETPRI;
2339     MUTEX_ENTER(&call->lock);
2340
2341     if (rc == 0 && call->error == 0) {
2342         call->abortCode = 0;
2343         call->abortCount = 0;
2344     }
2345
2346     call->arrivalProc = (void (*)())0;
2347     if (rc && call->error == 0) {
2348         rxi_CallError(call, rc);
2349         call->mode = RX_MODE_ERROR;
2350         /* Send an abort message to the peer if this error code has
2351          * only just been set.  If it was set previously, assume the
2352          * peer has already been sent the error code or will request it
2353          */
2354         rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2355     }
2356     if (conn->type == RX_SERVER_CONNECTION) {
2357         /* Make sure reply or at least dummy reply is sent */
2358         if (call->mode == RX_MODE_RECEIVING) {
2359             MUTEX_EXIT(&call->lock);
2360             rxi_WriteProc(call, 0, 0);
2361             MUTEX_ENTER(&call->lock);
2362         }
2363         if (call->mode == RX_MODE_SENDING) {
2364             MUTEX_EXIT(&call->lock);
2365             rxi_FlushWrite(call);
2366             MUTEX_ENTER(&call->lock);
2367         }
2368         rxi_calltrace(RX_CALL_END, call);
2369         /* Call goes to hold state until reply packets are acknowledged */
2370         if (call->tfirst + call->nSoftAcked < call->tnext) {
2371             call->state = RX_STATE_HOLD;
2372         } else {
2373             call->state = RX_STATE_DALLY;
2374             rxi_ClearTransmitQueue(call, 0);
2375             rxi_rto_cancel(call);
2376             rxevent_Cancel(&call->keepAliveEvent, call,
2377                            RX_CALL_REFCOUNT_ALIVE);
2378         }
2379     } else {                    /* Client connection */
2380         char dummy;
2381         /* Make sure server receives input packets, in the case where
2382          * no reply arguments are expected */
2383         if ((call->mode == RX_MODE_SENDING)
2384             || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2385             MUTEX_EXIT(&call->lock);
2386             (void)rxi_ReadProc(call, &dummy, 1);
2387             MUTEX_ENTER(&call->lock);
2388         }
2389
2390         /* If we had an outstanding delayed ack, be nice to the server
2391          * and force-send it now.
2392          */
2393         if (call->delayedAckEvent) {
2394             rxevent_Cancel(&call->delayedAckEvent, call,
2395                            RX_CALL_REFCOUNT_DELAY);
2396             rxi_SendDelayedAck(NULL, call, NULL, 0);
2397         }
2398
2399         /* We need to release the call lock since it's lower than the
2400          * conn_call_lock and we don't want to hold the conn_call_lock
2401          * over the rx_ReadProc call. The conn_call_lock needs to be held
2402          * here for the case where rx_NewCall is perusing the calls on
2403          * the connection structure. We don't want to signal until
2404          * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2405          * have checked this call, found it active and by the time it
2406          * goes to sleep, will have missed the signal.
2407          */
2408         MUTEX_EXIT(&call->lock);
2409         MUTEX_ENTER(&conn->conn_call_lock);
2410         MUTEX_ENTER(&call->lock);
2411
2412         if (!(call->flags & RX_CALL_PEER_BUSY)) {
2413             conn->lastBusy[call->channel] = 0;
2414         }
2415
2416         MUTEX_ENTER(&conn->conn_data_lock);
2417         conn->flags |= RX_CONN_BUSY;
2418         if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2419             MUTEX_EXIT(&conn->conn_data_lock);
2420 #ifdef  RX_ENABLE_LOCKS
2421             CV_BROADCAST(&conn->conn_call_cv);
2422 #else
2423             osi_rxWakeup(conn);
2424 #endif
2425         }
2426 #ifdef RX_ENABLE_LOCKS
2427         else {
2428             MUTEX_EXIT(&conn->conn_data_lock);
2429         }
2430 #endif /* RX_ENABLE_LOCKS */
2431         call->state = RX_STATE_DALLY;
2432     }
2433     error = call->error;
2434
2435     /* currentPacket, nLeft, and NFree must be zeroed here, because
2436      * ResetCall cannot: ResetCall may be called at splnet(), in the
2437      * kernel version, and may interrupt the macros rx_Read or
2438      * rx_Write, which run at normal priority for efficiency. */
2439     if (call->currentPacket) {
2440 #ifdef RX_TRACK_PACKETS
2441         call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2442 #endif
2443         rxi_FreePacket(call->currentPacket);
2444         call->currentPacket = (struct rx_packet *)0;
2445     }
2446
2447     call->nLeft = call->nFree = call->curlen = 0;
2448
2449     /* Free any packets from the last call to ReadvProc/WritevProc */
2450 #ifdef RXDEBUG_PACKET
2451     call->iovqc -=
2452 #endif /* RXDEBUG_PACKET */
2453         rxi_FreePackets(0, &call->iovq);
2454     MUTEX_EXIT(&call->lock);
2455
2456     CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2457     if (conn->type == RX_CLIENT_CONNECTION) {
2458         MUTEX_ENTER(&conn->conn_data_lock);
2459         conn->flags &= ~RX_CONN_BUSY;
2460         MUTEX_EXIT(&conn->conn_data_lock);
2461         MUTEX_EXIT(&conn->conn_call_lock);
2462     }
2463     USERPRI;
2464     /*
2465      * Map errors to the local host's errno.h format.
2466      */
2467     error = ntoh_syserr_conv(error);
2468     return error;
2469 }
2470
2471 #if !defined(KERNEL)
2472
2473 /* Call this routine when shutting down a server or client (especially
2474  * clients).  This will allow Rx to gracefully garbage collect server
2475  * connections, and reduce the number of retries that a server might
2476  * make to a dead client.
2477  * This is not quite right, since some calls may still be ongoing and
2478  * we can't lock them to destroy them. */
2479 void
2480 rx_Finalize(void)
2481 {
2482     struct rx_connection **conn_ptr, **conn_end;
2483
2484     INIT_PTHREAD_LOCKS;
2485     LOCK_RX_INIT;
2486     if (rxinit_status == 1) {
2487         UNLOCK_RX_INIT;
2488         return;                 /* Already shutdown. */
2489     }
2490     rxi_DeleteCachedConnections();
2491     if (rx_connHashTable) {
2492         MUTEX_ENTER(&rx_connHashTable_lock);
2493         for (conn_ptr = &rx_connHashTable[0], conn_end =
2494              &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2495              conn_ptr++) {
2496             struct rx_connection *conn, *next;
2497             for (conn = *conn_ptr; conn; conn = next) {
2498                 next = conn->next;
2499                 if (conn->type == RX_CLIENT_CONNECTION) {
2500                     MUTEX_ENTER(&rx_refcnt_mutex);
2501                     conn->refCount++;
2502                     MUTEX_EXIT(&rx_refcnt_mutex);
2503 #ifdef RX_ENABLE_LOCKS
2504                     rxi_DestroyConnectionNoLock(conn);
2505 #else /* RX_ENABLE_LOCKS */
2506                     rxi_DestroyConnection(conn);
2507 #endif /* RX_ENABLE_LOCKS */
2508                 }
2509             }
2510         }
2511 #ifdef RX_ENABLE_LOCKS
2512         while (rx_connCleanup_list) {
2513             struct rx_connection *conn;
2514             conn = rx_connCleanup_list;
2515             rx_connCleanup_list = rx_connCleanup_list->next;
2516             MUTEX_EXIT(&rx_connHashTable_lock);
2517             rxi_CleanupConnection(conn);
2518             MUTEX_ENTER(&rx_connHashTable_lock);
2519         }
2520         MUTEX_EXIT(&rx_connHashTable_lock);
2521 #endif /* RX_ENABLE_LOCKS */
2522     }
2523     rxi_flushtrace();
2524
2525 #ifdef AFS_NT40_ENV
2526     afs_winsockCleanup();
2527 #endif
2528
2529     rxinit_status = 1;
2530     UNLOCK_RX_INIT;
2531 }
2532 #endif
2533
2534 /* if we wakeup packet waiter too often, can get in loop with two
2535     AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2536 void
2537 rxi_PacketsUnWait(void)
2538 {
2539     if (!rx_waitingForPackets) {
2540         return;
2541     }
2542 #ifdef KERNEL
2543     if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2544         return;                 /* still over quota */
2545     }
2546 #endif /* KERNEL */
2547     rx_waitingForPackets = 0;
2548 #ifdef  RX_ENABLE_LOCKS
2549     CV_BROADCAST(&rx_waitingForPackets_cv);
2550 #else
2551     osi_rxWakeup(&rx_waitingForPackets);
2552 #endif
2553     return;
2554 }
2555
2556
2557 /* ------------------Internal interfaces------------------------- */
2558
2559 /* Return this process's service structure for the
2560  * specified socket and service */
2561 static struct rx_service *
2562 rxi_FindService(osi_socket socket, u_short serviceId)
2563 {
2564     struct rx_service **sp;
2565     for (sp = &rx_services[0]; *sp; sp++) {
2566         if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2567             return *sp;
2568     }
2569     return 0;
2570 }
2571
2572 #ifdef RXDEBUG_PACKET
2573 #ifdef KDUMP_RX_LOCK
2574 static struct rx_call_rx_lock *rx_allCallsp = 0;
2575 #else
2576 static struct rx_call *rx_allCallsp = 0;
2577 #endif
2578 #endif /* RXDEBUG_PACKET */
2579
2580 /* Allocate a call structure, for the indicated channel of the
2581  * supplied connection.  The mode and state of the call must be set by
2582  * the caller. Returns the call with mutex locked. */
2583 static struct rx_call *
2584 rxi_NewCall(struct rx_connection *conn, int channel)
2585 {
2586     struct rx_call *call;
2587 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
2588     struct rx_call *cp; /* Call pointer temp */
2589     struct rx_call *nxp;        /* Next call pointer, for queue_Scan */
2590 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2591
2592     dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2593
2594     /* Grab an existing call structure, or allocate a new one.
2595      * Existing call structures are assumed to have been left reset by
2596      * rxi_FreeCall */
2597     MUTEX_ENTER(&rx_freeCallQueue_lock);
2598
2599 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
2600     /*
2601      * EXCEPT that the TQ might not yet be cleared out.
2602      * Skip over those with in-use TQs.
2603      */
2604     call = NULL;
2605     for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2606         if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2607             call = cp;
2608             break;
2609         }
2610     }
2611     if (call) {
2612 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2613     if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2614         call = queue_First(&rx_freeCallQueue, rx_call);
2615 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2616         queue_Remove(call);
2617         if (rx_stats_active)
2618             rx_atomic_dec(&rx_stats.nFreeCallStructs);
2619         MUTEX_EXIT(&rx_freeCallQueue_lock);
2620         MUTEX_ENTER(&call->lock);
2621         CLEAR_CALL_QUEUE_LOCK(call);
2622 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
2623         /* Now, if TQ wasn't cleared earlier, do it now. */
2624         rxi_WaitforTQBusy(call);
2625         if (call->flags & RX_CALL_TQ_CLEARME) {
2626             rxi_ClearTransmitQueue(call, 1);
2627             /*queue_Init(&call->tq);*/
2628         }
2629 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2630         /* Bind the call to its connection structure */
2631         call->conn = conn;
2632         rxi_ResetCall(call, 1);
2633     } else {
2634
2635         call = rxi_Alloc(sizeof(struct rx_call));
2636 #ifdef RXDEBUG_PACKET
2637         call->allNextp = rx_allCallsp;
2638         rx_allCallsp = call;
2639         call->call_id =
2640             rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2641 #else /* RXDEBUG_PACKET */
2642         rx_atomic_inc(&rx_stats.nCallStructs);
2643 #endif /* RXDEBUG_PACKET */
2644
2645         MUTEX_EXIT(&rx_freeCallQueue_lock);
2646         MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2647         MUTEX_ENTER(&call->lock);
2648         CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2649         CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2650         CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2651
2652         /* Initialize once-only items */
2653         queue_Init(&call->tq);
2654         queue_Init(&call->rq);
2655         queue_Init(&call->iovq);
2656 #ifdef RXDEBUG_PACKET
2657         call->rqc = call->tqc = call->iovqc = 0;
2658 #endif /* RXDEBUG_PACKET */
2659         /* Bind the call to its connection structure (prereq for reset) */
2660         call->conn = conn;
2661         rxi_ResetCall(call, 1);
2662     }
2663     call->channel = channel;
2664     call->callNumber = &conn->callNumber[channel];
2665     call->rwind = conn->rwind[channel];
2666     call->twind = conn->twind[channel];
2667     /* Note that the next expected call number is retained (in
2668      * conn->callNumber[i]), even if we reallocate the call structure
2669      */
2670     conn->call[channel] = call;
2671     /* if the channel's never been used (== 0), we should start at 1, otherwise
2672      * the call number is valid from the last time this channel was used */
2673     if (*call->callNumber == 0)
2674         *call->callNumber = 1;
2675
2676     return call;
2677 }
2678
2679 /* A call has been inactive long enough that so we can throw away
2680  * state, including the call structure, which is placed on the call
2681  * free list.
2682  *
2683  * call->lock amd rx_refcnt_mutex are held upon entry.
2684  * haveCTLock is set when called from rxi_ReapConnections.
2685  *
2686  * return 1 if the call is freed, 0 if not.
2687  */
2688 static int
2689 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2690 {
2691     int channel = call->channel;
2692     struct rx_connection *conn = call->conn;
2693     u_char state = call->state;
2694
2695     /*
2696      * We are setting the state to RX_STATE_RESET to
2697      * ensure that no one else will attempt to use this
2698      * call once we drop the refcnt lock. We must drop
2699      * the refcnt lock before calling rxi_ResetCall
2700      * because it cannot be held across acquiring the
2701      * freepktQ lock. NewCall does the same.
2702      */
2703     call->state = RX_STATE_RESET;
2704     MUTEX_EXIT(&rx_refcnt_mutex);
2705     rxi_ResetCall(call, 0);
2706
2707     if (MUTEX_TRYENTER(&conn->conn_call_lock))
2708     {
2709         if (state == RX_STATE_DALLY || state == RX_STATE_HOLD)
2710             (*call->callNumber)++;
2711
2712         if (call->conn->call[channel] == call)
2713             call->conn->call[channel] = 0;
2714         MUTEX_EXIT(&conn->conn_call_lock);
2715     } else {
2716         /*
2717          * We couldn't obtain the conn_call_lock so we can't
2718          * disconnect the call from the connection.  Set the
2719          * call state to dally so that the call can be reused.
2720          */
2721         MUTEX_ENTER(&rx_refcnt_mutex);
2722         call->state = RX_STATE_DALLY;
2723         return 0;
2724     }
2725
2726     MUTEX_ENTER(&rx_freeCallQueue_lock);
2727     SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2728 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2729     /* A call may be free even though its transmit queue is still in use.
2730      * Since we search the call list from head to tail, put busy calls at
2731      * the head of the list, and idle calls at the tail.
2732      */
2733     if (call->flags & RX_CALL_TQ_BUSY)
2734         queue_Prepend(&rx_freeCallQueue, call);
2735     else
2736         queue_Append(&rx_freeCallQueue, call);
2737 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2738     queue_Append(&rx_freeCallQueue, call);
2739 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2740     if (rx_stats_active)
2741         rx_atomic_inc(&rx_stats.nFreeCallStructs);
2742     MUTEX_EXIT(&rx_freeCallQueue_lock);
2743
2744     /* Destroy the connection if it was previously slated for
2745      * destruction, i.e. the Rx client code previously called
2746      * rx_DestroyConnection (client connections), or
2747      * rxi_ReapConnections called the same routine (server
2748      * connections).  Only do this, however, if there are no
2749      * outstanding calls. Note that for fine grain locking, there appears
2750      * to be a deadlock in that rxi_FreeCall has a call locked and
2751      * DestroyConnectionNoLock locks each call in the conn. But note a
2752      * few lines up where we have removed this call from the conn.
2753      * If someone else destroys a connection, they either have no
2754      * call lock held or are going through this section of code.
2755      */
2756     MUTEX_ENTER(&conn->conn_data_lock);
2757     if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2758         MUTEX_ENTER(&rx_refcnt_mutex);
2759         conn->refCount++;
2760         MUTEX_EXIT(&rx_refcnt_mutex);
2761         MUTEX_EXIT(&conn->conn_data_lock);
2762 #ifdef RX_ENABLE_LOCKS
2763         if (haveCTLock)
2764             rxi_DestroyConnectionNoLock(conn);
2765         else
2766             rxi_DestroyConnection(conn);
2767 #else /* RX_ENABLE_LOCKS */
2768         rxi_DestroyConnection(conn);
2769 #endif /* RX_ENABLE_LOCKS */
2770     } else {
2771         MUTEX_EXIT(&conn->conn_data_lock);
2772     }
2773     MUTEX_ENTER(&rx_refcnt_mutex);
2774     return 1;
2775 }
2776
2777 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2778 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2779
2780 void *
2781 rxi_Alloc(size_t size)
2782 {
2783     char *p;
2784
2785     if (rx_stats_active) {
2786         rx_atomic_add(&rxi_Allocsize, (int) size);
2787         rx_atomic_inc(&rxi_Alloccnt);
2788     }
2789
2790 p = (char *)
2791 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2792   afs_osi_Alloc_NoSleep(size);
2793 #else
2794   osi_Alloc(size);
2795 #endif
2796     if (!p)
2797         osi_Panic("rxi_Alloc error");
2798     memset(p, 0, size);
2799     return p;
2800 }
2801
2802 void
2803 rxi_Free(void *addr, size_t size)
2804 {
2805     if (rx_stats_active) {
2806         rx_atomic_sub(&rxi_Allocsize, (int) size);
2807         rx_atomic_dec(&rxi_Alloccnt);
2808     }
2809     osi_Free(addr, size);
2810 }
2811
2812 void
2813 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2814 {
2815     struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2816     struct rx_peer *next = NULL;
2817     int hashIndex;
2818
2819     if (!peer) {
2820         MUTEX_ENTER(&rx_peerHashTable_lock);
2821         if (port == 0) {
2822             peer_ptr = &rx_peerHashTable[0];
2823             peer_end = &rx_peerHashTable[rx_hashTableSize];
2824             next = NULL;
2825         resume:
2826             for ( ; peer_ptr < peer_end; peer_ptr++) {
2827                 if (!peer)
2828                     peer = *peer_ptr;
2829                 for ( ; peer; peer = next) {
2830                     next = peer->next;
2831                     if (host == peer->host)
2832                         break;
2833                 }
2834             }
2835         } else {
2836             hashIndex = PEER_HASH(host, port);
2837             for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2838                 if ((peer->host == host) && (peer->port == port))
2839                     break;
2840             }
2841         }
2842     } else {
2843         MUTEX_ENTER(&rx_peerHashTable_lock);
2844     }
2845
2846     if (peer) {
2847         peer->refCount++;
2848         MUTEX_EXIT(&rx_peerHashTable_lock);
2849
2850         MUTEX_ENTER(&peer->peer_lock);
2851         /* We don't handle dropping below min, so don't */
2852         mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2853         peer->ifMTU=MIN(mtu, peer->ifMTU);
2854         peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2855         /* if we tweaked this down, need to tune our peer MTU too */
2856         peer->MTU = MIN(peer->MTU, peer->natMTU);
2857         /* if we discovered a sub-1500 mtu, degrade */
2858         if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2859             peer->maxDgramPackets = 1;
2860         /* We no longer have valid peer packet information */
2861         if (peer->maxPacketSize-RX_IPUDP_SIZE > peer->ifMTU)
2862             peer->maxPacketSize = 0;
2863         MUTEX_EXIT(&peer->peer_lock);
2864
2865         MUTEX_ENTER(&rx_peerHashTable_lock);
2866         peer->refCount--;
2867         if (host && !port) {
2868             peer = next;
2869             /* pick up where we left off */
2870             goto resume;
2871         }
2872     }
2873     MUTEX_EXIT(&rx_peerHashTable_lock);
2874 }
2875
2876 /* Find the peer process represented by the supplied (host,port)
2877  * combination.  If there is no appropriate active peer structure, a
2878  * new one will be allocated and initialized
2879  * The origPeer, if set, is a pointer to a peer structure on which the
2880  * refcount will be be decremented. This is used to replace the peer
2881  * structure hanging off a connection structure */
2882 struct rx_peer *
2883 rxi_FindPeer(afs_uint32 host, u_short port,
2884              struct rx_peer *origPeer, int create)
2885 {
2886     struct rx_peer *pp;
2887     int hashIndex;
2888     hashIndex = PEER_HASH(host, port);
2889     MUTEX_ENTER(&rx_peerHashTable_lock);
2890     for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2891         if ((pp->host == host) && (pp->port == port))
2892             break;
2893     }
2894     if (!pp) {
2895         if (create) {
2896             pp = rxi_AllocPeer();       /* This bzero's *pp */
2897             pp->host = host;    /* set here or in InitPeerParams is zero */
2898             pp->port = port;
2899             MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2900             queue_Init(&pp->congestionQueue);
2901             queue_Init(&pp->rpcStats);
2902             pp->next = rx_peerHashTable[hashIndex];
2903             rx_peerHashTable[hashIndex] = pp;
2904             rxi_InitPeerParams(pp);
2905             if (rx_stats_active)
2906                 rx_atomic_inc(&rx_stats.nPeerStructs);
2907         }
2908     }
2909     if (pp && create) {
2910         pp->refCount++;
2911     }
2912     if (origPeer)
2913         origPeer->refCount--;
2914     MUTEX_EXIT(&rx_peerHashTable_lock);
2915     return pp;
2916 }
2917
2918
2919 /* Find the connection at (host, port) started at epoch, and with the
2920  * given connection id.  Creates the server connection if necessary.
2921  * The type specifies whether a client connection or a server
2922  * connection is desired.  In both cases, (host, port) specify the
2923  * peer's (host, pair) pair.  Client connections are not made
2924  * automatically by this routine.  The parameter socket gives the
2925  * socket descriptor on which the packet was received.  This is used,
2926  * in the case of server connections, to check that *new* connections
2927  * come via a valid (port, serviceId).  Finally, the securityIndex
2928  * parameter must match the existing index for the connection.  If a
2929  * server connection is created, it will be created using the supplied
2930  * index, if the index is valid for this service */
2931 struct rx_connection *
2932 rxi_FindConnection(osi_socket socket, afs_uint32 host,
2933                    u_short port, u_short serviceId, afs_uint32 cid,
2934                    afs_uint32 epoch, int type, u_int securityIndex)
2935 {
2936     int hashindex, flag, i;
2937     struct rx_connection *conn;
2938     hashindex = CONN_HASH(host, port, cid, epoch, type);
2939     MUTEX_ENTER(&rx_connHashTable_lock);
2940     rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2941                                                   rx_connHashTable[hashindex],
2942                                                   flag = 1);
2943     for (; conn;) {
2944         if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2945             && (epoch == conn->epoch)) {
2946             struct rx_peer *pp = conn->peer;
2947             if (securityIndex != conn->securityIndex) {
2948                 /* this isn't supposed to happen, but someone could forge a packet
2949                  * like this, and there seems to be some CM bug that makes this
2950                  * happen from time to time -- in which case, the fileserver
2951                  * asserts. */
2952                 MUTEX_EXIT(&rx_connHashTable_lock);
2953                 return (struct rx_connection *)0;
2954             }
2955             if (pp->host == host && pp->port == port)
2956                 break;
2957             if (type == RX_CLIENT_CONNECTION && pp->port == port)
2958                 break;
2959             /* So what happens when it's a callback connection? */
2960             if (                /*type == RX_CLIENT_CONNECTION && */
2961                    (conn->epoch & 0x80000000))
2962                 break;
2963         }
2964         if (!flag) {
2965             /* the connection rxLastConn that was used the last time is not the
2966              ** one we are looking for now. Hence, start searching in the hash */
2967             flag = 1;
2968             conn = rx_connHashTable[hashindex];
2969         } else
2970             conn = conn->next;
2971     }
2972     if (!conn) {
2973         struct rx_service *service;
2974         if (type == RX_CLIENT_CONNECTION) {
2975             MUTEX_EXIT(&rx_connHashTable_lock);
2976             return (struct rx_connection *)0;
2977         }
2978         service = rxi_FindService(socket, serviceId);
2979         if (!service || (securityIndex >= service->nSecurityObjects)
2980             || (service->securityObjects[securityIndex] == 0)) {
2981             MUTEX_EXIT(&rx_connHashTable_lock);
2982             return (struct rx_connection *)0;
2983         }
2984         conn = rxi_AllocConnection();   /* This bzero's the connection */
2985         MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2986         MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2987         CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2988         conn->next = rx_connHashTable[hashindex];
2989         rx_connHashTable[hashindex] = conn;
2990         conn->peer = rxi_FindPeer(host, port, 0, 1);
2991         conn->type = RX_SERVER_CONNECTION;
2992         conn->lastSendTime = clock_Sec();       /* don't GC immediately */
2993         conn->epoch = epoch;
2994         conn->cid = cid & RX_CIDMASK;
2995         /* conn->serial = conn->lastSerial = 0; */
2996         /* conn->timeout = 0; */
2997         conn->ackRate = RX_FAST_ACK_RATE;
2998         conn->service = service;
2999         conn->serviceId = serviceId;
3000         conn->securityIndex = securityIndex;
3001         conn->securityObject = service->securityObjects[securityIndex];
3002         conn->nSpecific = 0;
3003         conn->specific = NULL;
3004         rx_SetConnDeadTime(conn, service->connDeadTime);
3005         conn->idleDeadTime = service->idleDeadTime;
3006         conn->idleDeadDetection = service->idleDeadErr ? 1 : 0;
3007         for (i = 0; i < RX_MAXCALLS; i++) {
3008             conn->twind[i] = rx_initSendWindow;
3009             conn->rwind[i] = rx_initReceiveWindow;
3010         }
3011         /* Notify security object of the new connection */
3012         RXS_NewConnection(conn->securityObject, conn);
3013         /* XXXX Connection timeout? */
3014         if (service->newConnProc)
3015             (*service->newConnProc) (conn);
3016         if (rx_stats_active)
3017             rx_atomic_inc(&rx_stats.nServerConns);
3018     }
3019
3020     MUTEX_ENTER(&rx_refcnt_mutex);
3021     conn->refCount++;
3022     MUTEX_EXIT(&rx_refcnt_mutex);
3023
3024     rxLastConn = conn;          /* store this connection as the last conn used */
3025     MUTEX_EXIT(&rx_connHashTable_lock);
3026     return conn;
3027 }
3028
3029 /**
3030  * Timeout a call on a busy call channel if appropriate.
3031  *
3032  * @param[in] call The busy call.
3033  *
3034  * @pre 'call' is marked as busy (namely,
3035  *      call->conn->lastBusy[call->channel] != 0)
3036  *
3037  * @pre call->lock is held
3038  * @pre rxi_busyChannelError is nonzero
3039  *
3040  * @note call->lock is dropped and reacquired
3041  */
3042 static void
3043 rxi_CheckBusy(struct rx_call *call)
3044 {
3045     struct rx_connection *conn = call->conn;
3046     int channel = call->channel;
3047     int freechannel = 0;
3048     int i;
3049     afs_uint32 callNumber;
3050
3051     MUTEX_EXIT(&call->lock);
3052
3053     MUTEX_ENTER(&conn->conn_call_lock);
3054     callNumber = *call->callNumber;
3055
3056     /* Are there any other call slots on this conn that we should try? Look for
3057      * slots that are empty and are either non-busy, or were marked as busy
3058      * longer than conn->secondsUntilDead seconds before this call started. */
3059
3060     for (i = 0; i < RX_MAXCALLS && !freechannel; i++) {
3061         if (i == channel) {
3062             /* only look at channels that aren't us */
3063             continue;
3064         }
3065
3066         if (conn->lastBusy[i]) {
3067             /* if this channel looked busy too recently, don't look at it */
3068             if (conn->lastBusy[i] >= call->startTime.sec) {
3069                 continue;
3070             }
3071             if (call->startTime.sec - conn->lastBusy[i] < conn->secondsUntilDead) {
3072                 continue;
3073             }
3074         }
3075
3076         if (conn->call[i]) {
3077             struct rx_call *tcall = conn->call[i];
3078             MUTEX_ENTER(&tcall->lock);
3079             if (tcall->state == RX_STATE_DALLY) {
3080                 freechannel = 1;
3081             }
3082             MUTEX_EXIT(&tcall->lock);
3083         } else {
3084             freechannel = 1;
3085         }
3086     }
3087
3088     MUTEX_ENTER(&call->lock);
3089
3090     /* Since the call->lock and conn->conn_call_lock have been released it is
3091      * possible that (1) the call may no longer be busy and/or (2) the call may
3092      * have been reused by another waiting thread. Therefore, we must confirm
3093      * that the call state has not changed when deciding whether or not to
3094      * force this application thread to retry by forcing a Timeout error. */
3095
3096     if (freechannel && *call->callNumber == callNumber &&
3097         (call->flags & RX_CALL_PEER_BUSY)) {
3098         /* Since 'freechannel' is set, there exists another channel in this
3099          * rx_conn that the application thread might be able to use. We know
3100          * that we have the correct call since callNumber is unchanged, and we
3101          * know that the call is still busy. So, set the call error state to
3102          * rxi_busyChannelError so the application can retry the request,
3103          * presumably on a less-busy call channel. */
3104
3105         rxi_CallError(call, RX_CALL_BUSY);
3106     }
3107     MUTEX_EXIT(&conn->conn_call_lock);
3108 }
3109
3110 /* There are two packet tracing routines available for testing and monitoring
3111  * Rx.  One is called just after every packet is received and the other is
3112  * called just before every packet is sent.  Received packets, have had their
3113  * headers decoded, and packets to be sent have not yet had their headers
3114  * encoded.  Both take two parameters: a pointer to the packet and a sockaddr
3115  * containing the network address.  Both can be modified.  The return value, if
3116  * non-zero, indicates that the packet should be dropped.  */
3117
3118 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
3119 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
3120
3121 /* A packet has been received off the interface.  Np is the packet, socket is
3122  * the socket number it was received from (useful in determining which service
3123  * this packet corresponds to), and (host, port) reflect the host,port of the
3124  * sender.  This call returns the packet to the caller if it is finished with
3125  * it, rather than de-allocating it, just as a small performance hack */
3126
3127 struct rx_packet *
3128 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
3129                   afs_uint32 host, u_short port, int *tnop,
3130                   struct rx_call **newcallp)
3131 {
3132     struct rx_call *call;
3133     struct rx_connection *conn;
3134     int channel;
3135     afs_uint32 currentCallNumber;
3136     int type;
3137     int skew;
3138 #ifdef RXDEBUG
3139     char *packetType;
3140 #endif
3141     struct rx_packet *tnp;
3142
3143 #ifdef RXDEBUG
3144 /* We don't print out the packet until now because (1) the time may not be
3145  * accurate enough until now in the lwp implementation (rx_Listener only gets
3146  * the time after the packet is read) and (2) from a protocol point of view,
3147  * this is the first time the packet has been seen */
3148     packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
3149         ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
3150     dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT"\n",
3151          np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
3152          np->header.epoch, np->header.cid, np->header.callNumber,
3153          np->header.seq, np->header.flags, np));
3154 #endif
3155
3156     if (np->header.type == RX_PACKET_TYPE_VERSION) {
3157         return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
3158     }
3159
3160     if (np->header.type == RX_PACKET_TYPE_DEBUG) {
3161         return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
3162     }
3163 #ifdef RXDEBUG
3164     /* If an input tracer function is defined, call it with the packet and
3165      * network address.  Note this function may modify its arguments. */
3166     if (rx_justReceived) {
3167         struct sockaddr_in addr;
3168         int drop;
3169         addr.sin_family = AF_INET;
3170         addr.sin_port = port;
3171         addr.sin_addr.s_addr = host;
3172 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
3173         addr.sin_len = sizeof(addr);
3174 #endif /* AFS_OSF_ENV */
3175         drop = (*rx_justReceived) (np, &addr);
3176         /* drop packet if return value is non-zero */
3177         if (drop)
3178             return np;
3179         port = addr.sin_port;   /* in case fcn changed addr */
3180         host = addr.sin_addr.s_addr;
3181     }
3182 #endif
3183
3184     /* If packet was not sent by the client, then *we* must be the client */
3185     type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
3186         ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
3187
3188     /* Find the connection (or fabricate one, if we're the server & if
3189      * necessary) associated with this packet */
3190     conn =
3191         rxi_FindConnection(socket, host, port, np->header.serviceId,
3192                            np->header.cid, np->header.epoch, type,
3193                            np->header.securityIndex);
3194
3195     if (!conn) {
3196         /* If no connection found or fabricated, just ignore the packet.
3197          * (An argument could be made for sending an abort packet for
3198          * the conn) */
3199         return np;
3200     }
3201
3202     /* If the connection is in an error state, send an abort packet and ignore
3203      * the incoming packet */
3204     if (conn->error) {
3205         /* Don't respond to an abort packet--we don't want loops! */
3206         MUTEX_ENTER(&conn->conn_data_lock);
3207         if (np->header.type != RX_PACKET_TYPE_ABORT)
3208             np = rxi_SendConnectionAbort(conn, np, 1, 0);
3209         putConnection(conn);
3210         MUTEX_EXIT(&conn->conn_data_lock);
3211         return np;
3212     }
3213
3214     /* Check for connection-only requests (i.e. not call specific). */
3215     if (np->header.callNumber == 0) {
3216         switch (np->header.type) {
3217         case RX_PACKET_TYPE_ABORT: {
3218             /* What if the supplied error is zero? */
3219             afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
3220             dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
3221             rxi_ConnectionError(conn, errcode);
3222             putConnection(conn);
3223             return np;
3224         }
3225         case RX_PACKET_TYPE_CHALLENGE:
3226             tnp = rxi_ReceiveChallengePacket(conn, np, 1);
3227             putConnection(conn);
3228             return tnp;
3229         case RX_PACKET_TYPE_RESPONSE:
3230             tnp = rxi_ReceiveResponsePacket(conn, np, 1);
3231             putConnection(conn);
3232             return tnp;
3233         case RX_PACKET_TYPE_PARAMS:
3234         case RX_PACKET_TYPE_PARAMS + 1:
3235         case RX_PACKET_TYPE_PARAMS + 2:
3236             /* ignore these packet types for now */
3237             putConnection(conn);
3238             return np;
3239
3240         default:
3241             /* Should not reach here, unless the peer is broken: send an
3242              * abort packet */
3243             rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
3244             MUTEX_ENTER(&conn->conn_data_lock);
3245             tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
3246             putConnection(conn);
3247             MUTEX_EXIT(&conn->conn_data_lock);
3248             return tnp;
3249         }
3250     }
3251
3252     channel = np->header.cid & RX_CHANNELMASK;
3253     MUTEX_ENTER(&conn->conn_call_lock);
3254     call = conn->call[channel];
3255
3256     if (call) {
3257         MUTEX_ENTER(&call->lock);
3258         currentCallNumber = conn->callNumber[channel];
3259         MUTEX_EXIT(&conn->conn_call_lock);
3260     } else if (type == RX_SERVER_CONNECTION) {  /* No call allocated */
3261         call = conn->call[channel];
3262         if (call) {
3263             MUTEX_ENTER(&call->lock);
3264             currentCallNumber = conn->callNumber[channel];
3265             MUTEX_EXIT(&conn->conn_call_lock);
3266         } else {
3267             call = rxi_NewCall(conn, channel);  /* returns locked call */
3268             *call->callNumber = currentCallNumber = np->header.callNumber;
3269             MUTEX_EXIT(&conn->conn_call_lock);
3270 #ifdef RXDEBUG
3271             if (np->header.callNumber == 0)
3272                 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" len %d\n",
3273                      np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3274                      np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3275                      np->header.flags, np, np->length));
3276 #endif
3277             call->state = RX_STATE_PRECALL;
3278             clock_GetTime(&call->queueTime);
3279             hzero(call->bytesSent);
3280             hzero(call->bytesRcvd);
3281             /*
3282              * If the number of queued calls exceeds the overload
3283              * threshold then abort this call.
3284              */
3285             if ((rx_BusyThreshold > 0) &&
3286                 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3287                 struct rx_packet *tp;
3288
3289                 rxi_CallError(call, rx_BusyError);
3290                 tp = rxi_SendCallAbort(call, np, 1, 0);
3291                 MUTEX_EXIT(&call->lock);
3292                 putConnection(conn);
3293                 if (rx_stats_active)
3294                     rx_atomic_inc(&rx_stats.nBusies);
3295                 return tp;
3296             }
3297             rxi_KeepAliveOn(call);
3298         }
3299     } else {    /* RX_CLIENT_CONNECTION and No call allocated */
3300         /* This packet can't be for this call. If the new call address is
3301          * 0 then no call is running on this channel. If there is a call
3302          * then, since this is a client connection we're getting data for
3303          * it must be for the previous call.
3304          */
3305         if (rx_stats_active)
3306             rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3307         putConnection(conn);
3308         return np;
3309     }
3310
3311     /* There is a non-NULL locked call at this point */
3312     if (type == RX_SERVER_CONNECTION) { /* We're the server */
3313         if (np->header.callNumber < currentCallNumber) {
3314             MUTEX_EXIT(&call->lock);
3315             if (rx_stats_active)
3316                 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3317             putConnection(conn);
3318             return np;
3319         } else if (np->header.callNumber != currentCallNumber) {
3320             /* Wait until the transmit queue is idle before deciding
3321              * whether to reset the current call. Chances are that the
3322              * call will be in ether DALLY or HOLD state once the TQ_BUSY
3323              * flag is cleared.
3324              */
3325 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3326             if (call->state == RX_STATE_ACTIVE) {
3327                 rxi_WaitforTQBusy(call);
3328                 /*
3329                  * If we entered error state while waiting,
3330                  * must call rxi_CallError to permit rxi_ResetCall
3331                  * to processed when the tqWaiter count hits zero.
3332                  */
3333                 if (call->error) {
3334                     rxi_CallError(call, call->error);
3335                     MUTEX_EXIT(&call->lock);
3336                     putConnection(conn);
3337                     return np;
3338                 }
3339             }
3340 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3341             /* If the new call cannot be taken right now send a busy and set
3342              * the error condition in this call, so that it terminates as
3343              * quickly as possible */
3344             if (call->state == RX_STATE_ACTIVE) {
3345                 struct rx_packet *tp;
3346
3347                 rxi_CallError(call, RX_CALL_DEAD);
3348                 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
3349                                      NULL, 0, 1);
3350                 MUTEX_EXIT(&call->lock);
3351                 putConnection(conn);
3352                 return tp;
3353             }
3354             rxi_ResetCall(call, 0);
3355             /*
3356              * The conn_call_lock is not held but no one else should be
3357              * using this call channel while we are processing this incoming
3358              * packet.  This assignment should be safe.
3359              */
3360             *call->callNumber = np->header.callNumber;
3361 #ifdef RXDEBUG
3362             if (np->header.callNumber == 0)
3363                 dpf(("RecPacket call 0 %d %s: %x.%u.%u.%u.%u.%u.%u flags %d, packet %"AFS_PTR_FMT" len %d\n",
3364                       np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3365                       np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3366                       np->header.flags, np, np->length));
3367 #endif
3368             call->state = RX_STATE_PRECALL;
3369             clock_GetTime(&call->queueTime);
3370             hzero(call->bytesSent);
3371             hzero(call->bytesRcvd);
3372             /*
3373              * If the number of queued calls exceeds the overload
3374              * threshold then abort this call.
3375              */
3376             if ((rx_BusyThreshold > 0) &&
3377                 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3378                 struct rx_packet *tp;
3379
3380                 rxi_CallError(call, rx_BusyError);
3381                 tp = rxi_SendCallAbort(call, np, 1, 0);
3382                 MUTEX_EXIT(&call->lock);
3383                 putConnection(conn);
3384                 if (rx_stats_active)
3385                     rx_atomic_inc(&rx_stats.nBusies);
3386                 return tp;
3387             }
3388             rxi_KeepAliveOn(call);
3389         } else {
3390             /* Continuing call; do nothing here. */
3391         }
3392     } else {                    /* we're the client */
3393         /* Ignore all incoming acknowledgements for calls in DALLY state */
3394         if ((call->state == RX_STATE_DALLY)
3395             && (np->header.type == RX_PACKET_TYPE_ACK)) {
3396             if (rx_stats_active)
3397                 rx_atomic_inc(&rx_stats.ignorePacketDally);
3398             MUTEX_EXIT(&call->lock);
3399             putConnection(conn);
3400             return np;
3401         }
3402
3403         /* Ignore anything that's not relevant to the current call.  If there
3404          * isn't a current call, then no packet is relevant. */
3405         if (np->header.callNumber != currentCallNumber) {
3406             if (rx_stats_active)
3407                 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3408             MUTEX_EXIT(&call->lock);
3409             putConnection(conn);
3410             return np;
3411         }
3412         /* If the service security object index stamped in the packet does not
3413          * match the connection's security index, ignore the packet */
3414         if (np->header.securityIndex != conn->securityIndex) {
3415             MUTEX_EXIT(&call->lock);
3416             putConnection(conn);
3417             return np;
3418         }
3419
3420         /* If we're receiving the response, then all transmit packets are
3421          * implicitly acknowledged.  Get rid of them. */
3422         if (np->header.type == RX_PACKET_TYPE_DATA) {
3423 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
3424             /* XXX Hack. Because we must release the global rx lock when
3425              * sending packets (osi_NetSend) we drop all acks while we're
3426              * traversing the tq in rxi_Start sending packets out because
3427              * packets may move to the freePacketQueue as result of being here!
3428              * So we drop these packets until we're safely out of the
3429              * traversing. Really ugly!
3430              * For fine grain RX locking, we set the acked field in the
3431              * packets and let rxi_Start remove them from the transmit queue.
3432              */
3433             if (call->flags & RX_CALL_TQ_BUSY) {
3434 #ifdef  RX_ENABLE_LOCKS
3435                 rxi_SetAcksInTransmitQueue(call);
3436 #else
3437                 putConnection(conn);
3438                 return np;      /* xmitting; drop packet */
3439 #endif
3440             } else {
3441                 rxi_ClearTransmitQueue(call, 0);
3442             }
3443 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
3444             rxi_ClearTransmitQueue(call, 0);
3445 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3446         } else {
3447             if (np->header.type == RX_PACKET_TYPE_ACK) {
3448                 /* now check to see if this is an ack packet acknowledging that the
3449                  * server actually *lost* some hard-acked data.  If this happens we
3450                  * ignore this packet, as it may indicate that the server restarted in
3451                  * the middle of a call.  It is also possible that this is an old ack
3452                  * packet.  We don't abort the connection in this case, because this
3453                  * *might* just be an old ack packet.  The right way to detect a server
3454                  * restart in the midst of a call is to notice that the server epoch
3455                  * changed, btw.  */
3456                 /* XXX I'm not sure this is exactly right, since tfirst **IS**
3457                  * XXX unacknowledged.  I think that this is off-by-one, but
3458                  * XXX I don't dare change it just yet, since it will
3459                  * XXX interact badly with the server-restart detection
3460                  * XXX code in receiveackpacket.  */
3461                 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
3462                     if (rx_stats_active)
3463                         rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3464                     MUTEX_EXIT(&call->lock);
3465                     putConnection(conn);
3466                     return np;
3467                 }
3468             }
3469         }                       /* else not a data packet */
3470     }
3471
3472     osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
3473     /* Set remote user defined status from packet */
3474     call->remoteStatus = np->header.userStatus;
3475
3476     /* Note the gap between the expected next packet and the actual
3477      * packet that arrived, when the new packet has a smaller serial number
3478      * than expected.  Rioses frequently reorder packets all by themselves,
3479      * so this will be quite important with very large window sizes.
3480      * Skew is checked against 0 here to avoid any dependence on the type of
3481      * inPacketSkew (which may be unsigned).  In C, -1 > (unsigned) 0 is always
3482      * true!
3483      * The inPacketSkew should be a smoothed running value, not just a maximum.  MTUXXX
3484      * see CalculateRoundTripTime for an example of how to keep smoothed values.
3485      * I think using a beta of 1/8 is probably appropriate.  93.04.21
3486      */
3487     MUTEX_ENTER(&conn->conn_data_lock);
3488     skew = conn->lastSerial - np->header.serial;
3489     conn->lastSerial = np->header.serial;
3490     MUTEX_EXIT(&conn->conn_data_lock);
3491     if (skew > 0) {
3492         struct rx_peer *peer;
3493         peer = conn->peer;
3494         if (skew > peer->inPacketSkew) {
3495             dpf(("*** In skew changed from %d to %d\n",
3496                   peer->inPacketSkew, skew));
3497             peer->inPacketSkew = skew;
3498         }
3499     }
3500
3501     /* Now do packet type-specific processing */
3502     switch (np->header.type) {
3503     case RX_PACKET_TYPE_DATA:
3504         np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3505                                    newcallp);
3506         break;
3507     case RX_PACKET_TYPE_ACK:
3508         /* Respond immediately to ack packets requesting acknowledgement
3509          * (ping packets) */
3510         if (np->header.flags & RX_REQUEST_ACK) {
3511             if (call->error)
3512                 (void)rxi_SendCallAbort(call, 0, 1, 0);
3513             else
3514                 (void)rxi_SendAck(call, 0, np->header.serial,
3515                                   RX_ACK_PING_RESPONSE, 1);
3516         }
3517         np = rxi_ReceiveAckPacket(call, np, 1);
3518         break;
3519     case RX_PACKET_TYPE_ABORT: {
3520         /* An abort packet: reset the call, passing the error up to the user. */
3521         /* What if error is zero? */
3522         /* What if the error is -1? the application will treat it as a timeout. */
3523         afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3524         dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3525         rxi_CallError(call, errdata);
3526         MUTEX_EXIT(&call->lock);
3527         putConnection(conn);
3528         return np;              /* xmitting; drop packet */
3529     }
3530     case RX_PACKET_TYPE_BUSY: {
3531         struct clock busyTime;
3532         clock_NewTime();
3533         clock_GetTime(&busyTime);
3534
3535         MUTEX_EXIT(&call->lock);
3536
3537         MUTEX_ENTER(&conn->conn_call_lock);
3538         MUTEX_ENTER(&call->lock);
3539         conn->lastBusy[call->channel] = busyTime.sec;
3540         call->flags |= RX_CALL_PEER_BUSY;
3541         MUTEX_EXIT(&call->lock);
3542         MUTEX_EXIT(&conn->conn_call_lock);
3543
3544         putConnection(conn);
3545         return np;
3546     }
3547
3548     case RX_PACKET_TYPE_ACKALL:
3549         /* All packets acknowledged, so we can drop all packets previously
3550          * readied for sending */
3551 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
3552         /* XXX Hack. We because we can't release the global rx lock when
3553          * sending packets (osi_NetSend) we drop all ack pkts while we're
3554          * traversing the tq in rxi_Start sending packets out because
3555          * packets may move to the freePacketQueue as result of being
3556          * here! So we drop these packets until we're safely out of the
3557          * traversing. Really ugly!
3558          * For fine grain RX locking, we set the acked field in the packets
3559          * and let rxi_Start remove the packets from the transmit queue.
3560          */
3561         if (call->flags & RX_CALL_TQ_BUSY) {
3562 #ifdef  RX_ENABLE_LOCKS
3563             rxi_SetAcksInTransmitQueue(call);
3564             break;
3565 #else /* RX_ENABLE_LOCKS */
3566             MUTEX_EXIT(&call->lock);
3567             putConnection(conn);
3568             return np;          /* xmitting; drop packet */
3569 #endif /* RX_ENABLE_LOCKS */
3570         }
3571 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3572         rxi_ClearTransmitQueue(call, 0);
3573         break;
3574     default:
3575         /* Should not reach here, unless the peer is broken: send an abort
3576          * packet */
3577         rxi_CallError(call, RX_PROTOCOL_ERROR);
3578         np = rxi_SendCallAbort(call, np, 1, 0);
3579         break;
3580     };
3581     /* Note when this last legitimate packet was received, for keep-alive
3582      * processing.  Note, we delay getting the time until now in the hope that
3583      * the packet will be delivered to the user before any get time is required
3584      * (if not, then the time won't actually be re-evaluated here). */
3585     call->lastReceiveTime = clock_Sec();
3586     /* we've received a legit packet, so the channel is not busy */
3587     call->flags &= ~RX_CALL_PEER_BUSY;
3588     MUTEX_EXIT(&call->lock);
3589     putConnection(conn);
3590     return np;
3591 }
3592
3593 /* return true if this is an "interesting" connection from the point of view
3594     of someone trying to debug the system */
3595 int
3596 rxi_IsConnInteresting(struct rx_connection *aconn)
3597 {
3598     int i;
3599     struct rx_call *tcall;
3600
3601     if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3602         return 1;
3603
3604     for (i = 0; i < RX_MAXCALLS; i++) {
3605         tcall = aconn->call[i];
3606         if (tcall) {
3607             if ((tcall->state == RX_STATE_PRECALL)
3608                 || (tcall->state == RX_STATE_ACTIVE))
3609                 return 1;
3610             if ((tcall->mode == RX_MODE_SENDING)
3611                 || (tcall->mode == RX_MODE_RECEIVING))
3612                 return 1;
3613         }
3614     }
3615     return 0;
3616 }
3617
3618 #ifdef KERNEL
3619 /* if this is one of the last few packets AND it wouldn't be used by the
3620    receiving call to immediately satisfy a read request, then drop it on
3621    the floor, since accepting it might prevent a lock-holding thread from
3622    making progress in its reading. If a call has been cleared while in
3623    the precall state then ignore all subsequent packets until the call
3624    is assigned to a thread. */
3625
3626 static int
3627 TooLow(struct rx_packet *ap, struct rx_call *acall)
3628 {
3629     int rc = 0;
3630
3631     MUTEX_ENTER(&rx_quota_mutex);
3632     if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3633          && (acall->state == RX_STATE_PRECALL))
3634         || ((rx_nFreePackets < rxi_dataQuota + 2)
3635             && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3636                  && (acall->flags & RX_CALL_READER_WAIT)))) {
3637         rc = 1;
3638     }
3639     MUTEX_EXIT(&rx_quota_mutex);
3640     return rc;
3641 }
3642 #endif /* KERNEL */
3643
3644 /*!
3645  * Clear the attach wait flag on a connection and proceed.
3646  *
3647  * Any processing waiting for a connection to be attached should be
3648  * unblocked. We clear the flag and do any other needed tasks.
3649  *
3650  * @param[in] conn
3651  *      the conn to unmark waiting for attach
3652  *
3653  * @pre conn's conn_data_lock must be locked before calling this function
3654  *
3655  */
3656 static void
3657 rxi_ConnClearAttachWait(struct rx_connection *conn)
3658 {
3659     /* Indicate that rxi_CheckReachEvent is no longer running by
3660      * clearing the flag.  Must be atomic under conn_data_lock to
3661      * avoid a new call slipping by: rxi_CheckConnReach holds
3662      * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3663      */
3664     conn->flags &= ~RX_CONN_ATTACHWAIT;
3665     if (conn->flags & RX_CONN_NAT_PING) {
3666         conn->flags &= ~RX_CONN_NAT_PING;
3667         rxi_ScheduleNatKeepAliveEvent(conn);
3668     }
3669 }
3670
3671 static void
3672 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2, int dummy)
3673 {
3674     struct rx_connection *conn = arg1;
3675     struct rx_call *acall = arg2;
3676     struct rx_call *call = acall;
3677     struct clock when, now;
3678     int i, waiting;
3679
3680     MUTEX_ENTER(&conn->conn_data_lock);
3681
3682     if (event) {
3683         rxevent_Put(conn->checkReachEvent);
3684         conn->checkReachEvent = NULL;
3685     }
3686
3687     waiting = conn->flags & RX_CONN_ATTACHWAIT;
3688     if (event) {
3689         putConnection(conn);
3690     }
3691     MUTEX_EXIT(&conn->conn_data_lock);
3692
3693     if (waiting) {
3694         if (!call) {
3695             MUTEX_ENTER(&conn->conn_call_lock);
3696             MUTEX_ENTER(&conn->conn_data_lock);
3697             for (i = 0; i < RX_MAXCALLS; i++) {
3698                 struct rx_call *tc = conn->call[i];
3699                 if (tc && tc->state == RX_STATE_PRECALL) {
3700                     call = tc;
3701                     break;
3702                 }
3703             }
3704             if (!call)
3705                 rxi_ConnClearAttachWait(conn);
3706             MUTEX_EXIT(&conn->conn_data_lock);
3707             MUTEX_EXIT(&conn->conn_call_lock);
3708         }
3709
3710         if (call) {
3711             if (call != acall)
3712                 MUTEX_ENTER(&call->lock);
3713             rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3714             if (call != acall)
3715                 MUTEX_EXIT(&call->lock);
3716
3717             clock_GetTime(&now);
3718             when = now;
3719             when.sec += RX_CHECKREACH_TIMEOUT;
3720             MUTEX_ENTER(&conn->conn_data_lock);
3721             if (!conn->checkReachEvent) {
3722                 MUTEX_ENTER(&rx_refcnt_mutex);
3723                 conn->refCount++;
3724                 MUTEX_EXIT(&rx_refcnt_mutex);
3725                 conn->checkReachEvent = rxevent_Post(&when, &now,
3726                                                      rxi_CheckReachEvent, conn,
3727                                                      NULL, 0);
3728             }
3729             MUTEX_EXIT(&conn->conn_data_lock);
3730         }
3731     }
3732 }
3733
3734 static int
3735 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3736 {
3737     struct rx_service *service = conn->service;
3738     struct rx_peer *peer = conn->peer;
3739     afs_uint32 now, lastReach;
3740
3741     if (service->checkReach == 0)
3742         return 0;
3743
3744     now = clock_Sec();
3745     MUTEX_ENTER(&peer->peer_lock);
3746     lastReach = peer->lastReachTime;
3747     MUTEX_EXIT(&peer->peer_lock);
3748     if (now - lastReach < RX_CHECKREACH_TTL)
3749         return 0;
3750
3751     MUTEX_ENTER(&conn->conn_data_lock);
3752     if (conn->flags & RX_CONN_ATTACHWAIT) {
3753         MUTEX_EXIT(&conn->conn_data_lock);
3754         return 1;
3755     }
3756     conn->flags |= RX_CONN_ATTACHWAIT;
3757     MUTEX_EXIT(&conn->conn_data_lock);
3758     if (!conn->checkReachEvent)
3759         rxi_CheckReachEvent(NULL, conn, call, 0);
3760
3761     return 1;
3762 }
3763
3764 /* try to attach call, if authentication is complete */
3765 static void
3766 TryAttach(struct rx_call *acall, osi_socket socket,
3767           int *tnop, struct rx_call **newcallp,
3768           int reachOverride)
3769 {
3770     struct rx_connection *conn = acall->conn;
3771
3772     if (conn->type == RX_SERVER_CONNECTION
3773         && acall->state == RX_STATE_PRECALL) {
3774         /* Don't attach until we have any req'd. authentication. */
3775         if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3776             if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3777                 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3778             /* Note:  this does not necessarily succeed; there
3779              * may not any proc available
3780              */
3781         } else {
3782             rxi_ChallengeOn(acall->conn);
3783         }
3784     }
3785 }
3786
3787 /* A data packet has been received off the interface.  This packet is
3788  * appropriate to the call (the call is in the right state, etc.).  This
3789  * routine can return a packet to the caller, for re-use */
3790
3791 struct rx_packet *
3792 rxi_ReceiveDataPacket(struct rx_call *call,
3793                       struct rx_packet *np, int istack,
3794                       osi_socket socket, afs_uint32 host, u_short port,
3795                       int *tnop, struct rx_call **newcallp)
3796 {
3797     int ackNeeded = 0;          /* 0 means no, otherwise ack_reason */
3798     int newPackets = 0;
3799     int didHardAck = 0;
3800     int haveLast = 0;
3801     afs_uint32 seq;
3802     afs_uint32 serial=0, flags=0;
3803     int isFirst;
3804     struct rx_packet *tnp;
3805     if (rx_stats_active)
3806         rx_atomic_inc(&rx_stats.dataPacketsRead);
3807
3808 #ifdef KERNEL
3809     /* If there are no packet buffers, drop this new packet, unless we can find
3810      * packet buffers from inactive calls */
3811     if (!call->error
3812         && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3813         MUTEX_ENTER(&rx_freePktQ_lock);
3814         rxi_NeedMorePackets = TRUE;
3815         MUTEX_EXIT(&rx_freePktQ_lock);
3816         if (rx_stats_active)
3817             rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3818         call->rprev = np->header.serial;
3819         rxi_calltrace(RX_TRACE_DROP, call);
3820         dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems\n", np));
3821         /* We used to clear the receive queue here, in an attempt to free
3822          * packets. However this is unsafe if the queue has received a
3823          * soft ACK for the final packet */
3824         rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
3825
3826         /* we've damaged this call already, might as well do it in. */
3827         return np;
3828     }
3829 #endif /* KERNEL */
3830
3831     /*
3832      * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3833      * packet is one of several packets transmitted as a single
3834      * datagram. Do not send any soft or hard acks until all packets
3835      * in a jumbogram have been processed. Send negative acks right away.
3836      */
3837     for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3838         /* tnp is non-null when there are more packets in the
3839          * current jumbo gram */
3840         if (tnp) {
3841             if (np)
3842                 rxi_FreePacket(np);
3843             np = tnp;
3844         }
3845
3846         seq = np->header.seq;
3847         serial = np->header.serial;
3848         flags = np->header.flags;
3849
3850         /* If the call is in an error state, send an abort message */
3851         if (call->error)
3852             return rxi_SendCallAbort(call, np, istack, 0);
3853
3854         /* The RX_JUMBO_PACKET is set in all but the last packet in each
3855          * AFS 3.5 jumbogram. */
3856         if (flags & RX_JUMBO_PACKET) {
3857             tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3858         } else {
3859             tnp = NULL;
3860         }
3861
3862         if (np->header.spare != 0) {
3863             MUTEX_ENTER(&call->conn->conn_data_lock);
3864             call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3865             MUTEX_EXIT(&call->conn->conn_data_lock);
3866         }
3867
3868         /* The usual case is that this is the expected next packet */
3869         if (seq == call->rnext) {
3870
3871             /* Check to make sure it is not a duplicate of one already queued */
3872             if (queue_IsNotEmpty(&call->rq)
3873                 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3874                 if (rx_stats_active)
3875                     rx_atomic_inc(&rx_stats.dupPacketsRead);
3876                 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate\n", np));
3877                 rxevent_Cancel(&call->delayedAckEvent, call,
3878                                RX_CALL_REFCOUNT_DELAY);
3879                 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3880                 ackNeeded = 0;
3881                 call->rprev = seq;
3882                 continue;
3883             }
3884
3885             /* It's the next packet. Stick it on the receive queue
3886              * for this call. Set newPackets to make sure we wake
3887              * the reader once all packets have been processed */
3888 #ifdef RX_TRACK_PACKETS
3889             np->flags |= RX_PKTFLAG_RQ;
3890 #endif
3891             queue_Prepend(&call->rq, np);
3892 #ifdef RXDEBUG_PACKET
3893             call->rqc++;
3894 #endif /* RXDEBUG_PACKET */
3895             call->nSoftAcks++;
3896             np = NULL;          /* We can't use this anymore */
3897             newPackets = 1;
3898
3899             /* If an ack is requested then set a flag to make sure we
3900              * send an acknowledgement for this packet */
3901             if (flags & RX_REQUEST_ACK) {
3902                 ackNeeded = RX_ACK_REQUESTED;
3903             }
3904
3905             /* Keep track of whether we have received the last packet */
3906             if (flags & RX_LAST_PACKET) {
3907                 call->flags |= RX_CALL_HAVE_LAST;
3908                 haveLast = 1;
3909             }
3910
3911             /* Check whether we have all of the packets for this call */
3912             if (call->flags & RX_CALL_HAVE_LAST) {
3913                 afs_uint32 tseq;        /* temporary sequence number */
3914                 struct rx_packet *tp;   /* Temporary packet pointer */
3915                 struct rx_packet *nxp;  /* Next pointer, for queue_Scan */
3916
3917                 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3918                     if (tseq != tp->header.seq)
3919                         break;
3920                     if (tp->header.flags & RX_LAST_PACKET) {
3921                         call->flags |= RX_CALL_RECEIVE_DONE;
3922                         break;
3923                     }
3924                     tseq++;
3925                 }
3926             }
3927
3928             /* Provide asynchronous notification for those who want it
3929              * (e.g. multi rx) */
3930             if (call->arrivalProc) {
3931                 (*call->arrivalProc) (call, call->arrivalProcHandle,
3932                                       call->arrivalProcArg);
3933                 call->arrivalProc = (void (*)())0;
3934             }
3935
3936             /* Update last packet received */
3937             call->rprev = seq;
3938
3939             /* If there is no server process serving this call, grab
3940              * one, if available. We only need to do this once. If a
3941              * server thread is available, this thread becomes a server
3942              * thread and the server thread becomes a listener thread. */
3943             if (isFirst) {
3944                 TryAttach(call, socket, tnop, newcallp, 0);
3945             }
3946         }
3947         /* This is not the expected next packet. */
3948         else {
3949             /* Determine whether this is a new or old packet, and if it's
3950              * a new one, whether it fits into the current receive window.
3951              * Also figure out whether the packet was delivered in sequence.
3952              * We use the prev variable to determine whether the new packet
3953              * is the successor of its immediate predecessor in the
3954              * receive queue, and the missing flag to determine whether
3955              * any of this packets predecessors are missing.  */
3956
3957             afs_uint32 prev;    /* "Previous packet" sequence number */
3958             struct rx_packet *tp;       /* Temporary packet pointer */
3959             struct rx_packet *nxp;      /* Next pointer, for queue_Scan */
3960             int missing;        /* Are any predecessors missing? */
3961
3962             /* If the new packet's sequence number has been sent to the
3963              * application already, then this is a duplicate */
3964             if (seq < call->rnext) {
3965                 if (rx_stats_active)
3966                     rx_atomic_inc(&rx_stats.dupPacketsRead);
3967                 rxevent_Cancel(&call->delayedAckEvent, call,
3968                                RX_CALL_REFCOUNT_DELAY);
3969                 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3970                 ackNeeded = 0;
3971                 call->rprev = seq;
3972                 continue;
3973             }
3974
3975             /* If the sequence number is greater than what can be
3976              * accomodated by the current window, then send a negative
3977              * acknowledge and drop the packet */
3978             if ((call->rnext + call->rwind) <= seq) {
3979                 rxevent_Cancel(&call->delayedAckEvent, call,
3980                                RX_CALL_REFCOUNT_DELAY);
3981                 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3982                                  istack);
3983                 ackNeeded = 0;
3984                 call->rprev = seq;
3985                 continue;
3986             }
3987
3988             /* Look for the packet in the queue of old received packets */
3989             for (prev = call->rnext - 1, missing =
3990                  0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3991                 /*Check for duplicate packet */
3992                 if (seq == tp->header.seq) {
3993                     if (rx_stats_active)
3994                         rx_atomic_inc(&rx_stats.dupPacketsRead);
3995                     rxevent_Cancel(&call->delayedAckEvent, call,
3996                                    RX_CALL_REFCOUNT_DELAY);
3997                     np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3998                                      istack);
3999                     ackNeeded = 0;
4000                     call->rprev = seq;
4001                     goto nextloop;
4002                 }
4003                 /* If we find a higher sequence packet, break out and
4004                  * insert the new packet here. */
4005                 if (seq < tp->header.seq)
4006                     break;
4007                 /* Check for missing packet */
4008                 if (tp->header.seq != prev + 1) {
4009                     missing = 1;
4010                 }
4011
4012                 prev = tp->header.seq;
4013             }
4014
4015             /* Keep track of whether we have received the last packet. */
4016             if (flags & RX_LAST_PACKET) {
4017                 call->flags |= RX_CALL_HAVE_LAST;
4018             }
4019
4020             /* It's within the window: add it to the the receive queue.
4021              * tp is left by the previous loop either pointing at the
4022              * packet before which to insert the new packet, or at the
4023              * queue head if the queue is empty or the packet should be
4024              * appended. */
4025 #ifdef RX_TRACK_PACKETS
4026             np->flags |= RX_PKTFLAG_RQ;
4027 #endif
4028 #ifdef RXDEBUG_PACKET
4029             call->rqc++;
4030 #endif /* RXDEBUG_PACKET */
4031             queue_InsertBefore(tp, np);
4032             call->nSoftAcks++;
4033             np = NULL;
4034
4035             /* Check whether we have all of the packets for this call */
4036             if ((call->flags & RX_CALL_HAVE_LAST)
4037                 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
4038                 afs_uint32 tseq;        /* temporary sequence number */
4039
4040                 for (tseq =
4041                      call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
4042                     if (tseq != tp->header.seq)
4043                         break;
4044                     if (tp->header.flags & RX_LAST_PACKET) {
4045                         call->flags |= RX_CALL_RECEIVE_DONE;
4046                         break;
4047                     }
4048                     tseq++;
4049                 }
4050             }
4051
4052             /* We need to send an ack of the packet is out of sequence,
4053              * or if an ack was requested by the peer. */
4054             if (seq != prev + 1 || missing) {
4055                 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
4056             } else if (flags & RX_REQUEST_ACK) {
4057                 ackNeeded = RX_ACK_REQUESTED;
4058             }
4059
4060             /* Acknowledge the last packet for each call */
4061             if (flags & RX_LAST_PACKET) {
4062                 haveLast = 1;
4063             }
4064
4065             call->rprev = seq;
4066         }
4067       nextloop:;
4068     }
4069
4070     if (newPackets) {
4071         /*
4072          * If the receiver is waiting for an iovec, fill the iovec
4073          * using the data from the receive queue */
4074         if (call->flags & RX_CALL_IOVEC_WAIT) {
4075             didHardAck = rxi_FillReadVec(call, serial);
4076             /* the call may have been aborted */
4077             if (call->error) {
4078                 return NULL;
4079             }
4080             if (didHardAck) {
4081                 ackNeeded = 0;
4082             }
4083         }
4084
4085         /* Wakeup the reader if any */
4086         if ((call->flags & RX_CALL_READER_WAIT)
4087             && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
4088                 || (call->iovNext >= call->iovMax)
4089                 || (call->flags & RX_CALL_RECEIVE_DONE))) {
4090             call->flags &= ~RX_CALL_READER_WAIT;
4091 #ifdef  RX_ENABLE_LOCKS
4092             CV_BROADCAST(&call->cv_rq);
4093 #else
4094             osi_rxWakeup(&call->rq);
4095 #endif
4096         }
4097     }
4098
4099     /*
4100      * Send an ack when requested by the peer, or once every
4101      * rxi_SoftAckRate packets until the last packet has been
4102      * received. Always send a soft ack for the last packet in
4103      * the server's reply. */
4104     if (ackNeeded) {
4105         rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4106         np = rxi_SendAck(call, np, serial, ackNeeded, istack);
4107     } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
4108         rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4109         np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
4110     } else if (call->nSoftAcks) {
4111         if (haveLast && !(flags & RX_CLIENT_INITIATED))
4112             rxi_PostDelayedAckEvent(call, &rx_lastAckDelay);
4113         else
4114             rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
4115     } else if (call->flags & RX_CALL_RECEIVE_DONE) {
4116         rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
4117     }
4118
4119     return np;
4120 }
4121
4122 static void
4123 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
4124 {
4125     struct rx_peer *peer = conn->peer;
4126
4127     MUTEX_ENTER(&peer->peer_lock);
4128     peer->lastReachTime = clock_Sec();
4129     MUTEX_EXIT(&peer->peer_lock);
4130
4131     MUTEX_ENTER(&conn->conn_data_lock);
4132     if (conn->flags & RX_CONN_ATTACHWAIT) {
4133         int i;
4134
4135         rxi_ConnClearAttachWait(conn);
4136         MUTEX_EXIT(&conn->conn_data_lock);
4137
4138         for (i = 0; i < RX_MAXCALLS; i++) {
4139             struct rx_call *call = conn->call[i];
4140             if (call) {
4141                 if (call != acall)
4142                     MUTEX_ENTER(&call->lock);
4143                 /* tnop can be null if newcallp is null */
4144                 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
4145                 if (call != acall)
4146                     MUTEX_EXIT(&call->lock);
4147             }
4148         }
4149     } else
4150         MUTEX_EXIT(&conn->conn_data_lock);
4151 }
4152
4153 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
4154 static const char *
4155 rx_ack_reason(int reason)
4156 {
4157     switch (reason) {
4158     case RX_ACK_REQUESTED:
4159         return "requested";
4160     case RX_ACK_DUPLICATE:
4161         return "duplicate";
4162     case RX_ACK_OUT_OF_SEQUENCE:
4163         return "sequence";
4164     case RX_ACK_EXCEEDS_WINDOW:
4165         return "window";
4166     case RX_ACK_NOSPACE:
4167         return "nospace";
4168     case RX_ACK_PING:
4169         return "ping";
4170     case RX_ACK_PING_RESPONSE:
4171         return "response";
4172     case RX_ACK_DELAY:
4173         return "delay";
4174     case RX_ACK_IDLE:
4175         return "idle";
4176     default:
4177         return "unknown!!";
4178     }
4179 }
4180 #endif
4181
4182
4183 /* The real smarts of the whole thing.  */
4184 struct rx_packet *
4185 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
4186                      int istack)
4187 {
4188     struct rx_ackPacket *ap;
4189     int nAcks;
4190     struct rx_packet *tp;
4191     struct rx_packet *nxp;      /* Next packet pointer for queue_Scan */
4192     struct rx_connection *conn = call->conn;
4193     struct rx_peer *peer = conn->peer;
4194     struct clock now;           /* Current time, for RTT calculations */
4195     afs_uint32 first;
4196     afs_uint32 prev;
4197     afs_uint32 serial;
4198     /* because there are CM's that are bogus, sending weird values for this. */
4199     afs_uint32 skew = 0;
4200     int nbytes;
4201     int missing;
4202     int acked;
4203     int nNacked = 0;
4204     int newAckCount = 0;
4205     int maxDgramPackets = 0;    /* Set if peer supports AFS 3.5 jumbo datagrams */
4206     int pktsize = 0;            /* Set if we need to update the peer mtu */
4207     int conn_data_locked = 0;
4208
4209     if (rx_stats_active)
4210         rx_atomic_inc(&rx_stats.ackPacketsRead);
4211     ap = (struct rx_ackPacket *)rx_DataOf(np);
4212     nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
4213     if (nbytes < 0)
4214         return np;              /* truncated ack packet */
4215
4216     /* depends on ack packet struct */
4217     nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
4218     first = ntohl(ap->firstPacket);
4219     prev = ntohl(ap->previousPacket);
4220     serial = ntohl(ap->serial);
4221     /* temporarily disabled -- needs to degrade over time
4222      * skew = ntohs(ap->maxSkew); */
4223
4224     /* Ignore ack packets received out of order */
4225     if (first < call->tfirst ||
4226         (first == call->tfirst && prev < call->tprev)) {
4227         return np;
4228     }
4229
4230     call->tprev = prev;
4231
4232     if (np->header.flags & RX_SLOW_START_OK) {
4233         call->flags |= RX_CALL_SLOW_START_OK;
4234     }
4235
4236     if (ap->reason == RX_ACK_PING_RESPONSE)
4237         rxi_UpdatePeerReach(conn, call);
4238
4239     if (conn->lastPacketSizeSeq) {
4240         MUTEX_ENTER(&conn->conn_data_lock);
4241         conn_data_locked = 1;
4242         if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
4243             pktsize = conn->lastPacketSize;
4244             conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
4245         }
4246     }
4247     if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
4248         if (!conn_data_locked) {
4249             MUTEX_ENTER(&conn->conn_data_lock);
4250             conn_data_locked = 1;
4251         }
4252         if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
4253             /* process mtu ping ack */
4254             pktsize = conn->lastPingSize;
4255             conn->lastPingSizeSer = conn->lastPingSize = 0;
4256         }
4257     }
4258
4259     if (conn_data_locked) {
4260         MUTEX_EXIT(&conn->conn_data_lock);
4261         conn_data_locked = 0;
4262     }
4263 #ifdef RXDEBUG
4264 #ifdef AFS_NT40_ENV
4265     if (rxdebug_active) {
4266         char msg[512];
4267         size_t len;
4268
4269         len = _snprintf(msg, sizeof(msg),
4270                         "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
4271                          GetCurrentThreadId(), rx_ack_reason(ap->reason),
4272                          ntohl(ap->serial), ntohl(ap->previousPacket),
4273                          (unsigned int)np->header.seq, (unsigned int)skew,
4274                          ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
4275         if (nAcks) {
4276             int offset;
4277
4278             for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
4279                 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4280         }
4281         msg[len++]='\n';
4282         msg[len] = '\0';
4283         OutputDebugString(msg);
4284     }
4285 #else /* AFS_NT40_ENV */
4286     if (rx_Log) {
4287         fprintf(rx_Log,
4288                 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
4289                 ap->reason, ntohl(ap->previousPacket),
4290                 (unsigned int)np->header.seq, (unsigned int)serial,
4291                 (unsigned int)skew, ntohl(ap->firstPacket));
4292         if (nAcks) {
4293             int offset;
4294             for (offset = 0; offset < nAcks; offset++)
4295                 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4296                      rx_Log);
4297         }
4298         putc('\n', rx_Log);
4299     }
4300 #endif /* AFS_NT40_ENV */
4301 #endif
4302
4303     MUTEX_ENTER(&peer->peer_lock);
4304     if (pktsize) {
4305         /*
4306          * Start somewhere. Can't assume we can send what we can receive,
4307          * but we are clearly receiving.
4308          */
4309         if (!peer->maxPacketSize)
4310             peer->maxPacketSize = RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE;
4311
4312         if (pktsize > peer->maxPacketSize) {
4313             peer->maxPacketSize = pktsize;
4314             if ((pktsize-RX_IPUDP_SIZE > peer->ifMTU)) {
4315                 peer->ifMTU=pktsize-RX_IPUDP_SIZE;
4316                 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4317                 rxi_ScheduleGrowMTUEvent(call, 1);
4318             }
4319         }
4320     }
4321
4322     /* Update the outgoing packet skew value to the latest value of
4323      * the peer's incoming packet skew value.  The ack packet, of
4324      * course, could arrive out of order, but that won't affect things
4325      * much */
4326     peer->outPacketSkew = skew;
4327
4328
4329     clock_GetTime(&now);
4330
4331     /* The transmit queue splits into 4 sections.
4332      *
4333      * The first section is packets which have now been acknowledged
4334      * by a window size change in the ack. These have reached the
4335      * application layer, and may be discarded. These are packets
4336      * with sequence numbers < ap->firstPacket.
4337      *
4338      * The second section is packets which have sequence numbers in
4339      * the range ap->firstPacket to ap->firstPacket + ap->nAcks. The
4340      * contents of the packet's ack array determines whether these
4341      * packets are acknowledged or not.
4342      *
4343      * The third section is packets which fall above the range
4344      * addressed in the ack packet. These have not yet been received
4345      * by the peer.
4346      *
4347      * The four section is packets which have not yet been transmitted.
4348      * These packets will have a header.serial of 0.
4349      */
4350
4351     /* First section - implicitly acknowledged packets that can be
4352      * disposed of
4353      */
4354
4355     tp = queue_First(&call->tq, rx_packet);
4356     while(!queue_IsEnd(&call->tq, tp) && tp->header.seq < first) {
4357         struct rx_packet *next;
4358
4359         next = queue_Next(tp, rx_packet);
4360         call->tfirst = tp->header.seq + 1;
4361
4362         if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4363             newAckCount++;
4364             rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4365         }
4366
4367 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
4368         /* XXX Hack. Because we have to release the global rx lock when sending
4369          * packets (osi_NetSend) we drop all acks while we're traversing the tq
4370          * in rxi_Start sending packets out because packets may move to the
4371          * freePacketQueue as result of being here! So we drop these packets until
4372          * we're safely out of the traversing. Really ugly!
4373          * To make it even uglier, if we're using fine grain locking, we can
4374          * set the ack bits in the packets and have rxi_Start remove the packets
4375          * when it's done transmitting.
4376          */
4377         if (call->flags & RX_CALL_TQ_BUSY) {
4378 #ifdef RX_ENABLE_LOCKS
4379             tp->flags |= RX_PKTFLAG_ACKED;
4380             call->flags |= RX_CALL_TQ_SOME_ACKED;
4381 #else /* RX_ENABLE_LOCKS */
4382             break;
4383 #endif /* RX_ENABLE_LOCKS */
4384         } else
4385 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4386         {
4387             queue_Remove(tp);
4388 #ifdef RX_TRACK_PACKETS
4389             tp->flags &= ~RX_PKTFLAG_TQ;
4390 #endif
4391 #ifdef RXDEBUG_PACKET
4392             call->tqc--;
4393 #endif /* RXDEBUG_PACKET */
4394             rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4395         }
4396         tp = next;
4397     }
4398
4399     /* N.B. we don't turn off any timers here.  They'll go away by themselves, anyway */
4400
4401     /* Second section of the queue - packets for which we are receiving
4402      * soft ACKs
4403      *
4404      * Go through the explicit acks/nacks and record the results in
4405      * the waiting packets.  These are packets that can't be released
4406      * yet, even with a positive acknowledge.  This positive
4407      * acknowledge only means the packet has been received by the
4408      * peer, not that it will be retained long enough to be sent to
4409      * the peer's upper level.  In addition, reset the transmit timers
4410      * of any missing packets (those packets that must be missing
4411      * because this packet was out of sequence) */
4412
4413     call->nSoftAcked = 0;
4414     missing = 0;
4415     while (!queue_IsEnd(&call->tq, tp) && tp->header.seq < first + nAcks) {
4416         /* Set the acknowledge flag per packet based on the
4417          * information in the ack packet. An acknowlegded packet can
4418          * be downgraded when the server has discarded a packet it
4419          * soacked previously, or when an ack packet is received
4420          * out of sequence. */
4421         if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4422             if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4423                 newAckCount++;
4424                 tp->flags |= RX_PKTFLAG_ACKED;
4425                 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4426             }
4427             if (missing) {
4428                 nNacked++;
4429             } else {
4430                 call->nSoftAcked++;
4431             }
4432         } else /* RX_ACK_TYPE_NACK */ {
4433             tp->flags &= ~RX_PKTFLAG_ACKED;
4434             missing = 1;
4435         }
4436
4437         tp = queue_Next(tp, rx_packet);
4438     }
4439
4440     /* We don't need to take any action with the 3rd or 4th section in the
4441      * queue - they're not addressed by the contents of this ACK packet.
4442      */
4443
4444     /* If the window has been extended by this acknowledge packet,
4445      * then wakeup a sender waiting in alloc for window space, or try
4446      * sending packets now, if he's been sitting on packets due to
4447      * lack of window space */
4448     if (call->tnext < (call->tfirst + call->twind)) {
4449 #ifdef  RX_ENABLE_LOCKS
4450         CV_SIGNAL(&call->cv_twind);
4451 #else
4452         if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4453             call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4454             osi_rxWakeup(&call->twind);
4455         }
4456 #endif
4457         if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4458             call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4459         }
4460     }
4461
4462     /* if the ack packet has a receivelen field hanging off it,
4463      * update our state */
4464     if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4465         afs_uint32 tSize;
4466
4467         /* If the ack packet has a "recommended" size that is less than
4468          * what I am using now, reduce my size to match */
4469         rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4470                       (int)sizeof(afs_int32), &tSize);
4471         tSize = (afs_uint32) ntohl(tSize);
4472         peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4473
4474         /* Get the maximum packet size to send to this peer */
4475         rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4476                       &tSize);
4477         tSize = (afs_uint32) ntohl(tSize);
4478         tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4479         tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4480
4481         /* sanity check - peer might have restarted with different params.
4482          * If peer says "send less", dammit, send less...  Peer should never
4483          * be unable to accept packets of the size that prior AFS versions would
4484          * send without asking.  */
4485         if (peer->maxMTU != tSize) {
4486             if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4487                 peer->congestSeq++;
4488             peer->maxMTU = tSize;
4489             peer->MTU = MIN(tSize, peer->MTU);
4490             call->MTU = MIN(call->MTU, tSize);
4491         }
4492
4493         if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4494             /* AFS 3.4a */
4495             rx_packetread(np,
4496                           rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4497                           (int)sizeof(afs_int32), &tSize);
4498             tSize = (afs_uint32) ntohl(tSize);  /* peer's receive window, if it's */
4499             if (tSize < call->twind) {  /* smaller than our send */
4500                 call->twind = tSize;    /* window, we must send less... */
4501                 call->ssthresh = MIN(call->twind, call->ssthresh);
4502                 call->conn->twind[call->channel] = call->twind;
4503             }
4504
4505             /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4506              * network MTU confused with the loopback MTU. Calculate the
4507              * maximum MTU here for use in the slow start code below.
4508              */
4509             /* Did peer restart with older RX version? */
4510             if (peer->maxDgramPackets > 1) {
4511                 peer->maxDgramPackets = 1;
4512             }
4513         } else if (np->length >=
4514                    rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4515             /* AFS 3.5 */
4516             rx_packetread(np,
4517                           rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4518                           sizeof(afs_int32), &tSize);
4519             tSize = (afs_uint32) ntohl(tSize);
4520             /*
4521              * As of AFS 3.5 we set the send window to match the receive window.
4522              */
4523             if (tSize < call->twind) {
4524                 call->twind = tSize;
4525                 call->conn->twind[call->channel] = call->twind;
4526                 call->ssthresh = MIN(call->twind, call->ssthresh);
4527             } else if (tSize > call->twind) {
4528                 call->twind = tSize;
4529                 call->conn->twind[call->channel] = call->twind;
4530             }
4531
4532             /*
4533              * As of AFS 3.5, a jumbogram is more than one fixed size
4534              * packet transmitted in a single UDP datagram. If the remote
4535              * MTU is smaller than our local MTU then never send a datagram
4536              * larger than the natural MTU.
4537              */
4538             rx_packetread(np,
4539                           rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4540                           (int)sizeof(afs_int32), &tSize);
4541             maxDgramPackets = (afs_uint32) ntohl(tSize);
4542             maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4543             maxDgramPackets =
4544                 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4545             if (maxDgramPackets > 1) {
4546                 peer->maxDgramPackets = maxDgramPackets;
4547                 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4548             } else {
4549                 peer->maxDgramPackets = 1;
4550                 call->MTU = peer->natMTU;
4551             }
4552         } else if (peer->maxDgramPackets > 1) {
4553             /* Restarted with lower version of RX */
4554             peer->maxDgramPackets = 1;
4555         }
4556     } else if (peer->maxDgramPackets > 1
4557                || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4558         /* Restarted with lower version of RX */
4559         peer->maxMTU = OLD_MAX_PACKET_SIZE;
4560         peer->natMTU = OLD_MAX_PACKET_SIZE;
4561         peer->MTU = OLD_MAX_PACKET_SIZE;
4562         peer->maxDgramPackets = 1;
4563         peer->nDgramPackets = 1;
4564         peer->congestSeq++;
4565         call->MTU = OLD_MAX_PACKET_SIZE;
4566     }
4567
4568     if (nNacked) {
4569         /*
4570          * Calculate how many datagrams were successfully received after
4571          * the first missing packet and adjust the negative ack counter
4572          * accordingly.
4573          */
4574         call->nAcks = 0;
4575         call->nNacks++;
4576         nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4577         if (call->nNacks < nNacked) {
4578             call->nNacks = nNacked;
4579         }
4580     } else {
4581         call->nAcks += newAckCount;
4582         call->nNacks = 0;
4583     }
4584
4585     /* If the packet contained new acknowledgements, rather than just
4586      * being a duplicate of one we have previously seen, then we can restart
4587      * the RTT timer
4588      */
4589     if (newAckCount > 0)
4590         rxi_rto_packet_acked(call, istack);
4591
4592     if (call->flags & RX_CALL_FAST_RECOVER) {
4593         if (newAckCount == 0) {
4594             call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4595         } else {
4596             call->flags &= ~RX_CALL_FAST_RECOVER;
4597             call->cwind = call->nextCwind;
4598             call->nextCwind = 0;
4599             call->nAcks = 0;
4600         }
4601         call->nCwindAcks = 0;
4602     } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4603         /* Three negative acks in a row trigger congestion recovery */
4604         call->flags |= RX_CALL_FAST_RECOVER;
4605         call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4606         call->cwind =
4607             MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4608         call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4609         call->nextCwind = call->ssthresh;
4610         call->nAcks = 0;
4611         call->nNacks = 0;
4612         peer->MTU = call->MTU;
4613         peer->cwind = call->nextCwind;
4614         peer->nDgramPackets = call->nDgramPackets;
4615         peer->congestSeq++;
4616         call->congestSeq = peer->congestSeq;
4617
4618         /* Reset the resend times on the packets that were nacked
4619          * so we will retransmit as soon as the window permits
4620          */
4621
4622         for (acked = 0, queue_ScanBackwards(&call->tq, tp, nxp, rx_packet)) {
4623             if (acked) {
4624                 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4625                     tp->flags &= ~RX_PKTFLAG_SENT;
4626                 }
4627             } else if (tp->flags & RX_PKTFLAG_ACKED) {
4628                 acked = 1;
4629             }
4630         }
4631     } else {
4632         /* If cwind is smaller than ssthresh, then increase
4633          * the window one packet for each ack we receive (exponential
4634          * growth).
4635          * If cwind is greater than or equal to ssthresh then increase
4636          * the congestion window by one packet for each cwind acks we
4637          * receive (linear growth).  */
4638         if (call->cwind < call->ssthresh) {
4639             call->cwind =
4640                 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4641             call->nCwindAcks = 0;
4642         } else {
4643             call->nCwindAcks += newAckCount;
4644             if (call->nCwindAcks >= call->cwind) {
4645                 call->nCwindAcks = 0;
4646                 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4647             }
4648         }
4649         /*
4650          * If we have received several acknowledgements in a row then
4651          * it is time to increase the size of our datagrams
4652          */
4653         if ((int)call->nAcks > rx_nDgramThreshold) {
4654             if (peer->maxDgramPackets > 1) {
4655                 if (call->nDgramPackets < peer->maxDgramPackets) {
4656                     call->nDgramPackets++;
4657                 }
4658                 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4659             } else if (call->MTU < peer->maxMTU) {
4660                 /* don't upgrade if we can't handle it */
4661                 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4662                     call->MTU = peer->ifMTU;
4663                 else {
4664                     call->MTU += peer->natMTU;
4665                     call->MTU = MIN(call->MTU, peer->maxMTU);
4666                 }
4667             }
4668             call->nAcks = 0;
4669         }
4670     }
4671
4672     MUTEX_EXIT(&peer->peer_lock);       /* rxi_Start will lock peer. */
4673
4674     /* Servers need to hold the call until all response packets have
4675      * been acknowledged. Soft acks are good enough since clients
4676      * are not allowed to clear their receive queues. */
4677     if (call->state == RX_STATE_HOLD
4678         && call->tfirst + call->nSoftAcked >= call->tnext) {
4679         call->state = RX_STATE_DALLY;
4680         rxi_ClearTransmitQueue(call, 0);
4681         rxevent_Cancel(&call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
4682     } else if (!queue_IsEmpty(&call->tq)) {
4683         rxi_Start(call, istack);
4684     }
4685     return np;
4686 }
4687
4688 /* Received a response to a challenge packet */
4689 struct rx_packet *
4690 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4691                           struct rx_packet *np, int istack)
4692 {
4693     int error;
4694
4695     /* Ignore the packet if we're the client */
4696     if (conn->type == RX_CLIENT_CONNECTION)
4697         return np;
4698
4699     /* If already authenticated, ignore the packet (it's probably a retry) */
4700     if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4701         return np;
4702
4703     /* Otherwise, have the security object evaluate the response packet */
4704     error = RXS_CheckResponse(conn->securityObject, conn, np);
4705     if (error) {
4706         /* If the response is invalid, reset the connection, sending
4707          * an abort to the peer */
4708 #ifndef KERNEL
4709         rxi_Delay(1);
4710 #endif
4711         rxi_ConnectionError(conn, error);
4712         MUTEX_ENTER(&conn->conn_data_lock);
4713         np = rxi_SendConnectionAbort(conn, np, istack, 0);
4714         MUTEX_EXIT(&conn->conn_data_lock);
4715         return np;
4716     } else {
4717         /* If the response is valid, any calls waiting to attach
4718          * servers can now do so */
4719         int i;
4720
4721         for (i = 0; i < RX_MAXCALLS; i++) {
4722             struct rx_call *call = conn->call[i];
4723             if (call) {
4724                 MUTEX_ENTER(&call->lock);
4725                 if (call->state == RX_STATE_PRECALL)
4726                     rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4727                 /* tnop can be null if newcallp is null */
4728                 MUTEX_EXIT(&call->lock);
4729             }
4730         }
4731
4732         /* Update the peer reachability information, just in case
4733          * some calls went into attach-wait while we were waiting
4734          * for authentication..
4735          */
4736         rxi_UpdatePeerReach(conn, NULL);
4737     }
4738     return np;
4739 }
4740
4741 /* A client has received an authentication challenge: the security
4742  * object is asked to cough up a respectable response packet to send
4743  * back to the server.  The server is responsible for retrying the
4744  * challenge if it fails to get a response. */
4745
4746 struct rx_packet *
4747 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4748                            struct rx_packet *np, int istack)
4749 {
4750     int error;
4751
4752     /* Ignore the challenge if we're the server */
4753     if (conn->type == RX_SERVER_CONNECTION)
4754         return np;
4755
4756     /* Ignore the challenge if the connection is otherwise idle; someone's
4757      * trying to use us as an oracle. */
4758     if (!rxi_HasActiveCalls(conn))
4759         return np;
4760
4761     /* Send the security object the challenge packet.  It is expected to fill
4762      * in the response. */
4763     error = RXS_GetResponse(conn->securityObject, conn, np);
4764
4765     /* If the security object is unable to return a valid response, reset the
4766      * connection and send an abort to the peer.  Otherwise send the response
4767      * packet to the peer connection. */
4768     if (error) {
4769         rxi_ConnectionError(conn, error);
4770         MUTEX_ENTER(&conn->conn_data_lock);
4771         np = rxi_SendConnectionAbort(conn, np, istack, 0);
4772         MUTEX_EXIT(&conn->conn_data_lock);
4773     } else {
4774         np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4775                              RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4776     }
4777     return np;
4778 }
4779
4780
4781 /* Find an available server process to service the current request in
4782  * the given call structure.  If one isn't available, queue up this
4783  * call so it eventually gets one */
4784 void
4785 rxi_AttachServerProc(struct rx_call *call,
4786                      osi_socket socket, int *tnop,
4787                      struct rx_call **newcallp)
4788 {
4789     struct rx_serverQueueEntry *sq;
4790     struct rx_service *service = call->conn->service;
4791     int haveQuota = 0;
4792
4793     /* May already be attached */
4794     if (call->state == RX_STATE_ACTIVE)
4795         return;
4796
4797     MUTEX_ENTER(&rx_serverPool_lock);
4798
4799     haveQuota = QuotaOK(service);
4800     if ((!haveQuota) || queue_IsEmpty(&rx_idleServerQueue)) {
4801         /* If there are no processes available to service this call,
4802          * put the call on the incoming call queue (unless it's
4803          * already on the queue).
4804          */
4805 #ifdef RX_ENABLE_LOCKS
4806         if (haveQuota)
4807             ReturnToServerPool(service);
4808 #endif /* RX_ENABLE_LOCKS */
4809
4810         if (!(call->flags & RX_CALL_WAIT_PROC)) {
4811             call->flags |= RX_CALL_WAIT_PROC;
4812             rx_atomic_inc(&rx_nWaiting);
4813             rx_atomic_inc(&rx_nWaited);
4814             rxi_calltrace(RX_CALL_ARRIVAL, call);
4815             SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4816             queue_Append(&rx_incomingCallQueue, call);
4817         }
4818     } else {
4819         sq = queue_Last(&rx_idleServerQueue, rx_serverQueueEntry);
4820
4821         /* If hot threads are enabled, and both newcallp and sq->socketp
4822          * are non-null, then this thread will process the call, and the
4823          * idle server thread will start listening on this threads socket.
4824          */
4825         queue_Remove(sq);
4826         if (rx_enable_hot_thread && newcallp && sq->socketp) {
4827             *newcallp = call;
4828             *tnop = sq->tno;
4829             *sq->socketp = socket;
4830             clock_GetTime(&call->startTime);
4831             CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4832         } else {
4833             sq->newcall = call;
4834         }
4835         if (call->flags & RX_CALL_WAIT_PROC) {
4836             /* Conservative:  I don't think this should happen */
4837             call->flags &= ~RX_CALL_WAIT_PROC;
4838             if (queue_IsOnQueue(call)) {
4839                 queue_Remove(call);
4840
4841                 rx_atomic_dec(&rx_nWaiting);
4842             }
4843         }
4844         call->state = RX_STATE_ACTIVE;
4845         call->mode = RX_MODE_RECEIVING;
4846 #ifdef RX_KERNEL_TRACE
4847         {
4848             int glockOwner = ISAFS_GLOCK();
4849             if (!glockOwner)
4850                 AFS_GLOCK();
4851             afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4852                        __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4853                        call);
4854             if (!glockOwner)
4855                 AFS_GUNLOCK();
4856         }
4857 #endif
4858         if (call->flags & RX_CALL_CLEARED) {
4859             /* send an ack now to start the packet flow up again */
4860             call->flags &= ~RX_CALL_CLEARED;
4861             rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4862         }
4863 #ifdef  RX_ENABLE_LOCKS
4864         CV_SIGNAL(&sq->cv);
4865 #else
4866         service->nRequestsRunning++;
4867         MUTEX_ENTER(&rx_quota_mutex);
4868         if (service->nRequestsRunning <= service->minProcs)
4869             rxi_minDeficit--;
4870         rxi_availProcs--;
4871         MUTEX_EXIT(&rx_quota_mutex);
4872         osi_rxWakeup(sq);
4873 #endif
4874     }
4875     MUTEX_EXIT(&rx_serverPool_lock);
4876 }
4877
4878 /* Delay the sending of an acknowledge event for a short while, while
4879  * a new call is being prepared (in the case of a client) or a reply
4880  * is being prepared (in the case of a server).  Rather than sending
4881  * an ack packet, an ACKALL packet is sent. */
4882 void
4883 rxi_AckAll(struct rxevent *event, struct rx_call *call, char *dummy)
4884 {
4885 #ifdef RX_ENABLE_LOCKS
4886     if (event) {
4887         MUTEX_ENTER(&call->lock);
4888         rxevent_Put(call->delayedAckEvent);
4889         call->delayedAckEvent = NULL;
4890         CALL_RELE(call, RX_CALL_REFCOUNT_ACKALL);
4891     }
4892     rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4893                     RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4894     call->flags |= RX_CALL_ACKALL_SENT;
4895     if (event)
4896         MUTEX_EXIT(&call->lock);
4897 #else /* RX_ENABLE_LOCKS */
4898     if (event) {
4899         rxevent_Put(call->delayedAckEvent);
4900         call->delayedAckEvent = NULL;
4901     }
4902     rxi_SendSpecial(call, call->conn, (struct rx_packet *)0,
4903                     RX_PACKET_TYPE_ACKALL, NULL, 0, 0);
4904     call->flags |= RX_CALL_ACKALL_SENT;
4905 #endif /* RX_ENABLE_LOCKS */
4906 }
4907
4908 void
4909 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused1,
4910                    int unused2)
4911 {
4912     struct rx_call *call = arg1;
4913 #ifdef RX_ENABLE_LOCKS
4914     if (event) {
4915         MUTEX_ENTER(&call->lock);
4916         if (event == call->delayedAckEvent) {
4917             rxevent_Put(call->delayedAckEvent);
4918             call->delayedAckEvent = NULL;
4919         }
4920         CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4921     }
4922     (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4923     if (event)
4924         MUTEX_EXIT(&call->lock);
4925 #else /* RX_ENABLE_LOCKS */
4926     if (event) {
4927         rxevent_Put(call->delayedAckEvent);
4928         call->delayedAckEvent = NULL;
4929     }
4930     (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4931 #endif /* RX_ENABLE_LOCKS */
4932 }
4933
4934
4935 #ifdef RX_ENABLE_LOCKS
4936 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4937  * clearing them out.
4938  */
4939 static void
4940 rxi_SetAcksInTransmitQueue(struct rx_call *call)
4941 {
4942     struct rx_packet *p, *tp;
4943     int someAcked = 0;
4944
4945     for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4946         p->flags |= RX_PKTFLAG_ACKED;
4947         someAcked = 1;
4948     }
4949     if (someAcked) {
4950         call->flags |= RX_CALL_TQ_CLEARME;
4951         call->flags |= RX_CALL_TQ_SOME_ACKED;
4952     }
4953
4954     rxi_rto_cancel(call);
4955
4956     call->tfirst = call->tnext;
4957     call->nSoftAcked = 0;
4958
4959     if (call->flags & RX_CALL_FAST_RECOVER) {
4960         call->flags &= ~RX_CALL_FAST_RECOVER;
4961         call->cwind = call->nextCwind;
4962         call->nextCwind = 0;
4963     }
4964
4965     CV_SIGNAL(&call->cv_twind);
4966 }
4967 #endif /* RX_ENABLE_LOCKS */
4968
4969 /* Clear out the transmit queue for the current call (all packets have
4970  * been received by peer) */
4971 void
4972 rxi_ClearTransmitQueue(struct rx_call *call, int force)
4973 {
4974 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
4975     struct rx_packet *p, *tp;
4976
4977     if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4978         int someAcked = 0;
4979         for (queue_Scan(&call->tq, p, tp, rx_packet)) {
4980             p->flags |= RX_PKTFLAG_ACKED;
4981             someAcked = 1;
4982         }
4983         if (someAcked) {
4984             call->flags |= RX_CALL_TQ_CLEARME;
4985             call->flags |= RX_CALL_TQ_SOME_ACKED;
4986         }
4987     } else {
4988 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4989 #ifdef RXDEBUG_PACKET
4990         call->tqc -=
4991 #endif /* RXDEBUG_PACKET */
4992             rxi_FreePackets(0, &call->tq);
4993         rxi_WakeUpTransmitQueue(call);
4994 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
4995         call->flags &= ~RX_CALL_TQ_CLEARME;
4996     }
4997 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4998
4999     rxi_rto_cancel(call);
5000     call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
5001     call->nSoftAcked = 0;
5002
5003     if (call->flags & RX_CALL_FAST_RECOVER) {
5004         call->flags &= ~RX_CALL_FAST_RECOVER;
5005         call->cwind = call->nextCwind;
5006     }
5007 #ifdef  RX_ENABLE_LOCKS
5008     CV_SIGNAL(&call->cv_twind);
5009 #else
5010     osi_rxWakeup(&call->twind);
5011 #endif
5012 }
5013
5014 void
5015 rxi_ClearReceiveQueue(struct rx_call *call)
5016 {
5017     if (queue_IsNotEmpty(&call->rq)) {
5018         u_short count;
5019
5020         count = rxi_FreePackets(0, &call->rq);
5021         rx_packetReclaims += count;
5022 #ifdef RXDEBUG_PACKET
5023         call->rqc -= count;
5024         if ( call->rqc != 0 )
5025             dpf(("rxi_ClearReceiveQueue call %"AFS_PTR_FMT" rqc %u != 0\n", call, call->rqc));
5026 #endif
5027         call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
5028     }
5029     if (call->state == RX_STATE_PRECALL) {
5030         call->flags |= RX_CALL_CLEARED;
5031     }
5032 }
5033
5034 /* Send an abort packet for the specified call */
5035 struct rx_packet *
5036 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
5037                   int istack, int force)
5038 {
5039     afs_int32 error, cerror;
5040     struct clock when, now;
5041
5042     if (!call->error)
5043         return packet;
5044
5045     switch (call->error) {
5046     case RX_CALL_IDLE:
5047     case RX_CALL_BUSY:
5048         cerror = RX_CALL_TIMEOUT;
5049         break;
5050     default:
5051         cerror = call->error;
5052     }
5053
5054     /* Clients should never delay abort messages */
5055     if (rx_IsClientConn(call->conn))
5056         force = 1;
5057
5058     if (call->abortCode != cerror) {
5059         call->abortCode = cerror;
5060         call->abortCount = 0;
5061     }
5062
5063     if (force || rxi_callAbortThreshhold == 0
5064         || call->abortCount < rxi_callAbortThreshhold) {
5065         if (call->delayedAbortEvent) {
5066             rxevent_Cancel(&call->delayedAbortEvent, call,
5067                            RX_CALL_REFCOUNT_ABORT);
5068         }
5069         error = htonl(cerror);
5070         call->abortCount++;
5071         packet =
5072             rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5073                             (char *)&error, sizeof(error), istack);
5074     } else if (!call->delayedAbortEvent) {
5075         clock_GetTime(&now);
5076         when = now;
5077         clock_Addmsec(&when, rxi_callAbortDelay);
5078         CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
5079         call->delayedAbortEvent =
5080             rxevent_Post(&when, &now, rxi_SendDelayedCallAbort, call, 0, 0);
5081     }
5082     return packet;
5083 }
5084
5085 /* Send an abort packet for the specified connection.  Packet is an
5086  * optional pointer to a packet that can be used to send the abort.
5087  * Once the number of abort messages reaches the threshhold, an
5088  * event is scheduled to send the abort. Setting the force flag
5089  * overrides sending delayed abort messages.
5090  *
5091  * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
5092  *       to send the abort packet.
5093  */
5094 struct rx_packet *
5095 rxi_SendConnectionAbort(struct rx_connection *conn,
5096                         struct rx_packet *packet, int istack, int force)
5097 {
5098     afs_int32 error;
5099     struct clock when, now;
5100
5101     if (!conn->error)
5102         return packet;
5103
5104     /* Clients should never delay abort messages */
5105     if (rx_IsClientConn(conn))
5106         force = 1;
5107
5108     if (force || rxi_connAbortThreshhold == 0
5109         || conn->abortCount < rxi_connAbortThreshhold) {
5110
5111         rxevent_Cancel(&conn->delayedAbortEvent, NULL, 0);
5112         error = htonl(conn->error);
5113         conn->abortCount++;
5114         MUTEX_EXIT(&conn->conn_data_lock);
5115         packet =
5116             rxi_SendSpecial((struct rx_call *)0, conn, packet,
5117                             RX_PACKET_TYPE_ABORT, (char *)&error,
5118                             sizeof(error), istack);
5119         MUTEX_ENTER(&conn->conn_data_lock);
5120     } else if (!conn->delayedAbortEvent) {
5121         clock_GetTime(&now);
5122         when = now;
5123         clock_Addmsec(&when, rxi_connAbortDelay);
5124         conn->delayedAbortEvent =
5125             rxevent_Post(&when, &now, rxi_SendDelayedConnAbort, conn, NULL, 0);
5126     }
5127     return packet;
5128 }
5129
5130 /* Associate an error all of the calls owned by a connection.  Called
5131  * with error non-zero.  This is only for really fatal things, like
5132  * bad authentication responses.  The connection itself is set in
5133  * error at this point, so that future packets received will be
5134  * rejected. */
5135 void
5136 rxi_ConnectionError(struct rx_connection *conn,
5137                     afs_int32 error)
5138 {
5139     if (error) {
5140         int i;
5141
5142         dpf(("rxi_ConnectionError conn %"AFS_PTR_FMT" error %d\n", conn, error));
5143
5144         MUTEX_ENTER(&conn->conn_data_lock);
5145         rxevent_Cancel(&conn->challengeEvent, NULL, 0);
5146         rxevent_Cancel(&conn->natKeepAliveEvent, NULL, 0);
5147         if (conn->checkReachEvent) {
5148             rxevent_Cancel(&conn->checkReachEvent, NULL, 0);
5149             conn->flags &= ~(RX_CONN_ATTACHWAIT|RX_CONN_NAT_PING);
5150             putConnection(conn);
5151         }
5152         MUTEX_EXIT(&conn->conn_data_lock);
5153         for (i = 0; i < RX_MAXCALLS; i++) {
5154             struct rx_call *call = conn->call[i];
5155             if (call) {
5156                 MUTEX_ENTER(&call->lock);
5157                 rxi_CallError(call, error);
5158                 MUTEX_EXIT(&call->lock);
5159             }
5160         }
5161         conn->error = error;
5162         if (rx_stats_active)
5163             rx_atomic_inc(&rx_stats.fatalErrors);
5164     }
5165 }
5166
5167 /**
5168  * Interrupt an in-progress call with the specified error and wakeup waiters.
5169  *
5170  * @param[in] call  The call to interrupt
5171  * @param[in] error  The error code to send to the peer
5172  */
5173 void
5174 rx_InterruptCall(struct rx_call *call, afs_int32 error)
5175 {
5176     MUTEX_ENTER(&call->lock);
5177     rxi_CallError(call, error);
5178     rxi_SendCallAbort(call, NULL, 0, 1);
5179     MUTEX_EXIT(&call->lock);
5180 }
5181
5182 void
5183 rxi_CallError(struct rx_call *call, afs_int32 error)
5184 {
5185 #ifdef DEBUG
5186     osirx_AssertMine(&call->lock, "rxi_CallError");
5187 #endif
5188     dpf(("rxi_CallError call %"AFS_PTR_FMT" error %d call->error %d\n", call, error, call->error));
5189     if (call->error)
5190         error = call->error;
5191
5192 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
5193     if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
5194         rxi_ResetCall(call, 0);
5195     }
5196 #else
5197     rxi_ResetCall(call, 0);
5198 #endif
5199     call->error = error;
5200 }
5201
5202 /* Reset various fields in a call structure, and wakeup waiting
5203  * processes.  Some fields aren't changed: state & mode are not
5204  * touched (these must be set by the caller), and bufptr, nLeft, and
5205  * nFree are not reset, since these fields are manipulated by
5206  * unprotected macros, and may only be reset by non-interrupting code.
5207  */
5208
5209 void
5210 rxi_ResetCall(struct rx_call *call, int newcall)
5211 {
5212     int flags;
5213     struct rx_peer *peer;
5214     struct rx_packet *packet;
5215 #ifdef DEBUG
5216     osirx_AssertMine(&call->lock, "rxi_ResetCall");
5217 #endif
5218     dpf(("rxi_ResetCall(call %"AFS_PTR_FMT", newcall %d)\n", call, newcall));
5219
5220     /* Notify anyone who is waiting for asynchronous packet arrival */
5221     if (call->arrivalProc) {
5222         (*call->arrivalProc) (call, call->arrivalProcHandle,
5223                               call->arrivalProcArg);
5224         call->arrivalProc = (void (*)())0;
5225     }
5226
5227
5228     rxevent_Cancel(&call->growMTUEvent, call, RX_CALL_REFCOUNT_ALIVE);
5229
5230     if (call->delayedAbortEvent) {
5231         rxevent_Cancel(&call->delayedAbortEvent, call, RX_CALL_REFCOUNT_ABORT);
5232         packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5233         if (packet) {
5234             rxi_SendCallAbort(call, packet, 0, 1);
5235             rxi_FreePacket(packet);
5236         }
5237     }
5238
5239     /*
5240      * Update the peer with the congestion information in this call
5241      * so other calls on this connection can pick up where this call
5242      * left off. If the congestion sequence numbers don't match then
5243      * another call experienced a retransmission.
5244      */
5245     peer = call->conn->peer;
5246     MUTEX_ENTER(&peer->peer_lock);
5247     if (!newcall) {
5248         if (call->congestSeq == peer->congestSeq) {
5249             peer->cwind = MAX(peer->cwind, call->cwind);
5250             peer->MTU = MAX(peer->MTU, call->MTU);
5251             peer->nDgramPackets =
5252                 MAX(peer->nDgramPackets, call->nDgramPackets);
5253         }
5254     } else {
5255         call->abortCode = 0;
5256         call->abortCount = 0;
5257     }
5258     if (peer->maxDgramPackets > 1) {
5259         call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
5260     } else {
5261         call->MTU = peer->MTU;
5262     }
5263     call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
5264     call->ssthresh = rx_maxSendWindow;
5265     call->nDgramPackets = peer->nDgramPackets;
5266     call->congestSeq = peer->congestSeq;
5267     call->rtt = peer->rtt;
5268     call->rtt_dev = peer->rtt_dev;
5269     clock_Zero(&call->rto);
5270     clock_Addmsec(&call->rto,
5271                   MAX(((call->rtt >> 3) + call->rtt_dev), rx_minPeerTimeout) + 200);
5272     MUTEX_EXIT(&peer->peer_lock);
5273
5274     flags = call->flags;
5275 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
5276     rxi_WaitforTQBusy(call);
5277 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5278
5279     rxi_ClearTransmitQueue(call, 1);
5280     if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
5281         dpf(("rcall %"AFS_PTR_FMT" has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5282     }
5283     call->flags = 0;
5284
5285     if (!newcall && (flags & RX_CALL_PEER_BUSY)) {
5286         /* The call channel is still busy; resetting the call doesn't change
5287          * that. However, if 'newcall' is set, we are processing a call
5288          * structure that has either been recycled from the free list, or has
5289          * been newly allocated. So, RX_CALL_PEER_BUSY is not relevant if
5290          * 'newcall' is set, since it describes a completely different call
5291          * channel which we do not care about. */
5292         call->flags |= RX_CALL_PEER_BUSY;
5293     }
5294
5295     rxi_ClearReceiveQueue(call);
5296     /* why init the queue if you just emptied it? queue_Init(&call->rq); */
5297
5298
5299     call->error = 0;
5300     call->twind = call->conn->twind[call->channel];
5301     call->rwind = call->conn->rwind[call->channel];
5302     call->nSoftAcked = 0;
5303     call->nextCwind = 0;
5304     call->nAcks = 0;
5305     call->nNacks = 0;
5306     call->nCwindAcks = 0;
5307     call->nSoftAcks = 0;
5308     call->nHardAcks = 0;
5309
5310     call->tfirst = call->rnext = call->tnext = 1;
5311     call->tprev = 0;
5312     call->rprev = 0;
5313     call->lastAcked = 0;
5314     call->localStatus = call->remoteStatus = 0;
5315
5316     if (flags & RX_CALL_READER_WAIT) {
5317 #ifdef  RX_ENABLE_LOCKS
5318         CV_BROADCAST(&call->cv_rq);
5319 #else
5320         osi_rxWakeup(&call->rq);
5321 #endif
5322     }
5323     if (flags & RX_CALL_WAIT_PACKETS) {
5324         MUTEX_ENTER(&rx_freePktQ_lock);
5325         rxi_PacketsUnWait();    /* XXX */
5326         MUTEX_EXIT(&rx_freePktQ_lock);
5327     }
5328 #ifdef  RX_ENABLE_LOCKS
5329     CV_SIGNAL(&call->cv_twind);
5330 #else
5331     if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5332         osi_rxWakeup(&call->twind);
5333 #endif
5334
5335 #ifdef RX_ENABLE_LOCKS
5336     /* The following ensures that we don't mess with any queue while some
5337      * other thread might also be doing so. The call_queue_lock field is
5338      * is only modified under the call lock. If the call is in the process
5339      * of being removed from a queue, the call is not locked until the
5340      * the queue lock is dropped and only then is the call_queue_lock field
5341      * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5342      * Note that any other routine which removes a call from a queue has to
5343      * obtain the queue lock before examing the queue and removing the call.
5344      */
5345     if (call->call_queue_lock) {
5346         MUTEX_ENTER(call->call_queue_lock);
5347         if (queue_IsOnQueue(call)) {
5348             queue_Remove(call);
5349             if (flags & RX_CALL_WAIT_PROC) {
5350                 rx_atomic_dec(&rx_nWaiting);
5351             }
5352         }
5353         MUTEX_EXIT(call->call_queue_lock);
5354         CLEAR_CALL_QUEUE_LOCK(call);
5355     }
5356 #else /* RX_ENABLE_LOCKS */
5357     if (queue_IsOnQueue(call)) {
5358         queue_Remove(call);
5359         if (flags & RX_CALL_WAIT_PROC)
5360             rx_atomic_dec(&rx_nWaiting);
5361     }
5362 #endif /* RX_ENABLE_LOCKS */
5363
5364     rxi_KeepAliveOff(call);
5365     rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5366 }
5367
5368 /* Send an acknowledge for the indicated packet (seq,serial) of the
5369  * indicated call, for the indicated reason (reason).  This
5370  * acknowledge will specifically acknowledge receiving the packet, and
5371  * will also specify which other packets for this call have been
5372  * received.  This routine returns the packet that was used to the
5373  * caller.  The caller is responsible for freeing it or re-using it.
5374  * This acknowledgement also returns the highest sequence number
5375  * actually read out by the higher level to the sender; the sender
5376  * promises to keep around packets that have not been read by the
5377  * higher level yet (unless, of course, the sender decides to abort
5378  * the call altogether).  Any of p, seq, serial, pflags, or reason may
5379  * be set to zero without ill effect.  That is, if they are zero, they
5380  * will not convey any information.
5381  * NOW there is a trailer field, after the ack where it will safely be
5382  * ignored by mundanes, which indicates the maximum size packet this
5383  * host can swallow.  */
5384 /*
5385     struct rx_packet *optionalPacket;  use to send ack (or null)
5386     int seq;                     Sequence number of the packet we are acking
5387     int serial;                  Serial number of the packet
5388     int pflags;                  Flags field from packet header
5389     int reason;                  Reason an acknowledge was prompted
5390 */
5391
5392 struct rx_packet *
5393 rxi_SendAck(struct rx_call *call,
5394             struct rx_packet *optionalPacket, int serial, int reason,
5395             int istack)
5396 {
5397     struct rx_ackPacket *ap;
5398     struct rx_packet *rqp;
5399     struct rx_packet *nxp;      /* For queue_Scan */
5400     struct rx_packet *p;
5401     u_char offset = 0;
5402     afs_int32 templ;
5403     afs_uint32 padbytes = 0;
5404 #ifdef RX_ENABLE_TSFPQ
5405     struct rx_ts_info_t * rx_ts_info;
5406 #endif
5407
5408     /*
5409      * Open the receive window once a thread starts reading packets
5410      */
5411     if (call->rnext > 1) {
5412         call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5413     }
5414
5415     /* Don't attempt to grow MTU if this is a critical ping */
5416     if (reason == RX_ACK_MTU) {
5417         /* keep track of per-call attempts, if we're over max, do in small
5418          * otherwise in larger? set a size to increment by, decrease
5419          * on failure, here?
5420          */
5421         if (call->conn->peer->maxPacketSize &&
5422             (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5423              +RX_IPUDP_SIZE))
5424             padbytes = call->conn->peer->maxPacketSize+16;
5425         else
5426             padbytes = call->conn->peer->maxMTU + 128;
5427
5428         /* do always try a minimum size ping */
5429         padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5430
5431         /* subtract the ack payload */
5432         padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5433         reason = RX_ACK_PING;
5434     }
5435
5436     call->nHardAcks = 0;
5437     call->nSoftAcks = 0;
5438     if (call->rnext > call->lastAcked)
5439         call->lastAcked = call->rnext;
5440     p = optionalPacket;
5441
5442     if (p) {
5443         rx_computelen(p, p->length);    /* reset length, you never know */
5444     } /* where that's been...         */
5445 #ifdef RX_ENABLE_TSFPQ
5446     else {
5447         RX_TS_INFO_GET(rx_ts_info);
5448         if ((p = rx_ts_info->local_special_packet)) {
5449             rx_computelen(p, p->length);
5450         } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5451             rx_ts_info->local_special_packet = p;
5452         } else { /* We won't send the ack, but don't panic. */
5453             return optionalPacket;
5454         }
5455     }
5456 #else
5457     else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5458         /* We won't send the ack, but don't panic. */
5459         return optionalPacket;
5460     }
5461 #endif
5462
5463     templ = padbytes +
5464         rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5465         rx_GetDataSize(p);
5466     if (templ > 0) {
5467         if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5468 #ifndef RX_ENABLE_TSFPQ
5469             if (!optionalPacket)
5470                 rxi_FreePacket(p);
5471 #endif
5472             return optionalPacket;
5473         }
5474         templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5475         if (rx_Contiguous(p) < templ) {
5476 #ifndef RX_ENABLE_TSFPQ
5477             if (!optionalPacket)
5478                 rxi_FreePacket(p);
5479 #endif
5480             return optionalPacket;
5481         }
5482     }
5483
5484
5485     /* MTUXXX failing to send an ack is very serious.  We should */
5486     /* try as hard as possible to send even a partial ack; it's */
5487     /* better than nothing. */
5488     ap = (struct rx_ackPacket *)rx_DataOf(p);
5489     ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5490     ap->reason = reason;
5491
5492     /* The skew computation used to be bogus, I think it's better now. */
5493     /* We should start paying attention to skew.    XXX  */
5494     ap->serial = htonl(serial);
5495     ap->maxSkew = 0;            /* used to be peer->inPacketSkew */
5496
5497     /*
5498      * First packet not yet forwarded to reader. When ACKALL has been
5499      * sent the peer has been told that all received packets will be
5500      * delivered to the reader.  The value 'rnext' is used internally
5501      * to refer to the next packet in the receive queue that must be
5502      * delivered to the reader.  From the perspective of the peer it
5503      * already has so report the last sequence number plus one if there
5504      * are packets in the receive queue awaiting processing.
5505      */
5506     if ((call->flags & RX_CALL_ACKALL_SENT) &&
5507         !queue_IsEmpty(&call->rq)) {
5508         ap->firstPacket = htonl(queue_Last(&call->rq, rx_packet)->header.seq + 1);
5509     } else {
5510         ap->firstPacket = htonl(call->rnext);
5511
5512         ap->previousPacket = htonl(call->rprev);        /* Previous packet received */
5513
5514         /* No fear of running out of ack packet here because there can only be at most
5515          * one window full of unacknowledged packets.  The window size must be constrained
5516          * to be less than the maximum ack size, of course.  Also, an ack should always
5517          * fit into a single packet -- it should not ever be fragmented.  */
5518         for (offset = 0, queue_Scan(&call->rq, rqp, nxp, rx_packet)) {
5519             if (!rqp || !call->rq.next
5520                 || (rqp->header.seq > (call->rnext + call->rwind))) {
5521 #ifndef RX_ENABLE_TSFPQ
5522                 if (!optionalPacket)
5523                     rxi_FreePacket(p);
5524 #endif
5525                 rxi_CallError(call, RX_CALL_DEAD);
5526                 return optionalPacket;
5527             }
5528
5529             while (rqp->header.seq > call->rnext + offset)
5530                 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5531             ap->acks[offset++] = RX_ACK_TYPE_ACK;
5532
5533             if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5534 #ifndef RX_ENABLE_TSFPQ
5535                 if (!optionalPacket)
5536                     rxi_FreePacket(p);
5537 #endif
5538                 rxi_CallError(call, RX_CALL_DEAD);
5539                 return optionalPacket;
5540             }
5541         }
5542     }
5543
5544     ap->nAcks = offset;
5545     p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5546
5547     /* these are new for AFS 3.3 */
5548     templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5549     templ = htonl(templ);
5550     rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5551     templ = htonl(call->conn->peer->ifMTU);
5552     rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5553                    sizeof(afs_int32), &templ);
5554
5555     /* new for AFS 3.4 */
5556     templ = htonl(call->rwind);
5557     rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5558                    sizeof(afs_int32), &templ);
5559
5560     /* new for AFS 3.5 */
5561     templ = htonl(call->conn->peer->ifDgramPackets);
5562     rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5563                    sizeof(afs_int32), &templ);
5564
5565     p->header.serviceId = call->conn->serviceId;
5566     p->header.cid = (call->conn->cid | call->channel);
5567     p->header.callNumber = *call->callNumber;
5568     p->header.seq = 0;
5569     p->header.securityIndex = call->conn->securityIndex;
5570     p->header.epoch = call->conn->epoch;
5571     p->header.type = RX_PACKET_TYPE_ACK;
5572     p->header.flags = RX_SLOW_START_OK;
5573     if (reason == RX_ACK_PING) {
5574         p->header.flags |= RX_REQUEST_ACK;
5575         if (padbytes) {
5576             p->length = padbytes +
5577                 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32);
5578
5579             while (padbytes--)
5580                 /* not fast but we can potentially use this if truncated
5581                  * fragments are delivered to figure out the mtu.
5582                  */
5583                 rx_packetwrite(p, rx_AckDataSize(offset) + 4 *
5584                                sizeof(afs_int32), sizeof(afs_int32),
5585                                &padbytes);
5586         }
5587     }
5588     if (call->conn->type == RX_CLIENT_CONNECTION)
5589         p->header.flags |= RX_CLIENT_INITIATED;
5590
5591 #ifdef RXDEBUG
5592 #ifdef AFS_NT40_ENV
5593     if (rxdebug_active) {
5594         char msg[512];
5595         size_t len;
5596
5597         len = _snprintf(msg, sizeof(msg),
5598                         "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5599                          GetCurrentThreadId(), rx_ack_reason(ap->reason),
5600                          ntohl(ap->serial), ntohl(ap->previousPacket),
5601                          (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5602                          ap->nAcks, ntohs(ap->bufferSpace) );
5603         if (ap->nAcks) {
5604             int offset;
5605
5606             for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5607                 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5608         }
5609         msg[len++]='\n';
5610         msg[len] = '\0';
5611         OutputDebugString(msg);
5612     }
5613 #else /* AFS_NT40_ENV */
5614     if (rx_Log) {
5615         fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5616                 ap->reason, ntohl(ap->previousPacket),
5617                 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5618         if (ap->nAcks) {
5619             for (offset = 0; offset < ap->nAcks; offset++)
5620                 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5621                      rx_Log);
5622         }
5623         putc('\n', rx_Log);
5624     }
5625 #endif /* AFS_NT40_ENV */
5626 #endif
5627     {
5628         int i, nbytes = p->length;
5629
5630         for (i = 1; i < p->niovecs; i++) {      /* vec 0 is ALWAYS header */
5631             if (nbytes <= p->wirevec[i].iov_len) {
5632                 int savelen, saven;
5633
5634                 savelen = p->wirevec[i].iov_len;
5635                 saven = p->niovecs;
5636                 p->wirevec[i].iov_len = nbytes;
5637                 p->niovecs = i + 1;
5638                 rxi_Send(call, p, istack);
5639                 p->wirevec[i].iov_len = savelen;
5640                 p->niovecs = saven;
5641                 break;
5642             } else
5643                 nbytes -= p->wirevec[i].iov_len;
5644         }
5645     }
5646     if (rx_stats_active)
5647         rx_atomic_inc(&rx_stats.ackPacketsSent);
5648 #ifndef RX_ENABLE_TSFPQ
5649     if (!optionalPacket)
5650         rxi_FreePacket(p);
5651 #endif
5652     return optionalPacket;      /* Return packet for re-use by caller */
5653 }
5654
5655 struct xmitlist {
5656    struct rx_packet **list;
5657    int len;
5658    int resending;
5659 };
5660
5661 /* Send all of the packets in the list in single datagram */
5662 static void
5663 rxi_SendList(struct rx_call *call, struct xmitlist *xmit,
5664              int istack, int moreFlag)
5665 {
5666     int i;
5667     int requestAck = 0;
5668     int lastPacket = 0;
5669     struct clock now;
5670     struct rx_connection *conn = call->conn;
5671     struct rx_peer *peer = conn->peer;
5672
5673     MUTEX_ENTER(&peer->peer_lock);
5674     peer->nSent += xmit->len;
5675     if (xmit->resending)
5676         peer->reSends += xmit->len;
5677     MUTEX_EXIT(&peer->peer_lock);
5678
5679     if (rx_stats_active) {
5680         if (xmit->resending)
5681             rx_atomic_add(&rx_stats.dataPacketsReSent, xmit->len);
5682         else
5683             rx_atomic_add(&rx_stats.dataPacketsSent, xmit->len);
5684     }
5685
5686     clock_GetTime(&now);
5687
5688     if (xmit->list[xmit->len - 1]->header.flags & RX_LAST_PACKET) {
5689         lastPacket = 1;
5690     }
5691
5692     /* Set the packet flags and schedule the resend events */
5693     /* Only request an ack for the last packet in the list */
5694     for (i = 0; i < xmit->len; i++) {
5695         struct rx_packet *packet = xmit->list[i];
5696
5697         /* Record the time sent */
5698         packet->timeSent = now;
5699         packet->flags |= RX_PKTFLAG_SENT;
5700
5701         /* Ask for an ack on retransmitted packets,  on every other packet
5702          * if the peer doesn't support slow start. Ask for an ack on every
5703          * packet until the congestion window reaches the ack rate. */
5704         if (packet->header.serial) {
5705             requestAck = 1;
5706         } else {
5707             packet->firstSent = now;
5708             if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5709                                 || (!(call->flags & RX_CALL_SLOW_START_OK)
5710                                     && (packet->header.seq & 1)))) {
5711                 requestAck = 1;
5712             }
5713         }
5714
5715         /* Tag this packet as not being the last in this group,
5716          * for the receiver's benefit */
5717         if (i < xmit->len - 1 || moreFlag) {
5718             packet->header.flags |= RX_MORE_PACKETS;
5719         }
5720     }
5721
5722     if (requestAck) {
5723         xmit->list[xmit->len - 1]->header.flags |= RX_REQUEST_ACK;
5724     }
5725
5726     /* Since we're about to send a data packet to the peer, it's
5727      * safe to nuke any scheduled end-of-packets ack */
5728     rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
5729
5730     MUTEX_EXIT(&call->lock);
5731     CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5732     if (xmit->len > 1) {
5733         rxi_SendPacketList(call, conn, xmit->list, xmit->len, istack);
5734     } else {
5735         rxi_SendPacket(call, conn, xmit->list[0], istack);
5736     }
5737     MUTEX_ENTER(&call->lock);
5738     CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5739
5740     /* Tell the RTO calculation engine that we have sent a packet, and
5741      * if it was the last one */
5742     rxi_rto_packet_sent(call, lastPacket, istack);
5743
5744     /* Update last send time for this call (for keep-alive
5745      * processing), and for the connection (so that we can discover
5746      * idle connections) */
5747     conn->lastSendTime = call->lastSendTime = clock_Sec();
5748     /* Let a set of retransmits trigger an idle timeout */
5749     if (!xmit->resending)
5750         call->lastSendData = call->lastSendTime;
5751 }
5752
5753 /* When sending packets we need to follow these rules:
5754  * 1. Never send more than maxDgramPackets in a jumbogram.
5755  * 2. Never send a packet with more than two iovecs in a jumbogram.
5756  * 3. Never send a retransmitted packet in a jumbogram.
5757  * 4. Never send more than cwind/4 packets in a jumbogram
5758  * We always keep the last list we should have sent so we
5759  * can set the RX_MORE_PACKETS flags correctly.
5760  */
5761
5762 static void
5763 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5764                  int istack)
5765 {
5766     int i;
5767     int recovery;
5768     struct xmitlist working;
5769     struct xmitlist last;
5770
5771     struct rx_peer *peer = call->conn->peer;
5772     int morePackets = 0;
5773
5774     memset(&last, 0, sizeof(struct xmitlist));
5775     working.list = &list[0];
5776     working.len = 0;
5777     working.resending = 0;
5778
5779     recovery = call->flags & RX_CALL_FAST_RECOVER;
5780
5781     for (i = 0; i < len; i++) {
5782         /* Does the current packet force us to flush the current list? */
5783         if (working.len > 0
5784             && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5785                 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5786
5787             /* This sends the 'last' list and then rolls the current working
5788              * set into the 'last' one, and resets the working set */
5789
5790             if (last.len > 0) {
5791                 rxi_SendList(call, &last, istack, 1);
5792                 /* If the call enters an error state stop sending, or if
5793                  * we entered congestion recovery mode, stop sending */
5794                 if (call->error
5795                     || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5796                     return;
5797             }
5798             last = working;
5799             working.len = 0;
5800             working.resending = 0;
5801             working.list = &list[i];
5802         }
5803         /* Add the current packet to the list if it hasn't been acked.
5804          * Otherwise adjust the list pointer to skip the current packet.  */
5805         if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5806             working.len++;
5807
5808             if (list[i]->header.serial)
5809                 working.resending = 1;
5810
5811             /* Do we need to flush the list? */
5812             if (working.len >= (int)peer->maxDgramPackets
5813                 || working.len >= (int)call->nDgramPackets 
5814                 || working.len >= (int)call->cwind
5815                 || list[i]->header.serial
5816                 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5817                 if (last.len > 0) {
5818                     rxi_SendList(call, &last, istack, 1);
5819                     /* If the call enters an error state stop sending, or if
5820                      * we entered congestion recovery mode, stop sending */
5821                     if (call->error
5822                         || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5823                         return;
5824                 }
5825                 last = working;
5826                 working.len = 0;
5827                 working.resending = 0;
5828                 working.list = &list[i + 1];
5829             }
5830         } else {
5831             if (working.len != 0) {
5832                 osi_Panic("rxi_SendList error");
5833             }
5834             working.list = &list[i + 1];
5835         }
5836     }
5837
5838     /* Send the whole list when the call is in receive mode, when
5839      * the call is in eof mode, when we are in fast recovery mode,
5840      * and when we have the last packet */
5841     if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5842         || call->mode == RX_MODE_RECEIVING || call->mode == RX_MODE_EOF
5843         || (call->flags & RX_CALL_FAST_RECOVER)) {
5844         /* Check for the case where the current list contains
5845          * an acked packet. Since we always send retransmissions
5846          * in a separate packet, we only need to check the first
5847          * packet in the list */
5848         if (working.len > 0 && !(working.list[0]->flags & RX_PKTFLAG_ACKED)) {
5849             morePackets = 1;
5850         }
5851         if (last.len > 0) {
5852             rxi_SendList(call, &last, istack, morePackets);
5853             /* If the call enters an error state stop sending, or if
5854              * we entered congestion recovery mode, stop sending */
5855             if (call->error
5856                 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5857                 return;
5858         }
5859         if (morePackets) {
5860             rxi_SendList(call, &working, istack, 0);
5861         }
5862     } else if (last.len > 0) {
5863         rxi_SendList(call, &last, istack, 0);
5864         /* Packets which are in 'working' are not sent by this call */
5865     }
5866 }
5867
5868 static void
5869 rxi_Resend(struct rxevent *event, void *arg0, void *arg1, int istack)
5870 {
5871     struct rx_call *call = arg0;
5872     struct rx_peer *peer;
5873     struct rx_packet *p, *nxp;
5874     struct clock maxTimeout = { 60, 0 };
5875
5876     MUTEX_ENTER(&call->lock);
5877
5878     peer = call->conn->peer;
5879
5880     /* Make sure that the event pointer is removed from the call
5881      * structure, since there is no longer a per-call retransmission
5882      * event pending. */
5883     if (event == call->resendEvent) {
5884         CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5885         rxevent_Put(call->resendEvent);
5886         call->resendEvent = NULL;
5887     }
5888
5889     if (rxi_busyChannelError && (call->flags & RX_CALL_PEER_BUSY)) {
5890         rxi_CheckBusy(call);
5891     }
5892
5893     if (queue_IsEmpty(&call->tq)) {
5894         /* Nothing to do. This means that we've been raced, and that an
5895          * ACK has come in between when we were triggered, and when we
5896          * actually got to run. */
5897         goto out;
5898     }
5899
5900     /* We're in loss recovery */
5901     call->flags |= RX_CALL_FAST_RECOVER;
5902
5903     /* Mark all of the pending packets in the queue as being lost */
5904     for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5905         if (!(p->flags & RX_PKTFLAG_ACKED))
5906             p->flags &= ~RX_PKTFLAG_SENT;
5907     }
5908
5909     /* We're resending, so we double the timeout of the call. This will be
5910      * dropped back down by the first successful ACK that we receive.
5911      *
5912      * We apply a maximum value here of 60 seconds
5913      */
5914     clock_Add(&call->rto, &call->rto);
5915     if (clock_Gt(&call->rto, &maxTimeout))
5916         call->rto = maxTimeout;
5917
5918     /* Packet loss is most likely due to congestion, so drop our window size
5919      * and start again from the beginning */
5920     if (peer->maxDgramPackets >1) {
5921         call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
5922         call->MTU = MIN(peer->natMTU, peer->maxMTU);
5923     }
5924     call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
5925     call->nDgramPackets = 1;
5926     call->cwind = 1;
5927     call->nextCwind = 1;
5928     call->nAcks = 0;
5929     call->nNacks = 0;
5930     MUTEX_ENTER(&peer->peer_lock);
5931     peer->MTU = call->MTU;
5932     peer->cwind = call->cwind;
5933     peer->nDgramPackets = 1;
5934     peer->congestSeq++;
5935     call->congestSeq = peer->congestSeq;
5936     MUTEX_EXIT(&peer->peer_lock);
5937
5938     rxi_Start(call, istack);
5939
5940 out:
5941     MUTEX_EXIT(&call->lock);
5942 }
5943
5944 /* This routine is called when new packets are readied for
5945  * transmission and when retransmission may be necessary, or when the
5946  * transmission window or burst count are favourable.  This should be
5947  * better optimized for new packets, the usual case, now that we've
5948  * got rid of queues of send packets. XXXXXXXXXXX */
5949 void
5950 rxi_Start(struct rx_call *call, int istack)
5951 {
5952
5953     struct rx_packet *p;
5954     struct rx_packet *nxp;      /* Next pointer for queue_Scan */
5955     int nXmitPackets;
5956     int maxXmitPackets;
5957
5958     if (call->error) {
5959 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
5960         if (rx_stats_active)
5961             rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
5962 #endif
5963         return;
5964     }
5965
5966     if (queue_IsNotEmpty(&call->tq)) {  /* If we have anything to send */
5967
5968         /* Send (or resend) any packets that need it, subject to
5969          * window restrictions and congestion burst control
5970          * restrictions.  Ask for an ack on the last packet sent in
5971          * this burst.  For now, we're relying upon the window being
5972          * considerably bigger than the largest number of packets that
5973          * are typically sent at once by one initial call to
5974          * rxi_Start.  This is probably bogus (perhaps we should ask
5975          * for an ack when we're half way through the current
5976          * window?).  Also, for non file transfer applications, this
5977          * may end up asking for an ack for every packet.  Bogus. XXXX
5978          */
5979         /*
5980          * But check whether we're here recursively, and let the other guy
5981          * do the work.
5982          */
5983 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
5984         if (!(call->flags & RX_CALL_TQ_BUSY)) {
5985             call->flags |= RX_CALL_TQ_BUSY;
5986             do {
5987 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5988             restart:
5989 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
5990                 call->flags &= ~RX_CALL_NEED_START;
5991 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
5992                 nXmitPackets = 0;
5993                 maxXmitPackets = MIN(call->twind, call->cwind);
5994                 for (queue_Scan(&call->tq, p, nxp, rx_packet)) {
5995 #ifdef RX_TRACK_PACKETS
5996                     if ((p->flags & RX_PKTFLAG_FREE)
5997                         || (!queue_IsEnd(&call->tq, nxp)
5998                             && (nxp->flags & RX_PKTFLAG_FREE))
5999                         || (p == (struct rx_packet *)&rx_freePacketQueue)
6000                         || (nxp == (struct rx_packet *)&rx_freePacketQueue)) {
6001                         osi_Panic("rxi_Start: xmit queue clobbered");
6002                     }
6003 #endif
6004                     if (p->flags & RX_PKTFLAG_ACKED) {
6005                         /* Since we may block, don't trust this */
6006                         if (rx_stats_active)
6007                             rx_atomic_inc(&rx_stats.ignoreAckedPacket);
6008                         continue;       /* Ignore this packet if it has been acknowledged */
6009                     }
6010
6011                     /* Turn off all flags except these ones, which are the same
6012                      * on each transmission */
6013                     p->header.flags &= RX_PRESET_FLAGS;
6014
6015                     if (p->header.seq >=
6016                         call->tfirst + MIN((int)call->twind,
6017                                            (int)(call->nSoftAcked +
6018                                                  call->cwind))) {
6019                         call->flags |= RX_CALL_WAIT_WINDOW_SEND;        /* Wait for transmit window */
6020                         /* Note: if we're waiting for more window space, we can
6021                          * still send retransmits; hence we don't return here, but
6022                          * break out to schedule a retransmit event */
6023                         dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
6024                              *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
6025                              call->cwind));
6026                         break;
6027                     }
6028
6029                     /* Transmit the packet if it needs to be sent. */
6030                     if (!(p->flags & RX_PKTFLAG_SENT)) {
6031                         if (nXmitPackets == maxXmitPackets) {
6032                             rxi_SendXmitList(call, call->xmitList,
6033                                              nXmitPackets, istack);
6034                             goto restart;
6035                         }
6036                         dpf(("call %d xmit packet %"AFS_PTR_FMT"\n",
6037                               *(call->callNumber), p));
6038                         call->xmitList[nXmitPackets++] = p;
6039                     }
6040                 }
6041
6042                 /* xmitList now hold pointers to all of the packets that are
6043                  * ready to send. Now we loop to send the packets */
6044                 if (nXmitPackets > 0) {
6045                     rxi_SendXmitList(call, call->xmitList, nXmitPackets,
6046                                      istack);
6047                 }
6048
6049 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
6050                 if (call->error) {
6051                     /* We went into the error state while sending packets. Now is
6052                      * the time to reset the call. This will also inform the using
6053                      * process that the call is in an error state.
6054                      */
6055                     if (rx_stats_active)
6056                         rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
6057                     call->flags &= ~RX_CALL_TQ_BUSY;
6058                     rxi_WakeUpTransmitQueue(call);
6059                     rxi_CallError(call, call->error);
6060                     return;
6061                 }
6062 #ifdef RX_ENABLE_LOCKS
6063                 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
6064                     int missing;
6065                     call->flags &= ~RX_CALL_TQ_SOME_ACKED;
6066                     /* Some packets have received acks. If they all have, we can clear
6067                      * the transmit queue.
6068                      */
6069                     for (missing =
6070                          0, queue_Scan(&call->tq, p, nxp, rx_packet)) {
6071                         if (p->header.seq < call->tfirst
6072                             && (p->flags & RX_PKTFLAG_ACKED)) {
6073                             queue_Remove(p);
6074 #ifdef RX_TRACK_PACKETS
6075                             p->flags &= ~RX_PKTFLAG_TQ;
6076 #endif
6077 #ifdef RXDEBUG_PACKET
6078                             call->tqc--;
6079 #endif
6080                             rxi_FreePacket(p);
6081                         } else
6082                             missing = 1;
6083                     }
6084                     if (!missing)
6085                         call->flags |= RX_CALL_TQ_CLEARME;
6086                 }
6087 #endif /* RX_ENABLE_LOCKS */
6088                 if (call->flags & RX_CALL_TQ_CLEARME)
6089                     rxi_ClearTransmitQueue(call, 1);
6090             } while (call->flags & RX_CALL_NEED_START);
6091             /*
6092              * TQ references no longer protected by this flag; they must remain
6093              * protected by the global lock.
6094              */
6095             call->flags &= ~RX_CALL_TQ_BUSY;
6096             rxi_WakeUpTransmitQueue(call);
6097         } else {
6098             call->flags |= RX_CALL_NEED_START;
6099         }
6100 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
6101     } else {
6102         rxi_rto_cancel(call);
6103     }
6104 }
6105
6106 /* Also adjusts the keep alive parameters for the call, to reflect
6107  * that we have just sent a packet (so keep alives aren't sent
6108  * immediately) */
6109 void
6110 rxi_Send(struct rx_call *call, struct rx_packet *p,
6111          int istack)
6112 {
6113     struct rx_connection *conn = call->conn;
6114
6115     /* Stamp each packet with the user supplied status */
6116     p->header.userStatus = call->localStatus;
6117
6118     /* Allow the security object controlling this call's security to
6119      * make any last-minute changes to the packet */
6120     RXS_SendPacket(conn->securityObject, call, p);
6121
6122     /* Since we're about to send SOME sort of packet to the peer, it's
6123      * safe to nuke any scheduled end-of-packets ack */
6124     rxevent_Cancel(&call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
6125
6126     /* Actually send the packet, filling in more connection-specific fields */
6127     MUTEX_EXIT(&call->lock);
6128     CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6129     rxi_SendPacket(call, conn, p, istack);
6130     CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6131     MUTEX_ENTER(&call->lock);
6132
6133     /* Update last send time for this call (for keep-alive
6134      * processing), and for the connection (so that we can discover
6135      * idle connections) */
6136     if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6137         (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
6138         (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
6139     {
6140         conn->lastSendTime = call->lastSendTime = clock_Sec();
6141         /* Don't count keepalive ping/acks here, so idleness can be tracked. */
6142         if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6143             ((((struct rx_ackPacket *)rx_DataOf(p))->reason != RX_ACK_PING) &&
6144              (((struct rx_ackPacket *)rx_DataOf(p))->reason !=
6145               RX_ACK_PING_RESPONSE)))
6146             call->lastSendData = call->lastSendTime;
6147     }
6148 }
6149
6150 /* Check if a call needs to be destroyed.  Called by keep-alive code to ensure
6151  * that things are fine.  Also called periodically to guarantee that nothing
6152  * falls through the cracks (e.g. (error + dally) connections have keepalive
6153  * turned off.  Returns 0 if conn is well, -1 otherwise.  If otherwise, call
6154  *  may be freed!
6155  * haveCTLock Set if calling from rxi_ReapConnections
6156  */
6157 #ifdef RX_ENABLE_LOCKS
6158 int
6159 rxi_CheckCall(struct rx_call *call, int haveCTLock)
6160 #else /* RX_ENABLE_LOCKS */
6161 int
6162 rxi_CheckCall(struct rx_call *call)
6163 #endif                          /* RX_ENABLE_LOCKS */
6164 {
6165     struct rx_connection *conn = call->conn;
6166     afs_uint32 now;
6167     afs_uint32 deadTime, idleDeadTime = 0, hardDeadTime = 0;
6168     afs_uint32 fudgeFactor;
6169     int cerror = 0;
6170     int newmtu = 0;
6171     int idle_timeout = 0;
6172     afs_int32  clock_diff = 0;
6173
6174     now = clock_Sec();
6175
6176     /* Large swings in the clock can have a significant impact on
6177      * the performance of RX call processing.  Forward clock shifts
6178      * will result in premature event triggering or timeouts.
6179      * Backward shifts can result in calls not completing until
6180      * the clock catches up with the original start clock value.
6181      *
6182      * If a backward clock shift of more than five minutes is noticed,
6183      * just fail the call.
6184      */
6185     if (now < call->lastSendTime)
6186         clock_diff = call->lastSendTime - now;
6187     if (now < call->startWait)
6188         clock_diff = MAX(clock_diff, call->startWait - now);
6189     if (now < call->lastReceiveTime)
6190         clock_diff = MAX(clock_diff, call->lastReceiveTime - now);
6191     if (clock_diff > 5 * 60)
6192     {
6193         if (call->state == RX_STATE_ACTIVE)
6194             rxi_CallError(call, RX_CALL_TIMEOUT);
6195         return -1;
6196     }
6197
6198 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
6199     if (call->flags & RX_CALL_TQ_BUSY) {
6200         /* Call is active and will be reset by rxi_Start if it's
6201          * in an error state.
6202          */
6203         return 0;
6204     }
6205 #endif
6206     /* RTT + 8*MDEV, rounded up to the next second. */
6207     fudgeFactor = (((afs_uint32) call->rtt >> 3) +
6208                    ((afs_uint32) call->rtt_dev << 1) + 1023) >> 10;
6209
6210     deadTime = conn->secondsUntilDead + fudgeFactor;
6211     /* These are computed to the second (+- 1 second).  But that's
6212      * good enough for these values, which should be a significant
6213      * number of seconds. */
6214     if (now > (call->lastReceiveTime + deadTime)) {
6215         if (call->state == RX_STATE_ACTIVE) {
6216 #ifdef ADAPT_PMTU
6217 #if defined(KERNEL) && defined(AFS_SUN5_ENV)
6218             ire_t *ire;
6219 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
6220             netstack_t *ns =  netstack_find_by_stackid(GLOBAL_NETSTACKID);
6221             ip_stack_t *ipst = ns->netstack_ip;
6222 #endif
6223             ire = ire_cache_lookup(conn->peer->host
6224 #if defined(AFS_SUN510_ENV) && defined(ALL_ZONES)
6225                                    , ALL_ZONES
6226 #if defined(AFS_SUN510_ENV) && (defined(ICL_3_ARG) || defined(GLOBAL_NETSTACKID))
6227                                    , NULL
6228 #if defined(AFS_SUN510_ENV) && defined(GLOBAL_NETSTACKID)
6229                                    , ipst
6230 #endif
6231 #endif
6232 #endif
6233                 );
6234
6235             if (ire && ire->ire_max_frag > 0)
6236                 rxi_SetPeerMtu(NULL, conn->peer->host, 0,
6237                                ire->ire_max_frag);
6238 #if defined(GLOBAL_NETSTACKID)
6239             netstack_rele(ns);
6240 #endif
6241 #endif
6242 #endif /* ADAPT_PMTU */
6243             cerror = RX_CALL_DEAD;
6244             goto mtuout;
6245         } else {
6246 #ifdef RX_ENABLE_LOCKS
6247             /* Cancel pending events */
6248             rxevent_Cancel(&call->delayedAckEvent, call,
6249                            RX_CALL_REFCOUNT_DELAY);
6250             rxi_rto_cancel(call);
6251             rxevent_Cancel(&call->keepAliveEvent, call,
6252                            RX_CALL_REFCOUNT_ALIVE);
6253             rxevent_Cancel(&call->growMTUEvent, call,
6254                            RX_CALL_REFCOUNT_ALIVE);
6255             MUTEX_ENTER(&rx_refcnt_mutex);
6256             /* if rxi_FreeCall returns 1 it has freed the call */
6257             if (call->refCount == 0 &&
6258                 rxi_FreeCall(call, haveCTLock))
6259             {
6260                 MUTEX_EXIT(&rx_refcnt_mutex);
6261                 return -2;
6262             }
6263             MUTEX_EXIT(&rx_refcnt_mutex);
6264             return -1;
6265 #else /* RX_ENABLE_LOCKS */
6266             rxi_FreeCall(call, 0);
6267             return -2;
6268 #endif /* RX_ENABLE_LOCKS */
6269         }
6270         /* Non-active calls are destroyed if they are not responding
6271          * to pings; active calls are simply flagged in error, so the
6272          * attached process can die reasonably gracefully. */
6273     }
6274
6275     if (conn->idleDeadDetection) {
6276         if (conn->idleDeadTime) {
6277             idleDeadTime = conn->idleDeadTime + fudgeFactor;
6278         }
6279
6280         if (idleDeadTime) {
6281             /* see if we have a non-activity timeout */
6282             if (call->startWait && ((call->startWait + idleDeadTime) < now) &&
6283                 (call->flags & RX_CALL_READER_WAIT)) {
6284                 if (call->state == RX_STATE_ACTIVE) {
6285                     cerror = RX_CALL_TIMEOUT;
6286                     goto mtuout;
6287                 }
6288             }
6289
6290             if (call->lastSendData && ((call->lastSendData + idleDeadTime) < now)) {
6291                 if (call->state == RX_STATE_ACTIVE) {
6292                     cerror = conn->service ? conn->service->idleDeadErr : RX_CALL_IDLE;
6293                     idle_timeout = 1;
6294                     goto mtuout;
6295                 }
6296             }
6297         }
6298     }
6299
6300     if (conn->hardDeadTime) {
6301         hardDeadTime = conn->hardDeadTime + fudgeFactor;
6302     }
6303
6304     /* see if we have a hard timeout */
6305     if (hardDeadTime
6306         && (now > (hardDeadTime + call->startTime.sec))) {
6307         if (call->state == RX_STATE_ACTIVE)
6308             rxi_CallError(call, RX_CALL_TIMEOUT);
6309         return -1;
6310     }
6311     return 0;
6312 mtuout:
6313     if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT && !idle_timeout &&
6314         call->lastReceiveTime) {
6315         int oldMTU = conn->peer->ifMTU;
6316
6317         /* if we thought we could send more, perhaps things got worse */
6318         if (conn->peer->maxPacketSize > conn->lastPacketSize)
6319             /* maxpacketsize will be cleared in rxi_SetPeerMtu */
6320             newmtu = MAX(conn->peer->maxPacketSize-RX_IPUDP_SIZE,
6321                          conn->lastPacketSize-(128+RX_IPUDP_SIZE));
6322         else
6323             newmtu = conn->lastPacketSize-(128+RX_IPUDP_SIZE);
6324
6325         /* minimum capped in SetPeerMtu */
6326         rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6327
6328         /* clean up */
6329         conn->lastPacketSize = 0;
6330
6331         /* needed so ResetCall doesn't clobber us. */
6332         call->MTU = conn->peer->ifMTU;
6333
6334         /* if we never succeeded, let the error pass out as-is */
6335         if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6336             cerror = conn->msgsizeRetryErr;
6337
6338     }
6339     rxi_CallError(call, cerror);
6340     return -1;
6341 }
6342
6343 void
6344 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1,
6345                       void *dummy, int dummy2)
6346 {
6347     struct rx_connection *conn = arg1;
6348     struct rx_header theader;
6349     char tbuffer[1 + sizeof(struct rx_header)];
6350     struct sockaddr_in taddr;
6351     char *tp;
6352     char a[1] = { 0 };
6353     struct iovec tmpiov[2];
6354     osi_socket socket =
6355         (conn->type ==
6356          RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6357
6358
6359     tp = &tbuffer[sizeof(struct rx_header)];
6360     taddr.sin_family = AF_INET;
6361     taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6362     taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6363 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6364     taddr.sin_len = sizeof(struct sockaddr_in);
6365 #endif
6366     memset(&theader, 0, sizeof(theader));
6367     theader.epoch = htonl(999);
6368     theader.cid = 0;
6369     theader.callNumber = 0;
6370     theader.seq = 0;
6371     theader.serial = 0;
6372     theader.type = RX_PACKET_TYPE_VERSION;
6373     theader.flags = RX_LAST_PACKET;
6374     theader.serviceId = 0;
6375
6376     memcpy(tbuffer, &theader, sizeof(theader));
6377     memcpy(tp, &a, sizeof(a));
6378     tmpiov[0].iov_base = tbuffer;
6379     tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6380
6381     osi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6382
6383     MUTEX_ENTER(&conn->conn_data_lock);
6384     MUTEX_ENTER(&rx_refcnt_mutex);
6385     /* Only reschedule ourselves if the connection would not be destroyed */
6386     if (conn->refCount <= 1) {
6387         rxevent_Put(conn->natKeepAliveEvent);
6388         conn->natKeepAliveEvent = NULL;
6389         MUTEX_EXIT(&rx_refcnt_mutex);
6390         MUTEX_EXIT(&conn->conn_data_lock);
6391         rx_DestroyConnection(conn); /* drop the reference for this */
6392     } else {
6393         conn->refCount--; /* drop the reference for this */
6394         MUTEX_EXIT(&rx_refcnt_mutex);
6395         rxevent_Put(conn->natKeepAliveEvent);
6396         conn->natKeepAliveEvent = NULL;
6397         rxi_ScheduleNatKeepAliveEvent(conn);
6398         MUTEX_EXIT(&conn->conn_data_lock);
6399     }
6400 }
6401
6402 void
6403 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6404 {
6405     if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6406         struct clock when, now;
6407         clock_GetTime(&now);
6408         when = now;
6409         when.sec += conn->secondsUntilNatPing;
6410         MUTEX_ENTER(&rx_refcnt_mutex);
6411         conn->refCount++; /* hold a reference for this */
6412         MUTEX_EXIT(&rx_refcnt_mutex);
6413         conn->natKeepAliveEvent =
6414             rxevent_Post(&when, &now, rxi_NatKeepAliveEvent, conn, NULL, 0);
6415     }
6416 }
6417
6418 void
6419 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6420 {
6421     MUTEX_ENTER(&conn->conn_data_lock);
6422     conn->secondsUntilNatPing = seconds;
6423     if (seconds != 0) {
6424         if (!(conn->flags & RX_CONN_ATTACHWAIT))
6425             rxi_ScheduleNatKeepAliveEvent(conn);
6426         else
6427             conn->flags |= RX_CONN_NAT_PING;
6428     }
6429     MUTEX_EXIT(&conn->conn_data_lock);
6430 }
6431
6432 void
6433 rxi_NatKeepAliveOn(struct rx_connection *conn)
6434 {
6435     MUTEX_ENTER(&conn->conn_data_lock);
6436     /* if it's already attached */
6437     if (!(conn->flags & RX_CONN_ATTACHWAIT))
6438         rxi_ScheduleNatKeepAliveEvent(conn);
6439     else
6440         conn->flags |= RX_CONN_NAT_PING;
6441     MUTEX_EXIT(&conn->conn_data_lock);
6442 }
6443
6444 /* When a call is in progress, this routine is called occasionally to
6445  * make sure that some traffic has arrived (or been sent to) the peer.
6446  * If nothing has arrived in a reasonable amount of time, the call is
6447  * declared dead; if nothing has been sent for a while, we send a
6448  * keep-alive packet (if we're actually trying to keep the call alive)
6449  */
6450 void
6451 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy,
6452                    int dummy2)
6453 {
6454     struct rx_call *call = arg1;
6455     struct rx_connection *conn;
6456     afs_uint32 now;
6457
6458     CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6459     MUTEX_ENTER(&call->lock);
6460
6461     if (event == call->keepAliveEvent) {
6462         rxevent_Put(call->keepAliveEvent);
6463         call->keepAliveEvent = NULL;
6464     }
6465
6466     now = clock_Sec();
6467
6468 #ifdef RX_ENABLE_LOCKS
6469     if (rxi_CheckCall(call, 0)) {
6470         MUTEX_EXIT(&call->lock);
6471         return;
6472     }
6473 #else /* RX_ENABLE_LOCKS */
6474     if (rxi_CheckCall(call))
6475         return;
6476 #endif /* RX_ENABLE_LOCKS */
6477
6478     /* Don't try to keep alive dallying calls */
6479     if (call->state == RX_STATE_DALLY) {
6480         MUTEX_EXIT(&call->lock);
6481         return;
6482     }
6483
6484     conn = call->conn;
6485     if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6486         /* Don't try to send keepalives if there is unacknowledged data */
6487         /* the rexmit code should be good enough, this little hack
6488          * doesn't quite work XXX */
6489         (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6490     }
6491     rxi_ScheduleKeepAliveEvent(call);
6492     MUTEX_EXIT(&call->lock);
6493 }
6494
6495 /* Does what's on the nameplate. */
6496 void
6497 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy, int dummy2)
6498 {
6499     struct rx_call *call = arg1;
6500     struct rx_connection *conn;
6501
6502     CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6503     MUTEX_ENTER(&call->lock);
6504
6505     if (event == call->growMTUEvent) {
6506         rxevent_Put(call->growMTUEvent);
6507         call->growMTUEvent = NULL;
6508     }
6509
6510 #ifdef RX_ENABLE_LOCKS
6511     if (rxi_CheckCall(call, 0)) {
6512         MUTEX_EXIT(&call->lock);
6513         return;
6514     }
6515 #else /* RX_ENABLE_LOCKS */
6516     if (rxi_CheckCall(call))
6517         return;
6518 #endif /* RX_ENABLE_LOCKS */
6519
6520     /* Don't bother with dallying calls */
6521     if (call->state == RX_STATE_DALLY) {
6522         MUTEX_EXIT(&call->lock);
6523         return;
6524     }
6525
6526     conn = call->conn;
6527
6528     /*
6529      * keep being scheduled, just don't do anything if we're at peak,
6530      * or we're not set up to be properly handled (idle timeout required)
6531      */
6532     if ((conn->peer->maxPacketSize != 0) &&
6533         (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6534         conn->idleDeadDetection)
6535         (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6536     rxi_ScheduleGrowMTUEvent(call, 0);
6537     MUTEX_EXIT(&call->lock);
6538 }
6539
6540 void
6541 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6542 {
6543     if (!call->keepAliveEvent) {
6544         struct clock when, now;
6545         clock_GetTime(&now);
6546         when = now;
6547         when.sec += call->conn->secondsUntilPing;
6548         CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6549         call->keepAliveEvent =
6550             rxevent_Post(&when, &now, rxi_KeepAliveEvent, call, NULL, 0);
6551     }
6552 }
6553
6554 void
6555 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6556 {
6557     if (!call->growMTUEvent) {
6558         struct clock when, now;
6559
6560         clock_GetTime(&now);
6561         when = now;
6562         if (!secs) {
6563             if (call->conn->secondsUntilPing)
6564                 secs = (6*call->conn->secondsUntilPing)-1;
6565
6566             if (call->conn->secondsUntilDead)
6567                 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6568         }
6569
6570         when.sec += secs;
6571         CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6572         call->growMTUEvent =
6573             rxevent_Post(&when, &now, rxi_GrowMTUEvent, call, NULL, 0);
6574     }
6575 }
6576
6577 /* N.B. rxi_KeepAliveOff:  is defined earlier as a macro */
6578 void
6579 rxi_KeepAliveOn(struct rx_call *call)
6580 {
6581     /* Pretend last packet received was received now--i.e. if another
6582      * packet isn't received within the keep alive time, then the call
6583      * will die; Initialize last send time to the current time--even
6584      * if a packet hasn't been sent yet.  This will guarantee that a
6585      * keep-alive is sent within the ping time */
6586     call->lastReceiveTime = call->lastSendTime = clock_Sec();
6587     rxi_ScheduleKeepAliveEvent(call);
6588 }
6589
6590 /*
6591  * Solely in order that callers not need to include rx_call.h
6592  */
6593 void
6594 rx_KeepAliveOff(struct rx_call *call)
6595 {
6596     rxi_KeepAliveOff(call);
6597 }
6598 void
6599 rx_KeepAliveOn(struct rx_call *call)
6600 {
6601     rxi_KeepAliveOn(call);
6602 }
6603
6604 void
6605 rxi_GrowMTUOn(struct rx_call *call)
6606 {
6607     struct rx_connection *conn = call->conn;
6608     MUTEX_ENTER(&conn->conn_data_lock);
6609     conn->lastPingSizeSer = conn->lastPingSize = 0;
6610     MUTEX_EXIT(&conn->conn_data_lock);
6611     rxi_ScheduleGrowMTUEvent(call, 1);
6612 }
6613
6614 /* This routine is called to send connection abort messages
6615  * that have been delayed to throttle looping clients. */
6616 void
6617 rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1, void *unused,
6618                          int unused2)
6619 {
6620     struct rx_connection *conn = arg1;
6621
6622     afs_int32 error;
6623     struct rx_packet *packet;
6624
6625     MUTEX_ENTER(&conn->conn_data_lock);
6626     rxevent_Put(conn->delayedAbortEvent);
6627     conn->delayedAbortEvent = NULL;
6628     error = htonl(conn->error);
6629     conn->abortCount++;
6630     MUTEX_EXIT(&conn->conn_data_lock);
6631     packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6632     if (packet) {
6633         packet =
6634             rxi_SendSpecial((struct rx_call *)0, conn, packet,
6635                             RX_PACKET_TYPE_ABORT, (char *)&error,
6636                             sizeof(error), 0);
6637         rxi_FreePacket(packet);
6638     }
6639 }
6640
6641 /* This routine is called to send call abort messages
6642  * that have been delayed to throttle looping clients. */
6643 static void
6644 rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1, void *dummy,
6645                          int dummy2)
6646 {
6647     struct rx_call *call = arg1;
6648
6649     afs_int32 error;
6650     struct rx_packet *packet;
6651
6652     MUTEX_ENTER(&call->lock);
6653     rxevent_Put(call->delayedAbortEvent);
6654     call->delayedAbortEvent = NULL;
6655     error = htonl(call->error);
6656     call->abortCount++;
6657     packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6658     if (packet) {
6659         packet =
6660             rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6661                             (char *)&error, sizeof(error), 0);
6662         rxi_FreePacket(packet);
6663     }
6664     MUTEX_EXIT(&call->lock);
6665     CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6666 }
6667
6668 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6669  * seconds) to ask the client to authenticate itself.  The routine
6670  * issues a challenge to the client, which is obtained from the
6671  * security object associated with the connection */
6672 void
6673 rxi_ChallengeEvent(struct rxevent *event,
6674                    void *arg0, void *arg1, int tries)
6675 {
6676     struct rx_connection *conn = arg0;
6677
6678     if (event) {
6679         rxevent_Put(conn->challengeEvent);
6680         conn->challengeEvent = NULL;
6681     }
6682
6683     if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6684         struct rx_packet *packet;
6685         struct clock when, now;
6686
6687         if (tries <= 0) {
6688             /* We've failed to authenticate for too long.
6689              * Reset any calls waiting for authentication;
6690              * they are all in RX_STATE_PRECALL.
6691              */
6692             int i;
6693
6694             MUTEX_ENTER(&conn->conn_call_lock);
6695             for (i = 0; i < RX_MAXCALLS; i++) {
6696                 struct rx_call *call = conn->call[i];
6697                 if (call) {
6698                     MUTEX_ENTER(&call->lock);
6699                     if (call->state == RX_STATE_PRECALL) {
6700                         rxi_CallError(call, RX_CALL_DEAD);
6701                         rxi_SendCallAbort(call, NULL, 0, 0);
6702                     }
6703                     MUTEX_EXIT(&call->lock);
6704                 }
6705             }
6706             MUTEX_EXIT(&conn->conn_call_lock);
6707             return;
6708         }
6709
6710         packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6711         if (packet) {
6712             /* If there's no packet available, do this later. */
6713             RXS_GetChallenge(conn->securityObject, conn, packet);
6714             rxi_SendSpecial((struct rx_call *)0, conn, packet,
6715                             RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6716             rxi_FreePacket(packet);
6717         }
6718         clock_GetTime(&now);
6719         when = now;
6720         when.sec += RX_CHALLENGE_TIMEOUT;
6721         conn->challengeEvent =
6722             rxevent_Post(&when, &now, rxi_ChallengeEvent, conn, 0,
6723                          (tries - 1));
6724     }
6725 }
6726
6727 /* Call this routine to start requesting the client to authenticate
6728  * itself.  This will continue until authentication is established,
6729  * the call times out, or an invalid response is returned.  The
6730  * security object associated with the connection is asked to create
6731  * the challenge at this time.  N.B.  rxi_ChallengeOff is a macro,
6732  * defined earlier. */
6733 void
6734 rxi_ChallengeOn(struct rx_connection *conn)
6735 {
6736     if (!conn->challengeEvent) {
6737         RXS_CreateChallenge(conn->securityObject, conn);
6738         rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
6739     };
6740 }
6741
6742
6743 /* rxi_ComputeRoundTripTime is called with peer locked. */
6744 /* peer may be null */
6745 static void
6746 rxi_ComputeRoundTripTime(struct rx_packet *p,
6747                          struct rx_ackPacket *ack,
6748                          struct rx_call *call,
6749                          struct rx_peer *peer,
6750                          struct clock *now)
6751 {
6752     struct clock thisRtt, *sentp;
6753     int rtt_timeout;
6754     int serial;
6755
6756     /* If the ACK is delayed, then do nothing */
6757     if (ack->reason == RX_ACK_DELAY)
6758         return;
6759
6760     /* On the wire, jumbograms are a single UDP packet. We shouldn't count
6761      * their RTT multiple times, so only include the RTT of the last packet
6762      * in a jumbogram */
6763     if (p->flags & RX_JUMBO_PACKET)
6764         return;
6765
6766     /* Use the serial number to determine which transmission the ACK is for,
6767      * and set the sent time to match this. If we have no serial number, then
6768      * only use the ACK for RTT calculations if the packet has not been
6769      * retransmitted
6770      */
6771
6772     serial = ntohl(ack->serial);
6773     if (serial) {
6774         if (serial == p->header.serial) {
6775             sentp = &p->timeSent;
6776         } else if (serial == p->firstSerial) {
6777             sentp = &p->firstSent;
6778         } else if (clock_Eq(&p->timeSent, &p->firstSent)) {
6779             sentp = &p->firstSent;
6780         } else
6781             return;
6782     } else {
6783         if (clock_Eq(&p->timeSent, &p->firstSent)) {
6784             sentp = &p->firstSent;
6785         } else
6786             return;
6787     }
6788
6789     thisRtt = *now;
6790
6791     if (clock_Lt(&thisRtt, sentp))
6792         return;                 /* somebody set the clock back, don't count this time. */
6793
6794     clock_Sub(&thisRtt, sentp);
6795     dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rttp=%d.%06d sec)\n",
6796           p->header.callNumber, p, thisRtt.sec, thisRtt.usec));
6797
6798     if (clock_IsZero(&thisRtt)) {
6799         /*
6800          * The actual round trip time is shorter than the
6801          * clock_GetTime resolution.  It is most likely 1ms or 100ns.
6802          * Since we can't tell which at the moment we will assume 1ms.
6803          */
6804         thisRtt.usec = 1000;
6805     }
6806
6807     if (rx_stats_active) {
6808         MUTEX_ENTER(&rx_stats_mutex);
6809         if (clock_Lt(&thisRtt, &rx_stats.minRtt))
6810             rx_stats.minRtt = thisRtt;
6811         if (clock_Gt(&thisRtt, &rx_stats.maxRtt)) {
6812             if (thisRtt.sec > 60) {
6813                 MUTEX_EXIT(&rx_stats_mutex);
6814                 return;         /* somebody set the clock ahead */
6815             }
6816             rx_stats.maxRtt = thisRtt;
6817         }
6818         clock_Add(&rx_stats.totalRtt, &thisRtt);
6819         rx_atomic_inc(&rx_stats.nRttSamples);
6820         MUTEX_EXIT(&rx_stats_mutex);
6821     }
6822
6823     /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6824
6825     /* Apply VanJacobson round-trip estimations */
6826     if (call->rtt) {
6827         int delta;
6828
6829         /*
6830          * srtt (call->rtt) is in units of one-eighth-milliseconds.
6831          * srtt is stored as fixed point with 3 bits after the binary
6832          * point (i.e., scaled by 8). The following magic is
6833          * equivalent to the smoothing algorithm in rfc793 with an
6834          * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
6835          * srtt'*8 = rtt + srtt*7
6836          * srtt'*8 = srtt*8 + rtt - srtt
6837          * srtt' = srtt + rtt/8 - srtt/8
6838          * srtt' = srtt + (rtt - srtt)/8
6839          */
6840
6841         delta = _8THMSEC(&thisRtt) - call->rtt;
6842         call->rtt += (delta >> 3);
6843
6844         /*
6845          * We accumulate a smoothed rtt variance (actually, a smoothed
6846          * mean difference), then set the retransmit timer to smoothed
6847          * rtt + 4 times the smoothed variance (was 2x in van's original
6848          * paper, but 4x works better for me, and apparently for him as
6849          * well).
6850          * rttvar is stored as
6851          * fixed point with 2 bits after the binary point (scaled by
6852          * 4).  The following is equivalent to rfc793 smoothing with
6853          * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
6854          *   rttvar'*4 = rttvar*3 + |delta|
6855          *   rttvar'*4 = rttvar*4 + |delta| - rttvar
6856          *   rttvar' = rttvar + |delta|/4 - rttvar/4
6857          *   rttvar' = rttvar + (|delta| - rttvar)/4
6858          * This replaces rfc793's wired-in beta.
6859          * dev*4 = dev*4 + (|actual - expected| - dev)
6860          */
6861
6862         if (delta < 0)
6863             delta = -delta;
6864
6865         delta -= (call->rtt_dev << 1);
6866         call->rtt_dev += (delta >> 3);
6867     } else {
6868         /* I don't have a stored RTT so I start with this value.  Since I'm
6869          * probably just starting a call, and will be pushing more data down
6870          * this, I expect congestion to increase rapidly.  So I fudge a
6871          * little, and I set deviance to half the rtt.  In practice,
6872          * deviance tends to approach something a little less than
6873          * half the smoothed rtt. */
6874         call->rtt = _8THMSEC(&thisRtt) + 8;
6875         call->rtt_dev = call->rtt >> 2; /* rtt/2: they're scaled differently */
6876     }
6877     /* the smoothed RTT time is RTT + 4*MDEV
6878      *
6879      * We allow a user specified minimum to be set for this, to allow clamping
6880      * at a minimum value in the same way as TCP. In addition, we have to allow
6881      * for the possibility that this packet is answered by a delayed ACK, so we
6882      * add on a fixed 200ms to account for that timer expiring.
6883      */
6884
6885     rtt_timeout = MAX(((call->rtt >> 3) + call->rtt_dev),
6886                       rx_minPeerTimeout) + 200;
6887     clock_Zero(&call->rto);
6888     clock_Addmsec(&call->rto, rtt_timeout);
6889
6890     /* Update the peer, so any new calls start with our values */
6891     peer->rtt_dev = call->rtt_dev;
6892     peer->rtt = call->rtt;
6893
6894     dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rtt=%d ms, srtt=%d ms, rtt_dev=%d ms, timeout=%d.%06d sec)\n",
6895           p->header.callNumber, p, MSEC(&thisRtt), call->rtt >> 3, call->rtt_dev >> 2, (call->rto.sec), (call->rto.usec)));
6896 }
6897
6898
6899 /* Find all server connections that have not been active for a long time, and
6900  * toss them */
6901 void
6902 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2,
6903                     int unused3)
6904 {
6905     struct clock now, when;
6906     clock_GetTime(&now);
6907
6908     /* Find server connection structures that haven't been used for
6909      * greater than rx_idleConnectionTime */
6910     {
6911         struct rx_connection **conn_ptr, **conn_end;
6912         int i, havecalls = 0;
6913         MUTEX_ENTER(&rx_connHashTable_lock);
6914         for (conn_ptr = &rx_connHashTable[0], conn_end =
6915              &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
6916              conn_ptr++) {
6917             struct rx_connection *conn, *next;
6918             struct rx_call *call;
6919             int result;
6920
6921           rereap:
6922             for (conn = *conn_ptr; conn; conn = next) {
6923                 /* XXX -- Shouldn't the connection be locked? */
6924                 next = conn->next;
6925                 havecalls = 0;
6926                 for (i = 0; i < RX_MAXCALLS; i++) {
6927                     call = conn->call[i];
6928                     if (call) {
6929                         int code;
6930                         havecalls = 1;
6931                         code = MUTEX_TRYENTER(&call->lock);
6932                         if (!code)
6933                             continue;
6934 #ifdef RX_ENABLE_LOCKS
6935                         result = rxi_CheckCall(call, 1);
6936 #else /* RX_ENABLE_LOCKS */
6937                         result = rxi_CheckCall(call);
6938 #endif /* RX_ENABLE_LOCKS */
6939                         MUTEX_EXIT(&call->lock);
6940                         if (result == -2) {
6941                             /* If CheckCall freed the call, it might
6942                              * have destroyed  the connection as well,
6943                              * which screws up the linked lists.
6944                              */
6945                             goto rereap;
6946                         }
6947                     }
6948                 }
6949                 if (conn->type == RX_SERVER_CONNECTION) {
6950                     /* This only actually destroys the connection if
6951                      * there are no outstanding calls */
6952                     MUTEX_ENTER(&conn->conn_data_lock);
6953                     MUTEX_ENTER(&rx_refcnt_mutex);
6954                     if (!havecalls && !conn->refCount
6955                         && ((conn->lastSendTime + rx_idleConnectionTime) <
6956                             now.sec)) {
6957                         conn->refCount++;       /* it will be decr in rx_DestroyConn */
6958                         MUTEX_EXIT(&rx_refcnt_mutex);
6959                         MUTEX_EXIT(&conn->conn_data_lock);
6960 #ifdef RX_ENABLE_LOCKS
6961                         rxi_DestroyConnectionNoLock(conn);
6962 #else /* RX_ENABLE_LOCKS */
6963                         rxi_DestroyConnection(conn);
6964 #endif /* RX_ENABLE_LOCKS */
6965                     }
6966 #ifdef RX_ENABLE_LOCKS
6967                     else {
6968                         MUTEX_EXIT(&rx_refcnt_mutex);
6969                         MUTEX_EXIT(&conn->conn_data_lock);
6970                     }
6971 #endif /* RX_ENABLE_LOCKS */
6972                 }
6973             }
6974         }
6975 #ifdef RX_ENABLE_LOCKS
6976         while (rx_connCleanup_list) {
6977             struct rx_connection *conn;
6978             conn = rx_connCleanup_list;
6979             rx_connCleanup_list = rx_connCleanup_list->next;
6980             MUTEX_EXIT(&rx_connHashTable_lock);
6981             rxi_CleanupConnection(conn);
6982             MUTEX_ENTER(&rx_connHashTable_lock);
6983         }
6984         MUTEX_EXIT(&rx_connHashTable_lock);
6985 #endif /* RX_ENABLE_LOCKS */
6986     }
6987
6988     /* Find any peer structures that haven't been used (haven't had an
6989      * associated connection) for greater than rx_idlePeerTime */
6990     {
6991         struct rx_peer **peer_ptr, **peer_end;
6992         int code;
6993
6994         /*
6995          * Why do we need to hold the rx_peerHashTable_lock across
6996          * the incrementing of peer_ptr since the rx_peerHashTable
6997          * array is not changing?  We don't.
6998          *
6999          * By dropping the lock periodically we can permit other
7000          * activities to be performed while a rxi_ReapConnections
7001          * call is in progress.  The goal of reap connections
7002          * is to clean up quickly without causing large amounts
7003          * of contention.  Therefore, it is important that global
7004          * mutexes not be held for extended periods of time.
7005          */
7006         for (peer_ptr = &rx_peerHashTable[0], peer_end =
7007              &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7008              peer_ptr++) {
7009             struct rx_peer *peer, *next, *prev;
7010
7011             MUTEX_ENTER(&rx_peerHashTable_lock);
7012             for (prev = peer = *peer_ptr; peer; peer = next) {
7013                 next = peer->next;
7014                 code = MUTEX_TRYENTER(&peer->peer_lock);
7015                 if ((code) && (peer->refCount == 0)
7016                     && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
7017                     rx_interface_stat_p rpc_stat, nrpc_stat;
7018                     size_t space;
7019
7020                     /*
7021                      * now know that this peer object is one to be
7022                      * removed from the hash table.  Once it is removed
7023                      * it can't be referenced by other threads.
7024                      * Lets remove it first and decrement the struct
7025                      * nPeerStructs count.
7026                      */
7027                     if (peer == *peer_ptr) {
7028                         *peer_ptr = next;
7029                         prev = next;
7030                     } else
7031                         prev->next = next;
7032
7033                     if (rx_stats_active)
7034                         rx_atomic_dec(&rx_stats.nPeerStructs);
7035
7036                     /*
7037                      * Now if we hold references on 'prev' and 'next'
7038                      * we can safely drop the rx_peerHashTable_lock
7039                      * while we destroy this 'peer' object.
7040                      */
7041                     if (next)
7042                         next->refCount++;
7043                     if (prev)
7044                         prev->refCount++;
7045                     MUTEX_EXIT(&rx_peerHashTable_lock);
7046
7047                     MUTEX_EXIT(&peer->peer_lock);
7048                     MUTEX_DESTROY(&peer->peer_lock);
7049                     for (queue_Scan
7050                          (&peer->rpcStats, rpc_stat, nrpc_stat,
7051                           rx_interface_stat)) {
7052                         unsigned int num_funcs;
7053                         if (!rpc_stat)
7054                             break;
7055                         queue_Remove(&rpc_stat->queue_header);
7056                         queue_Remove(&rpc_stat->all_peers);
7057                         num_funcs = rpc_stat->stats[0].func_total;
7058                         space =
7059                             sizeof(rx_interface_stat_t) +
7060                             rpc_stat->stats[0].func_total *
7061                             sizeof(rx_function_entry_v1_t);
7062
7063                         rxi_Free(rpc_stat, space);
7064
7065                         MUTEX_ENTER(&rx_rpc_stats);
7066                         rxi_rpc_peer_stat_cnt -= num_funcs;
7067                         MUTEX_EXIT(&rx_rpc_stats);
7068                     }
7069                     rxi_FreePeer(peer);
7070
7071                     /*
7072                      * Regain the rx_peerHashTable_lock and
7073                      * decrement the reference count on 'prev'
7074                      * and 'next'.
7075                      */
7076                     MUTEX_ENTER(&rx_peerHashTable_lock);
7077                     if (next)
7078                         next->refCount--;
7079                     if (prev)
7080                         prev->refCount--;
7081                 } else {
7082                     if (code) {
7083                         MUTEX_EXIT(&peer->peer_lock);
7084                     }
7085                     prev = peer;
7086                 }
7087             }
7088             MUTEX_EXIT(&rx_peerHashTable_lock);
7089         }
7090     }
7091
7092     /* THIS HACK IS A TEMPORARY HACK.  The idea is that the race condition in
7093      * rxi_AllocSendPacket, if it hits, will be handled at the next conn
7094      * GC, just below.  Really, we shouldn't have to keep moving packets from
7095      * one place to another, but instead ought to always know if we can
7096      * afford to hold onto a packet in its particular use.  */
7097     MUTEX_ENTER(&rx_freePktQ_lock);
7098     if (rx_waitingForPackets) {
7099         rx_waitingForPackets = 0;
7100 #ifdef  RX_ENABLE_LOCKS
7101         CV_BROADCAST(&rx_waitingForPackets_cv);
7102 #else
7103         osi_rxWakeup(&rx_waitingForPackets);
7104 #endif
7105     }
7106     MUTEX_EXIT(&rx_freePktQ_lock);
7107
7108     when = now;
7109     when.sec += RX_REAP_TIME;   /* Check every RX_REAP_TIME seconds */
7110     rxevent_Put(rxevent_Post(&when, &now, rxi_ReapConnections, 0, NULL, 0));
7111 }
7112
7113
7114 /* rxs_Release - This isn't strictly necessary but, since the macro name from
7115  * rx.h is sort of strange this is better.  This is called with a security
7116  * object before it is discarded.  Each connection using a security object has
7117  * its own refcount to the object so it won't actually be freed until the last
7118  * connection is destroyed.
7119  *
7120  * This is the only rxs module call.  A hold could also be written but no one
7121  * needs it. */
7122
7123 int
7124 rxs_Release(struct rx_securityClass *aobj)
7125 {
7126     return RXS_Close(aobj);
7127 }
7128
7129 void
7130 rxi_DebugInit(void)
7131 {
7132 #ifdef RXDEBUG
7133 #ifdef AFS_NT40_ENV
7134 #define TRACE_OPTION_RX_DEBUG 16
7135     HKEY parmKey;
7136     DWORD dummyLen;
7137     DWORD TraceOption;
7138     long code;
7139
7140     rxdebug_active = 0;
7141
7142     code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
7143                          0, KEY_QUERY_VALUE, &parmKey);
7144     if (code != ERROR_SUCCESS)
7145         return;
7146
7147     dummyLen = sizeof(TraceOption);
7148     code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
7149                            (BYTE *) &TraceOption, &dummyLen);
7150     if (code == ERROR_SUCCESS) {
7151         rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
7152     }
7153     RegCloseKey (parmKey);
7154 #endif /* AFS_NT40_ENV */
7155 #endif
7156 }
7157
7158 void
7159 rx_DebugOnOff(int on)
7160 {
7161 #ifdef RXDEBUG
7162 #ifdef AFS_NT40_ENV
7163     rxdebug_active = on;
7164 #endif
7165 #endif
7166 }
7167
7168 void
7169 rx_StatsOnOff(int on)
7170 {
7171     rx_stats_active = on;
7172 }
7173
7174
7175 /* Don't call this debugging routine directly; use dpf */
7176 void
7177 rxi_DebugPrint(char *format, ...)
7178 {
7179 #ifdef RXDEBUG
7180     va_list ap;
7181 #ifdef AFS_NT40_ENV
7182     char msg[512];
7183     char tformat[256];
7184     size_t len;
7185
7186     va_start(ap, format);
7187
7188     len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7189
7190     if (len > 0) {
7191         len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7192         if (len > 0)
7193             OutputDebugString(msg);
7194     }
7195     va_end(ap);
7196 #else
7197     struct clock now;
7198
7199     va_start(ap, format);
7200
7201     clock_GetTime(&now);
7202     fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7203             (unsigned int)now.usec);
7204     vfprintf(rx_Log, format, ap);
7205     va_end(ap);
7206 #endif
7207 #endif
7208 }
7209
7210 #ifndef KERNEL
7211 /*
7212  * This function is used to process the rx_stats structure that is local
7213  * to a process as well as an rx_stats structure received from a remote
7214  * process (via rxdebug).  Therefore, it needs to do minimal version
7215  * checking.
7216  */
7217 void
7218 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7219                    afs_int32 freePackets, char version)
7220 {
7221     int i;
7222
7223     if (size != sizeof(struct rx_statistics)) {
7224         fprintf(file,
7225                 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7226                 size, sizeof(struct rx_statistics));
7227     }
7228
7229     fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7230             s->packetRequests);
7231
7232     if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7233         fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7234                 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7235                 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7236                 s->specialPktAllocFailures);
7237     } else {
7238         fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7239                 s->receivePktAllocFailures, s->sendPktAllocFailures,
7240                 s->specialPktAllocFailures);
7241     }
7242
7243     fprintf(file,
7244             "   greedy %u, " "bogusReads %u (last from host %x), "
7245             "noPackets %u, " "noBuffers %u, " "selects %u, "
7246             "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7247             s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7248             s->selects, s->sendSelects);
7249
7250     fprintf(file, "   packets read: ");
7251     for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7252         fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7253     }
7254     fprintf(file, "\n");
7255
7256     fprintf(file,
7257             "   other read counters: data %u, " "ack %u, " "dup %u "
7258             "spurious %u " "dally %u\n", s->dataPacketsRead,
7259             s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7260             s->ignorePacketDally);
7261
7262     fprintf(file, "   packets sent: ");
7263     for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7264         fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7265     }
7266     fprintf(file, "\n");
7267
7268     fprintf(file,
7269             "   other send counters: ack %u, " "data %u (not resends), "
7270             "resends %u, " "pushed %u, " "acked&ignored %u\n",
7271             s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7272             s->dataPacketsPushed, s->ignoreAckedPacket);
7273
7274     fprintf(file,
7275             "   \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7276             s->netSendFailures, (int)s->fatalErrors);
7277
7278     if (s->nRttSamples) {
7279         fprintf(file, "   Average rtt is %0.3f, with %d samples\n",
7280                 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7281
7282         fprintf(file, "   Minimum rtt is %0.3f, maximum is %0.3f\n",
7283                 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7284     }
7285
7286     fprintf(file,
7287             "   %d server connections, " "%d client connections, "
7288             "%d peer structs, " "%d call structs, " "%d free call structs\n",
7289             s->nServerConns, s->nClientConns, s->nPeerStructs,
7290             s->nCallStructs, s->nFreeCallStructs);
7291
7292 #if     !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7293     fprintf(file, "   %d clock updates\n", clock_nUpdates);
7294 #endif
7295 }
7296
7297 /* for backward compatibility */
7298 void
7299 rx_PrintStats(FILE * file)
7300 {
7301     MUTEX_ENTER(&rx_stats_mutex);
7302     rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7303                        sizeof(rx_stats), rx_nFreePackets,
7304                        RX_DEBUGI_VERSION);
7305     MUTEX_EXIT(&rx_stats_mutex);
7306 }
7307
7308 void
7309 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7310 {
7311     fprintf(file, "Peer %x.%d.  " "Burst size %d, " "burst wait %d.%06d.\n",
7312             ntohl(peer->host), (int)ntohs(peer->port), (int)peer->burstSize,
7313             (int)peer->burstWait.sec, (int)peer->burstWait.usec);
7314
7315     fprintf(file,
7316             "   Rtt %d, " "total sent %d, " "resent %d\n",
7317             peer->rtt, peer->nSent, peer->reSends);
7318
7319     fprintf(file,
7320             "   Packet size %d, " "max in packet skew %d, "
7321             "max out packet skew %d\n", peer->ifMTU, (int)peer->inPacketSkew,
7322             (int)peer->outPacketSkew);
7323 }
7324 #endif
7325
7326 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7327 /*
7328  * This mutex protects the following static variables:
7329  * counter
7330  */
7331
7332 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7333 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7334 #else
7335 #define LOCK_RX_DEBUG
7336 #define UNLOCK_RX_DEBUG
7337 #endif /* AFS_PTHREAD_ENV */
7338
7339 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7340 static int
7341 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7342               u_char type, void *inputData, size_t inputLength,
7343               void *outputData, size_t outputLength)
7344 {
7345     static afs_int32 counter = 100;
7346     time_t waitTime, waitCount;
7347     struct rx_header theader;
7348     char tbuffer[1500];
7349     afs_int32 code;
7350     struct timeval tv_now, tv_wake, tv_delta;
7351     struct sockaddr_in taddr, faddr;
7352 #ifdef AFS_NT40_ENV
7353     int faddrLen;
7354 #else
7355     socklen_t faddrLen;
7356 #endif
7357     fd_set imask;
7358     char *tp;
7359
7360     waitTime = 1;
7361     waitCount = 5;
7362     LOCK_RX_DEBUG;
7363     counter++;
7364     UNLOCK_RX_DEBUG;
7365     tp = &tbuffer[sizeof(struct rx_header)];
7366     taddr.sin_family = AF_INET;
7367     taddr.sin_port = remotePort;
7368     taddr.sin_addr.s_addr = remoteAddr;
7369 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7370     taddr.sin_len = sizeof(struct sockaddr_in);
7371 #endif
7372     while (1) {
7373         memset(&theader, 0, sizeof(theader));
7374         theader.epoch = htonl(999);
7375         theader.cid = 0;
7376         theader.callNumber = htonl(counter);
7377         theader.seq = 0;
7378         theader.serial = 0;
7379         theader.type = type;
7380         theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7381         theader.serviceId = 0;
7382
7383         memcpy(tbuffer, &theader, sizeof(theader));
7384         memcpy(tp, inputData, inputLength);
7385         code =
7386             sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7387                    (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7388
7389         /* see if there's a packet available */
7390         gettimeofday(&tv_wake, NULL);
7391         tv_wake.tv_sec += waitTime;
7392         for (;;) {
7393             FD_ZERO(&imask);
7394             FD_SET(socket, &imask);
7395             tv_delta.tv_sec = tv_wake.tv_sec;
7396             tv_delta.tv_usec = tv_wake.tv_usec;
7397             gettimeofday(&tv_now, NULL);
7398
7399             if (tv_delta.tv_usec < tv_now.tv_usec) {
7400                 /* borrow */
7401                 tv_delta.tv_usec += 1000000;
7402                 tv_delta.tv_sec--;
7403             }
7404             tv_delta.tv_usec -= tv_now.tv_usec;
7405
7406             if (tv_delta.tv_sec < tv_now.tv_sec) {
7407                 /* time expired */
7408                 break;
7409             }
7410             tv_delta.tv_sec -= tv_now.tv_sec;
7411
7412 #ifdef AFS_NT40_ENV
7413             code = select(0, &imask, 0, 0, &tv_delta);
7414 #else /* AFS_NT40_ENV */
7415             code = select(socket + 1, &imask, 0, 0, &tv_delta);
7416 #endif /* AFS_NT40_ENV */
7417             if (code == 1 && FD_ISSET(socket, &imask)) {
7418                 /* now receive a packet */
7419                 faddrLen = sizeof(struct sockaddr_in);
7420                 code =
7421                     recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7422                              (struct sockaddr *)&faddr, &faddrLen);
7423
7424                 if (code > 0) {
7425                     memcpy(&theader, tbuffer, sizeof(struct rx_header));
7426                     if (counter == ntohl(theader.callNumber))
7427                         goto success;
7428                     continue;
7429                 }
7430             }
7431             break;
7432         }
7433
7434         /* see if we've timed out */
7435         if (!--waitCount) {
7436             return -1;
7437         }
7438         waitTime <<= 1;
7439     }
7440
7441  success:
7442     code -= sizeof(struct rx_header);
7443     if (code > outputLength)
7444         code = outputLength;
7445     memcpy(outputData, tp, code);
7446     return code;
7447 }
7448 #endif /* RXDEBUG */
7449
7450 afs_int32
7451 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7452                   afs_uint16 remotePort, struct rx_debugStats * stat,
7453                   afs_uint32 * supportedValues)
7454 {
7455 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7456     afs_int32 rc = 0;
7457     struct rx_debugIn in;
7458
7459     *supportedValues = 0;
7460     in.type = htonl(RX_DEBUGI_GETSTATS);
7461     in.index = 0;
7462
7463     rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7464                        &in, sizeof(in), stat, sizeof(*stat));
7465
7466     /*
7467      * If the call was successful, fixup the version and indicate
7468      * what contents of the stat structure are valid.
7469      * Also do net to host conversion of fields here.
7470      */
7471
7472     if (rc >= 0) {
7473         if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7474             *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7475         }
7476         if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7477             *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7478         }
7479         if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7480             *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7481         }
7482         if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7483             *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7484         }
7485         if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7486             *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7487         }
7488         if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7489             *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7490         }
7491         if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7492             *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7493         }
7494         if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7495             *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7496         }
7497         if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7498             *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7499         }
7500         stat->nFreePackets = ntohl(stat->nFreePackets);
7501         stat->packetReclaims = ntohl(stat->packetReclaims);
7502         stat->callsExecuted = ntohl(stat->callsExecuted);
7503         stat->nWaiting = ntohl(stat->nWaiting);
7504         stat->idleThreads = ntohl(stat->idleThreads);
7505         stat->nWaited = ntohl(stat->nWaited);
7506         stat->nPackets = ntohl(stat->nPackets);
7507     }
7508 #else
7509     afs_int32 rc = -1;
7510 #endif
7511     return rc;
7512 }
7513
7514 afs_int32
7515 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7516                   afs_uint16 remotePort, struct rx_statistics * stat,
7517                   afs_uint32 * supportedValues)
7518 {
7519 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7520     afs_int32 rc = 0;
7521     struct rx_debugIn in;
7522     afs_int32 *lp = (afs_int32 *) stat;
7523     int i;
7524
7525     /*
7526      * supportedValues is currently unused, but added to allow future
7527      * versioning of this function.
7528      */
7529
7530     *supportedValues = 0;
7531     in.type = htonl(RX_DEBUGI_RXSTATS);
7532     in.index = 0;
7533     memset(stat, 0, sizeof(*stat));
7534
7535     rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7536                        &in, sizeof(in), stat, sizeof(*stat));
7537
7538     if (rc >= 0) {
7539
7540         /*
7541          * Do net to host conversion here
7542          */
7543
7544         for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7545             *lp = ntohl(*lp);
7546         }
7547     }
7548 #else
7549     afs_int32 rc = -1;
7550 #endif
7551     return rc;
7552 }
7553
7554 afs_int32
7555 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7556                     afs_uint16 remotePort, size_t version_length,
7557                     char *version)
7558 {
7559 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7560     char a[1] = { 0 };
7561     return MakeDebugCall(socket, remoteAddr, remotePort,
7562                          RX_PACKET_TYPE_VERSION, a, 1, version,
7563                          version_length);
7564 #else
7565     return -1;
7566 #endif
7567 }
7568
7569 afs_int32
7570 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7571                         afs_uint16 remotePort, afs_int32 * nextConnection,
7572                         int allConnections, afs_uint32 debugSupportedValues,
7573                         struct rx_debugConn * conn,
7574                         afs_uint32 * supportedValues)
7575 {
7576 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7577     afs_int32 rc = 0;
7578     struct rx_debugIn in;
7579     int i;
7580
7581     /*
7582      * supportedValues is currently unused, but added to allow future
7583      * versioning of this function.
7584      */
7585
7586     *supportedValues = 0;
7587     if (allConnections) {
7588         in.type = htonl(RX_DEBUGI_GETALLCONN);
7589     } else {
7590         in.type = htonl(RX_DEBUGI_GETCONN);
7591     }
7592     in.index = htonl(*nextConnection);
7593     memset(conn, 0, sizeof(*conn));
7594
7595     rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7596                        &in, sizeof(in), conn, sizeof(*conn));
7597
7598     if (rc >= 0) {
7599         *nextConnection += 1;
7600
7601         /*
7602          * Convert old connection format to new structure.
7603          */
7604
7605         if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7606             struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7607 #define MOVEvL(a) (conn->a = vL->a)
7608
7609             /* any old or unrecognized version... */
7610             for (i = 0; i < RX_MAXCALLS; i++) {
7611                 MOVEvL(callState[i]);
7612                 MOVEvL(callMode[i]);
7613                 MOVEvL(callFlags[i]);
7614                 MOVEvL(callOther[i]);
7615             }
7616             if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7617                 MOVEvL(secStats.type);
7618                 MOVEvL(secStats.level);
7619                 MOVEvL(secStats.flags);
7620                 MOVEvL(secStats.expires);
7621                 MOVEvL(secStats.packetsReceived);
7622                 MOVEvL(secStats.packetsSent);
7623                 MOVEvL(secStats.bytesReceived);
7624                 MOVEvL(secStats.bytesSent);
7625             }
7626         }
7627
7628         /*
7629          * Do net to host conversion here
7630          * NOTE:
7631          *    I don't convert host or port since we are most likely
7632          *    going to want these in NBO.
7633          */
7634         conn->cid = ntohl(conn->cid);
7635         conn->serial = ntohl(conn->serial);
7636         for (i = 0; i < RX_MAXCALLS; i++) {
7637             conn->callNumber[i] = ntohl(conn->callNumber[i]);
7638         }
7639         conn->error = ntohl(conn->error);
7640         conn->secStats.flags = ntohl(conn->secStats.flags);
7641         conn->secStats.expires = ntohl(conn->secStats.expires);
7642         conn->secStats.packetsReceived =
7643             ntohl(conn->secStats.packetsReceived);
7644         conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7645         conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7646         conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7647         conn->epoch = ntohl(conn->epoch);
7648         conn->natMTU = ntohl(conn->natMTU);
7649     }
7650 #else
7651     afs_int32 rc = -1;
7652 #endif
7653     return rc;
7654 }
7655
7656 afs_int32
7657 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7658                   afs_uint16 remotePort, afs_int32 * nextPeer,
7659                   afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7660                   afs_uint32 * supportedValues)
7661 {
7662 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7663     afs_int32 rc = 0;
7664     struct rx_debugIn in;
7665
7666     /*
7667      * supportedValues is currently unused, but added to allow future
7668      * versioning of this function.
7669      */
7670
7671     *supportedValues = 0;
7672     in.type = htonl(RX_DEBUGI_GETPEER);
7673     in.index = htonl(*nextPeer);
7674     memset(peer, 0, sizeof(*peer));
7675
7676     rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7677                        &in, sizeof(in), peer, sizeof(*peer));
7678
7679     if (rc >= 0) {
7680         *nextPeer += 1;
7681
7682         /*
7683          * Do net to host conversion here
7684          * NOTE:
7685          *    I don't convert host or port since we are most likely
7686          *    going to want these in NBO.
7687          */
7688         peer->ifMTU = ntohs(peer->ifMTU);
7689         peer->idleWhen = ntohl(peer->idleWhen);
7690         peer->refCount = ntohs(peer->refCount);
7691         peer->burstWait.sec = ntohl(peer->burstWait.sec);
7692         peer->burstWait.usec = ntohl(peer->burstWait.usec);
7693         peer->rtt = ntohl(peer->rtt);
7694         peer->rtt_dev = ntohl(peer->rtt_dev);
7695         peer->timeout.sec = 0;
7696         peer->timeout.usec = 0;
7697         peer->nSent = ntohl(peer->nSent);
7698         peer->reSends = ntohl(peer->reSends);
7699         peer->inPacketSkew = ntohl(peer->inPacketSkew);
7700         peer->outPacketSkew = ntohl(peer->outPacketSkew);
7701         peer->natMTU = ntohs(peer->natMTU);
7702         peer->maxMTU = ntohs(peer->maxMTU);
7703         peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7704         peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7705         peer->MTU = ntohs(peer->MTU);
7706         peer->cwind = ntohs(peer->cwind);
7707         peer->nDgramPackets = ntohs(peer->nDgramPackets);
7708         peer->congestSeq = ntohs(peer->congestSeq);
7709         peer->bytesSent.high = ntohl(peer->bytesSent.high);
7710         peer->bytesSent.low = ntohl(peer->bytesSent.low);
7711         peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7712         peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7713     }
7714 #else
7715     afs_int32 rc = -1;
7716 #endif
7717     return rc;
7718 }
7719
7720 afs_int32
7721 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7722                 struct rx_debugPeer * peerStats)
7723 {
7724         struct rx_peer *tp;
7725         afs_int32 error = 1; /* default to "did not succeed" */
7726         afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7727
7728         MUTEX_ENTER(&rx_peerHashTable_lock);
7729         for(tp = rx_peerHashTable[hashValue];
7730               tp != NULL; tp = tp->next) {
7731                 if (tp->host == peerHost)
7732                         break;
7733         }
7734
7735         if (tp) {
7736                 tp->refCount++;
7737                 MUTEX_EXIT(&rx_peerHashTable_lock);
7738
7739                 error = 0;
7740
7741                 MUTEX_ENTER(&tp->peer_lock);
7742                 peerStats->host = tp->host;
7743                 peerStats->port = tp->port;
7744                 peerStats->ifMTU = tp->ifMTU;
7745                 peerStats->idleWhen = tp->idleWhen;
7746                 peerStats->refCount = tp->refCount;
7747                 peerStats->burstSize = tp->burstSize;
7748                 peerStats->burst = tp->burst;
7749                 peerStats->burstWait.sec = tp->burstWait.sec;
7750                 peerStats->burstWait.usec = tp->burstWait.usec;
7751                 peerStats->rtt = tp->rtt;
7752                 peerStats->rtt_dev = tp->rtt_dev;
7753                 peerStats->timeout.sec = 0;
7754                 peerStats->timeout.usec = 0;
7755                 peerStats->nSent = tp->nSent;
7756                 peerStats->reSends = tp->reSends;
7757                 peerStats->inPacketSkew = tp->inPacketSkew;
7758                 peerStats->outPacketSkew = tp->outPacketSkew;
7759                 peerStats->natMTU = tp->natMTU;
7760                 peerStats->maxMTU = tp->maxMTU;
7761                 peerStats->maxDgramPackets = tp->maxDgramPackets;
7762                 peerStats->ifDgramPackets = tp->ifDgramPackets;
7763                 peerStats->MTU = tp->MTU;
7764                 peerStats->cwind = tp->cwind;
7765                 peerStats->nDgramPackets = tp->nDgramPackets;
7766                 peerStats->congestSeq = tp->congestSeq;
7767                 peerStats->bytesSent.high = tp->bytesSent.high;
7768                 peerStats->bytesSent.low = tp->bytesSent.low;
7769                 peerStats->bytesReceived.high = tp->bytesReceived.high;
7770                 peerStats->bytesReceived.low = tp->bytesReceived.low;
7771                 MUTEX_EXIT(&tp->peer_lock);
7772
7773                 MUTEX_ENTER(&rx_peerHashTable_lock);
7774                 tp->refCount--;
7775         }
7776         MUTEX_EXIT(&rx_peerHashTable_lock);
7777
7778         return error;
7779 }
7780
7781 void
7782 shutdown_rx(void)
7783 {
7784     struct rx_serverQueueEntry *np;
7785     int i, j;
7786 #ifndef KERNEL
7787     struct rx_call *call;
7788     struct rx_serverQueueEntry *sq;
7789 #endif /* KERNEL */
7790
7791     LOCK_RX_INIT;
7792     if (rxinit_status == 1) {
7793         UNLOCK_RX_INIT;
7794         return;                 /* Already shutdown. */
7795     }
7796 #ifndef KERNEL
7797     rx_port = 0;
7798 #ifndef AFS_PTHREAD_ENV
7799     FD_ZERO(&rx_selectMask);
7800 #endif /* AFS_PTHREAD_ENV */
7801     rxi_dataQuota = RX_MAX_QUOTA;
7802 #ifndef AFS_PTHREAD_ENV
7803     rxi_StopListener();
7804 #endif /* AFS_PTHREAD_ENV */
7805     shutdown_rxevent();
7806     rx_SetEpoch(0);
7807 #ifndef AFS_PTHREAD_ENV
7808 #ifndef AFS_USE_GETTIMEOFDAY
7809     clock_UnInit();
7810 #endif /* AFS_USE_GETTIMEOFDAY */
7811 #endif /* AFS_PTHREAD_ENV */
7812
7813     while (!queue_IsEmpty(&rx_freeCallQueue)) {
7814         call = queue_First(&rx_freeCallQueue, rx_call);
7815         queue_Remove(call);
7816         rxi_Free(call, sizeof(struct rx_call));
7817     }
7818
7819     while (!queue_IsEmpty(&rx_idleServerQueue)) {
7820         sq = queue_First(&rx_idleServerQueue, rx_serverQueueEntry);
7821         queue_Remove(sq);
7822     }
7823 #endif /* KERNEL */
7824
7825     {
7826         struct rx_peer **peer_ptr, **peer_end;
7827         for (peer_ptr = &rx_peerHashTable[0], peer_end =
7828              &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7829              peer_ptr++) {
7830             struct rx_peer *peer, *next;
7831
7832             MUTEX_ENTER(&rx_peerHashTable_lock);
7833             for (peer = *peer_ptr; peer; peer = next) {
7834                 rx_interface_stat_p rpc_stat, nrpc_stat;
7835                 size_t space;
7836
7837                 MUTEX_ENTER(&rx_rpc_stats);
7838                 MUTEX_ENTER(&peer->peer_lock);
7839                 for (queue_Scan
7840                      (&peer->rpcStats, rpc_stat, nrpc_stat,
7841                       rx_interface_stat)) {
7842                     unsigned int num_funcs;
7843                     if (!rpc_stat)
7844                         break;
7845                     queue_Remove(&rpc_stat->queue_header);
7846                     queue_Remove(&rpc_stat->all_peers);
7847                     num_funcs = rpc_stat->stats[0].func_total;
7848                     space =
7849                         sizeof(rx_interface_stat_t) +
7850                         rpc_stat->stats[0].func_total *
7851                         sizeof(rx_function_entry_v1_t);
7852
7853                     rxi_Free(rpc_stat, space);
7854
7855                     /* rx_rpc_stats must be held */
7856                     rxi_rpc_peer_stat_cnt -= num_funcs;
7857                 }
7858                 MUTEX_EXIT(&peer->peer_lock);
7859                 MUTEX_EXIT(&rx_rpc_stats);
7860
7861                 next = peer->next;
7862                 rxi_FreePeer(peer);
7863                 if (rx_stats_active)
7864                     rx_atomic_dec(&rx_stats.nPeerStructs);
7865             }
7866             MUTEX_EXIT(&rx_peerHashTable_lock);
7867         }
7868     }
7869     for (i = 0; i < RX_MAX_SERVICES; i++) {
7870         if (rx_services[i])
7871             rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7872     }
7873     for (i = 0; i < rx_hashTableSize; i++) {
7874         struct rx_connection *tc, *ntc;
7875         MUTEX_ENTER(&rx_connHashTable_lock);
7876         for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7877             ntc = tc->next;
7878             for (j = 0; j < RX_MAXCALLS; j++) {
7879                 if (tc->call[j]) {
7880                     rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7881                 }
7882             }
7883             rxi_Free(tc, sizeof(*tc));
7884         }
7885         MUTEX_EXIT(&rx_connHashTable_lock);
7886     }
7887
7888     MUTEX_ENTER(&freeSQEList_lock);
7889
7890     while ((np = rx_FreeSQEList)) {
7891         rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7892         MUTEX_DESTROY(&np->lock);
7893         rxi_Free(np, sizeof(*np));
7894     }
7895
7896     MUTEX_EXIT(&freeSQEList_lock);
7897     MUTEX_DESTROY(&freeSQEList_lock);
7898     MUTEX_DESTROY(&rx_freeCallQueue_lock);
7899     MUTEX_DESTROY(&rx_connHashTable_lock);
7900     MUTEX_DESTROY(&rx_peerHashTable_lock);
7901     MUTEX_DESTROY(&rx_serverPool_lock);
7902
7903     osi_Free(rx_connHashTable,
7904              rx_hashTableSize * sizeof(struct rx_connection *));
7905     osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7906
7907     UNPIN(rx_connHashTable,
7908           rx_hashTableSize * sizeof(struct rx_connection *));
7909     UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7910
7911     rxi_FreeAllPackets();
7912
7913     MUTEX_ENTER(&rx_quota_mutex);
7914     rxi_dataQuota = RX_MAX_QUOTA;
7915     rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
7916     MUTEX_EXIT(&rx_quota_mutex);
7917     rxinit_status = 1;
7918     UNLOCK_RX_INIT;
7919 }
7920
7921 #ifdef RX_ENABLE_LOCKS
7922 void
7923 osirx_AssertMine(afs_kmutex_t * lockaddr, char *msg)
7924 {
7925     if (!MUTEX_ISMINE(lockaddr))
7926         osi_Panic("Lock not held: %s", msg);
7927 }
7928 #endif /* RX_ENABLE_LOCKS */
7929
7930 #ifndef KERNEL
7931
7932 /*
7933  * Routines to implement connection specific data.
7934  */
7935
7936 int
7937 rx_KeyCreate(rx_destructor_t rtn)
7938 {
7939     int key;
7940     MUTEX_ENTER(&rxi_keyCreate_lock);
7941     key = rxi_keyCreate_counter++;
7942     rxi_keyCreate_destructor = (rx_destructor_t *)
7943         realloc((void *)rxi_keyCreate_destructor,
7944                 (key + 1) * sizeof(rx_destructor_t));
7945     rxi_keyCreate_destructor[key] = rtn;
7946     MUTEX_EXIT(&rxi_keyCreate_lock);
7947     return key;
7948 }
7949
7950 void
7951 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
7952 {
7953     int i;
7954     MUTEX_ENTER(&conn->conn_data_lock);
7955     if (!conn->specific) {
7956         conn->specific = (void **)malloc((key + 1) * sizeof(void *));
7957         for (i = 0; i < key; i++)
7958             conn->specific[i] = NULL;
7959         conn->nSpecific = key + 1;
7960         conn->specific[key] = ptr;
7961     } else if (key >= conn->nSpecific) {
7962         conn->specific = (void **)
7963             realloc(conn->specific, (key + 1) * sizeof(void *));
7964         for (i = conn->nSpecific; i < key; i++)
7965             conn->specific[i] = NULL;
7966         conn->nSpecific = key + 1;
7967         conn->specific[key] = ptr;
7968     } else {
7969         if (conn->specific[key] && rxi_keyCreate_destructor[key])
7970             (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
7971         conn->specific[key] = ptr;
7972     }
7973     MUTEX_EXIT(&conn->conn_data_lock);
7974 }
7975
7976 void
7977 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
7978 {
7979     int i;
7980     MUTEX_ENTER(&svc->svc_data_lock);
7981     if (!svc->specific) {
7982         svc->specific = (void **)malloc((key + 1) * sizeof(void *));
7983         for (i = 0; i < key; i++)
7984             svc->specific[i] = NULL;
7985         svc->nSpecific = key + 1;
7986         svc->specific[key] = ptr;
7987     } else if (key >= svc->nSpecific) {
7988         svc->specific = (void **)
7989             realloc(svc->specific, (key + 1) * sizeof(void *));
7990         for (i = svc->nSpecific; i < key; i++)
7991             svc->specific[i] = NULL;
7992         svc->nSpecific = key + 1;
7993         svc->specific[key] = ptr;
7994     } else {
7995         if (svc->specific[key] && rxi_keyCreate_destructor[key])
7996             (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
7997         svc->specific[key] = ptr;
7998     }
7999     MUTEX_EXIT(&svc->svc_data_lock);
8000 }
8001
8002 void *
8003 rx_GetSpecific(struct rx_connection *conn, int key)
8004 {
8005     void *ptr;
8006     MUTEX_ENTER(&conn->conn_data_lock);
8007     if (key >= conn->nSpecific)
8008         ptr = NULL;
8009     else
8010         ptr = conn->specific[key];
8011     MUTEX_EXIT(&conn->conn_data_lock);
8012     return ptr;
8013 }
8014
8015 void *
8016 rx_GetServiceSpecific(struct rx_service *svc, int key)
8017 {
8018     void *ptr;
8019     MUTEX_ENTER(&svc->svc_data_lock);
8020     if (key >= svc->nSpecific)
8021         ptr = NULL;
8022     else
8023         ptr = svc->specific[key];
8024     MUTEX_EXIT(&svc->svc_data_lock);
8025     return ptr;
8026 }
8027
8028
8029 #endif /* !KERNEL */
8030
8031 /*
8032  * processStats is a queue used to store the statistics for the local
8033  * process.  Its contents are similar to the contents of the rpcStats
8034  * queue on a rx_peer structure, but the actual data stored within
8035  * this queue contains totals across the lifetime of the process (assuming
8036  * the stats have not been reset) - unlike the per peer structures
8037  * which can come and go based upon the peer lifetime.
8038  */
8039
8040 static struct rx_queue processStats = { &processStats, &processStats };
8041
8042 /*
8043  * peerStats is a queue used to store the statistics for all peer structs.
8044  * Its contents are the union of all the peer rpcStats queues.
8045  */
8046
8047 static struct rx_queue peerStats = { &peerStats, &peerStats };
8048
8049 /*
8050  * rxi_monitor_processStats is used to turn process wide stat collection
8051  * on and off
8052  */
8053
8054 static int rxi_monitor_processStats = 0;
8055
8056 /*
8057  * rxi_monitor_peerStats is used to turn per peer stat collection on and off
8058  */
8059
8060 static int rxi_monitor_peerStats = 0;
8061
8062 /*
8063  * rxi_AddRpcStat - given all of the information for a particular rpc
8064  * call, create (if needed) and update the stat totals for the rpc.
8065  *
8066  * PARAMETERS
8067  *
8068  * IN stats - the queue of stats that will be updated with the new value
8069  *
8070  * IN rxInterface - a unique number that identifies the rpc interface
8071  *
8072  * IN currentFunc - the index of the function being invoked
8073  *
8074  * IN totalFunc - the total number of functions in this interface
8075  *
8076  * IN queueTime - the amount of time this function waited for a thread
8077  *
8078  * IN execTime - the amount of time this function invocation took to execute
8079  *
8080  * IN bytesSent - the number bytes sent by this invocation
8081  *
8082  * IN bytesRcvd - the number bytes received by this invocation
8083  *
8084  * IN isServer - if true, this invocation was made to a server
8085  *
8086  * IN remoteHost - the ip address of the remote host
8087  *
8088  * IN remotePort - the port of the remote host
8089  *
8090  * IN addToPeerList - if != 0, add newly created stat to the global peer list
8091  *
8092  * INOUT counter - if a new stats structure is allocated, the counter will
8093  * be updated with the new number of allocated stat structures
8094  *
8095  * RETURN CODES
8096  *
8097  * Returns void.
8098  */
8099
8100 static int
8101 rxi_AddRpcStat(struct rx_queue *stats, afs_uint32 rxInterface,
8102                afs_uint32 currentFunc, afs_uint32 totalFunc,
8103                struct clock *queueTime, struct clock *execTime,
8104                afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd, int isServer,
8105                afs_uint32 remoteHost, afs_uint32 remotePort,
8106                int addToPeerList, unsigned int *counter)
8107 {
8108     int rc = 0;
8109     rx_interface_stat_p rpc_stat, nrpc_stat;
8110
8111     /*
8112      * See if there's already a structure for this interface
8113      */
8114
8115     for (queue_Scan(stats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8116         if ((rpc_stat->stats[0].interfaceId == rxInterface)
8117             && (rpc_stat->stats[0].remote_is_server == isServer))
8118             break;
8119     }
8120
8121     /*
8122      * Didn't find a match so allocate a new structure and add it to the
8123      * queue.
8124      */
8125
8126     if (queue_IsEnd(stats, rpc_stat) || (rpc_stat == NULL)
8127         || (rpc_stat->stats[0].interfaceId != rxInterface)
8128         || (rpc_stat->stats[0].remote_is_server != isServer)) {
8129         int i;
8130         size_t space;
8131
8132         space =
8133             sizeof(rx_interface_stat_t) +
8134             totalFunc * sizeof(rx_function_entry_v1_t);
8135
8136         rpc_stat = rxi_Alloc(space);
8137         if (rpc_stat == NULL) {
8138             rc = 1;
8139             goto fail;
8140         }
8141         *counter += totalFunc;
8142         for (i = 0; i < totalFunc; i++) {
8143             rpc_stat->stats[i].remote_peer = remoteHost;
8144             rpc_stat->stats[i].remote_port = remotePort;
8145             rpc_stat->stats[i].remote_is_server = isServer;
8146             rpc_stat->stats[i].interfaceId = rxInterface;
8147             rpc_stat->stats[i].func_total = totalFunc;
8148             rpc_stat->stats[i].func_index = i;
8149             hzero(rpc_stat->stats[i].invocations);
8150             hzero(rpc_stat->stats[i].bytes_sent);
8151             hzero(rpc_stat->stats[i].bytes_rcvd);
8152             rpc_stat->stats[i].queue_time_sum.sec = 0;
8153             rpc_stat->stats[i].queue_time_sum.usec = 0;
8154             rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8155             rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8156             rpc_stat->stats[i].queue_time_min.sec = 9999999;
8157             rpc_stat->stats[i].queue_time_min.usec = 9999999;
8158             rpc_stat->stats[i].queue_time_max.sec = 0;
8159             rpc_stat->stats[i].queue_time_max.usec = 0;
8160             rpc_stat->stats[i].execution_time_sum.sec = 0;
8161             rpc_stat->stats[i].execution_time_sum.usec = 0;
8162             rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8163             rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8164             rpc_stat->stats[i].execution_time_min.sec = 9999999;
8165             rpc_stat->stats[i].execution_time_min.usec = 9999999;
8166             rpc_stat->stats[i].execution_time_max.sec = 0;
8167             rpc_stat->stats[i].execution_time_max.usec = 0;
8168         }
8169         queue_Prepend(stats, rpc_stat);
8170         if (addToPeerList) {
8171             queue_Prepend(&peerStats, &rpc_stat->all_peers);
8172         }
8173     }
8174
8175     /*
8176      * Increment the stats for this function
8177      */
8178
8179     hadd32(rpc_stat->stats[currentFunc].invocations, 1);
8180     hadd(rpc_stat->stats[currentFunc].bytes_sent, *bytesSent);
8181     hadd(rpc_stat->stats[currentFunc].bytes_rcvd, *bytesRcvd);
8182     clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8183     clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8184     if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8185         rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8186     }
8187     if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8188         rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8189     }
8190     clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8191     clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8192                 execTime);
8193     if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8194         rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8195     }
8196     if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8197         rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8198     }
8199
8200   fail:
8201     return rc;
8202 }
8203
8204 /*
8205  * rx_IncrementTimeAndCount - increment the times and count for a particular
8206  * rpc function.
8207  *
8208  * PARAMETERS
8209  *
8210  * IN peer - the peer who invoked the rpc
8211  *
8212  * IN rxInterface - a unique number that identifies the rpc interface
8213  *
8214  * IN currentFunc - the index of the function being invoked
8215  *
8216  * IN totalFunc - the total number of functions in this interface
8217  *
8218  * IN queueTime - the amount of time this function waited for a thread
8219  *
8220  * IN execTime - the amount of time this function invocation took to execute
8221  *
8222  * IN bytesSent - the number bytes sent by this invocation
8223  *
8224  * IN bytesRcvd - the number bytes received by this invocation
8225  *
8226  * IN isServer - if true, this invocation was made to a server
8227  *
8228  * RETURN CODES
8229  *
8230  * Returns void.
8231  */
8232
8233 void
8234 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8235                          afs_uint32 currentFunc, afs_uint32 totalFunc,
8236                          struct clock *queueTime, struct clock *execTime,
8237                          afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8238                          int isServer)
8239 {
8240
8241     if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8242         return;
8243
8244     MUTEX_ENTER(&rx_rpc_stats);
8245
8246     if (rxi_monitor_peerStats) {
8247         MUTEX_ENTER(&peer->peer_lock);
8248         rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8249                        queueTime, execTime, bytesSent, bytesRcvd, isServer,
8250                        peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8251         MUTEX_EXIT(&peer->peer_lock);
8252     }
8253
8254     if (rxi_monitor_processStats) {
8255         rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8256                        queueTime, execTime, bytesSent, bytesRcvd, isServer,
8257                        0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8258     }
8259
8260     MUTEX_EXIT(&rx_rpc_stats);
8261
8262 }
8263
8264 /*
8265  * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8266  *
8267  * PARAMETERS
8268  *
8269  * IN callerVersion - the rpc stat version of the caller.
8270  *
8271  * IN count - the number of entries to marshall.
8272  *
8273  * IN stats - pointer to stats to be marshalled.
8274  *
8275  * OUT ptr - Where to store the marshalled data.
8276  *
8277  * RETURN CODES
8278  *
8279  * Returns void.
8280  */
8281 void
8282 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8283                            rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8284 {
8285     int i;
8286     afs_uint32 *ptr;
8287
8288     /*
8289      * We only support the first version
8290      */
8291     for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8292         *(ptr++) = stats->remote_peer;
8293         *(ptr++) = stats->remote_port;
8294         *(ptr++) = stats->remote_is_server;
8295         *(ptr++) = stats->interfaceId;
8296         *(ptr++) = stats->func_total;
8297         *(ptr++) = stats->func_index;
8298         *(ptr++) = hgethi(stats->invocations);
8299         *(ptr++) = hgetlo(stats->invocations);
8300         *(ptr++) = hgethi(stats->bytes_sent);
8301         *(ptr++) = hgetlo(stats->bytes_sent);
8302         *(ptr++) = hgethi(stats->bytes_rcvd);
8303         *(ptr++) = hgetlo(stats->bytes_rcvd);
8304         *(ptr++) = stats->queue_time_sum.sec;
8305         *(ptr++) = stats->queue_time_sum.usec;
8306         *(ptr++) = stats->queue_time_sum_sqr.sec;
8307         *(ptr++) = stats->queue_time_sum_sqr.usec;
8308         *(ptr++) = stats->queue_time_min.sec;
8309         *(ptr++) = stats->queue_time_min.usec;
8310         *(ptr++) = stats->queue_time_max.sec;
8311         *(ptr++) = stats->queue_time_max.usec;
8312         *(ptr++) = stats->execution_time_sum.sec;
8313         *(ptr++) = stats->execution_time_sum.usec;
8314         *(ptr++) = stats->execution_time_sum_sqr.sec;
8315         *(ptr++) = stats->execution_time_sum_sqr.usec;
8316         *(ptr++) = stats->execution_time_min.sec;
8317         *(ptr++) = stats->execution_time_min.usec;
8318         *(ptr++) = stats->execution_time_max.sec;
8319         *(ptr++) = stats->execution_time_max.usec;
8320     }
8321     *ptrP = ptr;
8322 }
8323
8324 /*
8325  * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8326  * this process
8327  *
8328  * PARAMETERS
8329  *
8330  * IN callerVersion - the rpc stat version of the caller
8331  *
8332  * OUT myVersion - the rpc stat version of this function
8333  *
8334  * OUT clock_sec - local time seconds
8335  *
8336  * OUT clock_usec - local time microseconds
8337  *
8338  * OUT allocSize - the number of bytes allocated to contain stats
8339  *
8340  * OUT statCount - the number stats retrieved from this process.
8341  *
8342  * OUT stats - the actual stats retrieved from this process.
8343  *
8344  * RETURN CODES
8345  *
8346  * Returns void.  If successful, stats will != NULL.
8347  */
8348
8349 int
8350 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8351                            afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8352                            size_t * allocSize, afs_uint32 * statCount,
8353                            afs_uint32 ** stats)
8354 {
8355     size_t space = 0;
8356     afs_uint32 *ptr;
8357     struct clock now;
8358     int rc = 0;
8359
8360     *stats = 0;
8361     *allocSize = 0;
8362     *statCount = 0;
8363     *myVersion = RX_STATS_RETRIEVAL_VERSION;
8364
8365     /*
8366      * Check to see if stats are enabled
8367      */
8368
8369     MUTEX_ENTER(&rx_rpc_stats);
8370     if (!rxi_monitor_processStats) {
8371         MUTEX_EXIT(&rx_rpc_stats);
8372         return rc;
8373     }
8374
8375     clock_GetTime(&now);
8376     *clock_sec = now.sec;
8377     *clock_usec = now.usec;
8378
8379     /*
8380      * Allocate the space based upon the caller version
8381      *
8382      * If the client is at an older version than we are,
8383      * we return the statistic data in the older data format, but
8384      * we still return our version number so the client knows we
8385      * are maintaining more data than it can retrieve.
8386      */
8387
8388     if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8389         space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8390         *statCount = rxi_rpc_process_stat_cnt;
8391     } else {
8392         /*
8393          * This can't happen yet, but in the future version changes
8394          * can be handled by adding additional code here
8395          */
8396     }
8397
8398     if (space > (size_t) 0) {
8399         *allocSize = space;
8400         ptr = *stats = rxi_Alloc(space);
8401
8402         if (ptr != NULL) {
8403             rx_interface_stat_p rpc_stat, nrpc_stat;
8404
8405
8406             for (queue_Scan
8407                  (&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8408                 /*
8409                  * Copy the data based upon the caller version
8410                  */
8411                 rx_MarshallProcessRPCStats(callerVersion,
8412                                            rpc_stat->stats[0].func_total,
8413                                            rpc_stat->stats, &ptr);
8414             }
8415         } else {
8416             rc = ENOMEM;
8417         }
8418     }
8419     MUTEX_EXIT(&rx_rpc_stats);
8420     return rc;
8421 }
8422
8423 /*
8424  * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8425  *
8426  * PARAMETERS
8427  *
8428  * IN callerVersion - the rpc stat version of the caller
8429  *
8430  * OUT myVersion - the rpc stat version of this function
8431  *
8432  * OUT clock_sec - local time seconds
8433  *
8434  * OUT clock_usec - local time microseconds
8435  *
8436  * OUT allocSize - the number of bytes allocated to contain stats
8437  *
8438  * OUT statCount - the number of stats retrieved from the individual
8439  * peer structures.
8440  *
8441  * OUT stats - the actual stats retrieved from the individual peer structures.
8442  *
8443  * RETURN CODES
8444  *
8445  * Returns void.  If successful, stats will != NULL.
8446  */
8447
8448 int
8449 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8450                         afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8451                         size_t * allocSize, afs_uint32 * statCount,
8452                         afs_uint32 ** stats)
8453 {
8454     size_t space = 0;
8455     afs_uint32 *ptr;
8456     struct clock now;
8457     int rc = 0;
8458
8459     *stats = 0;
8460     *statCount = 0;
8461     *allocSize = 0;
8462     *myVersion = RX_STATS_RETRIEVAL_VERSION;
8463
8464     /*
8465      * Check to see if stats are enabled
8466      */
8467
8468     MUTEX_ENTER(&rx_rpc_stats);
8469     if (!rxi_monitor_peerStats) {
8470         MUTEX_EXIT(&rx_rpc_stats);
8471         return rc;
8472     }
8473
8474     clock_GetTime(&now);
8475     *clock_sec = now.sec;
8476     *clock_usec = now.usec;
8477
8478     /*
8479      * Allocate the space based upon the caller version
8480      *
8481      * If the client is at an older version than we are,
8482      * we return the statistic data in the older data format, but
8483      * we still return our version number so the client knows we
8484      * are maintaining more data than it can retrieve.
8485      */
8486
8487     if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8488         space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8489         *statCount = rxi_rpc_peer_stat_cnt;
8490     } else {
8491         /*
8492          * This can't happen yet, but in the future version changes
8493          * can be handled by adding additional code here
8494          */
8495     }
8496
8497     if (space > (size_t) 0) {
8498         *allocSize = space;
8499         ptr = *stats = rxi_Alloc(space);
8500
8501         if (ptr != NULL) {
8502             rx_interface_stat_p rpc_stat, nrpc_stat;
8503             char *fix_offset;
8504
8505             for (queue_Scan
8506                  (&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8507                 /*
8508                  * We have to fix the offset of rpc_stat since we are
8509                  * keeping this structure on two rx_queues.  The rx_queue
8510                  * package assumes that the rx_queue member is the first
8511                  * member of the structure.  That is, rx_queue assumes that
8512                  * any one item is only on one queue at a time.  We are
8513                  * breaking that assumption and so we have to do a little
8514                  * math to fix our pointers.
8515                  */
8516
8517                 fix_offset = (char *)rpc_stat;
8518                 fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8519                 rpc_stat = (rx_interface_stat_p) fix_offset;
8520
8521                 /*
8522                  * Copy the data based upon the caller version
8523                  */
8524                 rx_MarshallProcessRPCStats(callerVersion,
8525                                            rpc_stat->stats[0].func_total,
8526                                            rpc_stat->stats, &ptr);
8527             }
8528         } else {
8529             rc = ENOMEM;
8530         }
8531     }
8532     MUTEX_EXIT(&rx_rpc_stats);
8533     return rc;
8534 }
8535
8536 /*
8537  * rx_FreeRPCStats - free memory allocated by
8538  *                   rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
8539  *
8540  * PARAMETERS
8541  *
8542  * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
8543  * rx_RetrievePeerRPCStats
8544  *
8545  * IN allocSize - the number of bytes in stats.
8546  *
8547  * RETURN CODES
8548  *
8549  * Returns void.
8550  */
8551
8552 void
8553 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
8554 {
8555     rxi_Free(stats, allocSize);
8556 }
8557
8558 /*
8559  * rx_queryProcessRPCStats - see if process rpc stat collection is
8560  * currently enabled.
8561  *
8562  * PARAMETERS
8563  *
8564  * RETURN CODES
8565  *
8566  * Returns 0 if stats are not enabled != 0 otherwise
8567  */
8568
8569 int
8570 rx_queryProcessRPCStats(void)
8571 {
8572     int rc;
8573     MUTEX_ENTER(&rx_rpc_stats);
8574     rc = rxi_monitor_processStats;
8575     MUTEX_EXIT(&rx_rpc_stats);
8576     return rc;
8577 }
8578
8579 /*
8580  * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
8581  *
8582  * PARAMETERS
8583  *
8584  * RETURN CODES
8585  *
8586  * Returns 0 if stats are not enabled != 0 otherwise
8587  */
8588
8589 int
8590 rx_queryPeerRPCStats(void)
8591 {
8592     int rc;
8593     MUTEX_ENTER(&rx_rpc_stats);
8594     rc = rxi_monitor_peerStats;
8595     MUTEX_EXIT(&rx_rpc_stats);
8596     return rc;
8597 }
8598
8599 /*
8600  * rx_enableProcessRPCStats - begin rpc stat collection for entire process
8601  *
8602  * PARAMETERS
8603  *
8604  * RETURN CODES
8605  *
8606  * Returns void.
8607  */
8608
8609 void
8610 rx_enableProcessRPCStats(void)
8611 {
8612     MUTEX_ENTER(&rx_rpc_stats);
8613     rx_enable_stats = 1;
8614     rxi_monitor_processStats = 1;
8615     MUTEX_EXIT(&rx_rpc_stats);
8616 }
8617
8618 /*
8619  * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
8620  *
8621  * PARAMETERS
8622  *
8623  * RETURN CODES
8624  *
8625  * Returns void.
8626  */
8627
8628 void
8629 rx_enablePeerRPCStats(void)
8630 {
8631     MUTEX_ENTER(&rx_rpc_stats);
8632     rx_enable_stats = 1;
8633     rxi_monitor_peerStats = 1;
8634     MUTEX_EXIT(&rx_rpc_stats);
8635 }
8636
8637 /*
8638  * rx_disableProcessRPCStats - stop rpc stat collection for entire process
8639  *
8640  * PARAMETERS
8641  *
8642  * RETURN CODES
8643  *
8644  * Returns void.
8645  */
8646
8647 void
8648 rx_disableProcessRPCStats(void)
8649 {
8650     rx_interface_stat_p rpc_stat, nrpc_stat;
8651     size_t space;
8652
8653     MUTEX_ENTER(&rx_rpc_stats);
8654
8655     /*
8656      * Turn off process statistics and if peer stats is also off, turn
8657      * off everything
8658      */
8659
8660     rxi_monitor_processStats = 0;
8661     if (rxi_monitor_peerStats == 0) {
8662         rx_enable_stats = 0;
8663     }
8664
8665     for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8666         unsigned int num_funcs = 0;
8667         if (!rpc_stat)
8668             break;
8669         queue_Remove(rpc_stat);
8670         num_funcs = rpc_stat->stats[0].func_total;
8671         space =
8672             sizeof(rx_interface_stat_t) +
8673             rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
8674
8675         rxi_Free(rpc_stat, space);
8676         rxi_rpc_process_stat_cnt -= num_funcs;
8677     }
8678     MUTEX_EXIT(&rx_rpc_stats);
8679 }
8680
8681 /*
8682  * rx_disablePeerRPCStats - stop rpc stat collection for peers
8683  *
8684  * PARAMETERS
8685  *
8686  * RETURN CODES
8687  *
8688  * Returns void.
8689  */
8690
8691 void
8692 rx_disablePeerRPCStats(void)
8693 {
8694     struct rx_peer **peer_ptr, **peer_end;
8695     int code;
8696
8697     /*
8698      * Turn off peer statistics and if process stats is also off, turn
8699      * off everything
8700      */
8701
8702     rxi_monitor_peerStats = 0;
8703     if (rxi_monitor_processStats == 0) {
8704         rx_enable_stats = 0;
8705     }
8706
8707     for (peer_ptr = &rx_peerHashTable[0], peer_end =
8708          &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
8709          peer_ptr++) {
8710         struct rx_peer *peer, *next, *prev;
8711
8712         MUTEX_ENTER(&rx_peerHashTable_lock);
8713         MUTEX_ENTER(&rx_rpc_stats);
8714         for (prev = peer = *peer_ptr; peer; peer = next) {
8715             next = peer->next;
8716             code = MUTEX_TRYENTER(&peer->peer_lock);
8717             if (code) {
8718                 rx_interface_stat_p rpc_stat, nrpc_stat;
8719                 size_t space;
8720
8721                 if (prev == *peer_ptr) {
8722                     *peer_ptr = next;
8723                     prev = next;
8724                 } else
8725                     prev->next = next;
8726
8727                 if (next)
8728                     next->refCount++;
8729                 if (prev)
8730                     prev->refCount++;
8731                 peer->refCount++;
8732                 MUTEX_EXIT(&rx_peerHashTable_lock);
8733
8734                 for (queue_Scan
8735                      (&peer->rpcStats, rpc_stat, nrpc_stat,
8736                       rx_interface_stat)) {
8737                     unsigned int num_funcs = 0;
8738                     if (!rpc_stat)
8739                         break;
8740                     queue_Remove(&rpc_stat->queue_header);
8741                     queue_Remove(&rpc_stat->all_peers);
8742                     num_funcs = rpc_stat->stats[0].func_total;
8743                     space =
8744                         sizeof(rx_interface_stat_t) +
8745                         rpc_stat->stats[0].func_total *
8746                         sizeof(rx_function_entry_v1_t);
8747
8748                     rxi_Free(rpc_stat, space);
8749                     rxi_rpc_peer_stat_cnt -= num_funcs;
8750                 }
8751                 MUTEX_EXIT(&peer->peer_lock);
8752
8753                 MUTEX_ENTER(&rx_peerHashTable_lock);
8754                 if (next)
8755                     next->refCount--;
8756                 if (prev)
8757                     prev->refCount--;
8758                 peer->refCount--;
8759             } else {
8760                 prev = peer;
8761             }
8762         }
8763         MUTEX_EXIT(&rx_rpc_stats);
8764         MUTEX_EXIT(&rx_peerHashTable_lock);
8765     }
8766 }
8767
8768 /*
8769  * rx_clearProcessRPCStats - clear the contents of the rpc stats according
8770  * to clearFlag
8771  *
8772  * PARAMETERS
8773  *
8774  * IN clearFlag - flag indicating which stats to clear
8775  *
8776  * RETURN CODES
8777  *
8778  * Returns void.
8779  */
8780
8781 void
8782 rx_clearProcessRPCStats(afs_uint32 clearFlag)
8783 {
8784     rx_interface_stat_p rpc_stat, nrpc_stat;
8785
8786     MUTEX_ENTER(&rx_rpc_stats);
8787
8788     for (queue_Scan(&processStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8789         unsigned int num_funcs = 0, i;
8790         num_funcs = rpc_stat->stats[0].func_total;
8791         for (i = 0; i < num_funcs; i++) {
8792             if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8793                 hzero(rpc_stat->stats[i].invocations);
8794             }
8795             if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8796                 hzero(rpc_stat->stats[i].bytes_sent);
8797             }
8798             if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8799                 hzero(rpc_stat->stats[i].bytes_rcvd);
8800             }
8801             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8802                 rpc_stat->stats[i].queue_time_sum.sec = 0;
8803                 rpc_stat->stats[i].queue_time_sum.usec = 0;
8804             }
8805             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8806                 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8807                 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8808             }
8809             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8810                 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8811                 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8812             }
8813             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8814                 rpc_stat->stats[i].queue_time_max.sec = 0;
8815                 rpc_stat->stats[i].queue_time_max.usec = 0;
8816             }
8817             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8818                 rpc_stat->stats[i].execution_time_sum.sec = 0;
8819                 rpc_stat->stats[i].execution_time_sum.usec = 0;
8820             }
8821             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8822                 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8823                 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8824             }
8825             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8826                 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8827                 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8828             }
8829             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8830                 rpc_stat->stats[i].execution_time_max.sec = 0;
8831                 rpc_stat->stats[i].execution_time_max.usec = 0;
8832             }
8833         }
8834     }
8835
8836     MUTEX_EXIT(&rx_rpc_stats);
8837 }
8838
8839 /*
8840  * rx_clearPeerRPCStats - clear the contents of the rpc stats according
8841  * to clearFlag
8842  *
8843  * PARAMETERS
8844  *
8845  * IN clearFlag - flag indicating which stats to clear
8846  *
8847  * RETURN CODES
8848  *
8849  * Returns void.
8850  */
8851
8852 void
8853 rx_clearPeerRPCStats(afs_uint32 clearFlag)
8854 {
8855     rx_interface_stat_p rpc_stat, nrpc_stat;
8856
8857     MUTEX_ENTER(&rx_rpc_stats);
8858
8859     for (queue_Scan(&peerStats, rpc_stat, nrpc_stat, rx_interface_stat)) {
8860         unsigned int num_funcs = 0, i;
8861         char *fix_offset;
8862         /*
8863          * We have to fix the offset of rpc_stat since we are
8864          * keeping this structure on two rx_queues.  The rx_queue
8865          * package assumes that the rx_queue member is the first
8866          * member of the structure.  That is, rx_queue assumes that
8867          * any one item is only on one queue at a time.  We are
8868          * breaking that assumption and so we have to do a little
8869          * math to fix our pointers.
8870          */
8871
8872         fix_offset = (char *)rpc_stat;
8873         fix_offset -= offsetof(rx_interface_stat_t, all_peers);
8874         rpc_stat = (rx_interface_stat_p) fix_offset;
8875
8876         num_funcs = rpc_stat->stats[0].func_total;
8877         for (i = 0; i < num_funcs; i++) {
8878             if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8879                 hzero(rpc_stat->stats[i].invocations);
8880             }
8881             if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8882                 hzero(rpc_stat->stats[i].bytes_sent);
8883             }
8884             if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8885                 hzero(rpc_stat->stats[i].bytes_rcvd);
8886             }
8887             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8888                 rpc_stat->stats[i].queue_time_sum.sec = 0;
8889                 rpc_stat->stats[i].queue_time_sum.usec = 0;
8890             }
8891             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8892                 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8893                 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8894             }
8895             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8896                 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8897                 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8898             }
8899             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8900                 rpc_stat->stats[i].queue_time_max.sec = 0;
8901                 rpc_stat->stats[i].queue_time_max.usec = 0;
8902             }
8903             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
8904                 rpc_stat->stats[i].execution_time_sum.sec = 0;
8905                 rpc_stat->stats[i].execution_time_sum.usec = 0;
8906             }
8907             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
8908                 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
8909                 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
8910             }
8911             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
8912                 rpc_stat->stats[i].execution_time_min.sec = 9999999;
8913                 rpc_stat->stats[i].execution_time_min.usec = 9999999;
8914             }
8915             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
8916                 rpc_stat->stats[i].execution_time_max.sec = 0;
8917                 rpc_stat->stats[i].execution_time_max.usec = 0;
8918             }
8919         }
8920     }
8921
8922     MUTEX_EXIT(&rx_rpc_stats);
8923 }
8924
8925 /*
8926  * rxi_rxstat_userok points to a routine that returns 1 if the caller
8927  * is authorized to enable/disable/clear RX statistics.
8928  */
8929 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
8930
8931 void
8932 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
8933 {
8934     rxi_rxstat_userok = proc;
8935 }
8936
8937 int
8938 rx_RxStatUserOk(struct rx_call *call)
8939 {
8940     if (!rxi_rxstat_userok)
8941         return 0;
8942     return rxi_rxstat_userok(call);
8943 }
8944
8945 #ifdef AFS_NT40_ENV
8946 /*
8947  * DllMain() -- Entry-point function called by the DllMainCRTStartup()
8948  *     function in the MSVC runtime DLL (msvcrt.dll).
8949  *
8950  *     Note: the system serializes calls to this function.
8951  */
8952 BOOL WINAPI
8953 DllMain(HINSTANCE dllInstHandle,        /* instance handle for this DLL module */
8954         DWORD reason,                   /* reason function is being called */
8955         LPVOID reserved)                /* reserved for future use */
8956 {
8957     switch (reason) {
8958     case DLL_PROCESS_ATTACH:
8959         /* library is being attached to a process */
8960         INIT_PTHREAD_LOCKS;
8961         return TRUE;
8962
8963     case DLL_PROCESS_DETACH:
8964         return TRUE;
8965
8966     default:
8967         return FALSE;
8968     }
8969 }
8970 #endif /* AFS_NT40_ENV */
8971
8972 #ifndef KERNEL
8973 int rx_DumpCalls(FILE *outputFile, char *cookie)
8974 {
8975 #ifdef RXDEBUG_PACKET
8976 #ifdef KDUMP_RX_LOCK
8977     struct rx_call_rx_lock *c;
8978 #else
8979     struct rx_call *c;
8980 #endif
8981 #ifdef AFS_NT40_ENV
8982     int zilch;
8983     char output[2048];
8984 #define RXDPRINTF sprintf
8985 #define RXDPRINTOUT output
8986 #else
8987 #define RXDPRINTF fprintf
8988 #define RXDPRINTOUT outputFile
8989 #endif
8990
8991     RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
8992 #ifdef AFS_NT40_ENV
8993     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
8994 #endif
8995
8996     for (c = rx_allCallsp; c; c = c->allNextp) {
8997         u_short rqc, tqc, iovqc;
8998         struct rx_packet *p, *np;
8999
9000         MUTEX_ENTER(&c->lock);
9001         queue_Count(&c->rq, p, np, rx_packet, rqc);
9002         queue_Count(&c->tq, p, np, rx_packet, tqc);
9003         queue_Count(&c->iovq, p, np, rx_packet, iovqc);
9004
9005         RXDPRINTF(RXDPRINTOUT, "%s - call=0x%p, id=%u, state=%u, mode=%u, conn=%p, epoch=%u, cid=%u, callNum=%u, connFlags=0x%x, flags=0x%x, "
9006                 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
9007                 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
9008                 "resendEvent=%d, timeoutEvt=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
9009                 "lastSendTime=%u, lastRecvTime=%u, lastSendData=%u"
9010 #ifdef RX_ENABLE_LOCKS
9011                 ", refCount=%u"
9012 #endif
9013 #ifdef RX_REFCOUNT_CHECK
9014                 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
9015                 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
9016 #endif
9017                 "\r\n",
9018                 cookie, c, c->call_id, (afs_uint32)c->state, (afs_uint32)c->mode, c->conn, c->conn?c->conn->epoch:0, c->conn?c->conn->cid:0,
9019                 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
9020                 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
9021                 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
9022                 c->resendEvent?1:0, c->timeoutEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
9023                 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime, c->lastSendData
9024 #ifdef RX_ENABLE_LOCKS
9025                 , (afs_uint32)c->refCount
9026 #endif
9027 #ifdef RX_REFCOUNT_CHECK
9028                 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
9029 #endif
9030                 );
9031         MUTEX_EXIT(&c->lock);
9032
9033 #ifdef AFS_NT40_ENV
9034         WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9035 #endif
9036     }
9037     RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
9038 #ifdef AFS_NT40_ENV
9039     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9040 #endif
9041 #endif /* RXDEBUG_PACKET */
9042     return 0;
9043 }
9044 #endif