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