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