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