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