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