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