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