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