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