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