76d7d69031e3887f42136cce6e38857bc6d3266a
[openafs.git] / src / rx / rx.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  *
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /* RX:  Extended Remote Procedure Call */
11
12 #include <afsconfig.h>
13 #include <afs/param.h>
14
15 #ifdef KERNEL
16 # include "afs/sysincludes.h"
17 # include "afsincludes.h"
18 # ifndef UKERNEL
19 #  include "h/types.h"
20 #  include "h/time.h"
21 #  include "h/stat.h"
22 #  ifdef AFS_LINUX20_ENV
23 #   include "h/socket.h"
24 #  endif
25 #  include "netinet/in.h"
26 #  ifdef AFS_SUN5_ENV
27 #   include "netinet/ip6.h"
28 #   include "inet/common.h"
29 #   include "inet/ip.h"
30 #   include "inet/ip_ire.h"
31 #  endif
32 #  include "afs/afs_args.h"
33 #  include "afs/afs_osi.h"
34 #  ifdef RX_KERNEL_TRACE
35 #   include "rx_kcommon.h"
36 #  endif
37 #  if   defined(AFS_AIX_ENV)
38 #   include "h/systm.h"
39 #  endif
40 #  ifdef RXDEBUG
41 #   undef RXDEBUG                       /* turn off debugging */
42 #  endif /* RXDEBUG */
43 #  if defined(AFS_SGI_ENV)
44 #   include "sys/debug.h"
45 #  endif
46 # else /* !UKERNEL */
47 #  include "afs/sysincludes.h"
48 #  include "afsincludes.h"
49 # endif /* !UKERNEL */
50 # include "afs/lock.h"
51 # include "rx_kmutex.h"
52 # include "rx_kernel.h"
53 # define        AFSOP_STOP_RXCALLBACK   210     /* Stop CALLBACK process */
54 # define        AFSOP_STOP_AFS          211     /* Stop AFS process */
55 # define        AFSOP_STOP_BKG          212     /* Stop BKG process */
56 extern afs_int32 afs_termState;
57 # ifdef AFS_AIX41_ENV
58 #  include "sys/lockl.h"
59 #  include "sys/lock_def.h"
60 # endif /* AFS_AIX41_ENV */
61 # include "afs/rxgen_consts.h"
62 #else /* KERNEL */
63 # include <roken.h>
64
65 # ifdef AFS_NT40_ENV
66 #  include <afs/afsutil.h>
67 #  include <WINNT\afsreg.h>
68 # endif
69
70 # include <afs/opr.h>
71
72 # include "rx_user.h"
73 #endif /* KERNEL */
74
75 #include <opr/queue.h>
76 #include <hcrypto/rand.h>
77
78 #include "rx.h"
79 #include "rx_clock.h"
80 #include "rx_atomic.h"
81 #include "rx_globals.h"
82 #include "rx_trace.h"
83 #include "rx_internal.h"
84 #include "rx_stats.h"
85 #include "rx_event.h"
86
87 #include "rx_peer.h"
88 #include "rx_conn.h"
89 #include "rx_call.h"
90 #include "rx_packet.h"
91 #include "rx_server.h"
92
93 #include <afs/rxgen_consts.h>
94
95 #ifndef KERNEL
96 #ifdef AFS_PTHREAD_ENV
97 #ifndef AFS_NT40_ENV
98 int (*registerProgram) (pid_t, char *) = 0;
99 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
100 #endif
101 #else
102 int (*registerProgram) (PROCESS, char *) = 0;
103 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
104 #endif
105 #endif
106
107 /* Local static routines */
108 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
109 static void rxi_ComputeRoundTripTime(struct rx_packet *, struct rx_ackPacket *,
110                                      struct rx_call *, struct rx_peer *,
111                                      struct clock *);
112 static void rxi_Resend(struct rxevent *event, void *arg0, void *arg1,
113                        int istack);
114 static void rxi_SendDelayedAck(struct rxevent *event, void *call,
115                                void *dummy, int dummy2);
116 static void rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1,
117                                      void *dummy, int dummy2);
118 static void rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1,
119                                      void *unused, int unused2);
120 static void rxi_ReapConnections(struct rxevent *unused, void *unused1,
121                                 void *unused2, int unused3);
122 static struct rx_packet *rxi_SendCallAbort(struct rx_call *call,
123                                            struct rx_packet *packet,
124                                            int istack, int force);
125 static void rxi_AckAll(struct rx_call *call);
126 static struct rx_connection
127         *rxi_FindConnection(osi_socket socket, afs_uint32 host, u_short port,
128                             u_short serviceId, afs_uint32 cid,
129                             afs_uint32 epoch, int type, u_int securityIndex,
130                             int *unknownService);
131 static struct rx_packet
132         *rxi_ReceiveDataPacket(struct rx_call *call, struct rx_packet *np,
133                                int istack, osi_socket socket,
134                                afs_uint32 host, u_short port, int *tnop,
135                                struct rx_call **newcallp);
136 static struct rx_packet
137         *rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
138                               int istack);
139 static struct rx_packet
140         *rxi_ReceiveResponsePacket(struct rx_connection *conn,
141                                    struct rx_packet *np, int istack);
142 static struct rx_packet
143         *rxi_ReceiveChallengePacket(struct rx_connection *conn,
144                                     struct rx_packet *np, int istack);
145 static void rxi_AttachServerProc(struct rx_call *call, osi_socket socket,
146                                  int *tnop, struct rx_call **newcallp);
147 static void rxi_ClearTransmitQueue(struct rx_call *call, int force);
148 static void rxi_ClearReceiveQueue(struct rx_call *call);
149 static void rxi_ResetCall(struct rx_call *call, int newcall);
150 static void rxi_ScheduleKeepAliveEvent(struct rx_call *call);
151 static void rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn);
152 static void rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs);
153 static void rxi_KeepAliveOn(struct rx_call *call);
154 static void rxi_GrowMTUOn(struct rx_call *call);
155 static int rxi_ChallengeOn(struct rx_connection *conn);
156 static int rxi_CheckCall(struct rx_call *call, int haveCTLock);
157 static void rxi_AckAllInTransmitQueue(struct rx_call *call);
158 static void rxi_CancelKeepAliveEvent(struct rx_call *call);
159 static void rxi_CancelDelayedAbortEvent(struct rx_call *call);
160 static void rxi_CancelGrowMTUEvent(struct rx_call *call);
161 static void update_nextCid(void);
162
163 #ifndef KERNEL
164 static void rxi_Finalize_locked(void);
165 #elif defined(UKERNEL)
166 # define rxi_Finalize_locked() do { } while (0)
167 #endif
168
169 #ifdef RX_ENABLE_LOCKS
170 struct rx_tq_debug {
171     rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
172     rx_atomic_t rxi_start_in_error;
173 } rx_tq_debug;
174 #endif /* RX_ENABLE_LOCKS */
175
176 /* Constant delay time before sending an acknowledge of the last packet
177  * received.  This is to avoid sending an extra acknowledge when the
178  * client is about to make another call, anyway, or the server is
179  * about to respond.
180  *
181  * The lastAckDelay may not exceeed 400ms without causing peers to
182  * unecessarily timeout.
183  */
184 struct clock rx_lastAckDelay = {0, 400000};
185
186 /* Constant delay time before sending a soft ack when none was requested.
187  * This is to make sure we send soft acks before the sender times out,
188  * Normally we wait and send a hard ack when the receiver consumes the packet
189  *
190  * This value has been 100ms in all shipping versions of OpenAFS. Changing it
191  * will require changes to the peer's RTT calculations.
192  */
193 struct clock rx_softAckDelay = {0, 100000};
194
195 /*
196  * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
197  * currently allocated within rx.  This number is used to allocate the
198  * memory required to return the statistics when queried.
199  * Protected by the rx_rpc_stats mutex.
200  */
201
202 static unsigned int rxi_rpc_peer_stat_cnt;
203
204 /*
205  * rxi_rpc_process_stat_cnt counts the total number of local process stat
206  * structures currently allocated within rx.  The number is used to allocate
207  * the memory required to return the statistics when queried.
208  * Protected by the rx_rpc_stats mutex.
209  */
210
211 static unsigned int rxi_rpc_process_stat_cnt;
212
213 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
214 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
215
216 /* Incoming calls wait on this queue when there are no available
217  * server processes */
218 struct opr_queue rx_incomingCallQueue;
219
220 /* Server processes wait on this queue when there are no appropriate
221  * calls to process */
222 struct opr_queue rx_idleServerQueue;
223
224 /* List of free rx_serverQueueEntry structs */
225 struct opr_queue rx_freeServerQueue;
226
227 #if !defined(offsetof)
228 #include <stddef.h>             /* for definition of offsetof() */
229 #endif
230
231 #ifdef RX_ENABLE_LOCKS
232 afs_kmutex_t rx_atomic_mutex;
233 static afs_kmutex_t freeSQEList_lock;
234 #endif
235
236 /* Forward prototypes */
237 static struct rx_call * rxi_NewCall(struct rx_connection *, int);
238
239 static_inline void
240 putConnection (struct rx_connection *conn) {
241     MUTEX_ENTER(&rx_refcnt_mutex);
242     conn->refCount--;
243     MUTEX_EXIT(&rx_refcnt_mutex);
244 }
245
246 #ifdef AFS_PTHREAD_ENV
247
248 /*
249  * Use procedural initialization of mutexes/condition variables
250  * to ease NT porting
251  */
252
253 extern afs_kmutex_t rx_quota_mutex;
254 extern afs_kmutex_t rx_pthread_mutex;
255 extern afs_kmutex_t rx_packets_mutex;
256 extern afs_kmutex_t rx_refcnt_mutex;
257 extern afs_kmutex_t des_init_mutex;
258 extern afs_kmutex_t des_random_mutex;
259 #ifndef KERNEL
260 extern afs_kmutex_t rx_clock_mutex;
261 extern afs_kmutex_t rxi_connCacheMutex;
262 extern afs_kmutex_t event_handler_mutex;
263 extern afs_kmutex_t listener_mutex;
264 extern afs_kmutex_t rx_if_init_mutex;
265 extern afs_kmutex_t rx_if_mutex;
266
267 extern afs_kcondvar_t rx_event_handler_cond;
268 extern afs_kcondvar_t rx_listener_cond;
269 #endif /* !KERNEL */
270
271 static afs_kmutex_t epoch_mutex;
272 static afs_kmutex_t rx_init_mutex;
273 static afs_kmutex_t rx_debug_mutex;
274 static afs_kmutex_t rx_rpc_stats;
275
276 static void
277 rxi_InitPthread(void)
278 {
279     MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
280     MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
281     MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
282     MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
283 #ifndef KERNEL
284     MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
285     MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
286     MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
287     MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
288     MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
289     MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
290 #endif
291     MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
292     MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
293     MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
294     MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
295     MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
296
297 #ifndef KERNEL
298     CV_INIT(&rx_event_handler_cond, "evhand", CV_DEFAULT, 0);
299     CV_INIT(&rx_listener_cond, "rxlisten", CV_DEFAULT, 0);
300 #endif
301
302     osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
303     osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
304
305     MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
306     MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
307     MUTEX_INIT(&rx_mallocedPktQ_lock, "rx_mallocedPktQ_lock", MUTEX_DEFAULT,
308                0);
309
310 #ifdef  RX_ENABLE_LOCKS
311 #ifdef RX_LOCKS_DB
312     rxdb_init();
313 #endif /* RX_LOCKS_DB */
314     MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
315     MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
316                0);
317     CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
318             0);
319     MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
320                0);
321     MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
322                0);
323     MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
324 #ifndef KERNEL
325     MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
326 #endif
327 #endif /* RX_ENABLE_LOCKS */
328 }
329
330 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
331 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
332 /*
333  * The rx_stats_mutex mutex protects the following global variables:
334  * rxi_lowConnRefCount
335  * rxi_lowPeerRefCount
336  * rxi_nCalls
337  * rxi_Alloccnt
338  * rxi_Allocsize
339  * rx_tq_debug
340  * rx_stats
341  */
342
343 /*
344  * The rx_quota_mutex mutex protects the following global variables:
345  * rxi_dataQuota
346  * rxi_minDeficit
347  * rxi_availProcs
348  * rxi_totalMin
349  */
350
351 /*
352  * The rx_freePktQ_lock protects the following global variables:
353  * rx_nFreePackets
354  */
355
356 /*
357  * The rx_packets_mutex mutex protects the following global variables:
358  * rx_nPackets
359  * rx_TSFPQLocalMax
360  * rx_TSFPQGlobSize
361  * rx_TSFPQMaxProcs
362  */
363
364 /*
365  * The rx_pthread_mutex mutex protects the following global variables:
366  * rxi_fcfs_thread_num
367  */
368 #else
369 #define INIT_PTHREAD_LOCKS
370 #endif
371
372
373 /* Variables for handling the minProcs implementation.  availProcs gives the
374  * number of threads available in the pool at this moment (not counting dudes
375  * executing right now).  totalMin gives the total number of procs required
376  * for handling all minProcs requests.  minDeficit is a dynamic variable
377  * tracking the # of procs required to satisfy all of the remaining minProcs
378  * demands.
379  * For fine grain locking to work, the quota check and the reservation of
380  * a server thread has to come while rxi_availProcs and rxi_minDeficit
381  * are locked. To this end, the code has been modified under #ifdef
382  * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
383  * same time. A new function, ReturnToServerPool() returns the allocation.
384  *
385  * A call can be on several queue's (but only one at a time). When
386  * rxi_ResetCall wants to remove the call from a queue, it has to ensure
387  * that no one else is touching the queue. To this end, we store the address
388  * of the queue lock in the call structure (under the call lock) when we
389  * put the call on a queue, and we clear the call_queue_lock when the
390  * call is removed from a queue (once the call lock has been obtained).
391  * This allows rxi_ResetCall to safely synchronize with others wishing
392  * to manipulate the queue.
393  */
394
395 #if defined(RX_ENABLE_LOCKS)
396 static afs_kmutex_t rx_rpc_stats;
397 #endif
398
399 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
400 ** pretty good that the next packet coming in is from the same connection
401 ** as the last packet, since we're send multiple packets in a transmit window.
402 */
403 struct rx_connection *rxLastConn = 0;
404
405 #ifdef RX_ENABLE_LOCKS
406 /* The locking hierarchy for rx fine grain locking is composed of these
407  * tiers:
408  *
409  * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
410  *                         also protects updates to rx_nextCid
411  * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
412  * call->lock - locks call data fields.
413  * These are independent of each other:
414  *      rx_freeCallQueue_lock
415  *      rxi_keyCreate_lock
416  * rx_serverPool_lock
417  * freeSQEList_lock
418  *
419  * serverQueueEntry->lock
420  * rx_peerHashTable_lock - locked under rx_connHashTable_lock
421  * rx_rpc_stats
422  * peer->lock - locks peer data fields.
423  * conn_data_lock - that more than one thread is not updating a conn data
424  *                  field at the same time.
425  * rx_freePktQ_lock
426  *
427  * lowest level:
428  *      multi_handle->lock
429  *      rxevent_lock
430  *      rx_packets_mutex
431  *      rx_stats_mutex
432  *      rx_refcnt_mutex
433  *      rx_atomic_mutex
434  *
435  * Do we need a lock to protect the peer field in the conn structure?
436  *      conn->peer was previously a constant for all intents and so has no
437  *      lock protecting this field. The multihomed client delta introduced
438  *      a RX code change : change the peer field in the connection structure
439  *      to that remote interface from which the last packet for this
440  *      connection was sent out. This may become an issue if further changes
441  *      are made.
442  */
443 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
444 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
445 #ifdef RX_LOCKS_DB
446 /* rxdb_fileID is used to identify the lock location, along with line#. */
447 static int rxdb_fileID = RXDB_FILE_RX;
448 #endif /* RX_LOCKS_DB */
449 #else /* RX_ENABLE_LOCKS */
450 #define SET_CALL_QUEUE_LOCK(C, L)
451 #define CLEAR_CALL_QUEUE_LOCK(C)
452 #endif /* RX_ENABLE_LOCKS */
453 struct rx_serverQueueEntry *rx_waitForPacket = 0;
454
455 /*
456  * This mutex serializes calls to our initialization and shutdown routines
457  * (rx_InitHost, rx_Finalize and shutdown_rx). Only one thread can be running
458  * these at any time; all other threads must wait for it to finish running, and
459  * then examine the value of rxi_running afterwards.
460  */
461 #ifdef AFS_PTHREAD_ENV
462 # define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
463 # define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
464 #else
465 # define LOCK_RX_INIT
466 # define UNLOCK_RX_INIT
467 #endif
468
469 /* ------------Exported Interfaces------------- */
470
471 static rx_atomic_t rxi_running = RX_ATOMIC_INIT(0);
472 int
473 rxi_IsRunning(void)
474 {
475     return rx_atomic_read(&rxi_running);
476 }
477
478 /* Initialize rx.  A port number may be mentioned, in which case this
479  * becomes the default port number for any service installed later.
480  * If 0 is provided for the port number, a random port will be chosen
481  * by the kernel.  Whether this will ever overlap anything in
482  * /etc/services is anybody's guess...  Returns 0 on success, -1 on
483  * error. */
484 int
485 rx_InitHost(u_int host, u_int port)
486 {
487 #ifdef KERNEL
488     osi_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 (rxi_AbortIfServerBusy(socket, conn, np)) {
3298             MUTEX_EXIT(&conn->conn_call_lock);
3299             return NULL;
3300         }
3301
3302         call = rxi_NewCall(conn, channel);  /* returns locked call */
3303         *call->callNumber = np->header.callNumber;
3304         MUTEX_EXIT(&conn->conn_call_lock);
3305
3306         call->state = RX_STATE_PRECALL;
3307         clock_GetTime(&call->queueTime);
3308         call->app.bytesSent = 0;
3309         call->app.bytesRcvd = 0;
3310         rxi_KeepAliveOn(call);
3311
3312         return call;
3313     }
3314
3315     if (np->header.callNumber == conn->callNumber[channel]) {
3316         MUTEX_ENTER(&call->lock);
3317         MUTEX_EXIT(&conn->conn_call_lock);
3318         return call;
3319     }
3320
3321     if (np->header.callNumber < conn->callNumber[channel]) {
3322         MUTEX_EXIT(&conn->conn_call_lock);
3323         if (rx_stats_active)
3324             rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3325         return NULL;
3326     }
3327
3328     MUTEX_ENTER(&call->lock);
3329     MUTEX_EXIT(&conn->conn_call_lock);
3330
3331     /* Wait until the transmit queue is idle before deciding
3332      * whether to reset the current call. Chances are that the
3333      * call will be in ether DALLY or HOLD state once the TQ_BUSY
3334      * flag is cleared.
3335      */
3336 #ifdef RX_ENABLE_LOCKS
3337     if (call->state == RX_STATE_ACTIVE && !call->error) {
3338         rxi_WaitforTQBusy(call);
3339         /* If we entered error state while waiting,
3340          * must call rxi_CallError to permit rxi_ResetCall
3341          * to processed when the tqWaiter count hits zero.
3342          */
3343         if (call->error) {
3344             rxi_CallError(call, call->error);
3345             MUTEX_EXIT(&call->lock);
3346             return NULL;
3347         }
3348     }
3349 #endif /* RX_ENABLE_LOCKS */
3350     /* If the new call cannot be taken right now send a busy and set
3351      * the error condition in this call, so that it terminates as
3352      * quickly as possible */
3353     if (call->state == RX_STATE_ACTIVE) {
3354         rxi_CallError(call, RX_CALL_DEAD);
3355         rxi_SendSpecial(call, conn, NULL, RX_PACKET_TYPE_BUSY,
3356                         NULL, 0, 1);
3357         MUTEX_EXIT(&call->lock);
3358         return NULL;
3359     }
3360
3361     if (rxi_AbortIfServerBusy(socket, conn, np)) {
3362         MUTEX_EXIT(&call->lock);
3363         return NULL;
3364     }
3365
3366     rxi_ResetCall(call, 0);
3367     /* The conn_call_lock is not held but no one else should be
3368      * using this call channel while we are processing this incoming
3369      * packet.  This assignment should be safe.
3370      */
3371     *call->callNumber = np->header.callNumber;
3372     call->state = RX_STATE_PRECALL;
3373     clock_GetTime(&call->queueTime);
3374     call->app.bytesSent = 0;
3375     call->app.bytesRcvd = 0;
3376     rxi_KeepAliveOn(call);
3377
3378     return call;
3379 }
3380
3381
3382 /* There are two packet tracing routines available for testing and monitoring
3383  * Rx.  One is called just after every packet is received and the other is
3384  * called just before every packet is sent.  Received packets, have had their
3385  * headers decoded, and packets to be sent have not yet had their headers
3386  * encoded.  Both take two parameters: a pointer to the packet and a sockaddr
3387  * containing the network address.  Both can be modified.  The return value, if
3388  * non-zero, indicates that the packet should be dropped.  */
3389
3390 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
3391 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
3392
3393 /* A packet has been received off the interface.  Np is the packet, socket is
3394  * the socket number it was received from (useful in determining which service
3395  * this packet corresponds to), and (host, port) reflect the host,port of the
3396  * sender.  This call returns the packet to the caller if it is finished with
3397  * it, rather than de-allocating it, just as a small performance hack */
3398
3399 struct rx_packet *
3400 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
3401                   afs_uint32 host, u_short port, int *tnop,
3402                   struct rx_call **newcallp)
3403 {
3404     struct rx_call *call;
3405     struct rx_connection *conn;
3406     int type;
3407     int unknownService = 0;
3408 #ifdef RXDEBUG
3409     char *packetType;
3410 #endif
3411     struct rx_packet *tnp;
3412
3413 #ifdef RXDEBUG
3414 /* We don't print out the packet until now because (1) the time may not be
3415  * accurate enough until now in the lwp implementation (rx_Listener only gets
3416  * the time after the packet is read) and (2) from a protocol point of view,
3417  * this is the first time the packet has been seen */
3418     packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
3419         ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
3420     dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %p\n",
3421          np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
3422          np->header.epoch, np->header.cid, np->header.callNumber,
3423          np->header.seq, np->header.flags, np));
3424 #endif
3425
3426     /* Account for connectionless packets */
3427     if (rx_stats_active &&
3428         ((np->header.type == RX_PACKET_TYPE_VERSION) ||
3429          (np->header.type == RX_PACKET_TYPE_DEBUG))) {
3430         struct rx_peer *peer;
3431
3432         /* Try to look up the peer structure, but don't create one */
3433         peer = rxi_FindPeer(host, port, 0);
3434
3435         /* Since this may not be associated with a connection, it may have
3436          * no refCount, meaning we could race with ReapConnections
3437          */
3438
3439         if (peer && (peer->refCount > 0)) {
3440 #ifdef AFS_RXERRQ_ENV
3441             if (rx_atomic_read(&peer->neterrs)) {
3442                 rx_atomic_set(&peer->neterrs, 0);
3443             }
3444 #endif
3445             MUTEX_ENTER(&peer->peer_lock);
3446             peer->bytesReceived += np->length;
3447             MUTEX_EXIT(&peer->peer_lock);
3448         }
3449     }
3450
3451     if (np->header.type == RX_PACKET_TYPE_VERSION) {
3452         return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
3453     }
3454
3455     if (np->header.type == RX_PACKET_TYPE_DEBUG) {
3456         return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
3457     }
3458 #ifdef RXDEBUG
3459     /* If an input tracer function is defined, call it with the packet and
3460      * network address.  Note this function may modify its arguments. */
3461     if (rx_justReceived) {
3462         struct sockaddr_in addr;
3463         int drop;
3464         addr.sin_family = AF_INET;
3465         addr.sin_port = port;
3466         addr.sin_addr.s_addr = host;
3467         memset(&addr.sin_zero, 0, sizeof(addr.sin_zero));
3468 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
3469         addr.sin_len = sizeof(addr);
3470 #endif
3471         drop = (*rx_justReceived) (np, &addr);
3472         /* drop packet if return value is non-zero */
3473         if (drop)
3474             return np;
3475         port = addr.sin_port;   /* in case fcn changed addr */
3476         host = addr.sin_addr.s_addr;
3477     }
3478 #endif
3479
3480     /* If packet was not sent by the client, then *we* must be the client */
3481     type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
3482         ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
3483
3484     /* Find the connection (or fabricate one, if we're the server & if
3485      * necessary) associated with this packet */
3486     conn =
3487         rxi_FindConnection(socket, host, port, np->header.serviceId,
3488                            np->header.cid, np->header.epoch, type,
3489                            np->header.securityIndex, &unknownService);
3490
3491     /* To avoid having 2 connections just abort at each other,
3492        don't abort an abort. */
3493     if (!conn) {
3494         if (unknownService && (np->header.type != RX_PACKET_TYPE_ABORT))
3495             rxi_SendRawAbort(socket, host, port, 0, RX_INVALID_OPERATION,
3496                              np, 0);
3497         return np;
3498     }
3499
3500 #ifdef AFS_RXERRQ_ENV
3501     if (rx_atomic_read(&conn->peer->neterrs)) {
3502         rx_atomic_set(&conn->peer->neterrs, 0);
3503     }
3504 #endif
3505
3506     /* If we're doing statistics, then account for the incoming packet */
3507     if (rx_stats_active) {
3508         MUTEX_ENTER(&conn->peer->peer_lock);
3509         conn->peer->bytesReceived += np->length;
3510         MUTEX_EXIT(&conn->peer->peer_lock);
3511     }
3512
3513     /* If the connection is in an error state, send an abort packet and ignore
3514      * the incoming packet */
3515     if (conn->error) {
3516         /* Don't respond to an abort packet--we don't want loops! */
3517         MUTEX_ENTER(&conn->conn_data_lock);
3518         if (np->header.type != RX_PACKET_TYPE_ABORT)
3519             np = rxi_SendConnectionAbort(conn, np, 1, 0);
3520         putConnection(conn);
3521         MUTEX_EXIT(&conn->conn_data_lock);
3522         return np;
3523     }
3524
3525     /* Check for connection-only requests (i.e. not call specific). */
3526     if (np->header.callNumber == 0) {
3527         switch (np->header.type) {
3528         case RX_PACKET_TYPE_ABORT: {
3529             /* What if the supplied error is zero? */
3530             afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
3531             dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
3532             rxi_ConnectionError(conn, errcode);
3533             putConnection(conn);
3534             return np;
3535         }
3536         case RX_PACKET_TYPE_CHALLENGE:
3537             tnp = rxi_ReceiveChallengePacket(conn, np, 1);
3538             putConnection(conn);
3539             return tnp;
3540         case RX_PACKET_TYPE_RESPONSE:
3541             tnp = rxi_ReceiveResponsePacket(conn, np, 1);
3542             putConnection(conn);
3543             return tnp;
3544         case RX_PACKET_TYPE_PARAMS:
3545         case RX_PACKET_TYPE_PARAMS + 1:
3546         case RX_PACKET_TYPE_PARAMS + 2:
3547             /* ignore these packet types for now */
3548             putConnection(conn);
3549             return np;
3550
3551         default:
3552             /* Should not reach here, unless the peer is broken: send an
3553              * abort packet */
3554             rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
3555             MUTEX_ENTER(&conn->conn_data_lock);
3556             tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
3557             putConnection(conn);
3558             MUTEX_EXIT(&conn->conn_data_lock);
3559             return tnp;
3560         }
3561     }
3562
3563     if (type == RX_SERVER_CONNECTION)
3564         call = rxi_ReceiveServerCall(socket, np, conn);
3565     else
3566         call = rxi_ReceiveClientCall(np, conn);
3567
3568     if (call == NULL) {
3569         putConnection(conn);
3570         return np;
3571     }
3572
3573     MUTEX_ASSERT(&call->lock);
3574     /* Set remote user defined status from packet */
3575     call->remoteStatus = np->header.userStatus;
3576
3577     /* Now do packet type-specific processing */
3578     switch (np->header.type) {
3579     case RX_PACKET_TYPE_DATA:
3580         /* If we're a client, and receiving a response, then all the packets
3581          * we transmitted packets are implicitly acknowledged. */
3582         if (type == RX_CLIENT_CONNECTION && !opr_queue_IsEmpty(&call->tq))
3583             rxi_AckAllInTransmitQueue(call);
3584
3585         np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3586                                    newcallp);
3587         break;
3588     case RX_PACKET_TYPE_ACK:
3589         /* Respond immediately to ack packets requesting acknowledgement
3590          * (ping packets) */
3591         if (np->header.flags & RX_REQUEST_ACK) {
3592             if (call->error)
3593                 (void)rxi_SendCallAbort(call, 0, 1, 0);
3594             else
3595                 (void)rxi_SendAck(call, 0, np->header.serial,
3596                                   RX_ACK_PING_RESPONSE, 1);
3597         }
3598         np = rxi_ReceiveAckPacket(call, np, 1);
3599         break;
3600     case RX_PACKET_TYPE_ABORT: {
3601         /* An abort packet: reset the call, passing the error up to the user. */
3602         /* What if error is zero? */
3603         /* What if the error is -1? the application will treat it as a timeout. */
3604         afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3605         dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3606         rxi_CallError(call, errdata);
3607         MUTEX_EXIT(&call->lock);
3608         putConnection(conn);
3609         return np;              /* xmitting; drop packet */
3610     }
3611     case RX_PACKET_TYPE_BUSY:
3612         /* Mostly ignore BUSY packets. We will update lastReceiveTime below,
3613          * so we don't think the endpoint is completely dead, but otherwise
3614          * just act as if we never saw anything. If all we get are BUSY packets
3615          * back, then we will eventually error out with RX_CALL_TIMEOUT if the
3616          * connection is configured with idle/hard timeouts. */
3617         break;
3618
3619     case RX_PACKET_TYPE_ACKALL:
3620         /* All packets acknowledged, so we can drop all packets previously
3621          * readied for sending */
3622         rxi_AckAllInTransmitQueue(call);
3623         break;
3624     default:
3625         /* Should not reach here, unless the peer is broken: send an abort
3626          * packet */
3627         rxi_CallError(call, RX_PROTOCOL_ERROR);
3628         np = rxi_SendCallAbort(call, np, 1, 0);
3629         break;
3630     };
3631     /* Note when this last legitimate packet was received, for keep-alive
3632      * processing.  Note, we delay getting the time until now in the hope that
3633      * the packet will be delivered to the user before any get time is required
3634      * (if not, then the time won't actually be re-evaluated here). */
3635     call->lastReceiveTime = clock_Sec();
3636     MUTEX_EXIT(&call->lock);
3637     putConnection(conn);
3638     return np;
3639 }
3640
3641 /* return true if this is an "interesting" connection from the point of view
3642     of someone trying to debug the system */
3643 int
3644 rxi_IsConnInteresting(struct rx_connection *aconn)
3645 {
3646     int i;
3647     struct rx_call *tcall;
3648
3649     if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3650         return 1;
3651
3652     for (i = 0; i < RX_MAXCALLS; i++) {
3653         tcall = aconn->call[i];
3654         if (tcall) {
3655             if ((tcall->state == RX_STATE_PRECALL)
3656                 || (tcall->state == RX_STATE_ACTIVE))
3657                 return 1;
3658             if ((tcall->app.mode == RX_MODE_SENDING)
3659                 || (tcall->app.mode == RX_MODE_RECEIVING))
3660                 return 1;
3661         }
3662     }
3663     return 0;
3664 }
3665
3666 #ifdef KERNEL
3667 /* if this is one of the last few packets AND it wouldn't be used by the
3668    receiving call to immediately satisfy a read request, then drop it on
3669    the floor, since accepting it might prevent a lock-holding thread from
3670    making progress in its reading. If a call has been cleared while in
3671    the precall state then ignore all subsequent packets until the call
3672    is assigned to a thread. */
3673
3674 static int
3675 TooLow(struct rx_packet *ap, struct rx_call *acall)
3676 {
3677     int rc = 0;
3678
3679     MUTEX_ENTER(&rx_quota_mutex);
3680     if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3681          && (acall->state == RX_STATE_PRECALL))
3682         || ((rx_nFreePackets < rxi_dataQuota + 2)
3683             && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3684                  && (acall->flags & RX_CALL_READER_WAIT)))) {
3685         rc = 1;
3686     }
3687     MUTEX_EXIT(&rx_quota_mutex);
3688     return rc;
3689 }
3690 #endif /* KERNEL */
3691
3692 /*!
3693  * Clear the attach wait flag on a connection and proceed.
3694  *
3695  * Any processing waiting for a connection to be attached should be
3696  * unblocked. We clear the flag and do any other needed tasks.
3697  *
3698  * @param[in] conn
3699  *      the conn to unmark waiting for attach
3700  *
3701  * @pre conn's conn_data_lock must be locked before calling this function
3702  *
3703  */
3704 static void
3705 rxi_ConnClearAttachWait(struct rx_connection *conn)
3706 {
3707     /* Indicate that rxi_CheckReachEvent is no longer running by
3708      * clearing the flag.  Must be atomic under conn_data_lock to
3709      * avoid a new call slipping by: rxi_CheckConnReach holds
3710      * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3711      */
3712     conn->flags &= ~RX_CONN_ATTACHWAIT;
3713     if (conn->flags & RX_CONN_NAT_PING) {
3714         conn->flags &= ~RX_CONN_NAT_PING;
3715         rxi_ScheduleNatKeepAliveEvent(conn);
3716     }
3717 }
3718
3719 /*
3720  * Event handler function for connection-specific events for checking
3721  * reachability.  Also called directly from main code with |event| == NULL
3722  * in order to trigger the initial reachability check.
3723  *
3724  * When |event| == NULL, must be called with the connection data lock held,
3725  * but returns with the lock unlocked.
3726  */
3727 static void
3728 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2, int dummy)
3729 {
3730     struct rx_connection *conn = arg1;
3731     struct rx_call *acall = arg2;
3732     struct rx_call *call = acall;
3733     struct clock when, now;
3734     int i, waiting;
3735
3736     if (event != NULL)
3737         MUTEX_ENTER(&conn->conn_data_lock);
3738     else
3739         MUTEX_ASSERT(&conn->conn_data_lock);
3740
3741     if (event != NULL && event == conn->checkReachEvent)
3742         rxevent_Put(&conn->checkReachEvent);
3743     waiting = conn->flags & RX_CONN_ATTACHWAIT;
3744     MUTEX_EXIT(&conn->conn_data_lock);
3745
3746     if (waiting) {
3747         if (!call) {
3748             MUTEX_ENTER(&conn->conn_call_lock);
3749             MUTEX_ENTER(&conn->conn_data_lock);
3750             for (i = 0; i < RX_MAXCALLS; i++) {
3751                 struct rx_call *tc = conn->call[i];
3752                 if (tc && tc->state == RX_STATE_PRECALL) {
3753                     call = tc;
3754                     break;
3755                 }
3756             }
3757             if (!call)
3758                 rxi_ConnClearAttachWait(conn);
3759             MUTEX_EXIT(&conn->conn_data_lock);
3760             MUTEX_EXIT(&conn->conn_call_lock);
3761         }
3762
3763         if (call) {
3764             if (call != acall)
3765                 MUTEX_ENTER(&call->lock);
3766             rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3767             if (call != acall)
3768                 MUTEX_EXIT(&call->lock);
3769
3770             clock_GetTime(&now);
3771             when = now;
3772             when.sec += RX_CHECKREACH_TIMEOUT;
3773             MUTEX_ENTER(&conn->conn_data_lock);
3774             if (!conn->checkReachEvent) {
3775                 rx_GetConnection(conn);
3776                 conn->checkReachEvent = rxevent_Post(&when, &now,
3777                                                      rxi_CheckReachEvent, conn,
3778                                                      NULL, 0);
3779             }
3780             MUTEX_EXIT(&conn->conn_data_lock);
3781         }
3782     }
3783     /* If fired as an event handler, drop our refcount on the connection. */
3784     if (event != NULL)
3785         putConnection(conn);
3786 }
3787
3788 static int
3789 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3790 {
3791     struct rx_service *service = conn->service;
3792     struct rx_peer *peer = conn->peer;
3793     afs_uint32 now, lastReach;
3794
3795     if (service->checkReach == 0)
3796         return 0;
3797
3798     now = clock_Sec();
3799     MUTEX_ENTER(&peer->peer_lock);
3800     lastReach = peer->lastReachTime;
3801     MUTEX_EXIT(&peer->peer_lock);
3802     if (now - lastReach < RX_CHECKREACH_TTL)
3803         return 0;
3804
3805     MUTEX_ENTER(&conn->conn_data_lock);
3806     if (conn->flags & RX_CONN_ATTACHWAIT) {
3807         MUTEX_EXIT(&conn->conn_data_lock);
3808         return 1;
3809     }
3810     conn->flags |= RX_CONN_ATTACHWAIT;
3811     if (conn->checkReachEvent == NULL) {
3812         /* rxi_CheckReachEvent(NULL, ...) will drop the lock. */
3813         rxi_CheckReachEvent(NULL, conn, call, 0);
3814     } else {
3815         MUTEX_EXIT(&conn->conn_data_lock);
3816     }
3817
3818     return 1;
3819 }
3820
3821 /* try to attach call, if authentication is complete */
3822 static void
3823 TryAttach(struct rx_call *acall, osi_socket socket,
3824           int *tnop, struct rx_call **newcallp,
3825           int reachOverride, int istack)
3826 {
3827     struct rx_connection *conn = acall->conn;
3828
3829     if (conn->type == RX_SERVER_CONNECTION
3830         && acall->state == RX_STATE_PRECALL) {
3831         /* Don't attach until we have any req'd. authentication. */
3832         if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3833             if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3834                 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3835             /* Note:  this does not necessarily succeed; there
3836              * may not any proc available
3837              */
3838         } else {
3839             int code;
3840             code = rxi_ChallengeOn(acall->conn);
3841             if (code) {
3842                 /*
3843                  * Ideally we would rxi_ConnectionError here, but doing that is
3844                  * difficult, because some callers may have locked 'call',
3845                  * _and_ another call on the same conn. So we cannot
3846                  * rxi_ConnectionError, since that needs to lock every call on
3847                  * the conn. But we can at least abort the call we have.
3848                  */
3849                 rxi_CallError(acall, code);
3850                 rxi_SendCallAbort(acall, NULL, istack, 0);
3851             }
3852         }
3853     }
3854 }
3855
3856 /* A data packet has been received off the interface.  This packet is
3857  * appropriate to the call (the call is in the right state, etc.).  This
3858  * routine can return a packet to the caller, for re-use */
3859
3860 static struct rx_packet *
3861 rxi_ReceiveDataPacket(struct rx_call *call,
3862                       struct rx_packet *np, int istack,
3863                       osi_socket socket, afs_uint32 host, u_short port,
3864                       int *tnop, struct rx_call **newcallp)
3865 {
3866     int ackNeeded = 0;          /* 0 means no, otherwise ack_reason */
3867     int newPackets = 0;
3868     int didHardAck = 0;
3869     int haveLast = 0;
3870     afs_uint32 seq;
3871     afs_uint32 serial=0, flags=0;
3872     int isFirst;
3873     struct rx_packet *tnp;
3874     if (rx_stats_active)
3875         rx_atomic_inc(&rx_stats.dataPacketsRead);
3876
3877 #ifdef KERNEL
3878     /* If there are no packet buffers, drop this new packet, unless we can find
3879      * packet buffers from inactive calls */
3880     if (!call->error
3881         && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3882         MUTEX_ENTER(&rx_freePktQ_lock);
3883         rxi_NeedMorePackets = TRUE;
3884         MUTEX_EXIT(&rx_freePktQ_lock);
3885         if (rx_stats_active)
3886             rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3887         rxi_calltrace(RX_TRACE_DROP, call);
3888         dpf(("packet %p dropped on receipt - quota problems\n", np));
3889         /* We used to clear the receive queue here, in an attempt to free
3890          * packets. However this is unsafe if the queue has received a
3891          * soft ACK for the final packet */
3892         rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
3893         return np;
3894     }
3895 #endif /* KERNEL */
3896
3897     /*
3898      * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3899      * packet is one of several packets transmitted as a single
3900      * datagram. Do not send any soft or hard acks until all packets
3901      * in a jumbogram have been processed. Send negative acks right away.
3902      */
3903     for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3904         /* tnp is non-null when there are more packets in the
3905          * current jumbo gram */
3906         if (tnp) {
3907             if (np)
3908                 rxi_FreePacket(np);
3909             np = tnp;
3910         }
3911
3912         seq = np->header.seq;
3913         serial = np->header.serial;
3914         flags = np->header.flags;
3915
3916         /* If the call is in an error state, send an abort message */
3917         if (call->error)
3918             return rxi_SendCallAbort(call, np, istack, 0);
3919
3920         /* The RX_JUMBO_PACKET is set in all but the last packet in each
3921          * AFS 3.5 jumbogram. */
3922         if (flags & RX_JUMBO_PACKET) {
3923             tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3924         } else {
3925             tnp = NULL;
3926         }
3927
3928         if (np->header.spare != 0) {
3929             MUTEX_ENTER(&call->conn->conn_data_lock);
3930             call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3931             MUTEX_EXIT(&call->conn->conn_data_lock);
3932         }
3933
3934         /* The usual case is that this is the expected next packet */
3935         if (seq == call->rnext) {
3936
3937             /* Check to make sure it is not a duplicate of one already queued */
3938             if (!opr_queue_IsEmpty(&call->rq)
3939                 && opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq == seq) {
3940                 if (rx_stats_active)
3941                     rx_atomic_inc(&rx_stats.dupPacketsRead);
3942                 dpf(("packet %p dropped on receipt - duplicate\n", np));
3943                 rxi_CancelDelayedAckEvent(call);
3944                 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3945                 ackNeeded = 0;
3946                 call->rprev = seq;
3947                 continue;
3948             }
3949
3950             /* It's the next packet. Stick it on the receive queue
3951              * for this call. Set newPackets to make sure we wake
3952              * the reader once all packets have been processed */
3953 #ifdef RX_TRACK_PACKETS
3954             np->flags |= RX_PKTFLAG_RQ;
3955 #endif
3956             opr_queue_Prepend(&call->rq, &np->entry);
3957 #ifdef RXDEBUG_PACKET
3958             call->rqc++;
3959 #endif /* RXDEBUG_PACKET */
3960             call->nSoftAcks++;
3961             np = NULL;          /* We can't use this anymore */
3962             newPackets = 1;
3963
3964             /* If an ack is requested then set a flag to make sure we
3965              * send an acknowledgement for this packet */
3966             if (flags & RX_REQUEST_ACK) {
3967                 ackNeeded = RX_ACK_REQUESTED;
3968             }
3969
3970             /* Keep track of whether we have received the last packet */
3971             if (flags & RX_LAST_PACKET) {
3972                 call->flags |= RX_CALL_HAVE_LAST;
3973                 haveLast = 1;
3974             }
3975
3976             /* Check whether we have all of the packets for this call */
3977             if (call->flags & RX_CALL_HAVE_LAST) {
3978                 afs_uint32 tseq;        /* temporary sequence number */
3979                 struct opr_queue *cursor;
3980
3981                 for (tseq = seq, opr_queue_Scan(&call->rq, cursor)) {
3982                     struct rx_packet *tp;
3983                     
3984                     tp = opr_queue_Entry(cursor, struct rx_packet, entry);
3985                     if (tseq != tp->header.seq)
3986                         break;
3987                     if (tp->header.flags & RX_LAST_PACKET) {
3988                         call->flags |= RX_CALL_RECEIVE_DONE;
3989                         break;
3990                     }
3991                     tseq++;
3992                 }
3993             }
3994
3995             /* Provide asynchronous notification for those who want it
3996              * (e.g. multi rx) */
3997             if (call->arrivalProc) {
3998                 (*call->arrivalProc) (call, call->arrivalProcHandle,
3999                                       call->arrivalProcArg);
4000                 call->arrivalProc = NULL;
4001             }
4002
4003             /* Update last packet received */
4004             call->rprev = seq;
4005
4006             /* If there is no server process serving this call, grab
4007              * one, if available. We only need to do this once. If a
4008              * server thread is available, this thread becomes a server
4009              * thread and the server thread becomes a listener thread. */
4010             if (isFirst) {
4011                 TryAttach(call, socket, tnop, newcallp, 0, istack);
4012             }
4013         }
4014         /* This is not the expected next packet. */
4015         else {
4016             /* Determine whether this is a new or old packet, and if it's
4017              * a new one, whether it fits into the current receive window.
4018              * Also figure out whether the packet was delivered in sequence.
4019              * We use the prev variable to determine whether the new packet
4020              * is the successor of its immediate predecessor in the
4021              * receive queue, and the missing flag to determine whether
4022              * any of this packets predecessors are missing.  */
4023
4024             afs_uint32 prev;    /* "Previous packet" sequence number */
4025             struct opr_queue *cursor;
4026             int missing;        /* Are any predecessors missing? */
4027
4028             /* If the new packet's sequence number has been sent to the
4029              * application already, then this is a duplicate */
4030             if (seq < call->rnext) {
4031                 if (rx_stats_active)
4032                     rx_atomic_inc(&rx_stats.dupPacketsRead);
4033                 rxi_CancelDelayedAckEvent(call);
4034                 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
4035                 ackNeeded = 0;
4036                 call->rprev = seq;
4037                 continue;
4038             }
4039
4040             /* If the sequence number is greater than what can be
4041              * accomodated by the current window, then send a negative
4042              * acknowledge and drop the packet */
4043             if ((call->rnext + call->rwind) <= seq) {
4044                 rxi_CancelDelayedAckEvent(call);
4045                 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
4046                                  istack);
4047                 ackNeeded = 0;
4048                 call->rprev = seq;
4049                 continue;
4050             }
4051
4052             /* Look for the packet in the queue of old received packets */
4053             prev = call->rnext - 1;
4054             missing = 0;
4055             for (opr_queue_Scan(&call->rq, cursor)) {
4056                 struct rx_packet *tp
4057                     = opr_queue_Entry(cursor, struct rx_packet, entry);
4058
4059                 /*Check for duplicate packet */
4060                 if (seq == tp->header.seq) {
4061                     if (rx_stats_active)
4062                         rx_atomic_inc(&rx_stats.dupPacketsRead);
4063                     rxi_CancelDelayedAckEvent(call);
4064                     np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
4065                                      istack);
4066                     ackNeeded = 0;
4067                     call->rprev = seq;
4068                     goto nextloop;
4069                 }
4070                 /* If we find a higher sequence packet, break out and
4071                  * insert the new packet here. */
4072                 if (seq < tp->header.seq)
4073                     break;
4074                 /* Check for missing packet */
4075                 if (tp->header.seq != prev + 1) {
4076                     missing = 1;
4077                 }
4078
4079                 prev = tp->header.seq;
4080             }
4081
4082             /* Keep track of whether we have received the last packet. */
4083             if (flags & RX_LAST_PACKET) {
4084                 call->flags |= RX_CALL_HAVE_LAST;
4085             }
4086
4087             /* It's within the window: add it to the the receive queue.
4088              * tp is left by the previous loop either pointing at the
4089              * packet before which to insert the new packet, or at the
4090              * queue head if the queue is empty or the packet should be
4091              * appended. */
4092 #ifdef RX_TRACK_PACKETS
4093             np->flags |= RX_PKTFLAG_RQ;
4094 #endif
4095 #ifdef RXDEBUG_PACKET
4096             call->rqc++;
4097 #endif /* RXDEBUG_PACKET */
4098             opr_queue_InsertBefore(cursor, &np->entry);
4099             call->nSoftAcks++;
4100             np = NULL;
4101
4102             /* Check whether we have all of the packets for this call */
4103             if ((call->flags & RX_CALL_HAVE_LAST)
4104                 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
4105                 afs_uint32 tseq;        /* temporary sequence number */
4106
4107                 tseq = call->rnext;
4108                 for (opr_queue_Scan(&call->rq, cursor)) {
4109                     struct rx_packet *tp
4110                          = opr_queue_Entry(cursor, struct rx_packet, entry);
4111                     if (tseq != tp->header.seq)
4112                         break;
4113                     if (tp->header.flags & RX_LAST_PACKET) {
4114                         call->flags |= RX_CALL_RECEIVE_DONE;
4115                         break;
4116                     }
4117                     tseq++;
4118                 }
4119             }
4120
4121             /* We need to send an ack of the packet is out of sequence,
4122              * or if an ack was requested by the peer. */
4123             if (seq != prev + 1 || missing) {
4124                 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
4125             } else if (flags & RX_REQUEST_ACK) {
4126                 ackNeeded = RX_ACK_REQUESTED;
4127             }
4128
4129             /* Acknowledge the last packet for each call */
4130             if (flags & RX_LAST_PACKET) {
4131                 haveLast = 1;
4132             }
4133
4134             call->rprev = seq;
4135         }
4136       nextloop:;
4137     }
4138
4139     if (newPackets) {
4140         /*
4141          * If the receiver is waiting for an iovec, fill the iovec
4142          * using the data from the receive queue */
4143         if (call->flags & RX_CALL_IOVEC_WAIT) {
4144             didHardAck = rxi_FillReadVec(call, serial);
4145             /* the call may have been aborted */
4146             if (call->error) {
4147                 return NULL;
4148             }
4149             if (didHardAck) {
4150                 ackNeeded = 0;
4151             }
4152         }
4153
4154         /* Wakeup the reader if any */
4155         if ((call->flags & RX_CALL_READER_WAIT)
4156             && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
4157                 || (call->iovNext >= call->iovMax)
4158                 || (call->flags & RX_CALL_RECEIVE_DONE))) {
4159             call->flags &= ~RX_CALL_READER_WAIT;
4160 #ifdef  RX_ENABLE_LOCKS
4161             CV_BROADCAST(&call->cv_rq);
4162 #else
4163             osi_rxWakeup(&call->rq);
4164 #endif
4165         }
4166     }
4167
4168     /*
4169      * Send an ack when requested by the peer, or once every
4170      * rxi_SoftAckRate packets until the last packet has been
4171      * received. Always send a soft ack for the last packet in
4172      * the server's reply. */
4173     if (ackNeeded) {
4174         rxi_CancelDelayedAckEvent(call);
4175         np = rxi_SendAck(call, np, serial, ackNeeded, istack);
4176     } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
4177         rxi_CancelDelayedAckEvent(call);
4178         np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
4179     } else if (call->nSoftAcks) {
4180         if (haveLast && !(flags & RX_CLIENT_INITIATED))
4181             rxi_PostDelayedAckEvent(call, &rx_lastAckDelay);
4182         else
4183             rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
4184     } else if (call->flags & RX_CALL_RECEIVE_DONE) {
4185         rxi_CancelDelayedAckEvent(call);
4186     }
4187
4188     return np;
4189 }
4190
4191 static void
4192 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall,
4193                     int istack)
4194 {
4195     struct rx_peer *peer = conn->peer;
4196
4197     MUTEX_ENTER(&peer->peer_lock);
4198     peer->lastReachTime = clock_Sec();
4199     MUTEX_EXIT(&peer->peer_lock);
4200
4201     MUTEX_ENTER(&conn->conn_data_lock);
4202     if (conn->flags & RX_CONN_ATTACHWAIT) {
4203         int i;
4204
4205         rxi_ConnClearAttachWait(conn);
4206         MUTEX_EXIT(&conn->conn_data_lock);
4207
4208         for (i = 0; i < RX_MAXCALLS; i++) {
4209             struct rx_call *call = conn->call[i];
4210             if (call) {
4211                 if (call != acall)
4212                     MUTEX_ENTER(&call->lock);
4213                 /* tnop can be null if newcallp is null */
4214                 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1, istack);
4215                 if (call != acall)
4216                     MUTEX_EXIT(&call->lock);
4217             }
4218         }
4219     } else
4220         MUTEX_EXIT(&conn->conn_data_lock);
4221 }
4222
4223 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
4224 static const char *
4225 rx_ack_reason(int reason)
4226 {
4227     switch (reason) {
4228     case RX_ACK_REQUESTED:
4229         return "requested";
4230     case RX_ACK_DUPLICATE:
4231         return "duplicate";
4232     case RX_ACK_OUT_OF_SEQUENCE:
4233         return "sequence";
4234     case RX_ACK_EXCEEDS_WINDOW:
4235         return "window";
4236     case RX_ACK_NOSPACE:
4237         return "nospace";
4238     case RX_ACK_PING:
4239         return "ping";
4240     case RX_ACK_PING_RESPONSE:
4241         return "response";
4242     case RX_ACK_DELAY:
4243         return "delay";
4244     case RX_ACK_IDLE:
4245         return "idle";
4246     default:
4247         return "unknown!!";
4248     }
4249 }
4250 #endif
4251
4252 static_inline int
4253 ack_is_valid(struct rx_call *call, afs_uint32 first, afs_uint32 prev)
4254 {
4255     if (first < call->tfirst) {
4256         /*
4257          * The peer indicated that the window went backwards. That's not
4258          * allowed; the window can only move forwards.
4259          */
4260         return 0;
4261     }
4262
4263     if (first == call->tfirst && prev < call->tprev) {
4264         /*
4265          * The peer said the last DATA packet it received was seq X, but it
4266          * already told us before that it had received data after X. This is
4267          * probably just an out-of-order ACK, and so we can ignore it.
4268          */
4269         if (prev >= call->tfirst + call->twind) {
4270             /*
4271              * Some peers (OpenAFS libafs before 1.6.23) mistakenly set the
4272              * previousPacket field to a serial number, not a sequence number.
4273              * The sequence number the peer told us about is further than our
4274              * transmit window, so it cannot possibly be correct; it's probably
4275              * actually a serial number. Don't ignore packets based on this;
4276              * the previousPacket information is not accurate.
4277              */
4278             return 1;
4279         }
4280
4281         return 0;
4282     }
4283
4284     /* Otherwise, the ack looks valid. */
4285     return 1;
4286 }
4287
4288 /* The real smarts of the whole thing.  */
4289 static struct rx_packet *
4290 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
4291                      int istack)
4292 {
4293     struct rx_ackPacket *ap;
4294     int nAcks;
4295     struct rx_packet *tp;
4296     struct rx_connection *conn = call->conn;
4297     struct rx_peer *peer = conn->peer;
4298     struct opr_queue *cursor;
4299     struct clock now;           /* Current time, for RTT calculations */
4300     afs_uint32 first;
4301     afs_uint32 prev;
4302     afs_uint32 serial;
4303     int nbytes;
4304     int missing;
4305     int acked;
4306     int nNacked = 0;
4307     int newAckCount = 0;
4308     int maxDgramPackets = 0;    /* Set if peer supports AFS 3.5 jumbo datagrams */
4309     int pktsize = 0;            /* Set if we need to update the peer mtu */
4310     int conn_data_locked = 0;
4311
4312     if (rx_stats_active)
4313         rx_atomic_inc(&rx_stats.ackPacketsRead);
4314     ap = (struct rx_ackPacket *)rx_DataOf(np);
4315     nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
4316     if (nbytes < 0)
4317         return np;              /* truncated ack packet */
4318
4319     /* depends on ack packet struct */
4320     nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
4321     first = ntohl(ap->firstPacket);
4322     prev = ntohl(ap->previousPacket);
4323     serial = ntohl(ap->serial);
4324
4325     if (!ack_is_valid(call, first, prev)) {
4326         return np;
4327     }
4328
4329     call->tprev = prev;
4330
4331     if (np->header.flags & RX_SLOW_START_OK) {
4332         call->flags |= RX_CALL_SLOW_START_OK;
4333     }
4334
4335     if (ap->reason == RX_ACK_PING_RESPONSE)
4336         rxi_UpdatePeerReach(conn, call, istack);
4337
4338     if (conn->lastPacketSizeSeq) {
4339         MUTEX_ENTER(&conn->conn_data_lock);
4340         conn_data_locked = 1;
4341         if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
4342             pktsize = conn->lastPacketSize;
4343             conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
4344         }
4345     }
4346     if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
4347         if (!conn_data_locked) {
4348             MUTEX_ENTER(&conn->conn_data_lock);
4349             conn_data_locked = 1;
4350         }
4351         if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
4352             /* process mtu ping ack */
4353             pktsize = conn->lastPingSize;
4354             conn->lastPingSizeSer = conn->lastPingSize = 0;
4355         }
4356     }
4357
4358     if (conn_data_locked) {
4359         MUTEX_EXIT(&conn->conn_data_lock);
4360         conn_data_locked = 0;
4361     }
4362 #ifdef RXDEBUG
4363 #ifdef AFS_NT40_ENV
4364     if (rxdebug_active) {
4365         char msg[512];
4366         size_t len;
4367
4368         len = _snprintf(msg, sizeof(msg),
4369                         "tid[%d] RACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
4370                          GetCurrentThreadId(), rx_ack_reason(ap->reason),
4371                          ntohl(ap->serial), ntohl(ap->previousPacket),
4372                          (unsigned int)np->header.seq, ntohl(ap->firstPacket),
4373                          ap->nAcks, ntohs(ap->bufferSpace) );
4374         if (nAcks) {
4375             int offset;
4376
4377             for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
4378                 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4379         }
4380         msg[len++]='\n';
4381         msg[len] = '\0';
4382         OutputDebugString(msg);
4383     }
4384 #else /* AFS_NT40_ENV */
4385     if (rx_Log) {
4386         fprintf(rx_Log,
4387                 "RACK: reason %x previous %u seq %u serial %u first %u",
4388                 ap->reason, ntohl(ap->previousPacket),
4389                 (unsigned int)np->header.seq, (unsigned int)serial,
4390                 ntohl(ap->firstPacket));
4391         if (nAcks) {
4392             int offset;
4393             for (offset = 0; offset < nAcks; offset++)
4394                 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4395                      rx_Log);
4396         }
4397         putc('\n', rx_Log);
4398     }
4399 #endif /* AFS_NT40_ENV */
4400 #endif
4401
4402     MUTEX_ENTER(&peer->peer_lock);
4403     if (pktsize) {
4404         /*
4405          * Start somewhere. Can't assume we can send what we can receive,
4406          * but we are clearly receiving.
4407          */
4408         if (!peer->maxPacketSize)
4409             peer->maxPacketSize = RX_MIN_PACKET_SIZE - RX_HEADER_SIZE;
4410
4411         if (pktsize > peer->maxPacketSize) {
4412             peer->maxPacketSize = pktsize;
4413             if ((pktsize + RX_HEADER_SIZE > peer->ifMTU)) {
4414                 peer->ifMTU = pktsize + RX_HEADER_SIZE;
4415                 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4416                 rxi_ScheduleGrowMTUEvent(call, 1);
4417             }
4418         }
4419     }
4420
4421     clock_GetTime(&now);
4422
4423     /* The transmit queue splits into 4 sections.
4424      *
4425      * The first section is packets which have now been acknowledged
4426      * by a window size change in the ack. These have reached the
4427      * application layer, and may be discarded. These are packets
4428      * with sequence numbers < ap->firstPacket.
4429      *
4430      * The second section is packets which have sequence numbers in
4431      * the range ap->firstPacket to ap->firstPacket + ap->nAcks. The
4432      * contents of the packet's ack array determines whether these
4433      * packets are acknowledged or not.
4434      *
4435      * The third section is packets which fall above the range
4436      * addressed in the ack packet. These have not yet been received
4437      * by the peer.
4438      *
4439      * The four section is packets which have not yet been transmitted.
4440      * These packets will have a header.serial of 0.
4441      */
4442
4443     /* First section - implicitly acknowledged packets that can be
4444      * disposed of
4445      */
4446
4447     tp = opr_queue_First(&call->tq, struct rx_packet, entry);
4448     while(!opr_queue_IsEnd(&call->tq, &tp->entry) && tp->header.seq < first) {
4449         struct rx_packet *next;
4450
4451         next = opr_queue_Next(&tp->entry, struct rx_packet, entry);
4452         call->tfirst = tp->header.seq + 1;
4453
4454         if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4455             newAckCount++;
4456             rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4457         }
4458
4459 #ifdef RX_ENABLE_LOCKS
4460         /* XXX Hack. Because we have to release the global call lock when sending
4461          * packets (rxi_NetSend) we drop all acks while we're traversing the tq
4462          * in rxi_Start sending packets out because packets may move to the
4463          * freePacketQueue as result of being here! So we drop these packets until
4464          * we're safely out of the traversing. Really ugly!
4465          * To make it even uglier, if we're using fine grain locking, we can
4466          * set the ack bits in the packets and have rxi_Start remove the packets
4467          * when it's done transmitting.
4468          */
4469         if (call->flags & RX_CALL_TQ_BUSY) {
4470             tp->flags |= RX_PKTFLAG_ACKED;
4471             call->flags |= RX_CALL_TQ_SOME_ACKED;
4472         } else
4473 #endif /* RX_ENABLE_LOCKS */
4474         {
4475             opr_queue_Remove(&tp->entry);
4476 #ifdef RX_TRACK_PACKETS
4477             tp->flags &= ~RX_PKTFLAG_TQ;
4478 #endif
4479 #ifdef RXDEBUG_PACKET
4480             call->tqc--;
4481 #endif /* RXDEBUG_PACKET */
4482             rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4483         }
4484         tp = next;
4485     }
4486
4487     /* N.B. we don't turn off any timers here.  They'll go away by themselves, anyway */
4488
4489     /* Second section of the queue - packets for which we are receiving
4490      * soft ACKs
4491      *
4492      * Go through the explicit acks/nacks and record the results in
4493      * the waiting packets.  These are packets that can't be released
4494      * yet, even with a positive acknowledge.  This positive
4495      * acknowledge only means the packet has been received by the
4496      * peer, not that it will be retained long enough to be sent to
4497      * the peer's upper level.  In addition, reset the transmit timers
4498      * of any missing packets (those packets that must be missing
4499      * because this packet was out of sequence) */
4500
4501     call->nSoftAcked = 0;
4502     missing = 0;
4503     while (!opr_queue_IsEnd(&call->tq, &tp->entry) 
4504            && tp->header.seq < first + nAcks) {
4505         /* Set the acknowledge flag per packet based on the
4506          * information in the ack packet. An acknowlegded packet can
4507          * be downgraded when the server has discarded a packet it
4508          * soacked previously, or when an ack packet is received
4509          * out of sequence. */
4510         if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4511             if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4512                 newAckCount++;
4513                 tp->flags |= RX_PKTFLAG_ACKED;
4514                 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4515             }
4516             if (missing) {
4517                 nNacked++;
4518             } else {
4519                 call->nSoftAcked++;
4520             }
4521         } else /* RX_ACK_TYPE_NACK */ {
4522             tp->flags &= ~RX_PKTFLAG_ACKED;
4523             missing = 1;
4524         }
4525
4526         tp = opr_queue_Next(&tp->entry, struct rx_packet, entry);
4527     }
4528
4529     /* We don't need to take any action with the 3rd or 4th section in the
4530      * queue - they're not addressed by the contents of this ACK packet.
4531      */
4532
4533     /* if the ack packet has a receivelen field hanging off it,
4534      * update our state */
4535     if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4536         afs_uint32 tSize;
4537
4538         /* If the ack packet has a "recommended" size that is less than
4539          * what I am using now, reduce my size to match */
4540         rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4541                       (int)sizeof(afs_int32), &tSize);
4542         tSize = (afs_uint32) ntohl(tSize);
4543         if (tSize > RX_MAX_PACKET_SIZE)
4544             tSize = RX_MAX_PACKET_SIZE;
4545         if (tSize < RX_MIN_PACKET_SIZE)
4546             tSize = RX_MIN_PACKET_SIZE;
4547         peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4548
4549         /* Get the maximum packet size to send to this peer */
4550         rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4551                       &tSize);
4552         tSize = (afs_uint32) ntohl(tSize);
4553         if (tSize > RX_MAX_PACKET_SIZE)
4554             tSize = RX_MAX_PACKET_SIZE;
4555         if (tSize < RX_MIN_PACKET_SIZE)
4556             tSize = RX_MIN_PACKET_SIZE;
4557         tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4558         tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4559
4560         /* sanity check - peer might have restarted with different params.
4561          * If peer says "send less", dammit, send less...  Peer should never
4562          * be unable to accept packets of the size that prior AFS versions would
4563          * send without asking.  */
4564         if (peer->maxMTU != tSize) {
4565             if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4566                 peer->congestSeq++;
4567             peer->maxMTU = tSize;
4568             peer->MTU = MIN(tSize, peer->MTU);
4569             call->MTU = MIN(call->MTU, tSize);
4570         }
4571
4572         if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4573             /* AFS 3.4a */
4574             rx_packetread(np,
4575                           rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4576                           (int)sizeof(afs_int32), &tSize);
4577             tSize = (afs_uint32) ntohl(tSize);  /* peer's receive window, if it's */
4578             if (tSize == 0)
4579                 tSize = 1;
4580             if (tSize >= rx_maxSendWindow)
4581                 tSize = rx_maxSendWindow;
4582             if (tSize < call->twind) {  /* smaller than our send */
4583                 call->twind = tSize;    /* window, we must send less... */
4584                 call->ssthresh = MIN(call->twind, call->ssthresh);
4585                 call->conn->twind[call->channel] = call->twind;
4586             }
4587
4588             /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4589              * network MTU confused with the loopback MTU. Calculate the
4590              * maximum MTU here for use in the slow start code below.
4591              */
4592             /* Did peer restart with older RX version? */
4593             if (peer->maxDgramPackets > 1) {
4594                 peer->maxDgramPackets = 1;
4595             }
4596         } else if (np->length >=
4597                    rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4598             /* AFS 3.5 */
4599             rx_packetread(np,
4600                           rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4601                           sizeof(afs_int32), &tSize);
4602             tSize = (afs_uint32) ntohl(tSize);
4603             if (tSize == 0)
4604                 tSize = 1;
4605             if (tSize >= rx_maxSendWindow)
4606                 tSize = rx_maxSendWindow;
4607             /*
4608              * As of AFS 3.5 we set the send window to match the receive window.
4609              */
4610             if (tSize < call->twind) {
4611                 call->twind = tSize;
4612                 call->conn->twind[call->channel] = call->twind;
4613                 call->ssthresh = MIN(call->twind, call->ssthresh);
4614             } else if (tSize > call->twind) {
4615                 call->twind = tSize;
4616                 call->conn->twind[call->channel] = call->twind;
4617             }
4618
4619             /*
4620              * As of AFS 3.5, a jumbogram is more than one fixed size
4621              * packet transmitted in a single UDP datagram. If the remote
4622              * MTU is smaller than our local MTU then never send a datagram
4623              * larger than the natural MTU.
4624              */
4625             rx_packetread(np,
4626                           rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4627                           (int)sizeof(afs_int32), &tSize);
4628             maxDgramPackets = (afs_uint32) ntohl(tSize);
4629             maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4630             maxDgramPackets =
4631                 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4632             if (maxDgramPackets > 1) {
4633                 peer->maxDgramPackets = maxDgramPackets;
4634                 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4635             } else {
4636                 peer->maxDgramPackets = 1;
4637                 call->MTU = peer->natMTU;
4638             }
4639         } else if (peer->maxDgramPackets > 1) {
4640             /* Restarted with lower version of RX */
4641             peer->maxDgramPackets = 1;
4642         }
4643     } else if (peer->maxDgramPackets > 1
4644                || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4645         /* Restarted with lower version of RX */
4646         peer->maxMTU = OLD_MAX_PACKET_SIZE;
4647         peer->natMTU = OLD_MAX_PACKET_SIZE;
4648         peer->MTU = OLD_MAX_PACKET_SIZE;
4649         peer->maxDgramPackets = 1;
4650         peer->nDgramPackets = 1;
4651         peer->congestSeq++;
4652         call->MTU = OLD_MAX_PACKET_SIZE;
4653     }
4654
4655     /* If the window has been extended by this acknowledge packet,
4656      * then wakeup a sender waiting in alloc for window space, or try
4657      * sending packets now, if he's been sitting on packets due to
4658      * lack of window space */
4659     if (call->tnext < (call->tfirst + call->twind)) {
4660 #ifdef  RX_ENABLE_LOCKS
4661         CV_SIGNAL(&call->cv_twind);
4662 #else
4663         if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4664             call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4665             osi_rxWakeup(&call->twind);
4666         }
4667 #endif
4668         if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4669             call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4670         }
4671     }
4672
4673     if (nNacked) {
4674         /*
4675          * Calculate how many datagrams were successfully received after
4676          * the first missing packet and adjust the negative ack counter
4677          * accordingly.
4678          */
4679         call->nAcks = 0;
4680         call->nNacks++;
4681         nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4682         if (call->nNacks < nNacked) {
4683             call->nNacks = nNacked;
4684         }
4685     } else {
4686         call->nAcks += newAckCount;
4687         call->nNacks = 0;
4688     }
4689
4690     /* If the packet contained new acknowledgements, rather than just
4691      * being a duplicate of one we have previously seen, then we can restart
4692      * the RTT timer
4693      */
4694     if (newAckCount > 0)
4695         rxi_rto_packet_acked(call, istack);
4696
4697     if (call->flags & RX_CALL_FAST_RECOVER) {
4698         if (newAckCount == 0) {
4699             call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4700         } else {
4701             call->flags &= ~RX_CALL_FAST_RECOVER;
4702             call->cwind = call->nextCwind;
4703             call->nextCwind = 0;
4704             call->nAcks = 0;
4705         }
4706         call->nCwindAcks = 0;
4707     } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4708         /* Three negative acks in a row trigger congestion recovery */
4709         call->flags |= RX_CALL_FAST_RECOVER;
4710         call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4711         call->cwind =
4712             MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4713         call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4714         call->nextCwind = call->ssthresh;
4715         call->nAcks = 0;
4716         call->nNacks = 0;
4717         peer->MTU = call->MTU;
4718         peer->cwind = call->nextCwind;
4719         peer->nDgramPackets = call->nDgramPackets;
4720         peer->congestSeq++;
4721         call->congestSeq = peer->congestSeq;
4722
4723         /* Reset the resend times on the packets that were nacked
4724          * so we will retransmit as soon as the window permits
4725          */
4726
4727         acked = 0;
4728         for (opr_queue_ScanBackwards(&call->tq, cursor)) {
4729             struct rx_packet *tp =
4730                 opr_queue_Entry(cursor, struct rx_packet, entry);
4731             if (acked) {
4732                 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4733                     tp->flags &= ~RX_PKTFLAG_SENT;
4734                 }
4735             } else if (tp->flags & RX_PKTFLAG_ACKED) {
4736                 acked = 1;
4737             }
4738         }
4739     } else {
4740         /* If cwind is smaller than ssthresh, then increase
4741          * the window one packet for each ack we receive (exponential
4742          * growth).
4743          * If cwind is greater than or equal to ssthresh then increase
4744          * the congestion window by one packet for each cwind acks we
4745          * receive (linear growth).  */
4746         if (call->cwind < call->ssthresh) {
4747             call->cwind =
4748                 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4749             call->nCwindAcks = 0;
4750         } else {
4751             call->nCwindAcks += newAckCount;
4752             if (call->nCwindAcks >= call->cwind) {
4753                 call->nCwindAcks = 0;
4754                 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4755             }
4756         }
4757         /*
4758          * If we have received several acknowledgements in a row then
4759          * it is time to increase the size of our datagrams
4760          */
4761         if ((int)call->nAcks > rx_nDgramThreshold) {
4762             if (peer->maxDgramPackets > 1) {
4763                 if (call->nDgramPackets < peer->maxDgramPackets) {
4764                     call->nDgramPackets++;
4765                 }
4766                 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4767             } else if (call->MTU < peer->maxMTU) {
4768                 /* don't upgrade if we can't handle it */
4769                 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4770                     call->MTU = peer->ifMTU;
4771                 else {
4772                     call->MTU += peer->natMTU;
4773                     call->MTU = MIN(call->MTU, peer->maxMTU);
4774                 }
4775             }
4776             call->nAcks = 0;
4777         }
4778     }
4779
4780     MUTEX_EXIT(&peer->peer_lock);       /* rxi_Start will lock peer. */
4781
4782     /* Servers need to hold the call until all response packets have
4783      * been acknowledged. Soft acks are good enough since clients
4784      * are not allowed to clear their receive queues. */
4785     if (call->state == RX_STATE_HOLD
4786         && call->tfirst + call->nSoftAcked >= call->tnext) {
4787         call->state = RX_STATE_DALLY;
4788         rxi_ClearTransmitQueue(call, 0);
4789         rxi_CancelKeepAliveEvent(call);
4790     } else if (!opr_queue_IsEmpty(&call->tq)) {
4791         rxi_Start(call, istack);
4792     }
4793     return np;
4794 }
4795
4796 /**
4797  * Schedule a connection abort to be sent after some delay.
4798  *
4799  * @param[in] conn The connection to send the abort on.
4800  * @param[in] msec The number of milliseconds to wait before sending.
4801  *
4802  * @pre conn_data_lock must be held
4803  */
4804 static void
4805 rxi_SendConnectionAbortLater(struct rx_connection *conn, int msec)
4806 {
4807     struct clock when, now;
4808
4809     MUTEX_ASSERT(&conn->conn_data_lock);
4810     if (!conn->error) {
4811         return;
4812     }
4813     if (!conn->delayedAbortEvent) {
4814         clock_GetTime(&now);
4815         when = now;
4816         clock_Addmsec(&when, msec);
4817         rx_GetConnection(conn);
4818         conn->delayedAbortEvent =
4819             rxevent_Post(&when, &now, rxi_SendDelayedConnAbort, conn, NULL, 0);
4820     }
4821 }
4822
4823 /* Received a response to a challenge packet */
4824 static struct rx_packet *
4825 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4826                           struct rx_packet *np, int istack)
4827 {
4828     int error;
4829
4830     /* Ignore the packet if we're the client */
4831     if (conn->type == RX_CLIENT_CONNECTION)
4832         return np;
4833
4834     /* If already authenticated, ignore the packet (it's probably a retry) */
4835     if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4836         return np;
4837
4838     if (!conn->securityChallengeSent) {
4839         /* We've never sent out a challenge for this connection, so this
4840          * response cannot possibly be correct; ignore it. This can happen
4841          * if we sent a challenge to the client, then we were restarted, and
4842          * then the client sent us a response. If we ignore the response, the
4843          * client will eventually resend a data packet, causing us to send a
4844          * new challenge and the client to send a new response. */
4845         return np;
4846     }
4847
4848     /* Otherwise, have the security object evaluate the response packet */
4849     error = RXS_CheckResponse(conn->securityObject, conn, np);
4850     if (error) {
4851         /* If the response is invalid, reset the connection, sending
4852          * an abort to the peer. Send the abort with a 1 second delay,
4853          * to avoid a peer hammering us by constantly recreating a
4854          * connection with bad credentials. */
4855         rxi_ConnectionError(conn, error);
4856         MUTEX_ENTER(&conn->conn_data_lock);
4857         rxi_SendConnectionAbortLater(conn, 1000);
4858         MUTEX_EXIT(&conn->conn_data_lock);
4859         return np;
4860     } else {
4861         /* If the response is valid, any calls waiting to attach
4862          * servers can now do so */
4863         int i;
4864
4865         for (i = 0; i < RX_MAXCALLS; i++) {
4866             struct rx_call *call = conn->call[i];
4867             if (call) {
4868                 MUTEX_ENTER(&call->lock);
4869                 if (call->state == RX_STATE_PRECALL)
4870                     rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4871                 /* tnop can be null if newcallp is null */
4872                 MUTEX_EXIT(&call->lock);
4873             }
4874         }
4875
4876         /* Update the peer reachability information, just in case
4877          * some calls went into attach-wait while we were waiting
4878          * for authentication..
4879          */
4880         rxi_UpdatePeerReach(conn, NULL, istack);
4881     }
4882     return np;
4883 }
4884
4885 /* A client has received an authentication challenge: the security
4886  * object is asked to cough up a respectable response packet to send
4887  * back to the server.  The server is responsible for retrying the
4888  * challenge if it fails to get a response. */
4889
4890 static struct rx_packet *
4891 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4892                            struct rx_packet *np, int istack)
4893 {
4894     int error;
4895
4896     /* Ignore the challenge if we're the server */
4897     if (conn->type == RX_SERVER_CONNECTION)
4898         return np;
4899
4900     /* Ignore the challenge if the connection is otherwise idle; someone's
4901      * trying to use us as an oracle. */
4902     if (!rxi_HasActiveCalls(conn))
4903         return np;
4904
4905     /* Send the security object the challenge packet.  It is expected to fill
4906      * in the response. */
4907     error = RXS_GetResponse(conn->securityObject, conn, np);
4908
4909     /* If the security object is unable to return a valid response, reset the
4910      * connection and send an abort to the peer.  Otherwise send the response
4911      * packet to the peer connection. */
4912     if (error) {
4913         rxi_ConnectionError(conn, error);
4914         MUTEX_ENTER(&conn->conn_data_lock);
4915         np = rxi_SendConnectionAbort(conn, np, istack, 0);
4916         MUTEX_EXIT(&conn->conn_data_lock);
4917     } else {
4918         np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4919                              RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4920     }
4921     return np;
4922 }
4923
4924
4925 /* Find an available server process to service the current request in
4926  * the given call structure.  If one isn't available, queue up this
4927  * call so it eventually gets one */
4928 static void
4929 rxi_AttachServerProc(struct rx_call *call,
4930                      osi_socket socket, int *tnop,
4931                      struct rx_call **newcallp)
4932 {
4933     struct rx_serverQueueEntry *sq;
4934     struct rx_service *service = call->conn->service;
4935     int haveQuota = 0;
4936
4937     /* May already be attached */
4938     if (call->state == RX_STATE_ACTIVE)
4939         return;
4940
4941     MUTEX_ENTER(&rx_serverPool_lock);
4942
4943     haveQuota = QuotaOK(service);
4944     if ((!haveQuota) || opr_queue_IsEmpty(&rx_idleServerQueue)) {
4945         /* If there are no processes available to service this call,
4946          * put the call on the incoming call queue (unless it's
4947          * already on the queue).
4948          */
4949 #ifdef RX_ENABLE_LOCKS
4950         if (haveQuota)
4951             ReturnToServerPool(service);
4952 #endif /* RX_ENABLE_LOCKS */
4953
4954         if (!(call->flags & RX_CALL_WAIT_PROC)) {
4955             call->flags |= RX_CALL_WAIT_PROC;
4956             rx_atomic_inc(&rx_nWaiting);
4957             rx_atomic_inc(&rx_nWaited);
4958             rxi_calltrace(RX_CALL_ARRIVAL, call);
4959             SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4960             opr_queue_Append(&rx_incomingCallQueue, &call->entry);
4961         }
4962     } else {
4963         sq = opr_queue_Last(&rx_idleServerQueue,
4964                             struct rx_serverQueueEntry, entry);
4965
4966         /* If hot threads are enabled, and both newcallp and sq->socketp
4967          * are non-null, then this thread will process the call, and the
4968          * idle server thread will start listening on this threads socket.
4969          */
4970         opr_queue_Remove(&sq->entry);
4971
4972         if (rx_enable_hot_thread && newcallp && sq->socketp) {
4973             *newcallp = call;
4974             *tnop = sq->tno;
4975             *sq->socketp = socket;
4976             clock_GetTime(&call->startTime);
4977             CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4978         } else {
4979             sq->newcall = call;
4980         }
4981         if (call->flags & RX_CALL_WAIT_PROC) {
4982             /* Conservative:  I don't think this should happen */
4983             call->flags &= ~RX_CALL_WAIT_PROC;
4984             rx_atomic_dec(&rx_nWaiting);
4985             if (opr_queue_IsOnQueue(&call->entry)) {
4986                 opr_queue_Remove(&call->entry);
4987             }
4988             CLEAR_CALL_QUEUE_LOCK(call);
4989         }
4990         call->state = RX_STATE_ACTIVE;
4991         call->app.mode = RX_MODE_RECEIVING;
4992 #ifdef RX_KERNEL_TRACE
4993         {
4994             int glockOwner = ISAFS_GLOCK();
4995             if (!glockOwner)
4996                 AFS_GLOCK();
4997             afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4998                        __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4999                        call);
5000             if (!glockOwner)
5001                 AFS_GUNLOCK();
5002         }
5003 #endif
5004         if (call->flags & RX_CALL_CLEARED) {
5005             /* send an ack now to start the packet flow up again */
5006             call->flags &= ~RX_CALL_CLEARED;
5007             rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
5008         }
5009 #ifdef  RX_ENABLE_LOCKS
5010         CV_SIGNAL(&sq->cv);
5011 #else
5012         service->nRequestsRunning++;
5013         MUTEX_ENTER(&rx_quota_mutex);
5014         if (service->nRequestsRunning <= service->minProcs)
5015             rxi_minDeficit--;
5016         rxi_availProcs--;
5017         MUTEX_EXIT(&rx_quota_mutex);
5018         osi_rxWakeup(sq);
5019 #endif
5020     }
5021     MUTEX_EXIT(&rx_serverPool_lock);
5022 }
5023
5024 /* Delay the sending of an acknowledge event for a short while, while
5025  * a new call is being prepared (in the case of a client) or a reply
5026  * is being prepared (in the case of a server).  Rather than sending
5027  * an ack packet, an ACKALL packet is sent. */
5028 static void
5029 rxi_AckAll(struct rx_call *call)
5030 {
5031     rxi_SendSpecial(call, call->conn, NULL, RX_PACKET_TYPE_ACKALL, 
5032                     NULL, 0, 0);
5033     call->flags |= RX_CALL_ACKALL_SENT;
5034 }
5035
5036 /*
5037  * Event handler for per-call delayed acks.
5038  * Also called synchronously, with |event| == NULL, to send a "delayed" ack
5039  * immediately.
5040  */
5041 static void
5042 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused1,
5043                    int unused2)
5044 {
5045     struct rx_call *call = arg1;
5046 #ifdef RX_ENABLE_LOCKS
5047     if (event) {
5048         MUTEX_ENTER(&call->lock);
5049         if (event == call->delayedAckEvent)
5050             rxevent_Put(&call->delayedAckEvent);
5051     }
5052     (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
5053     if (event)
5054         MUTEX_EXIT(&call->lock);
5055 #else /* RX_ENABLE_LOCKS */
5056     if (event)
5057         rxevent_Put(&call->delayedAckEvent);
5058     (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
5059 #endif /* RX_ENABLE_LOCKS */
5060     /* Release the call reference for the event that fired. */
5061     if (event)
5062         CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
5063 }
5064
5065 #ifdef RX_ENABLE_LOCKS
5066 /* Set ack in all packets in transmit queue. rxi_Start will deal with
5067  * clearing them out.
5068  */
5069 static void
5070 rxi_SetAcksInTransmitQueue(struct rx_call *call)
5071 {
5072     struct opr_queue *cursor;
5073     int someAcked = 0;
5074
5075     for (opr_queue_Scan(&call->tq, cursor)) {
5076         struct rx_packet *p 
5077                 = opr_queue_Entry(cursor, struct rx_packet, entry);
5078
5079         p->flags |= RX_PKTFLAG_ACKED;
5080         someAcked = 1;
5081     }
5082
5083     if (someAcked) {
5084         call->flags |= RX_CALL_TQ_CLEARME;
5085         call->flags |= RX_CALL_TQ_SOME_ACKED;
5086     }
5087
5088     rxi_rto_cancel(call);
5089
5090     call->tfirst = call->tnext;
5091     call->nSoftAcked = 0;
5092
5093     if (call->flags & RX_CALL_FAST_RECOVER) {
5094         call->flags &= ~RX_CALL_FAST_RECOVER;
5095         call->cwind = call->nextCwind;
5096         call->nextCwind = 0;
5097     }
5098
5099     CV_SIGNAL(&call->cv_twind);
5100 }
5101 #endif /* RX_ENABLE_LOCKS */
5102
5103 /*!
5104  * Acknowledge the whole transmit queue.
5105  *
5106  * If we're running without locks, or the transmit queue isn't busy, then
5107  * we can just clear the queue now. Otherwise, we have to mark all of the
5108  * packets as acknowledged, and let rxi_Start clear it later on
5109  */
5110 static void
5111 rxi_AckAllInTransmitQueue(struct rx_call *call)
5112 {
5113 #ifdef RX_ENABLE_LOCKS
5114     if (call->flags & RX_CALL_TQ_BUSY) {
5115         rxi_SetAcksInTransmitQueue(call);
5116         return;
5117     }
5118 #endif
5119     rxi_ClearTransmitQueue(call, 0);
5120 }
5121 /* Clear out the transmit queue for the current call (all packets have
5122  * been received by peer) */
5123 static void
5124 rxi_ClearTransmitQueue(struct rx_call *call, int force)
5125 {
5126 #ifdef  RX_ENABLE_LOCKS
5127     struct opr_queue *cursor;
5128     if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
5129         int someAcked = 0;
5130         for (opr_queue_Scan(&call->tq, cursor)) {
5131             struct rx_packet *p 
5132                 = opr_queue_Entry(cursor, struct rx_packet, entry);
5133
5134             p->flags |= RX_PKTFLAG_ACKED;
5135             someAcked = 1;
5136         }
5137         if (someAcked) {
5138             call->flags |= RX_CALL_TQ_CLEARME;
5139             call->flags |= RX_CALL_TQ_SOME_ACKED;
5140         }
5141     } else {
5142 #endif /* RX_ENABLE_LOCKS */
5143 #ifdef RXDEBUG_PACKET
5144         call->tqc -=
5145 #endif /* RXDEBUG_PACKET */
5146             rxi_FreePackets(0, &call->tq);
5147         rxi_WakeUpTransmitQueue(call);
5148 #ifdef RX_ENABLE_LOCKS
5149         call->flags &= ~RX_CALL_TQ_CLEARME;
5150     }
5151 #endif
5152
5153     rxi_rto_cancel(call);
5154     call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
5155     call->nSoftAcked = 0;
5156
5157     if (call->flags & RX_CALL_FAST_RECOVER) {
5158         call->flags &= ~RX_CALL_FAST_RECOVER;
5159         call->cwind = call->nextCwind;
5160     }
5161 #ifdef  RX_ENABLE_LOCKS
5162     CV_SIGNAL(&call->cv_twind);
5163 #else
5164     osi_rxWakeup(&call->twind);
5165 #endif
5166 }
5167
5168 static void
5169 rxi_ClearReceiveQueue(struct rx_call *call)
5170 {
5171     if (!opr_queue_IsEmpty(&call->rq)) {
5172         u_short count;
5173
5174         count = rxi_FreePackets(0, &call->rq);
5175         rx_packetReclaims += count;
5176 #ifdef RXDEBUG_PACKET
5177         call->rqc -= count;
5178         if ( call->rqc != 0 )
5179           dpf(("rxi_ClearReceiveQueue call %p rqc %u != 0\n", call, call->rqc));
5180 #endif
5181         call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
5182     }
5183     if (call->state == RX_STATE_PRECALL) {
5184         call->flags |= RX_CALL_CLEARED;
5185     }
5186 }
5187
5188 /* Send an abort packet for the specified call */
5189 static struct rx_packet *
5190 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
5191                   int istack, int force)
5192 {
5193     afs_int32 error;
5194     struct clock when, now;
5195
5196     if (!call->error)
5197         return packet;
5198
5199     /* Clients should never delay abort messages */
5200     if (rx_IsClientConn(call->conn))
5201         force = 1;
5202
5203     /*
5204      * An opcode that has been deprecated or has yet to be implemented is not
5205      * a misbehavior of the client.  Do not punish the client by introducing
5206      * delays.
5207      */
5208     if (call->error == RXGEN_OPCODE) {
5209         force = 1;
5210     } else if (call->abortCode != call->error) {
5211         call->abortCode = call->error;
5212         call->abortCount = 0;
5213     }
5214
5215     if (force || rxi_callAbortThreshhold == 0
5216         || call->abortCount < rxi_callAbortThreshhold) {
5217         rxi_CancelDelayedAbortEvent(call);
5218         error = htonl(call->error);
5219         if (!force)
5220             call->abortCount++;
5221         packet =
5222             rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5223                             (char *)&error, sizeof(error), istack);
5224     } else if (!call->delayedAbortEvent) {
5225         clock_GetTime(&now);
5226         when = now;
5227         clock_Addmsec(&when, rxi_callAbortDelay);
5228         CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
5229         call->delayedAbortEvent =
5230             rxevent_Post(&when, &now, rxi_SendDelayedCallAbort, call, 0, 0);
5231     }
5232     return packet;
5233 }
5234
5235 static void
5236 rxi_CancelDelayedAbortEvent(struct rx_call *call)
5237 {
5238     MUTEX_ASSERT(&call->lock);
5239     if (rxevent_Cancel(&call->delayedAbortEvent))
5240         CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
5241 }
5242
5243 /* Send an abort packet for the specified connection.  Packet is an
5244  * optional pointer to a packet that can be used to send the abort.
5245  * Once the number of abort messages reaches the threshhold, an
5246  * event is scheduled to send the abort. Setting the force flag
5247  * overrides sending delayed abort messages.
5248  *
5249  * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
5250  *       to send the abort packet.
5251  */
5252 struct rx_packet *
5253 rxi_SendConnectionAbort(struct rx_connection *conn,
5254                         struct rx_packet *packet, int istack, int force)
5255 {
5256     afs_int32 error;
5257
5258     if (!conn->error)
5259         return packet;
5260
5261     /* Clients should never delay abort messages */
5262     if (rx_IsClientConn(conn))
5263         force = 1;
5264
5265     if (force || rxi_connAbortThreshhold == 0
5266         || conn->abortCount < rxi_connAbortThreshhold) {
5267
5268         if (rxevent_Cancel(&conn->delayedAbortEvent))
5269             putConnection(conn);
5270         error = htonl(conn->error);
5271         conn->abortCount++;
5272         MUTEX_EXIT(&conn->conn_data_lock);
5273         packet =
5274             rxi_SendSpecial((struct rx_call *)0, conn, packet,
5275                             RX_PACKET_TYPE_ABORT, (char *)&error,
5276                             sizeof(error), istack);
5277         MUTEX_ENTER(&conn->conn_data_lock);
5278     } else {
5279         rxi_SendConnectionAbortLater(conn, rxi_connAbortDelay);
5280     }
5281     return packet;
5282 }
5283
5284 /* Associate an error all of the calls owned by a connection.  Called
5285  * with error non-zero.  This is only for really fatal things, like
5286  * bad authentication responses.  The connection itself is set in
5287  * error at this point, so that future packets received will be
5288  * rejected. */
5289 void
5290 rxi_ConnectionError(struct rx_connection *conn,
5291                     afs_int32 error)
5292 {
5293     if (error) {
5294         int i;
5295
5296         dpf(("rxi_ConnectionError conn %p error %d\n", conn, error));
5297
5298         MUTEX_ENTER(&conn->conn_data_lock);
5299         if (rxevent_Cancel(&conn->challengeEvent))
5300             putConnection(conn);
5301         if (rxevent_Cancel(&conn->natKeepAliveEvent))
5302             putConnection(conn);
5303         if (rxevent_Cancel(&conn->checkReachEvent)) {
5304             conn->flags &= ~(RX_CONN_ATTACHWAIT|RX_CONN_NAT_PING);
5305             putConnection(conn);
5306         }
5307         MUTEX_EXIT(&conn->conn_data_lock);
5308         for (i = 0; i < RX_MAXCALLS; i++) {
5309             struct rx_call *call = conn->call[i];
5310             if (call) {
5311                 MUTEX_ENTER(&call->lock);
5312                 rxi_CallError(call, error);
5313                 MUTEX_EXIT(&call->lock);
5314             }
5315         }
5316         conn->error = error;
5317         if (rx_stats_active)
5318             rx_atomic_inc(&rx_stats.fatalErrors);
5319     }
5320 }
5321
5322 /**
5323  * Interrupt an in-progress call with the specified error and wakeup waiters.
5324  *
5325  * @param[in] call  The call to interrupt
5326  * @param[in] error  The error code to send to the peer
5327  */
5328 void
5329 rx_InterruptCall(struct rx_call *call, afs_int32 error)
5330 {
5331     MUTEX_ENTER(&call->lock);
5332     rxi_CallError(call, error);
5333     rxi_SendCallAbort(call, NULL, 0, 1);
5334     MUTEX_EXIT(&call->lock);
5335 }
5336
5337 void
5338 rxi_CallError(struct rx_call *call, afs_int32 error)
5339 {
5340     MUTEX_ASSERT(&call->lock);
5341     dpf(("rxi_CallError call %p error %d call->error %d\n", call, error, call->error));
5342     if (call->error)
5343         error = call->error;
5344
5345 #ifdef RX_ENABLE_LOCKS
5346     if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
5347         rxi_ResetCall(call, 0);
5348     }
5349 #else
5350     rxi_ResetCall(call, 0);
5351 #endif
5352     call->error = error;
5353 }
5354
5355 /* Reset various fields in a call structure, and wakeup waiting
5356  * processes.  Some fields aren't changed: state & mode are not
5357  * touched (these must be set by the caller), and bufptr, nLeft, and
5358  * nFree are not reset, since these fields are manipulated by
5359  * unprotected macros, and may only be reset by non-interrupting code.
5360  */
5361
5362 static void
5363 rxi_ResetCall(struct rx_call *call, int newcall)
5364 {
5365     int flags;
5366     struct rx_peer *peer;
5367     struct rx_packet *packet;
5368
5369     MUTEX_ASSERT(&call->lock);
5370     dpf(("rxi_ResetCall(call %p, newcall %d)\n", call, newcall));
5371
5372     /* Notify anyone who is waiting for asynchronous packet arrival */
5373     if (call->arrivalProc) {
5374         (*call->arrivalProc) (call, call->arrivalProcHandle,
5375                               call->arrivalProcArg);
5376         call->arrivalProc = NULL;
5377     }
5378
5379
5380     rxi_CancelGrowMTUEvent(call);
5381
5382     if (call->delayedAbortEvent) {
5383         rxi_CancelDelayedAbortEvent(call);
5384         packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5385         if (packet) {
5386             rxi_SendCallAbort(call, packet, 0, 1);
5387             rxi_FreePacket(packet);
5388         }
5389     }
5390
5391     /*
5392      * Update the peer with the congestion information in this call
5393      * so other calls on this connection can pick up where this call
5394      * left off. If the congestion sequence numbers don't match then
5395      * another call experienced a retransmission.
5396      */
5397     peer = call->conn->peer;
5398     MUTEX_ENTER(&peer->peer_lock);
5399     if (!newcall) {
5400         if (call->congestSeq == peer->congestSeq) {
5401             peer->cwind = MAX(peer->cwind, call->cwind);
5402             peer->MTU = MAX(peer->MTU, call->MTU);
5403             peer->nDgramPackets =
5404                 MAX(peer->nDgramPackets, call->nDgramPackets);
5405         }
5406     } else {
5407         call->abortCode = 0;
5408         call->abortCount = 0;
5409     }
5410     if (peer->maxDgramPackets > 1) {
5411         call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
5412     } else {
5413         call->MTU = peer->MTU;
5414     }
5415     call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
5416     call->ssthresh = rx_maxSendWindow;
5417     call->nDgramPackets = peer->nDgramPackets;
5418     call->congestSeq = peer->congestSeq;
5419     call->rtt = peer->rtt;
5420     call->rtt_dev = peer->rtt_dev;
5421     clock_Zero(&call->rto);
5422     clock_Addmsec(&call->rto,
5423                   MAX(((call->rtt >> 3) + call->rtt_dev), rx_minPeerTimeout) + 200);
5424     MUTEX_EXIT(&peer->peer_lock);
5425
5426     flags = call->flags;
5427     rxi_WaitforTQBusy(call);
5428
5429     rxi_ClearTransmitQueue(call, 1);
5430     if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
5431         dpf(("rcall %p has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5432     }
5433     call->flags = 0;
5434
5435     rxi_ClearReceiveQueue(call);
5436     /* why init the queue if you just emptied it? queue_Init(&call->rq); */
5437
5438
5439     call->error = 0;
5440     call->twind = call->conn->twind[call->channel];
5441     call->rwind = call->conn->rwind[call->channel];
5442     call->nSoftAcked = 0;
5443     call->nextCwind = 0;
5444     call->nAcks = 0;
5445     call->nNacks = 0;
5446     call->nCwindAcks = 0;
5447     call->nSoftAcks = 0;
5448     call->nHardAcks = 0;
5449
5450     call->tfirst = call->rnext = call->tnext = 1;
5451     call->tprev = 0;
5452     call->rprev = 0;
5453     call->lastAcked = 0;
5454     call->localStatus = call->remoteStatus = 0;
5455
5456     if (flags & RX_CALL_READER_WAIT) {
5457 #ifdef  RX_ENABLE_LOCKS
5458         CV_BROADCAST(&call->cv_rq);
5459 #else
5460         osi_rxWakeup(&call->rq);
5461 #endif
5462     }
5463     if (flags & RX_CALL_WAIT_PACKETS) {
5464         MUTEX_ENTER(&rx_freePktQ_lock);
5465         rxi_PacketsUnWait();    /* XXX */
5466         MUTEX_EXIT(&rx_freePktQ_lock);
5467     }
5468 #ifdef  RX_ENABLE_LOCKS
5469     CV_SIGNAL(&call->cv_twind);
5470 #else
5471     if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5472         osi_rxWakeup(&call->twind);
5473 #endif
5474
5475     if (flags & RX_CALL_WAIT_PROC) {
5476         rx_atomic_dec(&rx_nWaiting);
5477     }
5478 #ifdef RX_ENABLE_LOCKS
5479     /* The following ensures that we don't mess with any queue while some
5480      * other thread might also be doing so. The call_queue_lock field is
5481      * is only modified under the call lock. If the call is in the process
5482      * of being removed from a queue, the call is not locked until the
5483      * the queue lock is dropped and only then is the call_queue_lock field
5484      * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5485      * Note that any other routine which removes a call from a queue has to
5486      * obtain the queue lock before examing the queue and removing the call.
5487      */
5488     if (call->call_queue_lock) {
5489         MUTEX_ENTER(call->call_queue_lock);
5490         if (opr_queue_IsOnQueue(&call->entry)) {
5491             opr_queue_Remove(&call->entry);
5492         }
5493         MUTEX_EXIT(call->call_queue_lock);
5494         CLEAR_CALL_QUEUE_LOCK(call);
5495     }
5496 #else /* RX_ENABLE_LOCKS */
5497     if (opr_queue_IsOnQueue(&call->entry)) {
5498         opr_queue_Remove(&call->entry);
5499     }
5500 #endif /* RX_ENABLE_LOCKS */
5501
5502     rxi_CancelKeepAliveEvent(call);
5503     rxi_CancelDelayedAckEvent(call);
5504 }
5505
5506 /* Send an acknowledge for the indicated packet (seq,serial) of the
5507  * indicated call, for the indicated reason (reason).  This
5508  * acknowledge will specifically acknowledge receiving the packet, and
5509  * will also specify which other packets for this call have been
5510  * received.  This routine returns the packet that was used to the
5511  * caller.  The caller is responsible for freeing it or re-using it.
5512  * This acknowledgement also returns the highest sequence number
5513  * actually read out by the higher level to the sender; the sender
5514  * promises to keep around packets that have not been read by the
5515  * higher level yet (unless, of course, the sender decides to abort
5516  * the call altogether).  Any of p, seq, serial, pflags, or reason may
5517  * be set to zero without ill effect.  That is, if they are zero, they
5518  * will not convey any information.
5519  * NOW there is a trailer field, after the ack where it will safely be
5520  * ignored by mundanes, which indicates the maximum size packet this
5521  * host can swallow.  */
5522 /*
5523     struct rx_packet *optionalPacket;  use to send ack (or null)
5524     int seq;                     Sequence number of the packet we are acking
5525     int serial;                  Serial number of the packet
5526     int pflags;                  Flags field from packet header
5527     int reason;                  Reason an acknowledge was prompted
5528 */
5529
5530 #define RX_ZEROS 1024
5531 static char rx_zeros[RX_ZEROS];
5532
5533 struct rx_packet *
5534 rxi_SendAck(struct rx_call *call,
5535             struct rx_packet *optionalPacket, int serial, int reason,
5536             int istack)
5537 {
5538     struct rx_ackPacket *ap;
5539     struct rx_packet *p;
5540     struct opr_queue *cursor;
5541     u_char offset = 0;
5542     afs_int32 templ;
5543     afs_uint32 padbytes = 0;
5544 #ifdef RX_ENABLE_TSFPQ
5545     struct rx_ts_info_t * rx_ts_info;
5546 #endif
5547
5548     /*
5549      * Open the receive window once a thread starts reading packets
5550      */
5551     if (call->rnext > 1) {
5552         call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5553     }
5554
5555     /* Don't attempt to grow MTU if this is a critical ping */
5556     if (reason == RX_ACK_MTU) {
5557         /* keep track of per-call attempts, if we're over max, do in small
5558          * otherwise in larger? set a size to increment by, decrease
5559          * on failure, here?
5560          */
5561         if (call->conn->peer->maxPacketSize &&
5562             (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5563              - RX_HEADER_SIZE))
5564             padbytes = call->conn->peer->maxPacketSize+16;
5565         else
5566             padbytes = call->conn->peer->maxMTU + 128;
5567
5568         /* do always try a minimum size ping */
5569         padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5570
5571         /* subtract the ack payload */
5572         padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5573         reason = RX_ACK_PING;
5574     }
5575
5576     call->nHardAcks = 0;
5577     call->nSoftAcks = 0;
5578     if (call->rnext > call->lastAcked)
5579         call->lastAcked = call->rnext;
5580     p = optionalPacket;
5581
5582     if (p) {
5583         rx_computelen(p, p->length);    /* reset length, you never know */
5584     } /* where that's been...         */
5585 #ifdef RX_ENABLE_TSFPQ
5586     else {
5587         RX_TS_INFO_GET(rx_ts_info);
5588         if ((p = rx_ts_info->local_special_packet)) {
5589             rx_computelen(p, p->length);
5590         } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5591             rx_ts_info->local_special_packet = p;
5592         } else { /* We won't send the ack, but don't panic. */
5593             return optionalPacket;
5594         }
5595     }
5596 #else
5597     else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5598         /* We won't send the ack, but don't panic. */
5599         return optionalPacket;
5600     }
5601 #endif
5602
5603     templ = padbytes +
5604         rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5605         rx_GetDataSize(p);
5606     if (templ > 0) {
5607         if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5608 #ifndef RX_ENABLE_TSFPQ
5609             if (!optionalPacket)
5610                 rxi_FreePacket(p);
5611 #endif
5612             return optionalPacket;
5613         }
5614         templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5615         if (rx_Contiguous(p) < templ) {
5616 #ifndef RX_ENABLE_TSFPQ
5617             if (!optionalPacket)
5618                 rxi_FreePacket(p);
5619 #endif
5620             return optionalPacket;
5621         }
5622     }
5623
5624
5625     /* MTUXXX failing to send an ack is very serious.  We should */
5626     /* try as hard as possible to send even a partial ack; it's */
5627     /* better than nothing. */
5628     ap = (struct rx_ackPacket *)rx_DataOf(p);
5629     ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5630     ap->reason = reason;
5631
5632     /* The skew computation used to be bogus, I think it's better now. */
5633     /* We should start paying attention to skew.    XXX  */
5634     ap->serial = htonl(serial);
5635     ap->maxSkew = 0;            /* used to be peer->inPacketSkew */
5636
5637     /*
5638      * First packet not yet forwarded to reader. When ACKALL has been
5639      * sent the peer has been told that all received packets will be
5640      * delivered to the reader.  The value 'rnext' is used internally
5641      * to refer to the next packet in the receive queue that must be
5642      * delivered to the reader.  From the perspective of the peer it
5643      * already has so report the last sequence number plus one if there
5644      * are packets in the receive queue awaiting processing.
5645      */
5646     if ((call->flags & RX_CALL_ACKALL_SENT) &&
5647         !opr_queue_IsEmpty(&call->rq)) {
5648         ap->firstPacket = htonl(opr_queue_Last(&call->rq, struct rx_packet, entry)->header.seq + 1);
5649     } else {
5650         ap->firstPacket = htonl(call->rnext);
5651
5652         ap->previousPacket = htonl(call->rprev);        /* Previous packet received */
5653
5654         /* No fear of running out of ack packet here because there can only 
5655          * be at most one window full of unacknowledged packets.  The window
5656          * size must be constrained to be less than the maximum ack size, 
5657          * of course.  Also, an ack should always fit into a single packet 
5658          * -- it should not ever be fragmented.  */
5659         offset = 0;
5660         for (opr_queue_Scan(&call->rq, cursor)) {
5661             struct rx_packet *rqp
5662                 = opr_queue_Entry(cursor, struct rx_packet, entry);
5663
5664             if (!rqp || !call->rq.next
5665                 || (rqp->header.seq > (call->rnext + call->rwind))) {
5666 #ifndef RX_ENABLE_TSFPQ
5667                 if (!optionalPacket)
5668                     rxi_FreePacket(p);
5669 #endif
5670                 rxi_CallError(call, RX_CALL_DEAD);
5671                 return optionalPacket;
5672             }
5673
5674             while (rqp->header.seq > call->rnext + offset)
5675                 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5676             ap->acks[offset++] = RX_ACK_TYPE_ACK;
5677
5678             if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5679 #ifndef RX_ENABLE_TSFPQ
5680                 if (!optionalPacket)
5681                     rxi_FreePacket(p);
5682 #endif
5683                 rxi_CallError(call, RX_CALL_DEAD);
5684                 return optionalPacket;
5685             }
5686         }
5687     }
5688
5689     ap->nAcks = offset;
5690     p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5691
5692     /* Must zero the 3 octets that rx_AckDataSize skips at the end of the
5693      * ACK list.
5694      */
5695     rx_packetwrite(p, rx_AckDataSize(offset) - 3, 3, rx_zeros);
5696
5697     /* these are new for AFS 3.3 */
5698     templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5699     templ = htonl(templ);
5700     rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5701     templ = htonl(call->conn->peer->ifMTU);
5702     rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5703                    sizeof(afs_int32), &templ);
5704
5705     /* new for AFS 3.4 */
5706     templ = htonl(call->rwind);
5707     rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5708                    sizeof(afs_int32), &templ);
5709
5710     /* new for AFS 3.5 */
5711     templ = htonl(call->conn->peer->ifDgramPackets);
5712     rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5713                    sizeof(afs_int32), &templ);
5714
5715     p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5716
5717     p->header.serviceId = call->conn->serviceId;
5718     p->header.cid = (call->conn->cid | call->channel);
5719     p->header.callNumber = *call->callNumber;
5720     p->header.seq = 0;
5721     p->header.securityIndex = call->conn->securityIndex;
5722     p->header.epoch = call->conn->epoch;
5723     p->header.type = RX_PACKET_TYPE_ACK;
5724     p->header.flags = RX_SLOW_START_OK;
5725     if (reason == RX_ACK_PING)
5726         p->header.flags |= RX_REQUEST_ACK;
5727
5728     while (padbytes > 0) {
5729         if (padbytes > RX_ZEROS) {
5730             rx_packetwrite(p, p->length, RX_ZEROS, rx_zeros);
5731             p->length += RX_ZEROS;
5732             padbytes -= RX_ZEROS;
5733         } else {
5734             rx_packetwrite(p, p->length, padbytes, rx_zeros);
5735             p->length += padbytes;
5736             padbytes = 0;
5737         }
5738     }
5739
5740     if (call->conn->type == RX_CLIENT_CONNECTION)
5741         p->header.flags |= RX_CLIENT_INITIATED;
5742
5743 #ifdef RXDEBUG
5744 #ifdef AFS_NT40_ENV
5745     if (rxdebug_active) {
5746         char msg[512];
5747         size_t len;
5748
5749         len = _snprintf(msg, sizeof(msg),
5750                         "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5751                          GetCurrentThreadId(), rx_ack_reason(ap->reason),
5752                          ntohl(ap->serial), ntohl(ap->previousPacket),
5753                          (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5754                          ap->nAcks, ntohs(ap->bufferSpace) );
5755         if (ap->nAcks) {
5756             int offset;
5757
5758             for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5759                 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5760         }
5761         msg[len++]='\n';
5762         msg[len] = '\0';
5763         OutputDebugString(msg);
5764     }
5765 #else /* AFS_NT40_ENV */
5766     if (rx_Log) {
5767         fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5768                 ap->reason, ntohl(ap->previousPacket),
5769                 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5770         if (ap->nAcks) {
5771             for (offset = 0; offset < ap->nAcks; offset++)
5772                 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5773                      rx_Log);
5774         }
5775         putc('\n', rx_Log);
5776     }
5777 #endif /* AFS_NT40_ENV */
5778 #endif
5779     {
5780         int i, nbytes = p->length;
5781
5782         for (i = 1; i < p->niovecs; i++) {      /* vec 0 is ALWAYS header */
5783             if (nbytes <= p->wirevec[i].iov_len) {
5784                 int savelen, saven;
5785
5786                 savelen = p->wirevec[i].iov_len;
5787                 saven = p->niovecs;
5788                 p->wirevec[i].iov_len = nbytes;
5789                 p->niovecs = i + 1;
5790                 rxi_Send(call, p, istack);
5791                 p->wirevec[i].iov_len = savelen;
5792                 p->niovecs = saven;
5793                 break;
5794             } else
5795                 nbytes -= p->wirevec[i].iov_len;
5796         }
5797     }
5798     if (rx_stats_active)
5799         rx_atomic_inc(&rx_stats.ackPacketsSent);
5800 #ifndef RX_ENABLE_TSFPQ
5801     if (!optionalPacket)
5802         rxi_FreePacket(p);
5803 #endif
5804     return optionalPacket;      /* Return packet for re-use by caller */
5805 }
5806
5807 struct xmitlist {
5808    struct rx_packet **list;
5809    int len;
5810    int resending;
5811 };
5812
5813 /* Send all of the packets in the list in single datagram */
5814 static void
5815 rxi_SendList(struct rx_call *call, struct xmitlist *xmit,
5816              int istack, int moreFlag)
5817 {
5818     int i;
5819     int requestAck = 0;
5820     int lastPacket = 0;
5821     struct clock now;
5822     struct rx_connection *conn = call->conn;
5823     struct rx_peer *peer = conn->peer;
5824
5825     MUTEX_ENTER(&peer->peer_lock);
5826     peer->nSent += xmit->len;
5827     if (xmit->resending)
5828         peer->reSends += xmit->len;
5829     MUTEX_EXIT(&peer->peer_lock);
5830
5831     if (rx_stats_active) {
5832         if (xmit->resending)
5833             rx_atomic_add(&rx_stats.dataPacketsReSent, xmit->len);
5834         else
5835             rx_atomic_add(&rx_stats.dataPacketsSent, xmit->len);
5836     }
5837
5838     clock_GetTime(&now);
5839
5840     if (xmit->list[xmit->len - 1]->header.flags & RX_LAST_PACKET) {
5841         lastPacket = 1;
5842     }
5843
5844     /* Set the packet flags and schedule the resend events */
5845     /* Only request an ack for the last packet in the list */
5846     for (i = 0; i < xmit->len; i++) {
5847         struct rx_packet *packet = xmit->list[i];
5848
5849         /* Record the time sent */
5850         packet->timeSent = now;
5851         packet->flags |= RX_PKTFLAG_SENT;
5852
5853         /* Ask for an ack on retransmitted packets,  on every other packet
5854          * if the peer doesn't support slow start. Ask for an ack on every
5855          * packet until the congestion window reaches the ack rate. */
5856         if (packet->header.serial) {
5857             requestAck = 1;
5858         } else {
5859             packet->firstSent = now;
5860             if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5861                                 || (!(call->flags & RX_CALL_SLOW_START_OK)
5862                                     && (packet->header.seq & 1)))) {
5863                 requestAck = 1;
5864             }
5865         }
5866
5867         /* Tag this packet as not being the last in this group,
5868          * for the receiver's benefit */
5869         if (i < xmit->len - 1 || moreFlag) {
5870             packet->header.flags |= RX_MORE_PACKETS;
5871         }
5872     }
5873
5874     if (requestAck) {
5875         xmit->list[xmit->len - 1]->header.flags |= RX_REQUEST_ACK;
5876     }
5877
5878     /* Since we're about to send a data packet to the peer, it's
5879      * safe to nuke any scheduled end-of-packets ack */
5880     rxi_CancelDelayedAckEvent(call);
5881
5882     MUTEX_EXIT(&call->lock);
5883     CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5884     if (xmit->len > 1) {
5885         rxi_SendPacketList(call, conn, xmit->list, xmit->len, istack);
5886     } else {
5887         rxi_SendPacket(call, conn, xmit->list[0], istack);
5888     }
5889     MUTEX_ENTER(&call->lock);
5890     CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5891
5892     /* Tell the RTO calculation engine that we have sent a packet, and
5893      * if it was the last one */
5894     rxi_rto_packet_sent(call, lastPacket, istack);
5895
5896     /* Update last send time for this call (for keep-alive
5897      * processing), and for the connection (so that we can discover
5898      * idle connections) */
5899     conn->lastSendTime = call->lastSendTime = clock_Sec();
5900 }
5901
5902 /* When sending packets we need to follow these rules:
5903  * 1. Never send more than maxDgramPackets in a jumbogram.
5904  * 2. Never send a packet with more than two iovecs in a jumbogram.
5905  * 3. Never send a retransmitted packet in a jumbogram.
5906  * 4. Never send more than cwind/4 packets in a jumbogram
5907  * We always keep the last list we should have sent so we
5908  * can set the RX_MORE_PACKETS flags correctly.
5909  */
5910
5911 static void
5912 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5913                  int istack)
5914 {
5915     int i;
5916     int recovery;
5917     struct xmitlist working;
5918     struct xmitlist last;
5919
5920     struct rx_peer *peer = call->conn->peer;
5921     int morePackets = 0;
5922
5923     memset(&last, 0, sizeof(struct xmitlist));
5924     working.list = &list[0];
5925     working.len = 0;
5926     working.resending = 0;
5927
5928     recovery = call->flags & RX_CALL_FAST_RECOVER;
5929
5930     for (i = 0; i < len; i++) {
5931         /* Does the current packet force us to flush the current list? */
5932         if (working.len > 0
5933             && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5934                 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5935
5936             /* This sends the 'last' list and then rolls the current working
5937              * set into the 'last' one, and resets the working set */
5938
5939             if (last.len > 0) {
5940                 rxi_SendList(call, &last, istack, 1);
5941                 /* If the call enters an error state stop sending, or if
5942                  * we entered congestion recovery mode, stop sending */
5943                 if (call->error
5944                     || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5945                     return;
5946             }
5947             last = working;
5948             working.len = 0;
5949             working.resending = 0;
5950             working.list = &list[i];
5951         }
5952         /* Add the current packet to the list if it hasn't been acked.
5953          * Otherwise adjust the list pointer to skip the current packet.  */
5954         if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5955             working.len++;
5956
5957             if (list[i]->header.serial)
5958                 working.resending = 1;
5959
5960             /* Do we need to flush the list? */
5961             if (working.len >= (int)peer->maxDgramPackets
5962                 || working.len >= (int)call->nDgramPackets 
5963                 || working.len >= (int)call->cwind
5964                 || list[i]->header.serial
5965                 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5966                 if (last.len > 0) {
5967                     rxi_SendList(call, &last, istack, 1);
5968                     /* If the call enters an error state stop sending, or if
5969                      * we entered congestion recovery mode, stop sending */
5970                     if (call->error
5971                         || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5972                         return;
5973                 }
5974                 last = working;
5975                 working.len = 0;
5976                 working.resending = 0;
5977                 working.list = &list[i + 1];
5978             }
5979         } else {
5980             if (working.len != 0) {
5981                 osi_Panic("rxi_SendList error");
5982             }
5983             working.list = &list[i + 1];
5984         }
5985     }
5986
5987     /* Send the whole list when the call is in receive mode, when
5988      * the call is in eof mode, when we are in fast recovery mode,
5989      * and when we have the last packet */
5990     /* XXX - The accesses to app.mode aren't safe, as this may be called by
5991      * the listener or event threads
5992      */
5993     if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5994         || (call->flags & RX_CALL_FLUSH)
5995         || (call->flags & RX_CALL_FAST_RECOVER)) {
5996         /* Check for the case where the current list contains
5997          * an acked packet. Since we always send retransmissions
5998          * in a separate packet, we only need to check the first
5999          * packet in the list */
6000         if (working.len > 0 && !(working.list[0]->flags & RX_PKTFLAG_ACKED)) {
6001             morePackets = 1;
6002         }
6003         if (last.len > 0) {
6004             rxi_SendList(call, &last, istack, morePackets);
6005             /* If the call enters an error state stop sending, or if
6006              * we entered congestion recovery mode, stop sending */
6007             if (call->error
6008                 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
6009                 return;
6010         }
6011         if (morePackets) {
6012             rxi_SendList(call, &working, istack, 0);
6013         }
6014     } else if (last.len > 0) {
6015         rxi_SendList(call, &last, istack, 0);
6016         /* Packets which are in 'working' are not sent by this call */
6017     }
6018 }
6019
6020 /**
6021  * Check if the peer for the given call is known to be dead
6022  *
6023  * If the call's peer appears dead (it has encountered fatal network errors
6024  * since the call started) the call is killed with RX_CALL_DEAD if the call
6025  * is active. Otherwise, we do nothing.
6026  *
6027  * @param[in] call  The call to check
6028  *
6029  * @return status
6030  *  @retval 0 The call is fine, and we haven't done anything to the call
6031  *  @retval nonzero The call's peer appears dead, and the call has been
6032  *                  terminated if it was active
6033  *
6034  * @pre call->lock must be locked
6035  */
6036 static int
6037 rxi_CheckPeerDead(struct rx_call *call)
6038 {
6039 #ifdef AFS_RXERRQ_ENV
6040     int peererrs;
6041
6042     if (call->state == RX_STATE_DALLY) {
6043         return 0;
6044     }
6045
6046     peererrs = rx_atomic_read(&call->conn->peer->neterrs);
6047     if (call->neterr_gen < peererrs) {
6048         /* we have received network errors since this call started; kill
6049          * the call */
6050         if (call->state == RX_STATE_ACTIVE) {
6051             rxi_CallError(call, RX_CALL_DEAD);
6052         }
6053         return -1;
6054     }
6055     if (call->neterr_gen > peererrs) {
6056         /* someone has reset the number of peer errors; set the call error gen
6057          * so we can detect if more errors are encountered */
6058         call->neterr_gen = peererrs;
6059     }
6060 #endif
6061     return 0;
6062 }
6063
6064 static void
6065 rxi_Resend(struct rxevent *event, void *arg0, void *arg1, int istack)
6066 {
6067     struct rx_call *call = arg0;
6068     struct rx_peer *peer;
6069     struct opr_queue *cursor;
6070     struct clock maxTimeout = { 60, 0 };
6071
6072     MUTEX_ENTER(&call->lock);
6073
6074     peer = call->conn->peer;
6075
6076     /* Make sure that the event pointer is removed from the call
6077      * structure, since there is no longer a per-call retransmission
6078      * event pending. */
6079     if (event == call->resendEvent)
6080         rxevent_Put(&call->resendEvent);
6081
6082     rxi_CheckPeerDead(call);
6083
6084     if (opr_queue_IsEmpty(&call->tq)) {
6085         /* Nothing to do. This means that we've been raced, and that an
6086          * ACK has come in between when we were triggered, and when we
6087          * actually got to run. */
6088         goto out;
6089     }
6090
6091     /* We're in loss recovery */
6092     call->flags |= RX_CALL_FAST_RECOVER;
6093
6094     /* Mark all of the pending packets in the queue as being lost */
6095     for (opr_queue_Scan(&call->tq, cursor)) {
6096         struct rx_packet *p = opr_queue_Entry(cursor, struct rx_packet, entry);
6097         if (!(p->flags & RX_PKTFLAG_ACKED))
6098             p->flags &= ~RX_PKTFLAG_SENT;
6099     }
6100
6101     /* We're resending, so we double the timeout of the call. This will be
6102      * dropped back down by the first successful ACK that we receive.
6103      *
6104      * We apply a maximum value here of 60 seconds
6105      */
6106     clock_Add(&call->rto, &call->rto);
6107     if (clock_Gt(&call->rto, &maxTimeout))
6108         call->rto = maxTimeout;
6109
6110     /* Packet loss is most likely due to congestion, so drop our window size
6111      * and start again from the beginning */
6112     if (peer->maxDgramPackets >1) {
6113         call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
6114         call->MTU = MIN(peer->natMTU, peer->maxMTU);
6115     }
6116     call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
6117     call->nDgramPackets = 1;
6118     call->cwind = 1;
6119     call->nextCwind = 1;
6120     call->nAcks = 0;
6121     call->nNacks = 0;
6122     MUTEX_ENTER(&peer->peer_lock);
6123     peer->MTU = call->MTU;
6124     peer->cwind = call->cwind;
6125     peer->nDgramPackets = 1;
6126     peer->congestSeq++;
6127     call->congestSeq = peer->congestSeq;
6128     MUTEX_EXIT(&peer->peer_lock);
6129
6130     rxi_Start(call, istack);
6131
6132 out:
6133     CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
6134     MUTEX_EXIT(&call->lock);
6135 }
6136
6137 /* This routine is called when new packets are readied for
6138  * transmission and when retransmission may be necessary, or when the
6139  * transmission window or burst count are favourable.  This should be
6140  * better optimized for new packets, the usual case, now that we've
6141  * got rid of queues of send packets. XXXXXXXXXXX */
6142 void
6143 rxi_Start(struct rx_call *call, int istack)
6144 {
6145     struct opr_queue *cursor;
6146 #ifdef RX_ENABLE_LOCKS
6147     struct opr_queue *store;
6148 #endif
6149     int nXmitPackets;
6150     int maxXmitPackets;
6151
6152     if (call->error) {
6153 #ifdef RX_ENABLE_LOCKS
6154         if (rx_stats_active)
6155             rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
6156 #endif
6157         return;
6158     }
6159
6160     if (!opr_queue_IsEmpty(&call->tq)) {        /* If we have anything to send */
6161         /* Send (or resend) any packets that need it, subject to
6162          * window restrictions and congestion burst control
6163          * restrictions.  Ask for an ack on the last packet sent in
6164          * this burst.  For now, we're relying upon the window being
6165          * considerably bigger than the largest number of packets that
6166          * are typically sent at once by one initial call to
6167          * rxi_Start.  This is probably bogus (perhaps we should ask
6168          * for an ack when we're half way through the current
6169          * window?).  Also, for non file transfer applications, this
6170          * may end up asking for an ack for every packet.  Bogus. XXXX
6171          */
6172         /*
6173          * But check whether we're here recursively, and let the other guy
6174          * do the work.
6175          */
6176 #ifdef RX_ENABLE_LOCKS
6177         if (!(call->flags & RX_CALL_TQ_BUSY)) {
6178             call->flags |= RX_CALL_TQ_BUSY;
6179             do {
6180 #endif /* RX_ENABLE_LOCKS */
6181             restart:
6182 #ifdef RX_ENABLE_LOCKS
6183                 call->flags &= ~RX_CALL_NEED_START;
6184 #endif /* RX_ENABLE_LOCKS */
6185                 nXmitPackets = 0;
6186                 maxXmitPackets = MIN(call->twind, call->cwind);
6187                 for (opr_queue_Scan(&call->tq, cursor)) {
6188                     struct rx_packet *p
6189                         = opr_queue_Entry(cursor, struct rx_packet, entry);
6190
6191                     if (p->flags & RX_PKTFLAG_ACKED) {
6192                         /* Since we may block, don't trust this */
6193                         if (rx_stats_active)
6194                             rx_atomic_inc(&rx_stats.ignoreAckedPacket);
6195                         continue;       /* Ignore this packet if it has been acknowledged */
6196                     }
6197
6198                     /* Turn off all flags except these ones, which are the same
6199                      * on each transmission */
6200                     p->header.flags &= RX_PRESET_FLAGS;
6201
6202                     if (p->header.seq >=
6203                         call->tfirst + MIN((int)call->twind,
6204                                            (int)(call->nSoftAcked +
6205                                                  call->cwind))) {
6206                         call->flags |= RX_CALL_WAIT_WINDOW_SEND;        /* Wait for transmit window */
6207                         /* Note: if we're waiting for more window space, we can
6208                          * still send retransmits; hence we don't return here, but
6209                          * break out to schedule a retransmit event */
6210                         dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
6211                              *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
6212                              call->cwind));
6213                         break;
6214                     }
6215
6216                     /* Transmit the packet if it needs to be sent. */
6217                     if (!(p->flags & RX_PKTFLAG_SENT)) {
6218                         if (nXmitPackets == maxXmitPackets) {
6219                             rxi_SendXmitList(call, call->xmitList,
6220                                              nXmitPackets, istack);
6221                             goto restart;
6222                         }
6223                        dpf(("call %d xmit packet %p\n",
6224                               *(call->callNumber), p));
6225                         call->xmitList[nXmitPackets++] = p;
6226                     }
6227                 } /* end of the queue_Scan */
6228
6229                 /* xmitList now hold pointers to all of the packets that are
6230                  * ready to send. Now we loop to send the packets */
6231                 if (nXmitPackets > 0) {
6232                     rxi_SendXmitList(call, call->xmitList, nXmitPackets,
6233                                      istack);
6234                 }
6235
6236 #ifdef RX_ENABLE_LOCKS
6237                 if (call->error) {
6238                     /* We went into the error state while sending packets. Now is
6239                      * the time to reset the call. This will also inform the using
6240                      * process that the call is in an error state.
6241                      */
6242                     if (rx_stats_active)
6243                         rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
6244                     call->flags &= ~RX_CALL_TQ_BUSY;
6245                     rxi_WakeUpTransmitQueue(call);
6246                     rxi_CallError(call, call->error);
6247                     return;
6248                 }
6249
6250                 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
6251                     int missing;
6252                     call->flags &= ~RX_CALL_TQ_SOME_ACKED;
6253                     /* Some packets have received acks. If they all have, we can clear
6254                      * the transmit queue.
6255                      */
6256                     missing = 0;
6257                     for (opr_queue_ScanSafe(&call->tq, cursor, store)) {
6258                         struct rx_packet *p
6259                             = opr_queue_Entry(cursor, struct rx_packet, entry);
6260
6261                         if (p->header.seq < call->tfirst
6262                             && (p->flags & RX_PKTFLAG_ACKED)) {
6263                             opr_queue_Remove(&p->entry);
6264 #ifdef RX_TRACK_PACKETS
6265                             p->flags &= ~RX_PKTFLAG_TQ;
6266 #endif
6267 #ifdef RXDEBUG_PACKET
6268                             call->tqc--;
6269 #endif
6270                             rxi_FreePacket(p);
6271                         } else
6272                             missing = 1;
6273                     }
6274                     if (!missing)
6275                         call->flags |= RX_CALL_TQ_CLEARME;
6276                 }
6277                 if (call->flags & RX_CALL_TQ_CLEARME)
6278                     rxi_ClearTransmitQueue(call, 1);
6279             } while (call->flags & RX_CALL_NEED_START);
6280             /*
6281              * TQ references no longer protected by this flag; they must remain
6282              * protected by the call lock.
6283              */
6284             call->flags &= ~RX_CALL_TQ_BUSY;
6285             rxi_WakeUpTransmitQueue(call);
6286         } else {
6287             call->flags |= RX_CALL_NEED_START;
6288         }
6289 #endif /* RX_ENABLE_LOCKS */
6290     } else {
6291         rxi_rto_cancel(call);
6292     }
6293 }
6294
6295 /* Also adjusts the keep alive parameters for the call, to reflect
6296  * that we have just sent a packet (so keep alives aren't sent
6297  * immediately) */
6298 void
6299 rxi_Send(struct rx_call *call, struct rx_packet *p,
6300          int istack)
6301 {
6302     int code;
6303     struct rx_connection *conn = call->conn;
6304
6305     /* Stamp each packet with the user supplied status */
6306     p->header.userStatus = call->localStatus;
6307
6308     /* Allow the security object controlling this call's security to
6309      * make any last-minute changes to the packet */
6310     code = RXS_SendPacket(conn->securityObject, call, p);
6311     if (code) {
6312         MUTEX_EXIT(&call->lock);
6313         CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6314         rxi_ConnectionError(conn, code);
6315         CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6316         MUTEX_ENTER(&call->lock);
6317         return;
6318     }
6319
6320     /* Since we're about to send SOME sort of packet to the peer, it's
6321      * safe to nuke any scheduled end-of-packets ack */
6322     rxi_CancelDelayedAckEvent(call);
6323
6324     /* Actually send the packet, filling in more connection-specific fields */
6325     MUTEX_EXIT(&call->lock);
6326     CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6327     rxi_SendPacket(call, conn, p, istack);
6328     CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6329     MUTEX_ENTER(&call->lock);
6330
6331     /* Update last send time for this call (for keep-alive
6332      * processing), and for the connection (so that we can discover
6333      * idle connections) */
6334     if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6335         (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
6336         (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
6337     {
6338         conn->lastSendTime = call->lastSendTime = clock_Sec();
6339     }
6340 }
6341
6342 /* Check if a call needs to be destroyed.  Called by keep-alive code to ensure
6343  * that things are fine.  Also called periodically to guarantee that nothing
6344  * falls through the cracks (e.g. (error + dally) connections have keepalive
6345  * turned off.  Returns 0 if conn is well, -1 otherwise.  If otherwise, call
6346  *  may be freed!
6347  * haveCTLock Set if calling from rxi_ReapConnections
6348  */
6349 static int
6350 rxi_CheckCall(struct rx_call *call, int haveCTLock)
6351 {
6352     struct rx_connection *conn = call->conn;
6353     afs_uint32 now;
6354     afs_uint32 deadTime, idleDeadTime = 0, hardDeadTime = 0;
6355     afs_uint32 fudgeFactor;
6356     int cerror = 0;
6357     int newmtu = 0;
6358     int idle_timeout = 0;
6359     afs_int32  clock_diff = 0;
6360
6361     if (rxi_CheckPeerDead(call)) {
6362         return -1;
6363     }
6364
6365     now = clock_Sec();
6366
6367     /* Large swings in the clock can have a significant impact on
6368      * the performance of RX call processing.  Forward clock shifts
6369      * will result in premature event triggering or timeouts.
6370      * Backward shifts can result in calls not completing until
6371      * the clock catches up with the original start clock value.
6372      *
6373      * If a backward clock shift of more than five minutes is noticed,
6374      * just fail the call.
6375      */
6376     if (now < call->lastSendTime)
6377         clock_diff = call->lastSendTime - now;
6378     if (now < call->startWait)
6379         clock_diff = MAX(clock_diff, call->startWait - now);
6380     if (now < call->lastReceiveTime)
6381         clock_diff = MAX(clock_diff, call->lastReceiveTime - now);
6382     if (clock_diff > 5 * 60)
6383     {
6384         if (call->state == RX_STATE_ACTIVE)
6385             rxi_CallError(call, RX_CALL_TIMEOUT);
6386         return -1;
6387     }
6388
6389 #ifdef RX_ENABLE_LOCKS
6390     if (call->flags & RX_CALL_TQ_BUSY) {
6391         /* Call is active and will be reset by rxi_Start if it's
6392          * in an error state.
6393          */
6394         return 0;
6395     }
6396 #endif
6397     /* RTT + 8*MDEV, rounded up to the next second. */
6398     fudgeFactor = (((afs_uint32) call->rtt >> 3) +
6399                    ((afs_uint32) call->rtt_dev << 1) + 1023) >> 10;
6400
6401     deadTime = conn->secondsUntilDead + fudgeFactor;
6402     /* These are computed to the second (+- 1 second).  But that's
6403      * good enough for these values, which should be a significant
6404      * number of seconds. */
6405     if (now > (call->lastReceiveTime + deadTime)) {
6406         if (call->state == RX_STATE_ACTIVE) {
6407             cerror = RX_CALL_DEAD;
6408             goto mtuout;
6409         } else {
6410 #ifdef RX_ENABLE_LOCKS
6411             /* Cancel pending events */
6412             rxi_CancelDelayedAckEvent(call);
6413             rxi_rto_cancel(call);
6414             rxi_CancelKeepAliveEvent(call);
6415             rxi_CancelGrowMTUEvent(call);
6416             MUTEX_ENTER(&rx_refcnt_mutex);
6417             /* if rxi_FreeCall returns 1 it has freed the call */
6418             if (call->refCount == 0 &&
6419                 rxi_FreeCall(call, haveCTLock))
6420             {
6421                 MUTEX_EXIT(&rx_refcnt_mutex);
6422                 return -2;
6423             }
6424             MUTEX_EXIT(&rx_refcnt_mutex);
6425             return -1;
6426 #else /* RX_ENABLE_LOCKS */
6427             rxi_FreeCall(call, 0);
6428             return -2;
6429 #endif /* RX_ENABLE_LOCKS */
6430         }
6431         /* Non-active calls are destroyed if they are not responding
6432          * to pings; active calls are simply flagged in error, so the
6433          * attached process can die reasonably gracefully. */
6434     }
6435
6436     if (conn->idleDeadTime) {
6437         idleDeadTime = conn->idleDeadTime + fudgeFactor;
6438     }
6439
6440     if (idleDeadTime) {
6441         /* see if we have a non-activity timeout */
6442         if (call->startWait && ((call->startWait + idleDeadTime) < now)) {
6443             if (call->state == RX_STATE_ACTIVE) {
6444                 cerror = RX_CALL_TIMEOUT;
6445                 goto mtuout;
6446             }
6447         }
6448     }
6449
6450     if (conn->hardDeadTime) {
6451         hardDeadTime = conn->hardDeadTime + fudgeFactor;
6452     }
6453
6454     /* see if we have a hard timeout */
6455     if (hardDeadTime
6456         && (now > (hardDeadTime + call->startTime.sec))) {
6457         if (call->state == RX_STATE_ACTIVE)
6458             rxi_CallError(call, RX_CALL_TIMEOUT);
6459         return -1;
6460     }
6461     return 0;
6462 mtuout:
6463     if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT && !idle_timeout &&
6464         call->lastReceiveTime) {
6465         int oldMTU = conn->peer->ifMTU;
6466
6467         /* If we thought we could send more, perhaps things got worse.
6468          * Shrink by 128 bytes and try again. */
6469         if (conn->peer->maxPacketSize < conn->lastPacketSize)
6470             /* maxPacketSize will be cleared in rxi_SetPeerMtu */
6471             newmtu = MAX(conn->peer->maxPacketSize + RX_HEADER_SIZE,
6472                          conn->lastPacketSize - 128 + RX_HEADER_SIZE);
6473         else
6474             newmtu = conn->lastPacketSize - 128 + RX_HEADER_SIZE;
6475
6476         /* minimum capped in SetPeerMtu */
6477         rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6478
6479         /* clean up */
6480         conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
6481
6482         /* needed so ResetCall doesn't clobber us. */
6483         call->MTU = conn->peer->ifMTU;
6484
6485         /* if we never succeeded, let the error pass out as-is */
6486         if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6487             cerror = conn->msgsizeRetryErr;
6488
6489     }
6490     rxi_CallError(call, cerror);
6491     return -1;
6492 }
6493
6494 void
6495 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1,
6496                       void *dummy, int dummy2)
6497 {
6498     struct rx_connection *conn = arg1;
6499     struct rx_header theader;
6500     char tbuffer[1 + sizeof(struct rx_header)];
6501     struct sockaddr_in taddr;
6502     char *tp;
6503     char a[1] = { 0 };
6504     int resched = 0;
6505     struct iovec tmpiov[2];
6506     osi_socket socket =
6507         (conn->type ==
6508          RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6509
6510
6511     tp = &tbuffer[sizeof(struct rx_header)];
6512     taddr.sin_family = AF_INET;
6513     taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6514     taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6515     memset(&taddr.sin_zero, 0, sizeof(taddr.sin_zero));
6516 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6517     taddr.sin_len = sizeof(struct sockaddr_in);
6518 #endif
6519     memset(&theader, 0, sizeof(theader));
6520     theader.epoch = htonl(999);
6521     theader.cid = 0;
6522     theader.callNumber = 0;
6523     theader.seq = 0;
6524     theader.serial = 0;
6525     theader.type = RX_PACKET_TYPE_VERSION;
6526     theader.flags = RX_LAST_PACKET;
6527     theader.serviceId = 0;
6528
6529     memcpy(tbuffer, &theader, sizeof(theader));
6530     memcpy(tp, &a, sizeof(a));
6531     tmpiov[0].iov_base = tbuffer;
6532     tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6533
6534     rxi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6535
6536     MUTEX_ENTER(&conn->conn_data_lock);
6537     /* We ran, so the handle is no longer needed to try to cancel ourselves. */
6538     if (event == conn->natKeepAliveEvent)
6539         rxevent_Put(&conn->natKeepAliveEvent);
6540     MUTEX_ENTER(&rx_refcnt_mutex);
6541     /* Only reschedule ourselves if the connection would not be destroyed */
6542     if (conn->refCount > 1)
6543         resched = 1;
6544     if (conn->refCount <= 0) {
6545 #ifdef RX_REFCOUNT_CHECK
6546         osi_Assert(conn->refCount == 0);
6547 #endif
6548         if (rx_stats_active) {
6549             MUTEX_ENTER(&rx_stats_mutex);
6550             rxi_lowConnRefCount++;
6551             MUTEX_EXIT(&rx_stats_mutex);
6552         }
6553     }
6554     MUTEX_EXIT(&rx_refcnt_mutex);
6555     if (resched)
6556         rxi_ScheduleNatKeepAliveEvent(conn);
6557     MUTEX_EXIT(&conn->conn_data_lock);
6558     putConnection(conn);
6559 }
6560
6561 static void
6562 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6563 {
6564     MUTEX_ASSERT(&conn->conn_data_lock);
6565     if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6566         struct clock when, now;
6567         clock_GetTime(&now);
6568         when = now;
6569         when.sec += conn->secondsUntilNatPing;
6570         rx_GetConnection(conn);
6571         conn->natKeepAliveEvent =
6572             rxevent_Post(&when, &now, rxi_NatKeepAliveEvent, conn, NULL, 0);
6573     }
6574 }
6575
6576 void
6577 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6578 {
6579     MUTEX_ENTER(&conn->conn_data_lock);
6580     conn->secondsUntilNatPing = seconds;
6581     if (seconds != 0) {
6582         if (!(conn->flags & RX_CONN_ATTACHWAIT))
6583             rxi_ScheduleNatKeepAliveEvent(conn);
6584         else
6585             conn->flags |= RX_CONN_NAT_PING;
6586     }
6587     MUTEX_EXIT(&conn->conn_data_lock);
6588 }
6589
6590 /* When a call is in progress, this routine is called occasionally to
6591  * make sure that some traffic has arrived (or been sent to) the peer.
6592  * If nothing has arrived in a reasonable amount of time, the call is
6593  * declared dead; if nothing has been sent for a while, we send a
6594  * keep-alive packet (if we're actually trying to keep the call alive)
6595  */
6596 void
6597 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy,
6598                    int dummy2)
6599 {
6600     struct rx_call *call = arg1;
6601     struct rx_connection *conn;
6602     afs_uint32 now;
6603
6604     MUTEX_ENTER(&call->lock);
6605
6606     if (event == call->keepAliveEvent)
6607         rxevent_Put(&call->keepAliveEvent);
6608
6609     now = clock_Sec();
6610
6611     if (rxi_CheckCall(call, 0)) {
6612         MUTEX_EXIT(&call->lock);
6613         CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6614         return;
6615     }
6616
6617     /* Don't try to keep alive dallying calls */
6618     if (call->state == RX_STATE_DALLY) {
6619         MUTEX_EXIT(&call->lock);
6620         CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6621         return;
6622     }
6623
6624     conn = call->conn;
6625     if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6626         /* Don't try to send keepalives if there is unacknowledged data */
6627         /* the rexmit code should be good enough, this little hack
6628          * doesn't quite work XXX */
6629         (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6630     }
6631     rxi_ScheduleKeepAliveEvent(call);
6632     MUTEX_EXIT(&call->lock);
6633     CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6634 }
6635
6636 /* Does what's on the nameplate. */
6637 void
6638 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy, int dummy2)
6639 {
6640     struct rx_call *call = arg1;
6641     struct rx_connection *conn;
6642
6643     MUTEX_ENTER(&call->lock);
6644
6645     if (event == call->growMTUEvent)
6646         rxevent_Put(&call->growMTUEvent);
6647
6648     if (rxi_CheckCall(call, 0))
6649         goto out;
6650
6651     /* Don't bother with dallying calls */
6652     if (call->state == RX_STATE_DALLY)
6653         goto out;
6654
6655     conn = call->conn;
6656
6657     /*
6658      * keep being scheduled, just don't do anything if we're at peak,
6659      * or we're not set up to be properly handled (idle timeout required)
6660      */
6661     if ((conn->peer->maxPacketSize != 0) &&
6662         (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6663         conn->idleDeadTime)
6664         (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6665     rxi_ScheduleGrowMTUEvent(call, 0);
6666 out:
6667     MUTEX_EXIT(&call->lock);
6668     CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6669 }
6670
6671 static void
6672 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6673 {
6674     MUTEX_ASSERT(&call->lock);
6675     if (!call->keepAliveEvent) {
6676         struct clock when, now;
6677         clock_GetTime(&now);
6678         when = now;
6679         when.sec += call->conn->secondsUntilPing;
6680         CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6681         call->keepAliveEvent =
6682             rxevent_Post(&when, &now, rxi_KeepAliveEvent, call, NULL, 0);
6683     }
6684 }
6685
6686 static void
6687 rxi_CancelKeepAliveEvent(struct rx_call *call) {
6688     MUTEX_ASSERT(&call->lock);
6689     if (rxevent_Cancel(&call->keepAliveEvent))
6690         CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6691 }
6692
6693 static void
6694 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6695 {
6696     MUTEX_ASSERT(&call->lock);
6697     if (!call->growMTUEvent) {
6698         struct clock when, now;
6699
6700         clock_GetTime(&now);
6701         when = now;
6702         if (!secs) {
6703             if (call->conn->secondsUntilPing)
6704                 secs = (6*call->conn->secondsUntilPing)-1;
6705
6706             if (call->conn->secondsUntilDead)
6707                 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6708         }
6709
6710         when.sec += secs;
6711         CALL_HOLD(call, RX_CALL_REFCOUNT_MTU);
6712         call->growMTUEvent =
6713             rxevent_Post(&when, &now, rxi_GrowMTUEvent, call, NULL, 0);
6714     }
6715 }
6716
6717 static void
6718 rxi_CancelGrowMTUEvent(struct rx_call *call)
6719 {
6720     MUTEX_ASSERT(&call->lock);
6721     if (rxevent_Cancel(&call->growMTUEvent))
6722         CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6723 }
6724
6725 /*
6726  * Increment the counter for the next connection ID, handling overflow.
6727  */
6728 static void
6729 update_nextCid(void)
6730 {
6731     /* Overflow is technically undefined behavior; avoid it. */
6732     if (rx_nextCid > MAX_AFS_INT32 - (1 << RX_CIDSHIFT))
6733         rx_nextCid = -1 * ((MAX_AFS_INT32 / RX_CIDSHIFT) * RX_CIDSHIFT);
6734     else
6735         rx_nextCid += 1 << RX_CIDSHIFT;
6736 }
6737
6738 static void
6739 rxi_KeepAliveOn(struct rx_call *call)
6740 {
6741     /* Pretend last packet received was received now--i.e. if another
6742      * packet isn't received within the keep alive time, then the call
6743      * will die; Initialize last send time to the current time--even
6744      * if a packet hasn't been sent yet.  This will guarantee that a
6745      * keep-alive is sent within the ping time */
6746     call->lastReceiveTime = call->lastSendTime = clock_Sec();
6747     rxi_ScheduleKeepAliveEvent(call);
6748 }
6749
6750 static void
6751 rxi_GrowMTUOn(struct rx_call *call)
6752 {
6753     struct rx_connection *conn = call->conn;
6754     MUTEX_ENTER(&conn->conn_data_lock);
6755     conn->lastPingSizeSer = conn->lastPingSize = 0;
6756     MUTEX_EXIT(&conn->conn_data_lock);
6757     rxi_ScheduleGrowMTUEvent(call, 1);
6758 }
6759
6760 /* This routine is called to send connection abort messages
6761  * that have been delayed to throttle looping clients. */
6762 static void
6763 rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1, void *unused,
6764                          int unused2)
6765 {
6766     struct rx_connection *conn = arg1;
6767
6768     afs_int32 error;
6769     struct rx_packet *packet;
6770
6771     MUTEX_ENTER(&conn->conn_data_lock);
6772     if (event == conn->delayedAbortEvent)
6773         rxevent_Put(&conn->delayedAbortEvent);
6774     error = htonl(conn->error);
6775     conn->abortCount++;
6776     MUTEX_EXIT(&conn->conn_data_lock);
6777     packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6778     if (packet) {
6779         packet =
6780             rxi_SendSpecial((struct rx_call *)0, conn, packet,
6781                             RX_PACKET_TYPE_ABORT, (char *)&error,
6782                             sizeof(error), 0);
6783         rxi_FreePacket(packet);
6784     }
6785     putConnection(conn);
6786 }
6787
6788 /* This routine is called to send call abort messages
6789  * that have been delayed to throttle looping clients. */
6790 static void
6791 rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1, void *dummy,
6792                          int dummy2)
6793 {
6794     struct rx_call *call = arg1;
6795
6796     afs_int32 error;
6797     struct rx_packet *packet;
6798
6799     MUTEX_ENTER(&call->lock);
6800     if (event == call->delayedAbortEvent)
6801         rxevent_Put(&call->delayedAbortEvent);
6802     error = htonl(call->error);
6803     call->abortCount++;
6804     packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6805     if (packet) {
6806         packet =
6807             rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6808                             (char *)&error, sizeof(error), 0);
6809         rxi_FreePacket(packet);
6810     }
6811     MUTEX_EXIT(&call->lock);
6812     CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6813 }
6814
6815 /*
6816  * This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6817  * seconds) to ask the client to authenticate itself.  The routine
6818  * issues a challenge to the client, which is obtained from the
6819  * security object associated with the connection
6820  *
6821  * This routine is both an event handler and a function called directly;
6822  * when called directly the passed |event| is NULL and the
6823  * conn->conn->data>lock must must not be held.  Also, when called as an
6824  * an event handler, we must putConnection before we exit; but when called
6825  * directly (the first challenge), we must NOT putConnection.
6826  */
6827 static void
6828 rxi_ChallengeEvent(struct rxevent *event,
6829                    void *arg0, void *arg1, int tries)
6830 {
6831     struct rx_connection *conn = arg0;
6832     int event_raised = 0;       /* assume we were called directly */
6833
6834     MUTEX_ENTER(&conn->conn_data_lock);
6835     if (event != NULL && event == conn->challengeEvent) {
6836         event_raised = 1;       /* called as an event */
6837         rxevent_Put(&conn->challengeEvent);
6838     }
6839     MUTEX_EXIT(&conn->conn_data_lock);
6840
6841     /* If there are no active calls it is not worth re-issuing the
6842      * challenge.  If the client issues another call on this connection
6843      * the challenge can be requested at that time.
6844      */
6845     if (!rxi_HasActiveCalls(conn))
6846         goto done;
6847
6848     if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6849         struct rx_packet *packet;
6850         struct clock when, now;
6851
6852         if (tries <= 0) {
6853             /* We've failed to authenticate for too long.
6854              * Reset any calls waiting for authentication;
6855              * they are all in RX_STATE_PRECALL.
6856              */
6857             int i;
6858
6859             MUTEX_ENTER(&conn->conn_call_lock);
6860             for (i = 0; i < RX_MAXCALLS; i++) {
6861                 struct rx_call *call = conn->call[i];
6862                 if (call) {
6863                     MUTEX_ENTER(&call->lock);
6864                     if (call->state == RX_STATE_PRECALL) {
6865                         rxi_CallError(call, RX_CALL_DEAD);
6866                         rxi_SendCallAbort(call, NULL, 0, 0);
6867                     }
6868                     MUTEX_EXIT(&call->lock);
6869                 }
6870             }
6871             MUTEX_EXIT(&conn->conn_call_lock);
6872             goto done;
6873         }
6874
6875         packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6876         if (packet) {
6877             int code;
6878             code = RXS_GetChallenge(conn->securityObject, conn, packet);
6879             if (code && event_raised) {
6880                 /*
6881                  * We can only rxi_ConnectionError the connection if we are
6882                  * running as an event. Otherwise, the caller may have our call
6883                  * locked, and so we cannot call rxi_ConnectionError (since it
6884                  * tries to lock each call in the conn).
6885                  */
6886                 rxi_FreePacket(packet);
6887                 rxi_ConnectionError(conn, code);
6888                 goto done;
6889             }
6890             if (code == 0) {
6891                 /* Only send a challenge packet if we were able to allocate a
6892                  * packet, and the security layer successfully populated the
6893                  * challenge. */
6894                 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6895                                 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6896                 conn->securityChallengeSent = 1;
6897             }
6898             rxi_FreePacket(packet);
6899         }
6900         clock_GetTime(&now);
6901         when = now;
6902         when.sec += RX_CHALLENGE_TIMEOUT;
6903         MUTEX_ENTER(&conn->conn_data_lock);
6904         /* Only reschedule ourselves if not already pending. */
6905         if (conn->challengeEvent == NULL) {
6906             rx_GetConnection(conn);
6907             conn->challengeEvent =
6908                 rxevent_Post(&when, &now, rxi_ChallengeEvent, conn, 0,
6909                              (tries - 1));
6910         }
6911         MUTEX_EXIT(&conn->conn_data_lock);
6912     }
6913  done:
6914     if (event_raised)
6915         putConnection(conn);
6916 }
6917
6918 /* Call this routine to start requesting the client to authenticate
6919  * itself.  This will continue until authentication is established,
6920  * the call times out, or an invalid response is returned.  The
6921  * security object associated with the connection is asked to create
6922  * the challenge at this time. */
6923 static int
6924 rxi_ChallengeOn(struct rx_connection *conn)
6925 {
6926     int start = 0;
6927     MUTEX_ENTER(&conn->conn_data_lock);
6928     if (!conn->challengeEvent)
6929         start = 1;
6930     MUTEX_EXIT(&conn->conn_data_lock);
6931     if (start) {
6932         int code;
6933         code = RXS_CreateChallenge(conn->securityObject, conn);
6934         if (code) {
6935             return code;
6936         }
6937         rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
6938     }
6939     return 0;
6940 }
6941
6942
6943 /* rxi_ComputeRoundTripTime is called with peer locked. */
6944 /* peer may be null */
6945 static void
6946 rxi_ComputeRoundTripTime(struct rx_packet *p,
6947                          struct rx_ackPacket *ack,
6948                          struct rx_call *call,
6949                          struct rx_peer *peer,
6950                          struct clock *now)
6951 {
6952     struct clock thisRtt, *sentp;
6953     int rtt_timeout;
6954     int serial;
6955
6956     /* If the ACK is delayed, then do nothing */
6957     if (ack->reason == RX_ACK_DELAY)
6958         return;
6959
6960     /* On the wire, jumbograms are a single UDP packet. We shouldn't count
6961      * their RTT multiple times, so only include the RTT of the last packet
6962      * in a jumbogram */
6963     if (p->flags & RX_JUMBO_PACKET)
6964         return;
6965
6966     /* Use the serial number to determine which transmission the ACK is for,
6967      * and set the sent time to match this. If we have no serial number, then
6968      * only use the ACK for RTT calculations if the packet has not been
6969      * retransmitted
6970      */
6971
6972     serial = ntohl(ack->serial);
6973     if (serial) {
6974         if (serial == p->header.serial) {
6975             sentp = &p->timeSent;
6976         } else if (serial == p->firstSerial) {
6977             sentp = &p->firstSent;
6978         } else if (clock_Eq(&p->timeSent, &p->firstSent)) {
6979             sentp = &p->firstSent;
6980         } else
6981             return;
6982     } else {
6983         if (clock_Eq(&p->timeSent, &p->firstSent)) {
6984             sentp = &p->firstSent;
6985         } else
6986             return;
6987     }
6988
6989     thisRtt = *now;
6990
6991     if (clock_Lt(&thisRtt, sentp))
6992         return;                 /* somebody set the clock back, don't count this time. */
6993
6994     clock_Sub(&thisRtt, sentp);
6995     dpf(("rxi_ComputeRoundTripTime(call=%d packet=%p rttp=%d.%06d sec)\n",
6996           p->header.callNumber, p, thisRtt.sec, thisRtt.usec));
6997
6998     if (clock_IsZero(&thisRtt)) {
6999         /*
7000          * The actual round trip time is shorter than the
7001          * clock_GetTime resolution.  It is most likely 1ms or 100ns.
7002          * Since we can't tell which at the moment we will assume 1ms.
7003          */
7004         thisRtt.usec = 1000;
7005     }
7006
7007     if (rx_stats_active) {
7008         MUTEX_ENTER(&rx_stats_mutex);
7009         if (clock_Lt(&thisRtt, &rx_stats.minRtt))
7010             rx_stats.minRtt = thisRtt;
7011         if (clock_Gt(&thisRtt, &rx_stats.maxRtt)) {
7012             if (thisRtt.sec > 60) {
7013                 MUTEX_EXIT(&rx_stats_mutex);
7014                 return;         /* somebody set the clock ahead */
7015             }
7016             rx_stats.maxRtt = thisRtt;
7017         }
7018         clock_Add(&rx_stats.totalRtt, &thisRtt);
7019         rx_atomic_inc(&rx_stats.nRttSamples);
7020         MUTEX_EXIT(&rx_stats_mutex);
7021     }
7022
7023     /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
7024
7025     /* Apply VanJacobson round-trip estimations */
7026     if (call->rtt) {
7027         int delta;
7028
7029         /*
7030          * srtt (call->rtt) is in units of one-eighth-milliseconds.
7031          * srtt is stored as fixed point with 3 bits after the binary
7032          * point (i.e., scaled by 8). The following magic is
7033          * equivalent to the smoothing algorithm in rfc793 with an
7034          * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
7035          * srtt'*8 = rtt + srtt*7
7036          * srtt'*8 = srtt*8 + rtt - srtt
7037          * srtt' = srtt + rtt/8 - srtt/8
7038          * srtt' = srtt + (rtt - srtt)/8
7039          */
7040
7041         delta = _8THMSEC(&thisRtt) - call->rtt;
7042         call->rtt += (delta >> 3);
7043
7044         /*
7045          * We accumulate a smoothed rtt variance (actually, a smoothed
7046          * mean difference), then set the retransmit timer to smoothed
7047          * rtt + 4 times the smoothed variance (was 2x in van's original
7048          * paper, but 4x works better for me, and apparently for him as
7049          * well).
7050          * rttvar is stored as
7051          * fixed point with 2 bits after the binary point (scaled by
7052          * 4).  The following is equivalent to rfc793 smoothing with
7053          * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
7054          *   rttvar'*4 = rttvar*3 + |delta|
7055          *   rttvar'*4 = rttvar*4 + |delta| - rttvar
7056          *   rttvar' = rttvar + |delta|/4 - rttvar/4
7057          *   rttvar' = rttvar + (|delta| - rttvar)/4
7058          * This replaces rfc793's wired-in beta.
7059          * dev*4 = dev*4 + (|actual - expected| - dev)
7060          */
7061
7062         if (delta < 0)
7063             delta = -delta;
7064
7065         delta -= (call->rtt_dev << 1);
7066         call->rtt_dev += (delta >> 3);
7067     } else {
7068         /* I don't have a stored RTT so I start with this value.  Since I'm
7069          * probably just starting a call, and will be pushing more data down
7070          * this, I expect congestion to increase rapidly.  So I fudge a
7071          * little, and I set deviance to half the rtt.  In practice,
7072          * deviance tends to approach something a little less than
7073          * half the smoothed rtt. */
7074         call->rtt = _8THMSEC(&thisRtt) + 8;
7075         call->rtt_dev = call->rtt >> 2; /* rtt/2: they're scaled differently */
7076     }
7077     /* the smoothed RTT time is RTT + 4*MDEV
7078      *
7079      * We allow a user specified minimum to be set for this, to allow clamping
7080      * at a minimum value in the same way as TCP. In addition, we have to allow
7081      * for the possibility that this packet is answered by a delayed ACK, so we
7082      * add on a fixed 200ms to account for that timer expiring.
7083      */
7084
7085     rtt_timeout = MAX(((call->rtt >> 3) + call->rtt_dev),
7086                       rx_minPeerTimeout) + 200;
7087     clock_Zero(&call->rto);
7088     clock_Addmsec(&call->rto, rtt_timeout);
7089
7090     /* Update the peer, so any new calls start with our values */
7091     peer->rtt_dev = call->rtt_dev;
7092     peer->rtt = call->rtt;
7093
7094     dpf(("rxi_ComputeRoundTripTime(call=%d packet=%p rtt=%d ms, srtt=%d ms, "
7095          "rtt_dev=%d ms, timeout=%d.%06d sec)\n",
7096          p->header.callNumber, p, MSEC(&thisRtt), call->rtt >> 3,
7097          call->rtt_dev >> 2, (call->rto.sec), (call->rto.usec)));
7098 }
7099
7100
7101 /* Find all server connections that have not been active for a long time, and
7102  * toss them */
7103 static void
7104 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2,
7105                     int unused3)
7106 {
7107     struct clock now, when;
7108     struct rxevent *event;
7109     clock_GetTime(&now);
7110
7111     /* Find server connection structures that haven't been used for
7112      * greater than rx_idleConnectionTime */
7113     {
7114         struct rx_connection **conn_ptr, **conn_end;
7115         int i, havecalls = 0;
7116         MUTEX_ENTER(&rx_connHashTable_lock);
7117         for (conn_ptr = &rx_connHashTable[0], conn_end =
7118              &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
7119              conn_ptr++) {
7120             struct rx_connection *conn, *next;
7121             struct rx_call *call;
7122             int result;
7123
7124           rereap:
7125             for (conn = *conn_ptr; conn; conn = next) {
7126                 /* XXX -- Shouldn't the connection be locked? */
7127                 next = conn->next;
7128                 havecalls = 0;
7129                 for (i = 0; i < RX_MAXCALLS; i++) {
7130                     call = conn->call[i];
7131                     if (call) {
7132                         int code;
7133                         havecalls = 1;
7134                         code = MUTEX_TRYENTER(&call->lock);
7135                         if (!code)
7136                             continue;
7137                         result = rxi_CheckCall(call, 1);
7138                         MUTEX_EXIT(&call->lock);
7139                         if (result == -2) {
7140                             /* If CheckCall freed the call, it might
7141                              * have destroyed  the connection as well,
7142                              * which screws up the linked lists.
7143                              */
7144                             goto rereap;
7145                         }
7146                     }
7147                 }
7148                 if (conn->type == RX_SERVER_CONNECTION) {
7149                     /* This only actually destroys the connection if
7150                      * there are no outstanding calls */
7151                     MUTEX_ENTER(&conn->conn_data_lock);
7152                     MUTEX_ENTER(&rx_refcnt_mutex);
7153                     if (!havecalls && !conn->refCount
7154                         && ((conn->lastSendTime + rx_idleConnectionTime) <
7155                             now.sec)) {
7156                         conn->refCount++;       /* it will be decr in rx_DestroyConn */
7157                         MUTEX_EXIT(&rx_refcnt_mutex);
7158                         MUTEX_EXIT(&conn->conn_data_lock);
7159 #ifdef RX_ENABLE_LOCKS
7160                         rxi_DestroyConnectionNoLock(conn);
7161 #else /* RX_ENABLE_LOCKS */
7162                         rxi_DestroyConnection(conn);
7163 #endif /* RX_ENABLE_LOCKS */
7164                     }
7165 #ifdef RX_ENABLE_LOCKS
7166                     else {
7167                         MUTEX_EXIT(&rx_refcnt_mutex);
7168                         MUTEX_EXIT(&conn->conn_data_lock);
7169                     }
7170 #endif /* RX_ENABLE_LOCKS */
7171                 }
7172             }
7173         }
7174 #ifdef RX_ENABLE_LOCKS
7175         while (rx_connCleanup_list) {
7176             struct rx_connection *conn;
7177             conn = rx_connCleanup_list;
7178             rx_connCleanup_list = rx_connCleanup_list->next;
7179             MUTEX_EXIT(&rx_connHashTable_lock);
7180             rxi_CleanupConnection(conn);
7181             MUTEX_ENTER(&rx_connHashTable_lock);
7182         }
7183         MUTEX_EXIT(&rx_connHashTable_lock);
7184 #endif /* RX_ENABLE_LOCKS */
7185     }
7186
7187     /* Find any peer structures that haven't been used (haven't had an
7188      * associated connection) for greater than rx_idlePeerTime */
7189     {
7190         struct rx_peer **peer_ptr, **peer_end;
7191         int code;
7192
7193         /*
7194          * Why do we need to hold the rx_peerHashTable_lock across
7195          * the incrementing of peer_ptr since the rx_peerHashTable
7196          * array is not changing?  We don't.
7197          *
7198          * By dropping the lock periodically we can permit other
7199          * activities to be performed while a rxi_ReapConnections
7200          * call is in progress.  The goal of reap connections
7201          * is to clean up quickly without causing large amounts
7202          * of contention.  Therefore, it is important that global
7203          * mutexes not be held for extended periods of time.
7204          */
7205         for (peer_ptr = &rx_peerHashTable[0], peer_end =
7206              &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7207              peer_ptr++) {
7208             struct rx_peer *peer, *next, *prev;
7209
7210             MUTEX_ENTER(&rx_peerHashTable_lock);
7211             for (prev = peer = *peer_ptr; peer; peer = next) {
7212                 next = peer->next;
7213                 code = MUTEX_TRYENTER(&peer->peer_lock);
7214                 if ((code) && (peer->refCount == 0)
7215                     && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
7216                     struct opr_queue *cursor, *store;
7217                     size_t space;
7218
7219                     /*
7220                      * now know that this peer object is one to be
7221                      * removed from the hash table.  Once it is removed
7222                      * it can't be referenced by other threads.
7223                      * Lets remove it first and decrement the struct
7224                      * nPeerStructs count.
7225                      */
7226                     if (peer == *peer_ptr) {
7227                         *peer_ptr = next;
7228                         prev = next;
7229                     } else
7230                         prev->next = next;
7231
7232                     if (rx_stats_active)
7233                         rx_atomic_dec(&rx_stats.nPeerStructs);
7234
7235                     /*
7236                      * Now if we hold references on 'prev' and 'next'
7237                      * we can safely drop the rx_peerHashTable_lock
7238                      * while we destroy this 'peer' object.
7239                      */
7240                     if (next)
7241                         next->refCount++;
7242                     if (prev)
7243                         prev->refCount++;
7244                     MUTEX_EXIT(&rx_peerHashTable_lock);
7245
7246                     MUTEX_EXIT(&peer->peer_lock);
7247                     MUTEX_DESTROY(&peer->peer_lock);
7248
7249                     for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
7250                         unsigned int num_funcs;
7251                         struct rx_interface_stat *rpc_stat
7252                             = opr_queue_Entry(cursor, struct rx_interface_stat,
7253                                              entry);
7254                         if (!rpc_stat)
7255                             break;
7256
7257                         opr_queue_Remove(&rpc_stat->entry);
7258                         opr_queue_Remove(&rpc_stat->entryPeers);
7259
7260                         num_funcs = rpc_stat->stats[0].func_total;
7261                         space =
7262                             sizeof(rx_interface_stat_t) +
7263                             rpc_stat->stats[0].func_total *
7264                             sizeof(rx_function_entry_v1_t);
7265
7266                         rxi_Free(rpc_stat, space);
7267
7268                         MUTEX_ENTER(&rx_rpc_stats);
7269                         rxi_rpc_peer_stat_cnt -= num_funcs;
7270                         MUTEX_EXIT(&rx_rpc_stats);
7271                     }
7272                     rxi_FreePeer(peer);
7273
7274                     /*
7275                      * Regain the rx_peerHashTable_lock and
7276                      * decrement the reference count on 'prev'
7277                      * and 'next'.
7278                      */
7279                     MUTEX_ENTER(&rx_peerHashTable_lock);
7280                     if (next)
7281                         next->refCount--;
7282                     if (prev)
7283                         prev->refCount--;
7284                 } else {
7285                     if (code) {
7286                         MUTEX_EXIT(&peer->peer_lock);
7287                     }
7288                     prev = peer;
7289                 }
7290             }
7291             MUTEX_EXIT(&rx_peerHashTable_lock);
7292         }
7293     }
7294
7295     /* THIS HACK IS A TEMPORARY HACK.  The idea is that the race condition in
7296      * rxi_AllocSendPacket, if it hits, will be handled at the next conn
7297      * GC, just below.  Really, we shouldn't have to keep moving packets from
7298      * one place to another, but instead ought to always know if we can
7299      * afford to hold onto a packet in its particular use.  */
7300     MUTEX_ENTER(&rx_freePktQ_lock);
7301     if (rx_waitingForPackets) {
7302         rx_waitingForPackets = 0;
7303 #ifdef  RX_ENABLE_LOCKS
7304         CV_BROADCAST(&rx_waitingForPackets_cv);
7305 #else
7306         osi_rxWakeup(&rx_waitingForPackets);
7307 #endif
7308     }
7309     MUTEX_EXIT(&rx_freePktQ_lock);
7310
7311     when = now;
7312     when.sec += RX_REAP_TIME;   /* Check every RX_REAP_TIME seconds */
7313     event = rxevent_Post(&when, &now, rxi_ReapConnections, 0, NULL, 0);
7314     rxevent_Put(&event);
7315 }
7316
7317
7318 /* rxs_Release - This isn't strictly necessary but, since the macro name from
7319  * rx.h is sort of strange this is better.  This is called with a security
7320  * object before it is discarded.  Each connection using a security object has
7321  * its own refcount to the object so it won't actually be freed until the last
7322  * connection is destroyed.
7323  *
7324  * This is the only rxs module call.  A hold could also be written but no one
7325  * needs it. */
7326
7327 int
7328 rxs_Release(struct rx_securityClass *aobj)
7329 {
7330     return RXS_Close(aobj);
7331 }
7332
7333 void
7334 rxi_DebugInit(void)
7335 {
7336 #ifdef RXDEBUG
7337 #ifdef AFS_NT40_ENV
7338 #define TRACE_OPTION_RX_DEBUG 16
7339     HKEY parmKey;
7340     DWORD dummyLen;
7341     DWORD TraceOption;
7342     long code;
7343
7344     rxdebug_active = 0;
7345
7346     code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
7347                          0, KEY_QUERY_VALUE, &parmKey);
7348     if (code != ERROR_SUCCESS)
7349         return;
7350
7351     dummyLen = sizeof(TraceOption);
7352     code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
7353                            (BYTE *) &TraceOption, &dummyLen);
7354     if (code == ERROR_SUCCESS) {
7355         rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
7356     }
7357     RegCloseKey (parmKey);
7358 #endif /* AFS_NT40_ENV */
7359 #endif
7360 }
7361
7362 void
7363 rx_DebugOnOff(int on)
7364 {
7365 #ifdef RXDEBUG
7366 #ifdef AFS_NT40_ENV
7367     rxdebug_active = on;
7368 #endif
7369 #endif
7370 }
7371
7372 void
7373 rx_StatsOnOff(int on)
7374 {
7375     rx_stats_active = on;
7376 }
7377
7378
7379 /* Don't call this debugging routine directly; use dpf */
7380 void
7381 rxi_DebugPrint(char *format, ...)
7382 {
7383 #ifdef RXDEBUG
7384     va_list ap;
7385 #ifdef AFS_NT40_ENV
7386     char msg[512];
7387     char tformat[256];
7388     size_t len;
7389
7390     va_start(ap, format);
7391
7392     len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7393
7394     if (len > 0) {
7395         len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7396         if (len > 0)
7397             OutputDebugString(msg);
7398     }
7399     va_end(ap);
7400 #else
7401     struct clock now;
7402
7403     va_start(ap, format);
7404
7405     clock_GetTime(&now);
7406     fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7407             (unsigned int)now.usec);
7408     vfprintf(rx_Log, format, ap);
7409     va_end(ap);
7410 #endif
7411 #endif
7412 }
7413
7414 #ifndef KERNEL
7415 /*
7416  * This function is used to process the rx_stats structure that is local
7417  * to a process as well as an rx_stats structure received from a remote
7418  * process (via rxdebug).  Therefore, it needs to do minimal version
7419  * checking.
7420  */
7421 void
7422 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7423                    afs_int32 freePackets, char version)
7424 {
7425     int i;
7426
7427     if (size != sizeof(struct rx_statistics)) {
7428         fprintf(file,
7429                 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7430                 size, sizeof(struct rx_statistics));
7431     }
7432
7433     fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7434             s->packetRequests);
7435
7436     if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7437         fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7438                 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7439                 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7440                 s->specialPktAllocFailures);
7441     } else {
7442         fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7443                 s->receivePktAllocFailures, s->sendPktAllocFailures,
7444                 s->specialPktAllocFailures);
7445     }
7446
7447     fprintf(file,
7448             "   greedy %u, " "bogusReads %u (last from host %x), "
7449             "noPackets %u, " "noBuffers %u, " "selects %u, "
7450             "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7451             s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7452             s->selects, s->sendSelects);
7453
7454     fprintf(file, "   packets read: ");
7455     for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7456         fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7457     }
7458     fprintf(file, "\n");
7459
7460     fprintf(file,
7461             "   other read counters: data %u, " "ack %u, " "dup %u "
7462             "spurious %u " "dally %u\n", s->dataPacketsRead,
7463             s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7464             s->ignorePacketDally);
7465
7466     fprintf(file, "   packets sent: ");
7467     for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7468         fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7469     }
7470     fprintf(file, "\n");
7471
7472     fprintf(file,
7473             "   other send counters: ack %u, " "data %u (not resends), "
7474             "resends %u, " "pushed %u, " "acked&ignored %u\n",
7475             s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7476             s->dataPacketsPushed, s->ignoreAckedPacket);
7477
7478     fprintf(file,
7479             "   \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7480             s->netSendFailures, (int)s->fatalErrors);
7481
7482     if (s->nRttSamples) {
7483         fprintf(file, "   Average rtt is %0.3f, with %d samples\n",
7484                 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7485
7486         fprintf(file, "   Minimum rtt is %0.3f, maximum is %0.3f\n",
7487                 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7488     }
7489
7490     fprintf(file,
7491             "   %d server connections, " "%d client connections, "
7492             "%d peer structs, " "%d call structs, " "%d free call structs\n",
7493             s->nServerConns, s->nClientConns, s->nPeerStructs,
7494             s->nCallStructs, s->nFreeCallStructs);
7495
7496 #if     !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7497     fprintf(file, "   %d clock updates\n", clock_nUpdates);
7498 #endif
7499 }
7500
7501 /* for backward compatibility */
7502 void
7503 rx_PrintStats(FILE * file)
7504 {
7505     MUTEX_ENTER(&rx_stats_mutex);
7506     rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7507                        sizeof(rx_stats), rx_nFreePackets,
7508                        RX_DEBUGI_VERSION);
7509     MUTEX_EXIT(&rx_stats_mutex);
7510 }
7511
7512 void
7513 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7514 {
7515     fprintf(file, "Peer %x.%d.\n",
7516             ntohl(peer->host), (int)ntohs(peer->port));
7517
7518     fprintf(file,
7519             "   Rtt %d, " "total sent %d, " "resent %d\n",
7520             peer->rtt, peer->nSent, peer->reSends);
7521
7522     fprintf(file, "   Packet size %d\n", peer->ifMTU);
7523 }
7524 #endif
7525
7526 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7527 /*
7528  * This mutex protects the following static variables:
7529  * counter
7530  */
7531
7532 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7533 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7534 #else
7535 #define LOCK_RX_DEBUG
7536 #define UNLOCK_RX_DEBUG
7537 #endif /* AFS_PTHREAD_ENV */
7538
7539 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7540 static int
7541 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7542               u_char type, void *inputData, size_t inputLength,
7543               void *outputData, size_t outputLength)
7544 {
7545     static afs_int32 counter = 100;
7546     time_t waitTime, waitCount;
7547     struct rx_header theader;
7548     char tbuffer[1500];
7549     afs_int32 code;
7550     struct timeval tv_now, tv_wake, tv_delta;
7551     struct sockaddr_in taddr, faddr;
7552 #ifdef AFS_NT40_ENV
7553     int faddrLen;
7554 #else
7555     socklen_t faddrLen;
7556 #endif
7557     fd_set imask;
7558     char *tp;
7559
7560     waitTime = 1;
7561     waitCount = 5;
7562     LOCK_RX_DEBUG;
7563     counter++;
7564     UNLOCK_RX_DEBUG;
7565     tp = &tbuffer[sizeof(struct rx_header)];
7566     taddr.sin_family = AF_INET;
7567     taddr.sin_port = remotePort;
7568     taddr.sin_addr.s_addr = remoteAddr;
7569     memset(&taddr.sin_zero, 0, sizeof(taddr.sin_zero));
7570 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7571     taddr.sin_len = sizeof(struct sockaddr_in);
7572 #endif
7573     while (1) {
7574         memset(&theader, 0, sizeof(theader));
7575         theader.epoch = htonl(999);
7576         theader.cid = 0;
7577         theader.callNumber = htonl(counter);
7578         theader.seq = 0;
7579         theader.serial = 0;
7580         theader.type = type;
7581         theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7582         theader.serviceId = 0;
7583
7584         memcpy(tbuffer, &theader, sizeof(theader));
7585         memcpy(tp, inputData, inputLength);
7586         code =
7587             sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7588                    (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7589
7590         /* see if there's a packet available */
7591         gettimeofday(&tv_wake, NULL);
7592         tv_wake.tv_sec += waitTime;
7593         for (;;) {
7594             FD_ZERO(&imask);
7595             FD_SET(socket, &imask);
7596             tv_delta.tv_sec = tv_wake.tv_sec;
7597             tv_delta.tv_usec = tv_wake.tv_usec;
7598             gettimeofday(&tv_now, NULL);
7599
7600             if (tv_delta.tv_usec < tv_now.tv_usec) {
7601                 /* borrow */
7602                 tv_delta.tv_usec += 1000000;
7603                 tv_delta.tv_sec--;
7604             }
7605             tv_delta.tv_usec -= tv_now.tv_usec;
7606
7607             if (tv_delta.tv_sec < tv_now.tv_sec) {
7608                 /* time expired */
7609                 break;
7610             }
7611             tv_delta.tv_sec -= tv_now.tv_sec;
7612
7613 #ifdef AFS_NT40_ENV
7614             code = select(0, &imask, 0, 0, &tv_delta);
7615 #else /* AFS_NT40_ENV */
7616             code = select(socket + 1, &imask, 0, 0, &tv_delta);
7617 #endif /* AFS_NT40_ENV */
7618             if (code == 1 && FD_ISSET(socket, &imask)) {
7619                 /* now receive a packet */
7620                 faddrLen = sizeof(struct sockaddr_in);
7621                 code =
7622                     recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7623                              (struct sockaddr *)&faddr, &faddrLen);
7624
7625                 if (code > 0) {
7626                     memcpy(&theader, tbuffer, sizeof(struct rx_header));
7627                     if (counter == ntohl(theader.callNumber))
7628                         goto success;
7629                     continue;
7630                 }
7631             }
7632             break;
7633         }
7634
7635         /* see if we've timed out */
7636         if (!--waitCount) {
7637             return -1;
7638         }
7639         waitTime <<= 1;
7640     }
7641
7642  success:
7643     code -= sizeof(struct rx_header);
7644     if (code > outputLength)
7645         code = outputLength;
7646     memcpy(outputData, tp, code);
7647     return code;
7648 }
7649 #endif /* RXDEBUG */
7650
7651 afs_int32
7652 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7653                   afs_uint16 remotePort, struct rx_debugStats * stat,
7654                   afs_uint32 * supportedValues)
7655 {
7656 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7657     afs_int32 rc = 0;
7658     struct rx_debugIn in;
7659
7660     *supportedValues = 0;
7661     in.type = htonl(RX_DEBUGI_GETSTATS);
7662     in.index = 0;
7663
7664     rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7665                        &in, sizeof(in), stat, sizeof(*stat));
7666
7667     /*
7668      * If the call was successful, fixup the version and indicate
7669      * what contents of the stat structure are valid.
7670      * Also do net to host conversion of fields here.
7671      */
7672
7673     if (rc >= 0) {
7674         if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7675             *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7676         }
7677         if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7678             *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7679         }
7680         if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7681             *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7682         }
7683         if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7684             *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7685         }
7686         if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7687             *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7688         }
7689         if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7690             *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7691         }
7692         if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7693             *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7694         }
7695         if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7696             *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7697         }
7698         if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7699             *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7700         }
7701         stat->nFreePackets = ntohl(stat->nFreePackets);
7702         stat->packetReclaims = ntohl(stat->packetReclaims);
7703         stat->callsExecuted = ntohl(stat->callsExecuted);
7704         stat->nWaiting = ntohl(stat->nWaiting);
7705         stat->idleThreads = ntohl(stat->idleThreads);
7706         stat->nWaited = ntohl(stat->nWaited);
7707         stat->nPackets = ntohl(stat->nPackets);
7708     }
7709 #else
7710     afs_int32 rc = -1;
7711 #endif
7712     return rc;
7713 }
7714
7715 afs_int32
7716 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7717                   afs_uint16 remotePort, struct rx_statistics * stat,
7718                   afs_uint32 * supportedValues)
7719 {
7720 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7721     afs_int32 rc = 0;
7722     struct rx_debugIn in;
7723     afs_int32 *lp = (afs_int32 *) stat;
7724     int i;
7725
7726     /*
7727      * supportedValues is currently unused, but added to allow future
7728      * versioning of this function.
7729      */
7730
7731     *supportedValues = 0;
7732     in.type = htonl(RX_DEBUGI_RXSTATS);
7733     in.index = 0;
7734     memset(stat, 0, sizeof(*stat));
7735
7736     rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7737                        &in, sizeof(in), stat, sizeof(*stat));
7738
7739     if (rc >= 0) {
7740
7741         /*
7742          * Do net to host conversion here
7743          */
7744
7745         for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7746             *lp = ntohl(*lp);
7747         }
7748     }
7749 #else
7750     afs_int32 rc = -1;
7751 #endif
7752     return rc;
7753 }
7754
7755 afs_int32
7756 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7757                     afs_uint16 remotePort, size_t version_length,
7758                     char *version)
7759 {
7760 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7761     char a[1] = { 0 };
7762     return MakeDebugCall(socket, remoteAddr, remotePort,
7763                          RX_PACKET_TYPE_VERSION, a, 1, version,
7764                          version_length);
7765 #else
7766     return -1;
7767 #endif
7768 }
7769
7770 afs_int32
7771 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7772                         afs_uint16 remotePort, afs_int32 * nextConnection,
7773                         int allConnections, afs_uint32 debugSupportedValues,
7774                         struct rx_debugConn * conn,
7775                         afs_uint32 * supportedValues)
7776 {
7777 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7778     afs_int32 rc = 0;
7779     struct rx_debugIn in;
7780     int i;
7781
7782     /*
7783      * supportedValues is currently unused, but added to allow future
7784      * versioning of this function.
7785      */
7786
7787     *supportedValues = 0;
7788     if (allConnections) {
7789         in.type = htonl(RX_DEBUGI_GETALLCONN);
7790     } else {
7791         in.type = htonl(RX_DEBUGI_GETCONN);
7792     }
7793     in.index = htonl(*nextConnection);
7794     memset(conn, 0, sizeof(*conn));
7795
7796     rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7797                        &in, sizeof(in), conn, sizeof(*conn));
7798
7799     if (rc >= 0) {
7800         *nextConnection += 1;
7801
7802         /*
7803          * Convert old connection format to new structure.
7804          */
7805
7806         if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7807             struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7808 #define MOVEvL(a) (conn->a = vL->a)
7809
7810             /* any old or unrecognized version... */
7811             for (i = 0; i < RX_MAXCALLS; i++) {
7812                 MOVEvL(callState[i]);
7813                 MOVEvL(callMode[i]);
7814                 MOVEvL(callFlags[i]);
7815                 MOVEvL(callOther[i]);
7816             }
7817             if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7818                 MOVEvL(secStats.type);
7819                 MOVEvL(secStats.level);
7820                 MOVEvL(secStats.flags);
7821                 MOVEvL(secStats.expires);
7822                 MOVEvL(secStats.packetsReceived);
7823                 MOVEvL(secStats.packetsSent);
7824                 MOVEvL(secStats.bytesReceived);
7825                 MOVEvL(secStats.bytesSent);
7826             }
7827         }
7828
7829         /*
7830          * Do net to host conversion here
7831          * NOTE:
7832          *    I don't convert host or port since we are most likely
7833          *    going to want these in NBO.
7834          */
7835         conn->cid = ntohl(conn->cid);
7836         conn->serial = ntohl(conn->serial);
7837         for (i = 0; i < RX_MAXCALLS; i++) {
7838             conn->callNumber[i] = ntohl(conn->callNumber[i]);
7839         }
7840         conn->error = ntohl(conn->error);
7841         conn->secStats.flags = ntohl(conn->secStats.flags);
7842         conn->secStats.expires = ntohl(conn->secStats.expires);
7843         conn->secStats.packetsReceived =
7844             ntohl(conn->secStats.packetsReceived);
7845         conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7846         conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7847         conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7848         conn->epoch = ntohl(conn->epoch);
7849         conn->natMTU = ntohl(conn->natMTU);
7850     }
7851 #else
7852     afs_int32 rc = -1;
7853 #endif
7854     return rc;
7855 }
7856
7857 afs_int32
7858 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7859                   afs_uint16 remotePort, afs_int32 * nextPeer,
7860                   afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7861                   afs_uint32 * supportedValues)
7862 {
7863 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7864     afs_int32 rc = 0;
7865     struct rx_debugIn in;
7866
7867     /*
7868      * supportedValues is currently unused, but added to allow future
7869      * versioning of this function.
7870      */
7871
7872     *supportedValues = 0;
7873     in.type = htonl(RX_DEBUGI_GETPEER);
7874     in.index = htonl(*nextPeer);
7875     memset(peer, 0, sizeof(*peer));
7876
7877     rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7878                        &in, sizeof(in), peer, sizeof(*peer));
7879
7880     if (rc >= 0) {
7881         *nextPeer += 1;
7882
7883         /*
7884          * Do net to host conversion here
7885          * NOTE:
7886          *    I don't convert host or port since we are most likely
7887          *    going to want these in NBO.
7888          */
7889         peer->ifMTU = ntohs(peer->ifMTU);
7890         peer->idleWhen = ntohl(peer->idleWhen);
7891         peer->refCount = ntohs(peer->refCount);
7892         peer->rtt = ntohl(peer->rtt);
7893         peer->rtt_dev = ntohl(peer->rtt_dev);
7894         peer->timeout.sec = 0;
7895         peer->timeout.usec = 0;
7896         peer->nSent = ntohl(peer->nSent);
7897         peer->reSends = ntohl(peer->reSends);
7898         peer->natMTU = ntohs(peer->natMTU);
7899         peer->maxMTU = ntohs(peer->maxMTU);
7900         peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7901         peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7902         peer->MTU = ntohs(peer->MTU);
7903         peer->cwind = ntohs(peer->cwind);
7904         peer->nDgramPackets = ntohs(peer->nDgramPackets);
7905         peer->congestSeq = ntohs(peer->congestSeq);
7906         peer->bytesSent.high = ntohl(peer->bytesSent.high);
7907         peer->bytesSent.low = ntohl(peer->bytesSent.low);
7908         peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7909         peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7910     }
7911 #else
7912     afs_int32 rc = -1;
7913 #endif
7914     return rc;
7915 }
7916
7917 afs_int32
7918 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7919                 struct rx_debugPeer * peerStats)
7920 {
7921         struct rx_peer *tp;
7922         afs_int32 error = 1; /* default to "did not succeed" */
7923         afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7924
7925         MUTEX_ENTER(&rx_peerHashTable_lock);
7926         for(tp = rx_peerHashTable[hashValue];
7927               tp != NULL; tp = tp->next) {
7928                 if (tp->host == peerHost)
7929                         break;
7930         }
7931
7932         if (tp) {
7933                 tp->refCount++;
7934                 MUTEX_EXIT(&rx_peerHashTable_lock);
7935
7936                 error = 0;
7937
7938                 MUTEX_ENTER(&tp->peer_lock);
7939                 peerStats->host = tp->host;
7940                 peerStats->port = tp->port;
7941                 peerStats->ifMTU = tp->ifMTU;
7942                 peerStats->idleWhen = tp->idleWhen;
7943                 peerStats->refCount = tp->refCount;
7944                 peerStats->burstSize = 0;
7945                 peerStats->burst = 0;
7946                 peerStats->burstWait.sec = 0;
7947                 peerStats->burstWait.usec = 0;
7948                 peerStats->rtt = tp->rtt;
7949                 peerStats->rtt_dev = tp->rtt_dev;
7950                 peerStats->timeout.sec = 0;
7951                 peerStats->timeout.usec = 0;
7952                 peerStats->nSent = tp->nSent;
7953                 peerStats->reSends = tp->reSends;
7954                 peerStats->natMTU = tp->natMTU;
7955                 peerStats->maxMTU = tp->maxMTU;
7956                 peerStats->maxDgramPackets = tp->maxDgramPackets;
7957                 peerStats->ifDgramPackets = tp->ifDgramPackets;
7958                 peerStats->MTU = tp->MTU;
7959                 peerStats->cwind = tp->cwind;
7960                 peerStats->nDgramPackets = tp->nDgramPackets;
7961                 peerStats->congestSeq = tp->congestSeq;
7962                 peerStats->bytesSent.high = tp->bytesSent >> 32;
7963                 peerStats->bytesSent.low = tp->bytesSent & MAX_AFS_UINT32;
7964                 peerStats->bytesReceived.high = tp->bytesReceived >> 32;
7965                 peerStats->bytesReceived.low
7966                                 = tp->bytesReceived & MAX_AFS_UINT32;
7967                 MUTEX_EXIT(&tp->peer_lock);
7968
7969                 MUTEX_ENTER(&rx_peerHashTable_lock);
7970                 tp->refCount--;
7971         }
7972         MUTEX_EXIT(&rx_peerHashTable_lock);
7973
7974         return error;
7975 }
7976
7977 void
7978 shutdown_rx(void)
7979 {
7980     struct rx_serverQueueEntry *np;
7981     int i, j;
7982 #ifndef KERNEL
7983     struct rx_call *call;
7984     struct rx_serverQueueEntry *sq;
7985 #endif /* KERNEL */
7986
7987     LOCK_RX_INIT;
7988     if (!rxi_IsRunning()) {
7989         UNLOCK_RX_INIT;
7990         return;                 /* Already shutdown. */
7991     }
7992     rx_atomic_set(&rxi_running, 0);
7993 #ifndef KERNEL
7994     rx_port = 0;
7995 #ifndef AFS_PTHREAD_ENV
7996     FD_ZERO(&rx_selectMask);
7997 #endif /* AFS_PTHREAD_ENV */
7998     rxi_dataQuota = RX_MAX_QUOTA;
7999 #ifndef AFS_PTHREAD_ENV
8000     rxi_StopListener();
8001 #endif /* AFS_PTHREAD_ENV */
8002     shutdown_rxevent();
8003     rx_epoch = 0;
8004 #ifndef AFS_PTHREAD_ENV
8005 #ifndef AFS_USE_GETTIMEOFDAY
8006     clock_UnInit();
8007 #endif /* AFS_USE_GETTIMEOFDAY */
8008 #endif /* AFS_PTHREAD_ENV */
8009
8010     while (!opr_queue_IsEmpty(&rx_freeCallQueue)) {
8011         call = opr_queue_First(&rx_freeCallQueue, struct rx_call, entry);
8012         opr_queue_Remove(&call->entry);
8013         rxi_Free(call, sizeof(struct rx_call));
8014     }
8015
8016     while (!opr_queue_IsEmpty(&rx_idleServerQueue)) {
8017         sq = opr_queue_First(&rx_idleServerQueue, struct rx_serverQueueEntry,
8018                             entry);
8019         opr_queue_Remove(&sq->entry);
8020     }
8021 #endif /* KERNEL */
8022
8023     {
8024         struct rx_peer **peer_ptr, **peer_end;
8025         for (peer_ptr = &rx_peerHashTable[0], peer_end =
8026              &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
8027              peer_ptr++) {
8028             struct rx_peer *peer, *next;
8029
8030             MUTEX_ENTER(&rx_peerHashTable_lock);
8031             for (peer = *peer_ptr; peer; peer = next) {
8032                 struct opr_queue *cursor, *store;
8033                 size_t space;
8034
8035                 MUTEX_ENTER(&rx_rpc_stats);
8036                 MUTEX_ENTER(&peer->peer_lock);
8037                 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
8038                     unsigned int num_funcs;
8039                     struct rx_interface_stat *rpc_stat
8040                         = opr_queue_Entry(cursor, struct rx_interface_stat,
8041                                          entry);
8042                     if (!rpc_stat)
8043                         break;
8044                     opr_queue_Remove(&rpc_stat->entry);
8045                     opr_queue_Remove(&rpc_stat->entryPeers);
8046                     num_funcs = rpc_stat->stats[0].func_total;
8047                     space =
8048                         sizeof(rx_interface_stat_t) +
8049                         rpc_stat->stats[0].func_total *
8050                         sizeof(rx_function_entry_v1_t);
8051
8052                     rxi_Free(rpc_stat, space);
8053
8054                     /* rx_rpc_stats must be held */
8055                     rxi_rpc_peer_stat_cnt -= num_funcs;
8056                 }
8057                 MUTEX_EXIT(&peer->peer_lock);
8058                 MUTEX_EXIT(&rx_rpc_stats);
8059
8060                 next = peer->next;
8061                 rxi_FreePeer(peer);
8062                 if (rx_stats_active)
8063                     rx_atomic_dec(&rx_stats.nPeerStructs);
8064             }
8065             MUTEX_EXIT(&rx_peerHashTable_lock);
8066         }
8067     }
8068     for (i = 0; i < RX_MAX_SERVICES; i++) {
8069         if (rx_services[i])
8070             rxi_Free(rx_services[i], sizeof(*rx_services[i]));
8071     }
8072     for (i = 0; i < rx_hashTableSize; i++) {
8073         struct rx_connection *tc, *ntc;
8074         MUTEX_ENTER(&rx_connHashTable_lock);
8075         for (tc = rx_connHashTable[i]; tc; tc = ntc) {
8076             ntc = tc->next;
8077             for (j = 0; j < RX_MAXCALLS; j++) {
8078                 if (tc->call[j]) {
8079                     rxi_Free(tc->call[j], sizeof(*tc->call[j]));
8080                 }
8081             }
8082             rxi_Free(tc, sizeof(*tc));
8083         }
8084         MUTEX_EXIT(&rx_connHashTable_lock);
8085     }
8086
8087     MUTEX_ENTER(&freeSQEList_lock);
8088
8089     while (!opr_queue_IsEmpty(&rx_freeServerQueue)) {
8090         np = opr_queue_First(&rx_freeServerQueue, struct rx_serverQueueEntry,
8091                              entry);
8092         opr_queue_Remove(&np->entry);
8093         MUTEX_DESTROY(&np->lock);
8094         rxi_Free(np, sizeof(*np));
8095     }
8096
8097     MUTEX_EXIT(&freeSQEList_lock);
8098     MUTEX_DESTROY(&freeSQEList_lock);
8099     MUTEX_DESTROY(&rx_freeCallQueue_lock);
8100     MUTEX_DESTROY(&rx_connHashTable_lock);
8101     MUTEX_DESTROY(&rx_peerHashTable_lock);
8102     MUTEX_DESTROY(&rx_serverPool_lock);
8103
8104     osi_Free(rx_connHashTable,
8105              rx_hashTableSize * sizeof(struct rx_connection *));
8106     osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
8107
8108     UNPIN(rx_connHashTable,
8109           rx_hashTableSize * sizeof(struct rx_connection *));
8110     UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
8111
8112     MUTEX_ENTER(&rx_quota_mutex);
8113     rxi_dataQuota = RX_MAX_QUOTA;
8114     rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
8115     MUTEX_EXIT(&rx_quota_mutex);
8116     UNLOCK_RX_INIT;
8117 }
8118
8119 #ifndef KERNEL
8120
8121 /*
8122  * Routines to implement connection specific data.
8123  */
8124
8125 int
8126 rx_KeyCreate(rx_destructor_t rtn)
8127 {
8128     int key;
8129     MUTEX_ENTER(&rxi_keyCreate_lock);
8130     key = rxi_keyCreate_counter++;
8131     rxi_keyCreate_destructor = (rx_destructor_t *)
8132         realloc((void *)rxi_keyCreate_destructor,
8133                 (key + 1) * sizeof(rx_destructor_t));
8134     rxi_keyCreate_destructor[key] = rtn;
8135     MUTEX_EXIT(&rxi_keyCreate_lock);
8136     return key;
8137 }
8138
8139 void
8140 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
8141 {
8142     int i;
8143     MUTEX_ENTER(&conn->conn_data_lock);
8144     if (!conn->specific) {
8145         conn->specific = malloc((key + 1) * sizeof(void *));
8146         for (i = 0; i < key; i++)
8147             conn->specific[i] = NULL;
8148         conn->nSpecific = key + 1;
8149         conn->specific[key] = ptr;
8150     } else if (key >= conn->nSpecific) {
8151         conn->specific = (void **)
8152             realloc(conn->specific, (key + 1) * sizeof(void *));
8153         for (i = conn->nSpecific; i < key; i++)
8154             conn->specific[i] = NULL;
8155         conn->nSpecific = key + 1;
8156         conn->specific[key] = ptr;
8157     } else {
8158         if (conn->specific[key] && rxi_keyCreate_destructor[key])
8159             (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
8160         conn->specific[key] = ptr;
8161     }
8162     MUTEX_EXIT(&conn->conn_data_lock);
8163 }
8164
8165 void
8166 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
8167 {
8168     int i;
8169     MUTEX_ENTER(&svc->svc_data_lock);
8170     if (!svc->specific) {
8171         svc->specific = malloc((key + 1) * sizeof(void *));
8172         for (i = 0; i < key; i++)
8173             svc->specific[i] = NULL;
8174         svc->nSpecific = key + 1;
8175         svc->specific[key] = ptr;
8176     } else if (key >= svc->nSpecific) {
8177         svc->specific = (void **)
8178             realloc(svc->specific, (key + 1) * sizeof(void *));
8179         for (i = svc->nSpecific; i < key; i++)
8180             svc->specific[i] = NULL;
8181         svc->nSpecific = key + 1;
8182         svc->specific[key] = ptr;
8183     } else {
8184         if (svc->specific[key] && rxi_keyCreate_destructor[key])
8185             (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
8186         svc->specific[key] = ptr;
8187     }
8188     MUTEX_EXIT(&svc->svc_data_lock);
8189 }
8190
8191 void *
8192 rx_GetSpecific(struct rx_connection *conn, int key)
8193 {
8194     void *ptr;
8195     MUTEX_ENTER(&conn->conn_data_lock);
8196     if (key >= conn->nSpecific)
8197         ptr = NULL;
8198     else
8199         ptr = conn->specific[key];
8200     MUTEX_EXIT(&conn->conn_data_lock);
8201     return ptr;
8202 }
8203
8204 void *
8205 rx_GetServiceSpecific(struct rx_service *svc, int key)
8206 {
8207     void *ptr;
8208     MUTEX_ENTER(&svc->svc_data_lock);
8209     if (key >= svc->nSpecific)
8210         ptr = NULL;
8211     else
8212         ptr = svc->specific[key];
8213     MUTEX_EXIT(&svc->svc_data_lock);
8214     return ptr;
8215 }
8216
8217
8218 #endif /* !KERNEL */
8219
8220 /*
8221  * processStats is a queue used to store the statistics for the local
8222  * process.  Its contents are similar to the contents of the rpcStats
8223  * queue on a rx_peer structure, but the actual data stored within
8224  * this queue contains totals across the lifetime of the process (assuming
8225  * the stats have not been reset) - unlike the per peer structures
8226  * which can come and go based upon the peer lifetime.
8227  */
8228
8229 static struct opr_queue processStats = { &processStats, &processStats };
8230
8231 /*
8232  * peerStats is a queue used to store the statistics for all peer structs.
8233  * Its contents are the union of all the peer rpcStats queues.
8234  */
8235
8236 static struct opr_queue peerStats = { &peerStats, &peerStats };
8237
8238 /*
8239  * rxi_monitor_processStats is used to turn process wide stat collection
8240  * on and off
8241  */
8242
8243 static int rxi_monitor_processStats = 0;
8244
8245 /*
8246  * rxi_monitor_peerStats is used to turn per peer stat collection on and off
8247  */
8248
8249 static int rxi_monitor_peerStats = 0;
8250
8251
8252 void
8253 rxi_ClearRPCOpStat(rx_function_entry_v1_p rpc_stat)
8254 {
8255     rpc_stat->invocations = 0;
8256     rpc_stat->bytes_sent = 0;
8257     rpc_stat->bytes_rcvd = 0;
8258     rpc_stat->queue_time_sum.sec = 0;
8259     rpc_stat->queue_time_sum.usec = 0;
8260     rpc_stat->queue_time_sum_sqr.sec = 0;
8261     rpc_stat->queue_time_sum_sqr.usec = 0;
8262     rpc_stat->queue_time_min.sec = 9999999;
8263     rpc_stat->queue_time_min.usec = 9999999;
8264     rpc_stat->queue_time_max.sec = 0;
8265     rpc_stat->queue_time_max.usec = 0;
8266     rpc_stat->execution_time_sum.sec = 0;
8267     rpc_stat->execution_time_sum.usec = 0;
8268     rpc_stat->execution_time_sum_sqr.sec = 0;
8269     rpc_stat->execution_time_sum_sqr.usec = 0;
8270     rpc_stat->execution_time_min.sec = 9999999;
8271     rpc_stat->execution_time_min.usec = 9999999;
8272     rpc_stat->execution_time_max.sec = 0;
8273     rpc_stat->execution_time_max.usec = 0;
8274 }
8275
8276 /*!
8277  * Given all of the information for a particular rpc
8278  * call, find or create (if requested) the stat structure for the rpc.
8279  *
8280  * @param stats
8281  *      the queue of stats that will be updated with the new value
8282  *
8283  * @param rxInterface
8284  *      a unique number that identifies the rpc interface
8285  *
8286  * @param totalFunc
8287  *      the total number of functions in this interface. this is only
8288  *      required if create is true
8289  *
8290  * @param isServer
8291  *      if true, this invocation was made to a server
8292  *
8293  * @param remoteHost
8294  *      the ip address of the remote host. this is only required if create
8295  *      and addToPeerList are true
8296  *
8297  * @param remotePort
8298  *      the port of the remote host. this is only required if create
8299  *      and addToPeerList are true
8300  *
8301  * @param addToPeerList
8302  *      if != 0, add newly created stat to the global peer list
8303  *
8304  * @param counter
8305  *      if a new stats structure is allocated, the counter will
8306  *      be updated with the new number of allocated stat structures.
8307  *      only required if create is true
8308  *
8309  * @param create
8310  *      if no stats structure exists, allocate one
8311  *
8312  */
8313
8314 static rx_interface_stat_p
8315 rxi_FindRpcStat(struct opr_queue *stats, afs_uint32 rxInterface,
8316                 afs_uint32 totalFunc, int isServer, afs_uint32 remoteHost,
8317                 afs_uint32 remotePort, int addToPeerList,
8318                 unsigned int *counter, int create)
8319 {
8320     rx_interface_stat_p rpc_stat = NULL;
8321     struct opr_queue *cursor;
8322
8323     /*
8324      * See if there's already a structure for this interface
8325      */
8326
8327     for (opr_queue_Scan(stats, cursor)) {
8328         rpc_stat = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8329
8330         if ((rpc_stat->stats[0].interfaceId == rxInterface)
8331             && (rpc_stat->stats[0].remote_is_server == isServer))
8332             break;
8333     }
8334
8335     /* if they didn't ask us to create, we're done */
8336     if (!create) {
8337         if (opr_queue_IsEnd(stats, cursor))
8338             return NULL;
8339         else
8340             return rpc_stat;
8341     }
8342
8343     /* can't proceed without these */
8344     if (!totalFunc || !counter)
8345         return NULL;
8346
8347     /*
8348      * Didn't find a match so allocate a new structure and add it to the
8349      * queue.
8350      */
8351
8352     if (opr_queue_IsEnd(stats, cursor) || (rpc_stat == NULL)
8353         || (rpc_stat->stats[0].interfaceId != rxInterface)
8354         || (rpc_stat->stats[0].remote_is_server != isServer)) {
8355         int i;
8356         size_t space;
8357
8358         space =
8359             sizeof(rx_interface_stat_t) +
8360             totalFunc * sizeof(rx_function_entry_v1_t);
8361
8362         rpc_stat = rxi_Alloc(space);
8363         if (rpc_stat == NULL)
8364             return NULL;
8365
8366         *counter += totalFunc;
8367         for (i = 0; i < totalFunc; i++) {
8368             rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8369             rpc_stat->stats[i].remote_peer = remoteHost;
8370             rpc_stat->stats[i].remote_port = remotePort;
8371             rpc_stat->stats[i].remote_is_server = isServer;
8372             rpc_stat->stats[i].interfaceId = rxInterface;
8373             rpc_stat->stats[i].func_total = totalFunc;
8374             rpc_stat->stats[i].func_index = i;
8375         }
8376         opr_queue_Prepend(stats, &rpc_stat->entry);
8377         if (addToPeerList) {
8378             opr_queue_Prepend(&peerStats, &rpc_stat->entryPeers);
8379         }
8380     }
8381     return rpc_stat;
8382 }
8383
8384 void
8385 rx_ClearProcessRPCStats(afs_int32 rxInterface)
8386 {
8387     rx_interface_stat_p rpc_stat;
8388     int totalFunc, i;
8389
8390     if (rxInterface == -1)
8391         return;
8392
8393     MUTEX_ENTER(&rx_rpc_stats);
8394     rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8395                                0, 0, 0, 0, 0);
8396     if (rpc_stat) {
8397         totalFunc = rpc_stat->stats[0].func_total;
8398         for (i = 0; i < totalFunc; i++)
8399             rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8400     }
8401     MUTEX_EXIT(&rx_rpc_stats);
8402     return;
8403 }
8404
8405 void
8406 rx_ClearPeerRPCStats(afs_int32 rxInterface, afs_uint32 peerHost, afs_uint16 peerPort)
8407 {
8408     rx_interface_stat_p rpc_stat;
8409     int totalFunc, i;
8410     struct rx_peer * peer;
8411
8412     if (rxInterface == -1)
8413         return;
8414
8415     peer = rxi_FindPeer(peerHost, peerPort, 0);
8416     if (!peer)
8417         return;
8418
8419     MUTEX_ENTER(&rx_rpc_stats);
8420     rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
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_CopyProcessRPCStats(afs_uint64 op)
8433 {
8434     rx_interface_stat_p rpc_stat;
8435     rx_function_entry_v1_p rpcop_stat =
8436         rxi_Alloc(sizeof(rx_function_entry_v1_t));
8437     int currentFunc = (op & MAX_AFS_UINT32);
8438     afs_int32 rxInterface = (op >> 32);
8439
8440     if (!rxi_monitor_processStats)
8441         return NULL;
8442
8443     if (rxInterface == -1)
8444         return NULL;
8445
8446     if (rpcop_stat == NULL)
8447         return NULL;
8448
8449     MUTEX_ENTER(&rx_rpc_stats);
8450     rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8451                                0, 0, 0, 0, 0);
8452     if (rpc_stat)
8453         memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8454                sizeof(rx_function_entry_v1_t));
8455     MUTEX_EXIT(&rx_rpc_stats);
8456     if (!rpc_stat) {
8457         rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8458         return NULL;
8459     }
8460     return rpcop_stat;
8461 }
8462
8463 void *
8464 rx_CopyPeerRPCStats(afs_uint64 op, afs_uint32 peerHost, afs_uint16 peerPort)
8465 {
8466     rx_interface_stat_p rpc_stat;
8467     rx_function_entry_v1_p rpcop_stat =
8468         rxi_Alloc(sizeof(rx_function_entry_v1_t));
8469     int currentFunc = (op & MAX_AFS_UINT32);
8470     afs_int32 rxInterface = (op >> 32);
8471     struct rx_peer *peer;
8472
8473     if (!rxi_monitor_peerStats)
8474         return NULL;
8475
8476     if (rxInterface == -1)
8477         return NULL;
8478
8479     if (rpcop_stat == NULL)
8480         return NULL;
8481
8482     peer = rxi_FindPeer(peerHost, peerPort, 0);
8483     if (!peer)
8484         return NULL;
8485
8486     MUTEX_ENTER(&rx_rpc_stats);
8487     rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8488                                0, 0, 0, 0, 0);
8489     if (rpc_stat)
8490         memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8491                sizeof(rx_function_entry_v1_t));
8492     MUTEX_EXIT(&rx_rpc_stats);
8493     if (!rpc_stat) {
8494         rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8495         return NULL;
8496     }
8497     return rpcop_stat;
8498 }
8499
8500 void
8501 rx_ReleaseRPCStats(void *stats)
8502 {
8503     if (stats)
8504         rxi_Free(stats, sizeof(rx_function_entry_v1_t));
8505 }
8506
8507 /*!
8508  * Given all of the information for a particular rpc
8509  * call, create (if needed) and update the stat totals for the rpc.
8510  *
8511  * @param stats
8512  *      the queue of stats that will be updated with the new value
8513  *
8514  * @param rxInterface
8515  *      a unique number that identifies the rpc interface
8516  *
8517  * @param currentFunc
8518  *      the index of the function being invoked
8519  *
8520  * @param totalFunc
8521  *      the total number of functions in this interface
8522  *
8523  * @param queueTime
8524  *      the amount of time this function waited for a thread
8525  *
8526  * @param execTime
8527  *      the amount of time this function invocation took to execute
8528  *
8529  * @param bytesSent
8530  *      the number bytes sent by this invocation
8531  *
8532  * @param bytesRcvd
8533  *      the number bytes received by this invocation
8534  *
8535  * @param isServer
8536  *      if true, this invocation was made to a server
8537  *
8538  * @param remoteHost
8539  *      the ip address of the remote host
8540  *
8541  * @param remotePort
8542  *      the port of the remote host
8543  *
8544  * @param addToPeerList
8545  *      if != 0, add newly created stat to the global peer list
8546  *
8547  * @param counter
8548  *      if a new stats structure is allocated, the counter will
8549  *      be updated with the new number of allocated stat structures
8550  *
8551  */
8552
8553 static int
8554 rxi_AddRpcStat(struct opr_queue *stats, afs_uint32 rxInterface,
8555                afs_uint32 currentFunc, afs_uint32 totalFunc,
8556                struct clock *queueTime, struct clock *execTime,
8557                afs_uint64 bytesSent, afs_uint64 bytesRcvd, int isServer,
8558                afs_uint32 remoteHost, afs_uint32 remotePort,
8559                int addToPeerList, unsigned int *counter)
8560 {
8561     int rc = 0;
8562     rx_interface_stat_p rpc_stat;
8563
8564     rpc_stat = rxi_FindRpcStat(stats, rxInterface, totalFunc, isServer,
8565                                remoteHost, remotePort, addToPeerList, counter,
8566                                1);
8567     if (!rpc_stat) {
8568         rc = -1;
8569         goto fail;
8570     }
8571
8572     /*
8573      * Increment the stats for this function
8574      */
8575
8576     rpc_stat->stats[currentFunc].invocations++;
8577     rpc_stat->stats[currentFunc].bytes_sent += bytesSent;
8578     rpc_stat->stats[currentFunc].bytes_rcvd += bytesRcvd;
8579     clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8580     clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8581     if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8582         rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8583     }
8584     if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8585         rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8586     }
8587     clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8588     clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8589                 execTime);
8590     if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8591         rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8592     }
8593     if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8594         rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8595     }
8596
8597   fail:
8598     return rc;
8599 }
8600
8601 void
8602 rxi_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8603                           afs_uint32 currentFunc, afs_uint32 totalFunc,
8604                           struct clock *queueTime, struct clock *execTime,
8605                           afs_uint64 bytesSent, afs_uint64 bytesRcvd,
8606                           int isServer)
8607 {
8608
8609     if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8610         return;
8611
8612     MUTEX_ENTER(&rx_rpc_stats);
8613
8614     if (rxi_monitor_peerStats) {
8615         MUTEX_ENTER(&peer->peer_lock);
8616         rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8617                        queueTime, execTime, bytesSent, bytesRcvd, isServer,
8618                        peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8619         MUTEX_EXIT(&peer->peer_lock);
8620     }
8621
8622     if (rxi_monitor_processStats) {
8623         rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8624                        queueTime, execTime, bytesSent, bytesRcvd, isServer,
8625                        0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8626     }
8627
8628     MUTEX_EXIT(&rx_rpc_stats);
8629 }
8630
8631 /*!
8632  * Increment the times and count for a particular rpc function.
8633  *
8634  * Traditionally this call was invoked from rxgen stubs. Modern stubs
8635  * call rx_RecordCallStatistics instead, so the public version of this
8636  * function is left purely for legacy callers.
8637  *
8638  * @param peer
8639  *      The peer who invoked the rpc
8640  *
8641  * @param rxInterface
8642  *      A unique number that identifies the rpc interface
8643  *
8644  * @param currentFunc
8645  *      The index of the function being invoked
8646  *
8647  * @param totalFunc
8648  *      The total number of functions in this interface
8649  *
8650  * @param queueTime
8651  *      The amount of time this function waited for a thread
8652  *
8653  * @param execTime
8654  *      The amount of time this function invocation took to execute
8655  *
8656  * @param bytesSent
8657  *      The number bytes sent by this invocation
8658  *
8659  * @param bytesRcvd
8660  *      The number bytes received by this invocation
8661  *
8662  * @param isServer
8663  *      If true, this invocation was made to a server
8664  *
8665  */
8666 void
8667 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8668                          afs_uint32 currentFunc, afs_uint32 totalFunc,
8669                          struct clock *queueTime, struct clock *execTime,
8670                          afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8671                          int isServer)
8672 {
8673     afs_uint64 sent64;
8674     afs_uint64 rcvd64;
8675
8676     sent64 = ((afs_uint64)bytesSent->high << 32) + bytesSent->low;
8677     rcvd64 = ((afs_uint64)bytesRcvd->high << 32) + bytesRcvd->low;
8678
8679     rxi_IncrementTimeAndCount(peer, rxInterface, currentFunc, totalFunc,
8680                               queueTime, execTime, sent64, rcvd64,
8681                               isServer);
8682 }
8683
8684
8685
8686 /*
8687  * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8688  *
8689  * PARAMETERS
8690  *
8691  * IN callerVersion - the rpc stat version of the caller.
8692  *
8693  * IN count - the number of entries to marshall.
8694  *
8695  * IN stats - pointer to stats to be marshalled.
8696  *
8697  * OUT ptr - Where to store the marshalled data.
8698  *
8699  * RETURN CODES
8700  *
8701  * Returns void.
8702  */
8703 void
8704 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8705                            rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8706 {
8707     int i;
8708     afs_uint32 *ptr;
8709
8710     /*
8711      * We only support the first version
8712      */
8713     for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8714         *(ptr++) = stats->remote_peer;
8715         *(ptr++) = stats->remote_port;
8716         *(ptr++) = stats->remote_is_server;
8717         *(ptr++) = stats->interfaceId;
8718         *(ptr++) = stats->func_total;
8719         *(ptr++) = stats->func_index;
8720         *(ptr++) = stats->invocations >> 32;
8721         *(ptr++) = stats->invocations & MAX_AFS_UINT32;
8722         *(ptr++) = stats->bytes_sent >> 32;
8723         *(ptr++) = stats->bytes_sent & MAX_AFS_UINT32;
8724         *(ptr++) = stats->bytes_rcvd >> 32;
8725         *(ptr++) = stats->bytes_rcvd & MAX_AFS_UINT32;
8726         *(ptr++) = stats->queue_time_sum.sec;
8727         *(ptr++) = stats->queue_time_sum.usec;
8728         *(ptr++) = stats->queue_time_sum_sqr.sec;
8729         *(ptr++) = stats->queue_time_sum_sqr.usec;
8730         *(ptr++) = stats->queue_time_min.sec;
8731         *(ptr++) = stats->queue_time_min.usec;
8732         *(ptr++) = stats->queue_time_max.sec;
8733         *(ptr++) = stats->queue_time_max.usec;
8734         *(ptr++) = stats->execution_time_sum.sec;
8735         *(ptr++) = stats->execution_time_sum.usec;
8736         *(ptr++) = stats->execution_time_sum_sqr.sec;
8737         *(ptr++) = stats->execution_time_sum_sqr.usec;
8738         *(ptr++) = stats->execution_time_min.sec;
8739         *(ptr++) = stats->execution_time_min.usec;
8740         *(ptr++) = stats->execution_time_max.sec;
8741         *(ptr++) = stats->execution_time_max.usec;
8742     }
8743     *ptrP = ptr;
8744 }
8745
8746 /*
8747  * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8748  * this process
8749  *
8750  * PARAMETERS
8751  *
8752  * IN callerVersion - the rpc stat version of the caller
8753  *
8754  * OUT myVersion - the rpc stat version of this function
8755  *
8756  * OUT clock_sec - local time seconds
8757  *
8758  * OUT clock_usec - local time microseconds
8759  *
8760  * OUT allocSize - the number of bytes allocated to contain stats
8761  *
8762  * OUT statCount - the number stats retrieved from this process.
8763  *
8764  * OUT stats - the actual stats retrieved from this process.
8765  *
8766  * RETURN CODES
8767  *
8768  * Returns void.  If successful, stats will != NULL.
8769  */
8770
8771 int
8772 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8773                            afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8774                            size_t * allocSize, afs_uint32 * statCount,
8775                            afs_uint32 ** stats)
8776 {
8777     size_t space = 0;
8778     afs_uint32 *ptr;
8779     struct clock now;
8780     int rc = 0;
8781
8782     *stats = 0;
8783     *allocSize = 0;
8784     *statCount = 0;
8785     *myVersion = RX_STATS_RETRIEVAL_VERSION;
8786
8787     /*
8788      * Check to see if stats are enabled
8789      */
8790
8791     MUTEX_ENTER(&rx_rpc_stats);
8792     if (!rxi_monitor_processStats) {
8793         MUTEX_EXIT(&rx_rpc_stats);
8794         return rc;
8795     }
8796
8797     clock_GetTime(&now);
8798     *clock_sec = now.sec;
8799     *clock_usec = now.usec;
8800
8801     /*
8802      * Allocate the space based upon the caller version
8803      *
8804      * If the client is at an older version than we are,
8805      * we return the statistic data in the older data format, but
8806      * we still return our version number so the client knows we
8807      * are maintaining more data than it can retrieve.
8808      */
8809
8810     if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8811         space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8812         *statCount = rxi_rpc_process_stat_cnt;
8813     } else {
8814         /*
8815          * This can't happen yet, but in the future version changes
8816          * can be handled by adding additional code here
8817          */
8818     }
8819
8820     if (space > (size_t) 0) {
8821         *allocSize = space;
8822         ptr = *stats = rxi_Alloc(space);
8823
8824         if (ptr != NULL) {
8825             struct opr_queue *cursor;
8826
8827             for (opr_queue_Scan(&processStats, cursor)) {
8828                 struct rx_interface_stat *rpc_stat = 
8829                     opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8830                 /*
8831                  * Copy the data based upon the caller version
8832                  */
8833                 rx_MarshallProcessRPCStats(callerVersion,
8834                                            rpc_stat->stats[0].func_total,
8835                                            rpc_stat->stats, &ptr);
8836             }
8837         } else {
8838             rc = ENOMEM;
8839         }
8840     }
8841     MUTEX_EXIT(&rx_rpc_stats);
8842     return rc;
8843 }
8844
8845 /*
8846  * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8847  *
8848  * PARAMETERS
8849  *
8850  * IN callerVersion - the rpc stat version of the caller
8851  *
8852  * OUT myVersion - the rpc stat version of this function
8853  *
8854  * OUT clock_sec - local time seconds
8855  *
8856  * OUT clock_usec - local time microseconds
8857  *
8858  * OUT allocSize - the number of bytes allocated to contain stats
8859  *
8860  * OUT statCount - the number of stats retrieved from the individual
8861  * peer structures.
8862  *
8863  * OUT stats - the actual stats retrieved from the individual peer structures.
8864  *
8865  * RETURN CODES
8866  *
8867  * Returns void.  If successful, stats will != NULL.
8868  */
8869
8870 int
8871 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8872                         afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8873                         size_t * allocSize, afs_uint32 * statCount,
8874                         afs_uint32 ** stats)
8875 {
8876     size_t space = 0;
8877     afs_uint32 *ptr;
8878     struct clock now;
8879     int rc = 0;
8880
8881     *stats = 0;
8882     *statCount = 0;
8883     *allocSize = 0;
8884     *myVersion = RX_STATS_RETRIEVAL_VERSION;
8885
8886     /*
8887      * Check to see if stats are enabled
8888      */
8889
8890     MUTEX_ENTER(&rx_rpc_stats);
8891     if (!rxi_monitor_peerStats) {
8892         MUTEX_EXIT(&rx_rpc_stats);
8893         return rc;
8894     }
8895
8896     clock_GetTime(&now);
8897     *clock_sec = now.sec;
8898     *clock_usec = now.usec;
8899
8900     /*
8901      * Allocate the space based upon the caller version
8902      *
8903      * If the client is at an older version than we are,
8904      * we return the statistic data in the older data format, but
8905      * we still return our version number so the client knows we
8906      * are maintaining more data than it can retrieve.
8907      */
8908
8909     if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8910         space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8911         *statCount = rxi_rpc_peer_stat_cnt;
8912     } else {
8913         /*
8914          * This can't happen yet, but in the future version changes
8915          * can be handled by adding additional code here
8916          */
8917     }
8918
8919     if (space > (size_t) 0) {
8920         *allocSize = space;
8921         ptr = *stats = rxi_Alloc(space);
8922
8923         if (ptr != NULL) {
8924             struct opr_queue *cursor;
8925
8926             for (opr_queue_Scan(&peerStats, cursor)) {
8927                 struct rx_interface_stat *rpc_stat
8928                     = opr_queue_Entry(cursor, struct rx_interface_stat,
8929                                      entryPeers);
8930
8931                 /*
8932                  * Copy the data based upon the caller version
8933                  */
8934                 rx_MarshallProcessRPCStats(callerVersion,
8935                                            rpc_stat->stats[0].func_total,
8936                                            rpc_stat->stats, &ptr);
8937             }
8938         } else {
8939             rc = ENOMEM;
8940         }
8941     }
8942     MUTEX_EXIT(&rx_rpc_stats);
8943     return rc;
8944 }
8945
8946 /*
8947  * rx_FreeRPCStats - free memory allocated by
8948  *                   rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
8949  *
8950  * PARAMETERS
8951  *
8952  * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
8953  * rx_RetrievePeerRPCStats
8954  *
8955  * IN allocSize - the number of bytes in stats.
8956  *
8957  * RETURN CODES
8958  *
8959  * Returns void.
8960  */
8961
8962 void
8963 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
8964 {
8965     rxi_Free(stats, allocSize);
8966 }
8967
8968 /*
8969  * rx_queryProcessRPCStats - see if process rpc stat collection is
8970  * currently enabled.
8971  *
8972  * PARAMETERS
8973  *
8974  * RETURN CODES
8975  *
8976  * Returns 0 if stats are not enabled != 0 otherwise
8977  */
8978
8979 int
8980 rx_queryProcessRPCStats(void)
8981 {
8982     int rc;
8983     MUTEX_ENTER(&rx_rpc_stats);
8984     rc = rxi_monitor_processStats;
8985     MUTEX_EXIT(&rx_rpc_stats);
8986     return rc;
8987 }
8988
8989 /*
8990  * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
8991  *
8992  * PARAMETERS
8993  *
8994  * RETURN CODES
8995  *
8996  * Returns 0 if stats are not enabled != 0 otherwise
8997  */
8998
8999 int
9000 rx_queryPeerRPCStats(void)
9001 {
9002     int rc;
9003     MUTEX_ENTER(&rx_rpc_stats);
9004     rc = rxi_monitor_peerStats;
9005     MUTEX_EXIT(&rx_rpc_stats);
9006     return rc;
9007 }
9008
9009 /*
9010  * rx_enableProcessRPCStats - begin rpc stat collection for entire process
9011  *
9012  * PARAMETERS
9013  *
9014  * RETURN CODES
9015  *
9016  * Returns void.
9017  */
9018
9019 void
9020 rx_enableProcessRPCStats(void)
9021 {
9022     MUTEX_ENTER(&rx_rpc_stats);
9023     rx_enable_stats = 1;
9024     rxi_monitor_processStats = 1;
9025     MUTEX_EXIT(&rx_rpc_stats);
9026 }
9027
9028 /*
9029  * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
9030  *
9031  * PARAMETERS
9032  *
9033  * RETURN CODES
9034  *
9035  * Returns void.
9036  */
9037
9038 void
9039 rx_enablePeerRPCStats(void)
9040 {
9041     MUTEX_ENTER(&rx_rpc_stats);
9042     rx_enable_stats = 1;
9043     rxi_monitor_peerStats = 1;
9044     MUTEX_EXIT(&rx_rpc_stats);
9045 }
9046
9047 /*
9048  * rx_disableProcessRPCStats - stop rpc stat collection for entire process
9049  *
9050  * PARAMETERS
9051  *
9052  * RETURN CODES
9053  *
9054  * Returns void.
9055  */
9056
9057 void
9058 rx_disableProcessRPCStats(void)
9059 {
9060     struct opr_queue *cursor, *store;
9061     size_t space;
9062
9063     MUTEX_ENTER(&rx_rpc_stats);
9064
9065     /*
9066      * Turn off process statistics and if peer stats is also off, turn
9067      * off everything
9068      */
9069
9070     rxi_monitor_processStats = 0;
9071     if (rxi_monitor_peerStats == 0) {
9072         rx_enable_stats = 0;
9073     }
9074
9075     for (opr_queue_ScanSafe(&processStats, cursor, store)) {
9076         unsigned int num_funcs = 0;
9077         struct rx_interface_stat *rpc_stat
9078             = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
9079
9080         opr_queue_Remove(&rpc_stat->entry);
9081
9082         num_funcs = rpc_stat->stats[0].func_total;
9083         space =
9084             sizeof(rx_interface_stat_t) +
9085             rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
9086
9087         rxi_Free(rpc_stat, space);
9088         rxi_rpc_process_stat_cnt -= num_funcs;
9089     }
9090     MUTEX_EXIT(&rx_rpc_stats);
9091 }
9092
9093 /*
9094  * rx_disablePeerRPCStats - stop rpc stat collection for peers
9095  *
9096  * PARAMETERS
9097  *
9098  * RETURN CODES
9099  *
9100  * Returns void.
9101  */
9102
9103 void
9104 rx_disablePeerRPCStats(void)
9105 {
9106     struct rx_peer **peer_ptr, **peer_end;
9107     int code;
9108
9109     /*
9110      * Turn off peer statistics and if process stats is also off, turn
9111      * off everything
9112      */
9113
9114     rxi_monitor_peerStats = 0;
9115     if (rxi_monitor_processStats == 0) {
9116         rx_enable_stats = 0;
9117     }
9118
9119     for (peer_ptr = &rx_peerHashTable[0], peer_end =
9120          &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
9121          peer_ptr++) {
9122         struct rx_peer *peer, *next, *prev;
9123
9124         MUTEX_ENTER(&rx_peerHashTable_lock);
9125         MUTEX_ENTER(&rx_rpc_stats);
9126         for (prev = peer = *peer_ptr; peer; peer = next) {
9127             next = peer->next;
9128             code = MUTEX_TRYENTER(&peer->peer_lock);
9129             if (code) {
9130                 size_t space;
9131                 struct opr_queue *cursor, *store;
9132
9133                 if (prev == *peer_ptr) {
9134                     *peer_ptr = next;
9135                     prev = next;
9136                 } else
9137                     prev->next = next;
9138
9139                 if (next)
9140                     next->refCount++;
9141                 if (prev)
9142                     prev->refCount++;
9143                 peer->refCount++;
9144                 MUTEX_EXIT(&rx_peerHashTable_lock);
9145
9146                 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
9147                     unsigned int num_funcs = 0;
9148                     struct rx_interface_stat *rpc_stat
9149                         = opr_queue_Entry(cursor, struct rx_interface_stat,
9150                                          entry);
9151
9152                     opr_queue_Remove(&rpc_stat->entry);
9153                     opr_queue_Remove(&rpc_stat->entryPeers);
9154                     num_funcs = rpc_stat->stats[0].func_total;
9155                     space =
9156                         sizeof(rx_interface_stat_t) +
9157                         rpc_stat->stats[0].func_total *
9158                         sizeof(rx_function_entry_v1_t);
9159
9160                     rxi_Free(rpc_stat, space);
9161                     rxi_rpc_peer_stat_cnt -= num_funcs;
9162                 }
9163                 MUTEX_EXIT(&peer->peer_lock);
9164
9165                 MUTEX_ENTER(&rx_peerHashTable_lock);
9166                 if (next)
9167                     next->refCount--;
9168                 if (prev)
9169                     prev->refCount--;
9170                 peer->refCount--;
9171             } else {
9172                 prev = peer;
9173             }
9174         }
9175         MUTEX_EXIT(&rx_rpc_stats);
9176         MUTEX_EXIT(&rx_peerHashTable_lock);
9177     }
9178 }
9179
9180 /*
9181  * rx_clearProcessRPCStats - clear the contents of the rpc stats according
9182  * to clearFlag
9183  *
9184  * PARAMETERS
9185  *
9186  * IN clearFlag - flag indicating which stats to clear
9187  *
9188  * RETURN CODES
9189  *
9190  * Returns void.
9191  */
9192
9193 void
9194 rx_clearProcessRPCStats(afs_uint32 clearFlag)
9195 {
9196     struct opr_queue *cursor;
9197
9198     MUTEX_ENTER(&rx_rpc_stats);
9199
9200     for (opr_queue_Scan(&processStats, cursor)) {
9201         unsigned int num_funcs = 0, i;
9202         struct rx_interface_stat *rpc_stat
9203              = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
9204
9205         num_funcs = rpc_stat->stats[0].func_total;
9206         for (i = 0; i < num_funcs; i++) {
9207             if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9208                 rpc_stat->stats[i].invocations = 0;
9209             }
9210             if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9211                 rpc_stat->stats[i].bytes_sent = 0;
9212             }
9213             if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9214                 rpc_stat->stats[i].bytes_rcvd = 0;
9215             }
9216             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9217                 rpc_stat->stats[i].queue_time_sum.sec = 0;
9218                 rpc_stat->stats[i].queue_time_sum.usec = 0;
9219             }
9220             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9221                 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9222                 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9223             }
9224             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9225                 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9226                 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9227             }
9228             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9229                 rpc_stat->stats[i].queue_time_max.sec = 0;
9230                 rpc_stat->stats[i].queue_time_max.usec = 0;
9231             }
9232             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9233                 rpc_stat->stats[i].execution_time_sum.sec = 0;
9234                 rpc_stat->stats[i].execution_time_sum.usec = 0;
9235             }
9236             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9237                 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9238                 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9239             }
9240             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9241                 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9242                 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9243             }
9244             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9245                 rpc_stat->stats[i].execution_time_max.sec = 0;
9246                 rpc_stat->stats[i].execution_time_max.usec = 0;
9247             }
9248         }
9249     }
9250
9251     MUTEX_EXIT(&rx_rpc_stats);
9252 }
9253
9254 /*
9255  * rx_clearPeerRPCStats - clear the contents of the rpc stats according
9256  * to clearFlag
9257  *
9258  * PARAMETERS
9259  *
9260  * IN clearFlag - flag indicating which stats to clear
9261  *
9262  * RETURN CODES
9263  *
9264  * Returns void.
9265  */
9266
9267 void
9268 rx_clearPeerRPCStats(afs_uint32 clearFlag)
9269 {
9270     struct opr_queue *cursor;
9271
9272     MUTEX_ENTER(&rx_rpc_stats);
9273
9274     for (opr_queue_Scan(&peerStats, cursor)) {
9275         unsigned int num_funcs, i;
9276         struct rx_interface_stat *rpc_stat
9277             = opr_queue_Entry(cursor, struct rx_interface_stat, entryPeers);
9278
9279         num_funcs = rpc_stat->stats[0].func_total;
9280         for (i = 0; i < num_funcs; i++) {
9281             if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9282                 rpc_stat->stats[i].invocations = 0;
9283             }
9284             if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9285                 rpc_stat->stats[i].bytes_sent = 0;
9286             }
9287             if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9288                 rpc_stat->stats[i].bytes_rcvd = 0;
9289             }
9290             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9291                 rpc_stat->stats[i].queue_time_sum.sec = 0;
9292                 rpc_stat->stats[i].queue_time_sum.usec = 0;
9293             }
9294             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9295                 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9296                 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9297             }
9298             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9299                 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9300                 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9301             }
9302             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9303                 rpc_stat->stats[i].queue_time_max.sec = 0;
9304                 rpc_stat->stats[i].queue_time_max.usec = 0;
9305             }
9306             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9307                 rpc_stat->stats[i].execution_time_sum.sec = 0;
9308                 rpc_stat->stats[i].execution_time_sum.usec = 0;
9309             }
9310             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9311                 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9312                 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9313             }
9314             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9315                 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9316                 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9317             }
9318             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9319                 rpc_stat->stats[i].execution_time_max.sec = 0;
9320                 rpc_stat->stats[i].execution_time_max.usec = 0;
9321             }
9322         }
9323     }
9324
9325     MUTEX_EXIT(&rx_rpc_stats);
9326 }
9327
9328 /*
9329  * rxi_rxstat_userok points to a routine that returns 1 if the caller
9330  * is authorized to enable/disable/clear RX statistics.
9331  */
9332 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
9333
9334 void
9335 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
9336 {
9337     rxi_rxstat_userok = proc;
9338 }
9339
9340 int
9341 rx_RxStatUserOk(struct rx_call *call)
9342 {
9343     if (!rxi_rxstat_userok)
9344         return 0;
9345     return rxi_rxstat_userok(call);
9346 }
9347
9348 #ifdef AFS_NT40_ENV
9349 /*
9350  * DllMain() -- Entry-point function called by the DllMainCRTStartup()
9351  *     function in the MSVC runtime DLL (msvcrt.dll).
9352  *
9353  *     Note: the system serializes calls to this function.
9354  */
9355 BOOL WINAPI
9356 DllMain(HINSTANCE dllInstHandle,        /* instance handle for this DLL module */
9357         DWORD reason,                   /* reason function is being called */
9358         LPVOID reserved)                /* reserved for future use */
9359 {
9360     switch (reason) {
9361     case DLL_PROCESS_ATTACH:
9362         /* library is being attached to a process */
9363         INIT_PTHREAD_LOCKS;
9364         return TRUE;
9365
9366     case DLL_PROCESS_DETACH:
9367         return TRUE;
9368
9369     default:
9370         return FALSE;
9371     }
9372 }
9373 #endif /* AFS_NT40_ENV */
9374
9375 #ifndef KERNEL
9376 int rx_DumpCalls(FILE *outputFile, char *cookie)
9377 {
9378 #ifdef RXDEBUG_PACKET
9379 #ifdef KDUMP_RX_LOCK
9380     struct rx_call_rx_lock *c;
9381 #else
9382     struct rx_call *c;
9383 #endif
9384 #ifdef AFS_NT40_ENV
9385     int zilch;
9386     char output[2048];
9387 #define RXDPRINTF sprintf
9388 #define RXDPRINTOUT output
9389 #else
9390 #define RXDPRINTF fprintf
9391 #define RXDPRINTOUT outputFile
9392 #endif
9393
9394     RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
9395 #ifdef AFS_NT40_ENV
9396     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9397 #endif
9398
9399     for (c = rx_allCallsp; c; c = c->allNextp) {
9400         u_short rqc, tqc, iovqc;
9401
9402         MUTEX_ENTER(&c->lock);
9403         rqc = opr_queue_Count(&c->rq);
9404         tqc = opr_queue_Count(&c->tq);
9405         iovqc = opr_queue_Count(&c->app.iovq);
9406
9407         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, "
9408                 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
9409                 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
9410                 "resendEvent=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
9411                 "lastSendTime=%u, lastRecvTime=%u"
9412 #ifdef RX_ENABLE_LOCKS
9413                 ", refCount=%u"
9414 #endif
9415 #ifdef RX_REFCOUNT_CHECK
9416                 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
9417                 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
9418 #endif
9419                 "\r\n",
9420                 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,
9421                 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
9422                 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
9423                 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
9424                 c->resendEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
9425                 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime
9426 #ifdef RX_ENABLE_LOCKS
9427                 , (afs_uint32)c->refCount
9428 #endif
9429 #ifdef RX_REFCOUNT_CHECK
9430                 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
9431 #endif
9432                 );
9433         MUTEX_EXIT(&c->lock);
9434
9435 #ifdef AFS_NT40_ENV
9436         WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9437 #endif
9438     }
9439     RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
9440 #ifdef AFS_NT40_ENV
9441     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9442 #endif
9443 #endif /* RXDEBUG_PACKET */
9444     return 0;
9445 }
9446 #endif
9447
9448 #ifdef AFS_RXERRQ_ENV
9449 void
9450 rxi_HandleSocketErrors(osi_socket sock)
9451 {
9452     size_t cmsgbuf_len = 256;
9453     void *cmsgbuf;
9454 # ifndef KERNEL
9455     int errno_save = errno;
9456 # endif
9457
9458     cmsgbuf = rxi_Alloc(cmsgbuf_len);
9459     if (cmsgbuf == NULL) {
9460         goto done;
9461     }
9462
9463     while (osi_HandleSocketError(sock, cmsgbuf, cmsgbuf_len))
9464         ;
9465
9466     rxi_Free(cmsgbuf, cmsgbuf_len);
9467
9468  done:
9469 # ifndef KERNEL
9470     errno = errno_save;
9471 # endif
9472     return;
9473 }
9474
9475 static int
9476 NetSend_retry(osi_socket sock, void *addr, struct iovec *dvec, int nvecs,
9477               int length, int istack)
9478 {
9479     int code;
9480     int safety;
9481     /*
9482      * If an ICMP error comes in for any peer, sendmsg() can return -1 with an
9483      * errno of EHOSTUNREACH, ENETUNREACH, etc. There may be no problem with
9484      * sending this packet (an error is returned just to indicate we need to
9485      * read in pending errors), but the packet wasn't actually sent.
9486      *
9487      * It's difficult to determine in general whether sendmsg() is returning an
9488      * error due to a received ICMP error, or we're getting an actual error for
9489      * this specific sendmsg() call, since there may be other threads running
9490      * sendmsg/recvmsg/rxi_HandleSocketErrors at the same time. So, just retry
9491      * the sendmsg a few times; make sure not to retry forever, in case we are
9492      * getting an actual error from this sendmsg() call.
9493      *
9494      * Also note that if we accidentally drop a packet here that we didn't need
9495      * to, it's not the end of the world. Packets get dropped, and we should be
9496      * able to recover.
9497      */
9498     for (safety = 0; safety < RXI_SENDMSG_RETRY; safety++) {
9499         code = osi_NetSend(sock, addr, dvec, nvecs, length, istack);
9500         if (code == 0) {
9501             return 0;
9502         }
9503         rxi_HandleSocketErrors(sock);
9504     }
9505     return code;
9506
9507 }
9508 #endif
9509
9510 int
9511 rxi_NetSend(osi_socket socket, void *addr, struct iovec *dvec,
9512             int nvecs, int length, int istack)
9513 {
9514     if (rxi_IsRunning()) {
9515 #ifdef AFS_RXERRQ_ENV
9516         return NetSend_retry(socket, addr, dvec, nvecs, length, istack);
9517 #else
9518         return osi_NetSend(socket, addr, dvec, nvecs, length, istack);
9519 #endif
9520     }
9521 #ifdef AFS_NT40_ENV
9522     return WSAESHUTDOWN;
9523 #else
9524     return ESHUTDOWN;
9525 #endif
9526 }