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