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