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