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