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