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