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