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