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