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