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