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