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