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