Linux 5.15: Convert osi_Msg macro to a function
[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_LINUX_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_ACK) != 0 ? '*'
4444                                                                         : '-');
4445         }
4446         msg[len++]='\n';
4447         msg[len] = '\0';
4448         OutputDebugString(msg);
4449     }
4450 #else /* AFS_NT40_ENV */
4451     if (rx_Log) {
4452         fprintf(rx_Log,
4453                 "RACK: reason %x previous %u seq %u serial %u first %u",
4454                 ap->reason, ntohl(ap->previousPacket),
4455                 (unsigned int)np->header.seq, (unsigned int)serial,
4456                 ntohl(ap->firstPacket));
4457         if (nAcks) {
4458             int offset;
4459             for (offset = 0; offset < nAcks; offset++)
4460                 putc((ap->acks[offset] & RX_ACK_TYPE_ACK) != 0 ? '*' : '-',
4461                      rx_Log);
4462         }
4463         putc('\n', rx_Log);
4464     }
4465 #endif /* AFS_NT40_ENV */
4466 #endif
4467
4468     MUTEX_ENTER(&peer->peer_lock);
4469     if (pktsize) {
4470         /*
4471          * Start somewhere. Can't assume we can send what we can receive,
4472          * but we are clearly receiving.
4473          */
4474         if (!peer->maxPacketSize)
4475             peer->maxPacketSize = RX_MIN_PACKET_SIZE - RX_HEADER_SIZE;
4476
4477         if (pktsize > peer->maxPacketSize) {
4478             peer->maxPacketSize = pktsize;
4479             if ((pktsize + RX_HEADER_SIZE > peer->ifMTU)) {
4480                 peer->ifMTU = pktsize + RX_HEADER_SIZE;
4481                 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4482                 rxi_ScheduleGrowMTUEvent(call, 1);
4483             }
4484         }
4485     }
4486
4487     clock_GetTime(&now);
4488
4489     /* The transmit queue splits into 4 sections.
4490      *
4491      * The first section is packets which have now been acknowledged
4492      * by a window size change in the ack. These have reached the
4493      * application layer, and may be discarded. These are packets
4494      * with sequence numbers < ap->firstPacket.
4495      *
4496      * The second section is packets which have sequence numbers in
4497      * the range ap->firstPacket to ap->firstPacket + ap->nAcks. The
4498      * contents of the packet's ack array determines whether these
4499      * packets are acknowledged or not.
4500      *
4501      * The third section is packets which fall above the range
4502      * addressed in the ack packet. These have not yet been received
4503      * by the peer.
4504      *
4505      * The four section is packets which have not yet been transmitted.
4506      * These packets will have a header.serial of 0.
4507      */
4508
4509     /* First section - implicitly acknowledged packets that can be
4510      * disposed of
4511      */
4512
4513     tp = opr_queue_First(&call->tq, struct rx_packet, entry);
4514     while(!opr_queue_IsEnd(&call->tq, &tp->entry) && tp->header.seq < first) {
4515         struct rx_packet *next;
4516
4517         next = opr_queue_Next(&tp->entry, struct rx_packet, entry);
4518         call->tfirst = tp->header.seq + 1;
4519
4520         if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4521             newAckCount++;
4522             rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4523         }
4524
4525 #ifdef RX_ENABLE_LOCKS
4526         /* XXX Hack. Because we have to release the global call lock when sending
4527          * packets (rxi_NetSend) we drop all acks while we're traversing the tq
4528          * in rxi_Start sending packets out because packets may move to the
4529          * freePacketQueue as result of being here! So we drop these packets until
4530          * we're safely out of the traversing. Really ugly!
4531          * To make it even uglier, if we're using fine grain locking, we can
4532          * set the ack bits in the packets and have rxi_Start remove the packets
4533          * when it's done transmitting.
4534          */
4535         if (call->flags & RX_CALL_TQ_BUSY) {
4536             tp->flags |= RX_PKTFLAG_ACKED;
4537             call->flags |= RX_CALL_TQ_SOME_ACKED;
4538         } else
4539 #endif /* RX_ENABLE_LOCKS */
4540         {
4541             opr_queue_Remove(&tp->entry);
4542 #ifdef RX_TRACK_PACKETS
4543             tp->flags &= ~RX_PKTFLAG_TQ;
4544 #endif
4545 #ifdef RXDEBUG_PACKET
4546             call->tqc--;
4547 #endif /* RXDEBUG_PACKET */
4548             rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4549         }
4550         tp = next;
4551     }
4552
4553     /* N.B. we don't turn off any timers here.  They'll go away by themselves, anyway */
4554
4555     /* Second section of the queue - packets for which we are receiving
4556      * soft ACKs
4557      *
4558      * Go through the explicit acks/nacks and record the results in
4559      * the waiting packets.  These are packets that can't be released
4560      * yet, even with a positive acknowledge.  This positive
4561      * acknowledge only means the packet has been received by the
4562      * peer, not that it will be retained long enough to be sent to
4563      * the peer's upper level.  In addition, reset the transmit timers
4564      * of any missing packets (those packets that must be missing
4565      * because this packet was out of sequence) */
4566
4567     call->nSoftAcked = 0;
4568     missing = 0;
4569     while (!opr_queue_IsEnd(&call->tq, &tp->entry) 
4570            && tp->header.seq < first + nAcks) {
4571         /* Set the acknowledge flag per packet based on the
4572          * information in the ack packet. An acknowlegded packet can
4573          * be downgraded when the server has discarded a packet it
4574          * soacked previously, or when an ack packet is received
4575          * out of sequence. */
4576         if ((ap->acks[tp->header.seq - first] & RX_ACK_TYPE_ACK) != 0) {
4577             if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4578                 newAckCount++;
4579                 tp->flags |= RX_PKTFLAG_ACKED;
4580                 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4581             }
4582             if (missing) {
4583                 nNacked++;
4584             } else {
4585                 call->nSoftAcked++;
4586             }
4587         } else /* RX_ACK_TYPE_NACK */ {
4588             tp->flags &= ~RX_PKTFLAG_ACKED;
4589             missing = 1;
4590         }
4591
4592         tp = opr_queue_Next(&tp->entry, struct rx_packet, entry);
4593     }
4594
4595     /* We don't need to take any action with the 3rd or 4th section in the
4596      * queue - they're not addressed by the contents of this ACK packet.
4597      */
4598
4599     /* if the ack packet has a receivelen field hanging off it,
4600      * update our state */
4601     if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4602         afs_uint32 tSize;
4603
4604         /* If the ack packet has a "recommended" size that is less than
4605          * what I am using now, reduce my size to match */
4606         rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4607                       (int)sizeof(afs_int32), &tSize);
4608         tSize = (afs_uint32) ntohl(tSize);
4609         if (tSize > RX_MAX_PACKET_SIZE)
4610             tSize = RX_MAX_PACKET_SIZE;
4611         if (tSize < RX_MIN_PACKET_SIZE)
4612             tSize = RX_MIN_PACKET_SIZE;
4613         peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4614
4615         /* Get the maximum packet size to send to this peer */
4616         rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4617                       &tSize);
4618         tSize = (afs_uint32) ntohl(tSize);
4619         if (tSize > RX_MAX_PACKET_SIZE)
4620             tSize = RX_MAX_PACKET_SIZE;
4621         if (tSize < RX_MIN_PACKET_SIZE)
4622             tSize = RX_MIN_PACKET_SIZE;
4623         tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4624         tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4625
4626         /* sanity check - peer might have restarted with different params.
4627          * If peer says "send less", dammit, send less...  Peer should never
4628          * be unable to accept packets of the size that prior AFS versions would
4629          * send without asking.  */
4630         if (peer->maxMTU != tSize) {
4631             if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4632                 peer->congestSeq++;
4633             peer->maxMTU = tSize;
4634             peer->MTU = MIN(tSize, peer->MTU);
4635             call->MTU = MIN(call->MTU, tSize);
4636         }
4637
4638         if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4639             /* AFS 3.4a */
4640             rx_packetread(np,
4641                           rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4642                           (int)sizeof(afs_int32), &tSize);
4643             tSize = (afs_uint32) ntohl(tSize);  /* peer's receive window, if it's */
4644             if (tSize == 0)
4645                 tSize = 1;
4646             if (tSize >= rx_maxSendWindow)
4647                 tSize = rx_maxSendWindow;
4648             if (tSize < call->twind) {  /* smaller than our send */
4649                 call->twind = tSize;    /* window, we must send less... */
4650                 call->ssthresh = MIN(call->twind, call->ssthresh);
4651                 call->conn->twind[call->channel] = call->twind;
4652             }
4653
4654             /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4655              * network MTU confused with the loopback MTU. Calculate the
4656              * maximum MTU here for use in the slow start code below.
4657              */
4658             /* Did peer restart with older RX version? */
4659             if (peer->maxDgramPackets > 1) {
4660                 peer->maxDgramPackets = 1;
4661             }
4662         } else if (np->length >=
4663                    rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4664             /* AFS 3.5 */
4665             rx_packetread(np,
4666                           rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4667                           sizeof(afs_int32), &tSize);
4668             tSize = (afs_uint32) ntohl(tSize);
4669             if (tSize == 0)
4670                 tSize = 1;
4671             if (tSize >= rx_maxSendWindow)
4672                 tSize = rx_maxSendWindow;
4673             /*
4674              * As of AFS 3.5 we set the send window to match the receive window.
4675              */
4676             if (tSize < call->twind) {
4677                 call->twind = tSize;
4678                 call->conn->twind[call->channel] = call->twind;
4679                 call->ssthresh = MIN(call->twind, call->ssthresh);
4680             } else if (tSize > call->twind) {
4681                 call->twind = tSize;
4682                 call->conn->twind[call->channel] = call->twind;
4683             }
4684
4685             /*
4686              * As of AFS 3.5, a jumbogram is more than one fixed size
4687              * packet transmitted in a single UDP datagram. If the remote
4688              * MTU is smaller than our local MTU then never send a datagram
4689              * larger than the natural MTU.
4690              */
4691             rx_packetread(np,
4692                           rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4693                           (int)sizeof(afs_int32), &tSize);
4694             maxDgramPackets = (afs_uint32) ntohl(tSize);
4695             maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4696             maxDgramPackets =
4697                 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4698             if (maxDgramPackets > 1) {
4699                 peer->maxDgramPackets = maxDgramPackets;
4700                 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4701             } else {
4702                 peer->maxDgramPackets = 1;
4703                 call->MTU = peer->natMTU;
4704             }
4705         } else if (peer->maxDgramPackets > 1) {
4706             /* Restarted with lower version of RX */
4707             peer->maxDgramPackets = 1;
4708         }
4709     } else if (peer->maxDgramPackets > 1
4710                || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4711         /* Restarted with lower version of RX */
4712         peer->maxMTU = OLD_MAX_PACKET_SIZE;
4713         peer->natMTU = OLD_MAX_PACKET_SIZE;
4714         peer->MTU = OLD_MAX_PACKET_SIZE;
4715         peer->maxDgramPackets = 1;
4716         peer->nDgramPackets = 1;
4717         peer->congestSeq++;
4718         call->MTU = OLD_MAX_PACKET_SIZE;
4719     }
4720
4721     /* If the window has been extended by this acknowledge packet,
4722      * then wakeup a sender waiting in alloc for window space, or try
4723      * sending packets now, if he's been sitting on packets due to
4724      * lack of window space */
4725     if (call->tnext < (call->tfirst + call->twind)) {
4726 #ifdef  RX_ENABLE_LOCKS
4727         CV_SIGNAL(&call->cv_twind);
4728 #else
4729         if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4730             call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4731             osi_rxWakeup(&call->twind);
4732         }
4733 #endif
4734         if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4735             call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4736         }
4737     }
4738
4739     if (nNacked) {
4740         /*
4741          * Calculate how many datagrams were successfully received after
4742          * the first missing packet and adjust the negative ack counter
4743          * accordingly.
4744          */
4745         call->nAcks = 0;
4746         call->nNacks++;
4747         nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4748         if (call->nNacks < nNacked) {
4749             call->nNacks = nNacked;
4750         }
4751     } else {
4752         call->nAcks += newAckCount;
4753         call->nNacks = 0;
4754     }
4755
4756     /* If the packet contained new acknowledgements, rather than just
4757      * being a duplicate of one we have previously seen, then we can restart
4758      * the RTT timer
4759      */
4760     if (newAckCount > 0)
4761         rxi_rto_packet_acked(call, istack);
4762
4763     if (call->flags & RX_CALL_FAST_RECOVER) {
4764         if (newAckCount == 0) {
4765             call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4766         } else {
4767             call->flags &= ~RX_CALL_FAST_RECOVER;
4768             call->cwind = call->nextCwind;
4769             call->nextCwind = 0;
4770             call->nAcks = 0;
4771         }
4772         call->nCwindAcks = 0;
4773     } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4774         /* Three negative acks in a row trigger congestion recovery */
4775         call->flags |= RX_CALL_FAST_RECOVER;
4776         call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4777         call->cwind =
4778             MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4779         call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4780         call->nextCwind = call->ssthresh;
4781         call->nAcks = 0;
4782         call->nNacks = 0;
4783         peer->MTU = call->MTU;
4784         peer->cwind = call->nextCwind;
4785         peer->nDgramPackets = call->nDgramPackets;
4786         peer->congestSeq++;
4787         call->congestSeq = peer->congestSeq;
4788
4789         /* Reset the resend times on the packets that were nacked
4790          * so we will retransmit as soon as the window permits
4791          */
4792
4793         acked = 0;
4794         for (opr_queue_ScanBackwards(&call->tq, cursor)) {
4795             struct rx_packet *tp =
4796                 opr_queue_Entry(cursor, struct rx_packet, entry);
4797             if (acked) {
4798                 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4799                     tp->flags &= ~RX_PKTFLAG_SENT;
4800                 }
4801             } else if (tp->flags & RX_PKTFLAG_ACKED) {
4802                 acked = 1;
4803             }
4804         }
4805     } else {
4806         /* If cwind is smaller than ssthresh, then increase
4807          * the window one packet for each ack we receive (exponential
4808          * growth).
4809          * If cwind is greater than or equal to ssthresh then increase
4810          * the congestion window by one packet for each cwind acks we
4811          * receive (linear growth).  */
4812         if (call->cwind < call->ssthresh) {
4813             call->cwind =
4814                 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4815             call->nCwindAcks = 0;
4816         } else {
4817             call->nCwindAcks += newAckCount;
4818             if (call->nCwindAcks >= call->cwind) {
4819                 call->nCwindAcks = 0;
4820                 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4821             }
4822         }
4823         /*
4824          * If we have received several acknowledgements in a row then
4825          * it is time to increase the size of our datagrams
4826          */
4827         if ((int)call->nAcks > rx_nDgramThreshold) {
4828             if (peer->maxDgramPackets > 1) {
4829                 if (call->nDgramPackets < peer->maxDgramPackets) {
4830                     call->nDgramPackets++;
4831                 }
4832                 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4833             } else if (call->MTU < peer->maxMTU) {
4834                 /* don't upgrade if we can't handle it */
4835                 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4836                     call->MTU = peer->ifMTU;
4837                 else {
4838                     call->MTU += peer->natMTU;
4839                     call->MTU = MIN(call->MTU, peer->maxMTU);
4840                 }
4841             }
4842             call->nAcks = 0;
4843         }
4844     }
4845
4846     MUTEX_EXIT(&peer->peer_lock);       /* rxi_Start will lock peer. */
4847
4848     /* Servers need to hold the call until all response packets have
4849      * been acknowledged. Soft acks are good enough since clients
4850      * are not allowed to clear their receive queues. */
4851     if (call->state == RX_STATE_HOLD
4852         && call->tfirst + call->nSoftAcked >= call->tnext) {
4853         call->state = RX_STATE_DALLY;
4854         rxi_ClearTransmitQueue(call, 0);
4855         rxi_CancelKeepAliveEvent(call);
4856     } else if (!opr_queue_IsEmpty(&call->tq)) {
4857         rxi_Start(call, istack);
4858     }
4859     return np;
4860 }
4861
4862 /**
4863  * Schedule a connection abort to be sent after some delay.
4864  *
4865  * @param[in] conn The connection to send the abort on.
4866  * @param[in] msec The number of milliseconds to wait before sending.
4867  *
4868  * @pre conn_data_lock must be held
4869  */
4870 static void
4871 rxi_SendConnectionAbortLater(struct rx_connection *conn, int msec)
4872 {
4873     struct clock when, now;
4874
4875     MUTEX_ASSERT(&conn->conn_data_lock);
4876     if (!conn->error) {
4877         return;
4878     }
4879     if (!conn->delayedAbortEvent) {
4880         clock_GetTime(&now);
4881         when = now;
4882         clock_Addmsec(&when, msec);
4883         rx_GetConnection(conn);
4884         conn->delayedAbortEvent =
4885             rxevent_Post(&when, &now, rxi_SendDelayedConnAbort, conn, NULL, 0);
4886     }
4887 }
4888
4889 /* Received a response to a challenge packet */
4890 static struct rx_packet *
4891 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4892                           struct rx_packet *np, int istack)
4893 {
4894     int error;
4895
4896     /* Ignore the packet if we're the client */
4897     if (conn->type == RX_CLIENT_CONNECTION)
4898         return np;
4899
4900     /* If already authenticated, ignore the packet (it's probably a retry) */
4901     if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4902         return np;
4903
4904     if (!conn->securityChallengeSent) {
4905         /* We've never sent out a challenge for this connection, so this
4906          * response cannot possibly be correct; ignore it. This can happen
4907          * if we sent a challenge to the client, then we were restarted, and
4908          * then the client sent us a response. If we ignore the response, the
4909          * client will eventually resend a data packet, causing us to send a
4910          * new challenge and the client to send a new response. */
4911         return np;
4912     }
4913
4914     /* Otherwise, have the security object evaluate the response packet */
4915     error = RXS_CheckResponse(conn->securityObject, conn, np);
4916     if (error) {
4917         /* If the response is invalid, reset the connection, sending
4918          * an abort to the peer. Send the abort with a 1 second delay,
4919          * to avoid a peer hammering us by constantly recreating a
4920          * connection with bad credentials. */
4921         rxi_ConnectionError(conn, error);
4922         MUTEX_ENTER(&conn->conn_data_lock);
4923         rxi_SendConnectionAbortLater(conn, 1000);
4924         MUTEX_EXIT(&conn->conn_data_lock);
4925         return np;
4926     } else {
4927         /* If the response is valid, any calls waiting to attach
4928          * servers can now do so */
4929         int i;
4930
4931         for (i = 0; i < RX_MAXCALLS; i++) {
4932             struct rx_call *call = conn->call[i];
4933             if (call) {
4934                 MUTEX_ENTER(&call->lock);
4935                 if (call->state == RX_STATE_PRECALL)
4936                     rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4937                 /* tnop can be null if newcallp is null */
4938                 MUTEX_EXIT(&call->lock);
4939             }
4940         }
4941
4942         /* Update the peer reachability information, just in case
4943          * some calls went into attach-wait while we were waiting
4944          * for authentication..
4945          */
4946         rxi_UpdatePeerReach(conn, NULL, istack);
4947     }
4948     return np;
4949 }
4950
4951 /* A client has received an authentication challenge: the security
4952  * object is asked to cough up a respectable response packet to send
4953  * back to the server.  The server is responsible for retrying the
4954  * challenge if it fails to get a response. */
4955
4956 static struct rx_packet *
4957 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4958                            struct rx_packet *np, int istack)
4959 {
4960     int error;
4961
4962     /* Ignore the challenge if we're the server */
4963     if (conn->type == RX_SERVER_CONNECTION)
4964         return np;
4965
4966     /* Ignore the challenge if the connection is otherwise idle; someone's
4967      * trying to use us as an oracle. */
4968     if (!rxi_HasActiveCalls(conn))
4969         return np;
4970
4971     /* Send the security object the challenge packet.  It is expected to fill
4972      * in the response. */
4973     error = RXS_GetResponse(conn->securityObject, conn, np);
4974
4975     /* If the security object is unable to return a valid response, reset the
4976      * connection and send an abort to the peer.  Otherwise send the response
4977      * packet to the peer connection. */
4978     if (error) {
4979         rxi_ConnectionError(conn, error);
4980         MUTEX_ENTER(&conn->conn_data_lock);
4981         np = rxi_SendConnectionAbort(conn, np, istack, 0);
4982         MUTEX_EXIT(&conn->conn_data_lock);
4983     } else {
4984         np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4985                              RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4986     }
4987     return np;
4988 }
4989
4990
4991 /* Find an available server process to service the current request in
4992  * the given call structure.  If one isn't available, queue up this
4993  * call so it eventually gets one */
4994 static void
4995 rxi_AttachServerProc(struct rx_call *call,
4996                      osi_socket socket, int *tnop,
4997                      struct rx_call **newcallp)
4998 {
4999     struct rx_serverQueueEntry *sq;
5000     struct rx_service *service = call->conn->service;
5001     int haveQuota = 0;
5002
5003     /* May already be attached */
5004     if (call->state == RX_STATE_ACTIVE)
5005         return;
5006
5007     MUTEX_ENTER(&rx_serverPool_lock);
5008
5009     haveQuota = QuotaOK(service);
5010     if ((!haveQuota) || opr_queue_IsEmpty(&rx_idleServerQueue)) {
5011         /* If there are no processes available to service this call,
5012          * put the call on the incoming call queue (unless it's
5013          * already on the queue).
5014          */
5015 #ifdef RX_ENABLE_LOCKS
5016         if (haveQuota)
5017             ReturnToServerPool(service);
5018 #endif /* RX_ENABLE_LOCKS */
5019
5020         if (!(call->flags & RX_CALL_WAIT_PROC)) {
5021             call->flags |= RX_CALL_WAIT_PROC;
5022             rx_atomic_inc(&rx_nWaiting);
5023             rx_atomic_inc(&rx_nWaited);
5024             rxi_calltrace(RX_CALL_ARRIVAL, call);
5025             SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
5026             opr_queue_Append(&rx_incomingCallQueue, &call->entry);
5027         }
5028     } else {
5029         sq = opr_queue_Last(&rx_idleServerQueue,
5030                             struct rx_serverQueueEntry, entry);
5031
5032         /* If hot threads are enabled, and both newcallp and sq->socketp
5033          * are non-null, then this thread will process the call, and the
5034          * idle server thread will start listening on this threads socket.
5035          */
5036         opr_queue_Remove(&sq->entry);
5037
5038         if (rx_enable_hot_thread && newcallp && sq->socketp) {
5039             *newcallp = call;
5040             *tnop = sq->tno;
5041             *sq->socketp = socket;
5042             clock_GetTime(&call->startTime);
5043             CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
5044         } else {
5045             sq->newcall = call;
5046         }
5047         if (call->flags & RX_CALL_WAIT_PROC) {
5048             /* Conservative:  I don't think this should happen */
5049             call->flags &= ~RX_CALL_WAIT_PROC;
5050             rx_atomic_dec(&rx_nWaiting);
5051             if (opr_queue_IsOnQueue(&call->entry)) {
5052                 opr_queue_Remove(&call->entry);
5053             }
5054             CLEAR_CALL_QUEUE_LOCK(call);
5055         }
5056         call->state = RX_STATE_ACTIVE;
5057         call->app.mode = RX_MODE_RECEIVING;
5058 #ifdef RX_KERNEL_TRACE
5059         {
5060             int glockOwner = ISAFS_GLOCK();
5061             if (!glockOwner)
5062                 AFS_GLOCK();
5063             afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
5064                        __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
5065                        call);
5066             if (!glockOwner)
5067                 AFS_GUNLOCK();
5068         }
5069 #endif
5070         if (call->flags & RX_CALL_CLEARED) {
5071             /* send an ack now to start the packet flow up again */
5072             call->flags &= ~RX_CALL_CLEARED;
5073             rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
5074         }
5075 #ifdef  RX_ENABLE_LOCKS
5076         CV_SIGNAL(&sq->cv);
5077 #else
5078         service->nRequestsRunning++;
5079         MUTEX_ENTER(&rx_quota_mutex);
5080         if (service->nRequestsRunning <= service->minProcs)
5081             rxi_minDeficit--;
5082         rxi_availProcs--;
5083         MUTEX_EXIT(&rx_quota_mutex);
5084         osi_rxWakeup(sq);
5085 #endif
5086     }
5087     MUTEX_EXIT(&rx_serverPool_lock);
5088 }
5089
5090 /* Delay the sending of an acknowledge event for a short while, while
5091  * a new call is being prepared (in the case of a client) or a reply
5092  * is being prepared (in the case of a server).  Rather than sending
5093  * an ack packet, an ACKALL packet is sent. */
5094 static void
5095 rxi_AckAll(struct rx_call *call)
5096 {
5097     rxi_SendSpecial(call, call->conn, NULL, RX_PACKET_TYPE_ACKALL, 
5098                     NULL, 0, 0);
5099     call->flags |= RX_CALL_ACKALL_SENT;
5100 }
5101
5102 /*
5103  * Event handler for per-call delayed acks.
5104  * Also called synchronously, with |event| == NULL, to send a "delayed" ack
5105  * immediately.
5106  */
5107 static void
5108 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused1,
5109                    int unused2)
5110 {
5111     struct rx_call *call = arg1;
5112 #ifdef RX_ENABLE_LOCKS
5113     if (event) {
5114         MUTEX_ENTER(&call->lock);
5115         if (event == call->delayedAckEvent)
5116             rxevent_Put(&call->delayedAckEvent);
5117     }
5118     (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
5119     if (event)
5120         MUTEX_EXIT(&call->lock);
5121 #else /* RX_ENABLE_LOCKS */
5122     if (event)
5123         rxevent_Put(&call->delayedAckEvent);
5124     (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
5125 #endif /* RX_ENABLE_LOCKS */
5126     /* Release the call reference for the event that fired. */
5127     if (event)
5128         CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
5129 }
5130
5131 #ifdef RX_ENABLE_LOCKS
5132 /* Set ack in all packets in transmit queue. rxi_Start will deal with
5133  * clearing them out.
5134  */
5135 static void
5136 rxi_SetAcksInTransmitQueue(struct rx_call *call)
5137 {
5138     struct opr_queue *cursor;
5139     int someAcked = 0;
5140
5141     for (opr_queue_Scan(&call->tq, cursor)) {
5142         struct rx_packet *p 
5143                 = opr_queue_Entry(cursor, struct rx_packet, entry);
5144
5145         p->flags |= RX_PKTFLAG_ACKED;
5146         someAcked = 1;
5147     }
5148
5149     if (someAcked) {
5150         call->flags |= RX_CALL_TQ_CLEARME;
5151         call->flags |= RX_CALL_TQ_SOME_ACKED;
5152     }
5153
5154     rxi_rto_cancel(call);
5155
5156     call->tfirst = call->tnext;
5157     call->nSoftAcked = 0;
5158
5159     if (call->flags & RX_CALL_FAST_RECOVER) {
5160         call->flags &= ~RX_CALL_FAST_RECOVER;
5161         call->cwind = call->nextCwind;
5162         call->nextCwind = 0;
5163     }
5164
5165     CV_SIGNAL(&call->cv_twind);
5166 }
5167 #endif /* RX_ENABLE_LOCKS */
5168
5169 /*!
5170  * Acknowledge the whole transmit queue.
5171  *
5172  * If we're running without locks, or the transmit queue isn't busy, then
5173  * we can just clear the queue now. Otherwise, we have to mark all of the
5174  * packets as acknowledged, and let rxi_Start clear it later on
5175  */
5176 static void
5177 rxi_AckAllInTransmitQueue(struct rx_call *call)
5178 {
5179 #ifdef RX_ENABLE_LOCKS
5180     if (call->flags & RX_CALL_TQ_BUSY) {
5181         rxi_SetAcksInTransmitQueue(call);
5182         return;
5183     }
5184 #endif
5185     rxi_ClearTransmitQueue(call, 0);
5186 }
5187 /* Clear out the transmit queue for the current call (all packets have
5188  * been received by peer) */
5189 static void
5190 rxi_ClearTransmitQueue(struct rx_call *call, int force)
5191 {
5192 #ifdef  RX_ENABLE_LOCKS
5193     struct opr_queue *cursor;
5194     if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
5195         int someAcked = 0;
5196         for (opr_queue_Scan(&call->tq, cursor)) {
5197             struct rx_packet *p 
5198                 = opr_queue_Entry(cursor, struct rx_packet, entry);
5199
5200             p->flags |= RX_PKTFLAG_ACKED;
5201             someAcked = 1;
5202         }
5203         if (someAcked) {
5204             call->flags |= RX_CALL_TQ_CLEARME;
5205             call->flags |= RX_CALL_TQ_SOME_ACKED;
5206         }
5207     } else {
5208 #endif /* RX_ENABLE_LOCKS */
5209 #ifdef RXDEBUG_PACKET
5210         call->tqc -=
5211 #endif /* RXDEBUG_PACKET */
5212             rxi_FreePackets(0, &call->tq);
5213         rxi_WakeUpTransmitQueue(call);
5214 #ifdef RX_ENABLE_LOCKS
5215         call->flags &= ~RX_CALL_TQ_CLEARME;
5216     }
5217 #endif
5218
5219     rxi_rto_cancel(call);
5220     call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
5221     call->nSoftAcked = 0;
5222
5223     if (call->flags & RX_CALL_FAST_RECOVER) {
5224         call->flags &= ~RX_CALL_FAST_RECOVER;
5225         call->cwind = call->nextCwind;
5226     }
5227 #ifdef  RX_ENABLE_LOCKS
5228     CV_SIGNAL(&call->cv_twind);
5229 #else
5230     osi_rxWakeup(&call->twind);
5231 #endif
5232 }
5233
5234 static void
5235 rxi_ClearReceiveQueue(struct rx_call *call)
5236 {
5237     if (!opr_queue_IsEmpty(&call->rq)) {
5238         u_short count;
5239
5240         count = rxi_FreePackets(0, &call->rq);
5241         rx_packetReclaims += count;
5242 #ifdef RXDEBUG_PACKET
5243         call->rqc -= count;
5244         if ( call->rqc != 0 )
5245           dpf(("rxi_ClearReceiveQueue call %p rqc %u != 0\n", call, call->rqc));
5246 #endif
5247         call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
5248     }
5249     if (call->state == RX_STATE_PRECALL) {
5250         call->flags |= RX_CALL_CLEARED;
5251     }
5252 }
5253
5254 /* Send an abort packet for the specified call */
5255 static struct rx_packet *
5256 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
5257                   int istack, int force)
5258 {
5259     afs_int32 error;
5260     struct clock when, now;
5261
5262     if (!call->error)
5263         return packet;
5264
5265     /* Clients should never delay abort messages */
5266     if (rx_IsClientConn(call->conn))
5267         force = 1;
5268
5269     /*
5270      * An opcode that has been deprecated or has yet to be implemented is not
5271      * a misbehavior of the client.  Do not punish the client by introducing
5272      * delays.
5273      */
5274     if (call->error == RXGEN_OPCODE) {
5275         force = 1;
5276     } else if (call->abortCode != call->error) {
5277         call->abortCode = call->error;
5278         call->abortCount = 0;
5279     }
5280
5281     if (force || rxi_callAbortThreshhold == 0
5282         || call->abortCount < rxi_callAbortThreshhold) {
5283         rxi_CancelDelayedAbortEvent(call);
5284         error = htonl(call->error);
5285         if (!force)
5286             call->abortCount++;
5287         packet =
5288             rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5289                             (char *)&error, sizeof(error), istack);
5290     } else if (!call->delayedAbortEvent) {
5291         clock_GetTime(&now);
5292         when = now;
5293         clock_Addmsec(&when, rxi_callAbortDelay);
5294         CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
5295         call->delayedAbortEvent =
5296             rxevent_Post(&when, &now, rxi_SendDelayedCallAbort, call, 0, 0);
5297     }
5298     return packet;
5299 }
5300
5301 static void
5302 rxi_CancelDelayedAbortEvent(struct rx_call *call)
5303 {
5304     MUTEX_ASSERT(&call->lock);
5305     if (rxevent_Cancel(&call->delayedAbortEvent))
5306         CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
5307 }
5308
5309 /* Send an abort packet for the specified connection.  Packet is an
5310  * optional pointer to a packet that can be used to send the abort.
5311  * Once the number of abort messages reaches the threshhold, an
5312  * event is scheduled to send the abort. Setting the force flag
5313  * overrides sending delayed abort messages.
5314  *
5315  * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
5316  *       to send the abort packet.
5317  */
5318 struct rx_packet *
5319 rxi_SendConnectionAbort(struct rx_connection *conn,
5320                         struct rx_packet *packet, int istack, int force)
5321 {
5322     afs_int32 error;
5323
5324     if (!conn->error)
5325         return packet;
5326
5327     /* Clients should never delay abort messages */
5328     if (rx_IsClientConn(conn))
5329         force = 1;
5330
5331     if (force || rxi_connAbortThreshhold == 0
5332         || conn->abortCount < rxi_connAbortThreshhold) {
5333
5334         if (rxevent_Cancel(&conn->delayedAbortEvent))
5335             putConnection(conn);
5336         error = htonl(conn->error);
5337         conn->abortCount++;
5338         MUTEX_EXIT(&conn->conn_data_lock);
5339         packet =
5340             rxi_SendSpecial((struct rx_call *)0, conn, packet,
5341                             RX_PACKET_TYPE_ABORT, (char *)&error,
5342                             sizeof(error), istack);
5343         MUTEX_ENTER(&conn->conn_data_lock);
5344     } else {
5345         rxi_SendConnectionAbortLater(conn, rxi_connAbortDelay);
5346     }
5347     return packet;
5348 }
5349
5350 /* Associate an error all of the calls owned by a connection.  Called
5351  * with error non-zero.  This is only for really fatal things, like
5352  * bad authentication responses.  The connection itself is set in
5353  * error at this point, so that future packets received will be
5354  * rejected. */
5355 void
5356 rxi_ConnectionError(struct rx_connection *conn,
5357                     afs_int32 error)
5358 {
5359     if (error) {
5360         int i;
5361
5362         dpf(("rxi_ConnectionError conn %p error %d\n", conn, error));
5363
5364         MUTEX_ENTER(&conn->conn_data_lock);
5365         if (rxevent_Cancel(&conn->challengeEvent))
5366             putConnection(conn);
5367         if (rxevent_Cancel(&conn->natKeepAliveEvent))
5368             putConnection(conn);
5369         if (rxevent_Cancel(&conn->checkReachEvent)) {
5370             conn->flags &= ~(RX_CONN_ATTACHWAIT|RX_CONN_NAT_PING);
5371             putConnection(conn);
5372         }
5373         MUTEX_EXIT(&conn->conn_data_lock);
5374         for (i = 0; i < RX_MAXCALLS; i++) {
5375             struct rx_call *call = conn->call[i];
5376             if (call) {
5377                 MUTEX_ENTER(&call->lock);
5378                 rxi_CallError(call, error);
5379                 MUTEX_EXIT(&call->lock);
5380             }
5381         }
5382         conn->error = error;
5383         if (rx_stats_active)
5384             rx_atomic_inc(&rx_stats.fatalErrors);
5385     }
5386 }
5387
5388 /**
5389  * Interrupt an in-progress call with the specified error and wakeup waiters.
5390  *
5391  * @param[in] call  The call to interrupt
5392  * @param[in] error  The error code to send to the peer
5393  */
5394 void
5395 rx_InterruptCall(struct rx_call *call, afs_int32 error)
5396 {
5397     MUTEX_ENTER(&call->lock);
5398     rxi_CallError(call, error);
5399     rxi_SendCallAbort(call, NULL, 0, 1);
5400     MUTEX_EXIT(&call->lock);
5401 }
5402
5403 void
5404 rxi_CallError(struct rx_call *call, afs_int32 error)
5405 {
5406     MUTEX_ASSERT(&call->lock);
5407     dpf(("rxi_CallError call %p error %d call->error %d\n", call, error, call->error));
5408     if (call->error)
5409         error = call->error;
5410
5411 #ifdef RX_ENABLE_LOCKS
5412     if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
5413         rxi_ResetCall(call, 0);
5414     }
5415 #else
5416     rxi_ResetCall(call, 0);
5417 #endif
5418     call->error = error;
5419 }
5420
5421 /* Reset various fields in a call structure, and wakeup waiting
5422  * processes.  Some fields aren't changed: state & mode are not
5423  * touched (these must be set by the caller), and bufptr, nLeft, and
5424  * nFree are not reset, since these fields are manipulated by
5425  * unprotected macros, and may only be reset by non-interrupting code.
5426  */
5427
5428 static void
5429 rxi_ResetCall(struct rx_call *call, int newcall)
5430 {
5431     int flags;
5432     struct rx_peer *peer;
5433     struct rx_packet *packet;
5434
5435     MUTEX_ASSERT(&call->lock);
5436     dpf(("rxi_ResetCall(call %p, newcall %d)\n", call, newcall));
5437
5438     /* Notify anyone who is waiting for asynchronous packet arrival */
5439     if (call->arrivalProc) {
5440         (*call->arrivalProc) (call, call->arrivalProcHandle,
5441                               call->arrivalProcArg);
5442         call->arrivalProc = NULL;
5443     }
5444
5445
5446     rxi_CancelGrowMTUEvent(call);
5447
5448     if (call->delayedAbortEvent) {
5449         rxi_CancelDelayedAbortEvent(call);
5450         packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5451         if (packet) {
5452             rxi_SendCallAbort(call, packet, 0, 1);
5453             rxi_FreePacket(packet);
5454         }
5455     }
5456
5457     /*
5458      * Update the peer with the congestion information in this call
5459      * so other calls on this connection can pick up where this call
5460      * left off. If the congestion sequence numbers don't match then
5461      * another call experienced a retransmission.
5462      */
5463     peer = call->conn->peer;
5464     MUTEX_ENTER(&peer->peer_lock);
5465     if (!newcall) {
5466         if (call->congestSeq == peer->congestSeq) {
5467             peer->cwind = MAX(peer->cwind, call->cwind);
5468             peer->MTU = MAX(peer->MTU, call->MTU);
5469             peer->nDgramPackets =
5470                 MAX(peer->nDgramPackets, call->nDgramPackets);
5471         }
5472     } else {
5473         call->abortCode = 0;
5474         call->abortCount = 0;
5475     }
5476     if (peer->maxDgramPackets > 1) {
5477         call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
5478     } else {
5479         call->MTU = peer->MTU;
5480     }
5481     call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
5482     call->ssthresh = rx_maxSendWindow;
5483     call->nDgramPackets = peer->nDgramPackets;
5484     call->congestSeq = peer->congestSeq;
5485     call->rtt = peer->rtt;
5486     call->rtt_dev = peer->rtt_dev;
5487     clock_Zero(&call->rto);
5488     clock_Addmsec(&call->rto,
5489                   MAX(((call->rtt >> 3) + call->rtt_dev), rx_minPeerTimeout) + 200);
5490     MUTEX_EXIT(&peer->peer_lock);
5491
5492     flags = call->flags;
5493     rxi_WaitforTQBusy(call);
5494
5495     rxi_ClearTransmitQueue(call, 1);
5496     if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
5497         dpf(("rcall %p has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5498     }
5499     call->flags = 0;
5500
5501     rxi_ClearReceiveQueue(call);
5502     /* why init the queue if you just emptied it? queue_Init(&call->rq); */
5503
5504
5505     call->error = 0;
5506     call->twind = call->conn->twind[call->channel];
5507     call->rwind = call->conn->rwind[call->channel];
5508     call->nSoftAcked = 0;
5509     call->nextCwind = 0;
5510     call->nAcks = 0;
5511     call->nNacks = 0;
5512     call->nCwindAcks = 0;
5513     call->nSoftAcks = 0;
5514     call->nHardAcks = 0;
5515
5516     call->tfirst = call->rnext = call->tnext = 1;
5517     call->tprev = 0;
5518     call->rprev = 0;
5519     call->lastAcked = 0;
5520     call->localStatus = call->remoteStatus = 0;
5521
5522     if (flags & RX_CALL_READER_WAIT) {
5523 #ifdef  RX_ENABLE_LOCKS
5524         CV_BROADCAST(&call->cv_rq);
5525 #else
5526         osi_rxWakeup(&call->rq);
5527 #endif
5528     }
5529     if (flags & RX_CALL_WAIT_PACKETS) {
5530         MUTEX_ENTER(&rx_freePktQ_lock);
5531         rxi_PacketsUnWait();    /* XXX */
5532         MUTEX_EXIT(&rx_freePktQ_lock);
5533     }
5534 #ifdef  RX_ENABLE_LOCKS
5535     CV_SIGNAL(&call->cv_twind);
5536 #else
5537     if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5538         osi_rxWakeup(&call->twind);
5539 #endif
5540
5541     if (flags & RX_CALL_WAIT_PROC) {
5542         rx_atomic_dec(&rx_nWaiting);
5543     }
5544 #ifdef RX_ENABLE_LOCKS
5545     /* The following ensures that we don't mess with any queue while some
5546      * other thread might also be doing so. The call_queue_lock field is
5547      * is only modified under the call lock. If the call is in the process
5548      * of being removed from a queue, the call is not locked until the
5549      * the queue lock is dropped and only then is the call_queue_lock field
5550      * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5551      * Note that any other routine which removes a call from a queue has to
5552      * obtain the queue lock before examing the queue and removing the call.
5553      */
5554     if (call->call_queue_lock) {
5555         MUTEX_ENTER(call->call_queue_lock);
5556         if (opr_queue_IsOnQueue(&call->entry)) {
5557             opr_queue_Remove(&call->entry);
5558         }
5559         MUTEX_EXIT(call->call_queue_lock);
5560         CLEAR_CALL_QUEUE_LOCK(call);
5561     }
5562 #else /* RX_ENABLE_LOCKS */
5563     if (opr_queue_IsOnQueue(&call->entry)) {
5564         opr_queue_Remove(&call->entry);
5565     }
5566 #endif /* RX_ENABLE_LOCKS */
5567
5568     rxi_CancelKeepAliveEvent(call);
5569     rxi_CancelDelayedAckEvent(call);
5570 }
5571
5572 /* Send an acknowledge for the indicated packet (seq,serial) of the
5573  * indicated call, for the indicated reason (reason).  This
5574  * acknowledge will specifically acknowledge receiving the packet, and
5575  * will also specify which other packets for this call have been
5576  * received.  This routine returns the packet that was used to the
5577  * caller.  The caller is responsible for freeing it or re-using it.
5578  * This acknowledgement also returns the highest sequence number
5579  * actually read out by the higher level to the sender; the sender
5580  * promises to keep around packets that have not been read by the
5581  * higher level yet (unless, of course, the sender decides to abort
5582  * the call altogether).  Any of p, seq, serial, pflags, or reason may
5583  * be set to zero without ill effect.  That is, if they are zero, they
5584  * will not convey any information.
5585  * NOW there is a trailer field, after the ack where it will safely be
5586  * ignored by mundanes, which indicates the maximum size packet this
5587  * host can swallow.  */
5588 /*
5589     struct rx_packet *optionalPacket;  use to send ack (or null)
5590     int seq;                     Sequence number of the packet we are acking
5591     int serial;                  Serial number of the packet
5592     int pflags;                  Flags field from packet header
5593     int reason;                  Reason an acknowledge was prompted
5594 */
5595
5596 #define RX_ZEROS 1024
5597 static char rx_zeros[RX_ZEROS];
5598
5599 struct rx_packet *
5600 rxi_SendAck(struct rx_call *call,
5601             struct rx_packet *optionalPacket, int serial, int reason,
5602             int istack)
5603 {
5604     struct rx_ackPacket *ap;
5605     struct rx_packet *p;
5606     struct opr_queue *cursor;
5607     u_char offset = 0;
5608     afs_int32 templ;
5609     afs_uint32 padbytes = 0;
5610 #ifdef RX_ENABLE_TSFPQ
5611     struct rx_ts_info_t * rx_ts_info;
5612 #endif
5613
5614     /*
5615      * Open the receive window once a thread starts reading packets
5616      */
5617     if (call->rnext > 1) {
5618         call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5619     }
5620
5621     /* Don't attempt to grow MTU if this is a critical ping */
5622     if (reason == RX_ACK_MTU) {
5623         /* keep track of per-call attempts, if we're over max, do in small
5624          * otherwise in larger? set a size to increment by, decrease
5625          * on failure, here?
5626          */
5627         if (call->conn->peer->maxPacketSize &&
5628             (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5629              - RX_HEADER_SIZE))
5630             padbytes = call->conn->peer->maxPacketSize+16;
5631         else
5632             padbytes = call->conn->peer->maxMTU + 128;
5633
5634         /* do always try a minimum size ping */
5635         padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5636
5637         /* subtract the ack payload */
5638         padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5639         reason = RX_ACK_PING;
5640     }
5641
5642     call->nHardAcks = 0;
5643     call->nSoftAcks = 0;
5644     if (call->rnext > call->lastAcked)
5645         call->lastAcked = call->rnext;
5646     p = optionalPacket;
5647
5648     if (p) {
5649         rx_computelen(p, p->length);    /* reset length, you never know */
5650     } /* where that's been...         */
5651 #ifdef RX_ENABLE_TSFPQ
5652     else {
5653         RX_TS_INFO_GET(rx_ts_info);
5654         if ((p = rx_ts_info->local_special_packet)) {
5655             rx_computelen(p, p->length);
5656         } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5657             rx_ts_info->local_special_packet = p;
5658         } else { /* We won't send the ack, but don't panic. */
5659             return optionalPacket;
5660         }
5661     }
5662 #else
5663     else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5664         /* We won't send the ack, but don't panic. */
5665         return optionalPacket;
5666     }
5667 #endif
5668
5669     templ = padbytes +
5670         rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5671         rx_GetDataSize(p);
5672     if (templ > 0) {
5673         if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5674 #ifndef RX_ENABLE_TSFPQ
5675             if (!optionalPacket)
5676                 rxi_FreePacket(p);
5677 #endif
5678             return optionalPacket;
5679         }
5680         templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5681         if (rx_Contiguous(p) < templ) {
5682 #ifndef RX_ENABLE_TSFPQ
5683             if (!optionalPacket)
5684                 rxi_FreePacket(p);
5685 #endif
5686             return optionalPacket;
5687         }
5688     }
5689
5690
5691     /* MTUXXX failing to send an ack is very serious.  We should */
5692     /* try as hard as possible to send even a partial ack; it's */
5693     /* better than nothing. */
5694     ap = (struct rx_ackPacket *)rx_DataOf(p);
5695     ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5696     ap->reason = reason;
5697
5698     /* The skew computation used to be bogus, I think it's better now. */
5699     /* We should start paying attention to skew.    XXX  */
5700     ap->serial = htonl(serial);
5701     ap->maxSkew = 0;            /* used to be peer->inPacketSkew */
5702
5703     /*
5704      * First packet not yet forwarded to reader. When ACKALL has been
5705      * sent the peer has been told that all received packets will be
5706      * delivered to the reader.  The value 'rnext' is used internally
5707      * to refer to the next packet in the receive queue that must be
5708      * delivered to the reader.  From the perspective of the peer it
5709      * already has so report the last sequence number plus one if there
5710      * are packets in the receive queue awaiting processing.
5711      */
5712     if ((call->flags & RX_CALL_ACKALL_SENT) &&
5713         !opr_queue_IsEmpty(&call->rq)) {
5714         ap->firstPacket = htonl(opr_queue_Last(&call->rq, struct rx_packet, entry)->header.seq + 1);
5715     } else {
5716         ap->firstPacket = htonl(call->rnext);
5717
5718         ap->previousPacket = htonl(call->rprev);        /* Previous packet received */
5719
5720         /* No fear of running out of ack packet here because there can only 
5721          * be at most one window full of unacknowledged packets.  The window
5722          * size must be constrained to be less than the maximum ack size, 
5723          * of course.  Also, an ack should always fit into a single packet 
5724          * -- it should not ever be fragmented.  */
5725         offset = 0;
5726         for (opr_queue_Scan(&call->rq, cursor)) {
5727             struct rx_packet *rqp
5728                 = opr_queue_Entry(cursor, struct rx_packet, entry);
5729
5730             if (!rqp || !call->rq.next
5731                 || (rqp->header.seq > (call->rnext + call->rwind))) {
5732 #ifndef RX_ENABLE_TSFPQ
5733                 if (!optionalPacket)
5734                     rxi_FreePacket(p);
5735 #endif
5736                 rxi_CallError(call, RX_CALL_DEAD);
5737                 return optionalPacket;
5738             }
5739
5740             while (rqp->header.seq > call->rnext + offset)
5741                 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5742             ap->acks[offset++] = RX_ACK_TYPE_ACK;
5743
5744             if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5745 #ifndef RX_ENABLE_TSFPQ
5746                 if (!optionalPacket)
5747                     rxi_FreePacket(p);
5748 #endif
5749                 rxi_CallError(call, RX_CALL_DEAD);
5750                 return optionalPacket;
5751             }
5752         }
5753     }
5754
5755     ap->nAcks = offset;
5756     p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5757
5758     /* Must zero the 3 octets that rx_AckDataSize skips at the end of the
5759      * ACK list.
5760      */
5761     rx_packetwrite(p, rx_AckDataSize(offset) - 3, 3, rx_zeros);
5762
5763     /* these are new for AFS 3.3 */
5764     templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5765     templ = htonl(templ);
5766     rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5767     templ = htonl(call->conn->peer->ifMTU);
5768     rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5769                    sizeof(afs_int32), &templ);
5770
5771     /* new for AFS 3.4 */
5772     templ = htonl(call->rwind);
5773     rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5774                    sizeof(afs_int32), &templ);
5775
5776     /* new for AFS 3.5 */
5777     templ = htonl(call->conn->peer->ifDgramPackets);
5778     rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5779                    sizeof(afs_int32), &templ);
5780
5781     p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5782
5783     p->header.serviceId = call->conn->serviceId;
5784     p->header.cid = (call->conn->cid | call->channel);
5785     p->header.callNumber = *call->callNumber;
5786     p->header.seq = 0;
5787     p->header.securityIndex = call->conn->securityIndex;
5788     p->header.epoch = call->conn->epoch;
5789     p->header.type = RX_PACKET_TYPE_ACK;
5790     p->header.flags = RX_SLOW_START_OK;
5791     if (reason == RX_ACK_PING)
5792         p->header.flags |= RX_REQUEST_ACK;
5793
5794     while (padbytes > 0) {
5795         if (padbytes > RX_ZEROS) {
5796             rx_packetwrite(p, p->length, RX_ZEROS, rx_zeros);
5797             p->length += RX_ZEROS;
5798             padbytes -= RX_ZEROS;
5799         } else {
5800             rx_packetwrite(p, p->length, padbytes, rx_zeros);
5801             p->length += padbytes;
5802             padbytes = 0;
5803         }
5804     }
5805
5806     if (call->conn->type == RX_CLIENT_CONNECTION)
5807         p->header.flags |= RX_CLIENT_INITIATED;
5808
5809 #ifdef RXDEBUG
5810 #ifdef AFS_NT40_ENV
5811     if (rxdebug_active) {
5812         char msg[512];
5813         size_t len;
5814
5815         len = _snprintf(msg, sizeof(msg),
5816                         "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5817                          GetCurrentThreadId(), rx_ack_reason(ap->reason),
5818                          ntohl(ap->serial), ntohl(ap->previousPacket),
5819                          (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5820                          ap->nAcks, ntohs(ap->bufferSpace) );
5821         if (ap->nAcks) {
5822             int offset;
5823
5824             for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5825                 msg[len++] = ((ap->acks[offset] & RX_ACK_TYPE_ACK) != 0 ? '*'
5826                                                                         : '-');
5827         }
5828         msg[len++]='\n';
5829         msg[len] = '\0';
5830         OutputDebugString(msg);
5831     }
5832 #else /* AFS_NT40_ENV */
5833     if (rx_Log) {
5834         fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5835                 ap->reason, ntohl(ap->previousPacket),
5836                 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5837         if (ap->nAcks) {
5838             for (offset = 0; offset < ap->nAcks; offset++)
5839                 putc((ap->acks[offset] & RX_ACK_TYPE_ACK) != 0 ? '*' : '-',
5840                      rx_Log);
5841         }
5842         putc('\n', rx_Log);
5843     }
5844 #endif /* AFS_NT40_ENV */
5845 #endif
5846     {
5847         int i, nbytes = p->length;
5848
5849         for (i = 1; i < p->niovecs; i++) {      /* vec 0 is ALWAYS header */
5850             if (nbytes <= p->wirevec[i].iov_len) {
5851                 int savelen, saven;
5852
5853                 savelen = p->wirevec[i].iov_len;
5854                 saven = p->niovecs;
5855                 p->wirevec[i].iov_len = nbytes;
5856                 p->niovecs = i + 1;
5857                 rxi_Send(call, p, istack);
5858                 p->wirevec[i].iov_len = savelen;
5859                 p->niovecs = saven;
5860                 break;
5861             } else
5862                 nbytes -= p->wirevec[i].iov_len;
5863         }
5864     }
5865     if (rx_stats_active)
5866         rx_atomic_inc(&rx_stats.ackPacketsSent);
5867 #ifndef RX_ENABLE_TSFPQ
5868     if (!optionalPacket)
5869         rxi_FreePacket(p);
5870 #endif
5871     return optionalPacket;      /* Return packet for re-use by caller */
5872 }
5873
5874 struct xmitlist {
5875    struct rx_packet **list;
5876    int len;
5877    int resending;
5878 };
5879
5880 /* Send all of the packets in the list in single datagram */
5881 static void
5882 rxi_SendList(struct rx_call *call, struct xmitlist *xmit,
5883              int istack, int moreFlag)
5884 {
5885     int i;
5886     int requestAck = 0;
5887     int lastPacket = 0;
5888     struct clock now;
5889     struct rx_connection *conn = call->conn;
5890     struct rx_peer *peer = conn->peer;
5891
5892     MUTEX_ENTER(&peer->peer_lock);
5893     peer->nSent += xmit->len;
5894     if (xmit->resending)
5895         peer->reSends += xmit->len;
5896     MUTEX_EXIT(&peer->peer_lock);
5897
5898     if (rx_stats_active) {
5899         if (xmit->resending)
5900             rx_atomic_add(&rx_stats.dataPacketsReSent, xmit->len);
5901         else
5902             rx_atomic_add(&rx_stats.dataPacketsSent, xmit->len);
5903     }
5904
5905     clock_GetTime(&now);
5906
5907     if (xmit->list[xmit->len - 1]->header.flags & RX_LAST_PACKET) {
5908         lastPacket = 1;
5909     }
5910
5911     /* Set the packet flags and schedule the resend events */
5912     /* Only request an ack for the last packet in the list */
5913     for (i = 0; i < xmit->len; i++) {
5914         struct rx_packet *packet = xmit->list[i];
5915
5916         /* Record the time sent */
5917         packet->timeSent = now;
5918         packet->flags |= RX_PKTFLAG_SENT;
5919
5920         /* Ask for an ack on retransmitted packets,  on every other packet
5921          * if the peer doesn't support slow start. Ask for an ack on every
5922          * packet until the congestion window reaches the ack rate. */
5923         if (packet->header.serial) {
5924             requestAck = 1;
5925         } else {
5926             packet->firstSent = now;
5927             if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5928                                 || (!(call->flags & RX_CALL_SLOW_START_OK)
5929                                     && (packet->header.seq & 1)))) {
5930                 requestAck = 1;
5931             }
5932         }
5933
5934         /* Tag this packet as not being the last in this group,
5935          * for the receiver's benefit */
5936         if (i < xmit->len - 1 || moreFlag) {
5937             packet->header.flags |= RX_MORE_PACKETS;
5938         }
5939     }
5940
5941     if (requestAck) {
5942         xmit->list[xmit->len - 1]->header.flags |= RX_REQUEST_ACK;
5943     }
5944
5945     /* Since we're about to send a data packet to the peer, it's
5946      * safe to nuke any scheduled end-of-packets ack */
5947     rxi_CancelDelayedAckEvent(call);
5948
5949     MUTEX_EXIT(&call->lock);
5950     CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5951     if (xmit->len > 1) {
5952         rxi_SendPacketList(call, conn, xmit->list, xmit->len, istack);
5953     } else {
5954         rxi_SendPacket(call, conn, xmit->list[0], istack);
5955     }
5956     MUTEX_ENTER(&call->lock);
5957     CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5958
5959     /* Tell the RTO calculation engine that we have sent a packet, and
5960      * if it was the last one */
5961     rxi_rto_packet_sent(call, lastPacket, istack);
5962
5963     /* Update last send time for this call (for keep-alive
5964      * processing), and for the connection (so that we can discover
5965      * idle connections) */
5966     conn->lastSendTime = call->lastSendTime = clock_Sec();
5967 }
5968
5969 /* When sending packets we need to follow these rules:
5970  * 1. Never send more than maxDgramPackets in a jumbogram.
5971  * 2. Never send a packet with more than two iovecs in a jumbogram.
5972  * 3. Never send a retransmitted packet in a jumbogram.
5973  * 4. Never send more than cwind/4 packets in a jumbogram
5974  * We always keep the last list we should have sent so we
5975  * can set the RX_MORE_PACKETS flags correctly.
5976  */
5977
5978 static void
5979 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5980                  int istack)
5981 {
5982     int i;
5983     int recovery;
5984     struct xmitlist working;
5985     struct xmitlist last;
5986
5987     struct rx_peer *peer = call->conn->peer;
5988     int morePackets = 0;
5989
5990     memset(&last, 0, sizeof(struct xmitlist));
5991     working.list = &list[0];
5992     working.len = 0;
5993     working.resending = 0;
5994
5995     recovery = call->flags & RX_CALL_FAST_RECOVER;
5996
5997     for (i = 0; i < len; i++) {
5998         /* Does the current packet force us to flush the current list? */
5999         if (working.len > 0
6000             && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
6001                 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
6002
6003             /* This sends the 'last' list and then rolls the current working
6004              * set into the 'last' one, and resets the working set */
6005
6006             if (last.len > 0) {
6007                 rxi_SendList(call, &last, istack, 1);
6008                 /* If the call enters an error state stop sending, or if
6009                  * we entered congestion recovery mode, stop sending */
6010                 if (call->error
6011                     || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
6012                     return;
6013             }
6014             last = working;
6015             working.len = 0;
6016             working.resending = 0;
6017             working.list = &list[i];
6018         }
6019         /* Add the current packet to the list if it hasn't been acked.
6020          * Otherwise adjust the list pointer to skip the current packet.  */
6021         if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
6022             working.len++;
6023
6024             if (list[i]->header.serial)
6025                 working.resending = 1;
6026
6027             /* Do we need to flush the list? */
6028             if (working.len >= (int)peer->maxDgramPackets
6029                 || working.len >= (int)call->nDgramPackets 
6030                 || working.len >= (int)call->cwind
6031                 || list[i]->header.serial
6032                 || list[i]->length != RX_JUMBOBUFFERSIZE) {
6033                 if (last.len > 0) {
6034                     rxi_SendList(call, &last, istack, 1);
6035                     /* If the call enters an error state stop sending, or if
6036                      * we entered congestion recovery mode, stop sending */
6037                     if (call->error
6038                         || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
6039                         return;
6040                 }
6041                 last = working;
6042                 working.len = 0;
6043                 working.resending = 0;
6044                 working.list = &list[i + 1];
6045             }
6046         } else {
6047             if (working.len != 0) {
6048                 osi_Panic("rxi_SendList error");
6049             }
6050             working.list = &list[i + 1];
6051         }
6052     }
6053
6054     /* Send the whole list when the call is in receive mode, when
6055      * the call is in eof mode, when we are in fast recovery mode,
6056      * and when we have the last packet */
6057     /* XXX - The accesses to app.mode aren't safe, as this may be called by
6058      * the listener or event threads
6059      */
6060     if ((list[len - 1]->header.flags & RX_LAST_PACKET)
6061         || (call->flags & RX_CALL_FLUSH)
6062         || (call->flags & RX_CALL_FAST_RECOVER)) {
6063         /* Check for the case where the current list contains
6064          * an acked packet. Since we always send retransmissions
6065          * in a separate packet, we only need to check the first
6066          * packet in the list */
6067         if (working.len > 0 && !(working.list[0]->flags & RX_PKTFLAG_ACKED)) {
6068             morePackets = 1;
6069         }
6070         if (last.len > 0) {
6071             rxi_SendList(call, &last, istack, morePackets);
6072             /* If the call enters an error state stop sending, or if
6073              * we entered congestion recovery mode, stop sending */
6074             if (call->error
6075                 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
6076                 return;
6077         }
6078         if (morePackets) {
6079             rxi_SendList(call, &working, istack, 0);
6080         }
6081     } else if (last.len > 0) {
6082         rxi_SendList(call, &last, istack, 0);
6083         /* Packets which are in 'working' are not sent by this call */
6084     }
6085 }
6086
6087 /**
6088  * Check if the peer for the given call is known to be dead
6089  *
6090  * If the call's peer appears dead (it has encountered fatal network errors
6091  * since the call started) the call is killed with RX_CALL_DEAD if the call
6092  * is active. Otherwise, we do nothing.
6093  *
6094  * @param[in] call  The call to check
6095  *
6096  * @return status
6097  *  @retval 0 The call is fine, and we haven't done anything to the call
6098  *  @retval nonzero The call's peer appears dead, and the call has been
6099  *                  terminated if it was active
6100  *
6101  * @pre call->lock must be locked
6102  */
6103 static int
6104 rxi_CheckPeerDead(struct rx_call *call)
6105 {
6106 #ifdef AFS_RXERRQ_ENV
6107     int peererrs;
6108
6109     if (call->state == RX_STATE_DALLY) {
6110         return 0;
6111     }
6112
6113     peererrs = rx_atomic_read(&call->conn->peer->neterrs);
6114     if (call->neterr_gen < peererrs) {
6115         /* we have received network errors since this call started; kill
6116          * the call */
6117         if (call->state == RX_STATE_ACTIVE) {
6118             rxi_CallError(call, RX_CALL_DEAD);
6119         }
6120         return -1;
6121     }
6122     if (call->neterr_gen > peererrs) {
6123         /* someone has reset the number of peer errors; set the call error gen
6124          * so we can detect if more errors are encountered */
6125         call->neterr_gen = peererrs;
6126     }
6127 #endif
6128     return 0;
6129 }
6130
6131 static void
6132 rxi_Resend(struct rxevent *event, void *arg0, void *arg1, int istack)
6133 {
6134     struct rx_call *call = arg0;
6135     struct rx_peer *peer;
6136     struct opr_queue *cursor;
6137     struct clock maxTimeout = { 60, 0 };
6138
6139     MUTEX_ENTER(&call->lock);
6140
6141     peer = call->conn->peer;
6142
6143     /* Make sure that the event pointer is removed from the call
6144      * structure, since there is no longer a per-call retransmission
6145      * event pending. */
6146     if (event == call->resendEvent)
6147         rxevent_Put(&call->resendEvent);
6148
6149     rxi_CheckPeerDead(call);
6150
6151     if (opr_queue_IsEmpty(&call->tq)) {
6152         /* Nothing to do. This means that we've been raced, and that an
6153          * ACK has come in between when we were triggered, and when we
6154          * actually got to run. */
6155         goto out;
6156     }
6157
6158     /* We're in loss recovery */
6159     call->flags |= RX_CALL_FAST_RECOVER;
6160
6161     /* Mark all of the pending packets in the queue as being lost */
6162     for (opr_queue_Scan(&call->tq, cursor)) {
6163         struct rx_packet *p = opr_queue_Entry(cursor, struct rx_packet, entry);
6164         if (!(p->flags & RX_PKTFLAG_ACKED))
6165             p->flags &= ~RX_PKTFLAG_SENT;
6166     }
6167
6168     /* We're resending, so we double the timeout of the call. This will be
6169      * dropped back down by the first successful ACK that we receive.
6170      *
6171      * We apply a maximum value here of 60 seconds
6172      */
6173     clock_Add(&call->rto, &call->rto);
6174     if (clock_Gt(&call->rto, &maxTimeout))
6175         call->rto = maxTimeout;
6176
6177     /* Packet loss is most likely due to congestion, so drop our window size
6178      * and start again from the beginning */
6179     if (peer->maxDgramPackets >1) {
6180         call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
6181         call->MTU = MIN(peer->natMTU, peer->maxMTU);
6182     }
6183     call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
6184     call->nDgramPackets = 1;
6185     call->cwind = 1;
6186     call->nextCwind = 1;
6187     call->nAcks = 0;
6188     call->nNacks = 0;
6189     MUTEX_ENTER(&peer->peer_lock);
6190     peer->MTU = call->MTU;
6191     peer->cwind = call->cwind;
6192     peer->nDgramPackets = 1;
6193     peer->congestSeq++;
6194     call->congestSeq = peer->congestSeq;
6195     MUTEX_EXIT(&peer->peer_lock);
6196
6197     rxi_Start(call, istack);
6198
6199 out:
6200     CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
6201     MUTEX_EXIT(&call->lock);
6202 }
6203
6204 /* This routine is called when new packets are readied for
6205  * transmission and when retransmission may be necessary, or when the
6206  * transmission window or burst count are favourable.  This should be
6207  * better optimized for new packets, the usual case, now that we've
6208  * got rid of queues of send packets. XXXXXXXXXXX */
6209 void
6210 rxi_Start(struct rx_call *call, int istack)
6211 {
6212     struct opr_queue *cursor;
6213 #ifdef RX_ENABLE_LOCKS
6214     struct opr_queue *store;
6215 #endif
6216     int nXmitPackets;
6217     int maxXmitPackets;
6218
6219     if (call->error) {
6220 #ifdef RX_ENABLE_LOCKS
6221         if (rx_stats_active)
6222             rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
6223 #endif
6224         return;
6225     }
6226
6227     if (!opr_queue_IsEmpty(&call->tq)) {        /* If we have anything to send */
6228         /* Send (or resend) any packets that need it, subject to
6229          * window restrictions and congestion burst control
6230          * restrictions.  Ask for an ack on the last packet sent in
6231          * this burst.  For now, we're relying upon the window being
6232          * considerably bigger than the largest number of packets that
6233          * are typically sent at once by one initial call to
6234          * rxi_Start.  This is probably bogus (perhaps we should ask
6235          * for an ack when we're half way through the current
6236          * window?).  Also, for non file transfer applications, this
6237          * may end up asking for an ack for every packet.  Bogus. XXXX
6238          */
6239         /*
6240          * But check whether we're here recursively, and let the other guy
6241          * do the work.
6242          */
6243 #ifdef RX_ENABLE_LOCKS
6244         if (!(call->flags & RX_CALL_TQ_BUSY)) {
6245             call->flags |= RX_CALL_TQ_BUSY;
6246             do {
6247 #endif /* RX_ENABLE_LOCKS */
6248             restart:
6249 #ifdef RX_ENABLE_LOCKS
6250                 call->flags &= ~RX_CALL_NEED_START;
6251 #endif /* RX_ENABLE_LOCKS */
6252                 nXmitPackets = 0;
6253                 maxXmitPackets = MIN(call->twind, call->cwind);
6254                 for (opr_queue_Scan(&call->tq, cursor)) {
6255                     struct rx_packet *p
6256                         = opr_queue_Entry(cursor, struct rx_packet, entry);
6257
6258                     if (p->flags & RX_PKTFLAG_ACKED) {
6259                         /* Since we may block, don't trust this */
6260                         if (rx_stats_active)
6261                             rx_atomic_inc(&rx_stats.ignoreAckedPacket);
6262                         continue;       /* Ignore this packet if it has been acknowledged */
6263                     }
6264
6265                     /* Turn off all flags except these ones, which are the same
6266                      * on each transmission */
6267                     p->header.flags &= RX_PRESET_FLAGS;
6268
6269                     if (p->header.seq >=
6270                         call->tfirst + MIN((int)call->twind,
6271                                            (int)(call->nSoftAcked +
6272                                                  call->cwind))) {
6273                         call->flags |= RX_CALL_WAIT_WINDOW_SEND;        /* Wait for transmit window */
6274                         /* Note: if we're waiting for more window space, we can
6275                          * still send retransmits; hence we don't return here, but
6276                          * break out to schedule a retransmit event */
6277                         dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
6278                              *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
6279                              call->cwind));
6280                         break;
6281                     }
6282
6283                     /* Transmit the packet if it needs to be sent. */
6284                     if (!(p->flags & RX_PKTFLAG_SENT)) {
6285                         if (nXmitPackets == maxXmitPackets) {
6286                             rxi_SendXmitList(call, call->xmitList,
6287                                              nXmitPackets, istack);
6288                             goto restart;
6289                         }
6290                        dpf(("call %d xmit packet %p\n",
6291                               *(call->callNumber), p));
6292                         call->xmitList[nXmitPackets++] = p;
6293                     }
6294                 } /* end of the queue_Scan */
6295
6296                 /* xmitList now hold pointers to all of the packets that are
6297                  * ready to send. Now we loop to send the packets */
6298                 if (nXmitPackets > 0) {
6299                     rxi_SendXmitList(call, call->xmitList, nXmitPackets,
6300                                      istack);
6301                 }
6302
6303 #ifdef RX_ENABLE_LOCKS
6304                 if (call->error) {
6305                     /* We went into the error state while sending packets. Now is
6306                      * the time to reset the call. This will also inform the using
6307                      * process that the call is in an error state.
6308                      */
6309                     if (rx_stats_active)
6310                         rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
6311                     call->flags &= ~RX_CALL_TQ_BUSY;
6312                     rxi_WakeUpTransmitQueue(call);
6313                     rxi_CallError(call, call->error);
6314                     return;
6315                 }
6316
6317                 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
6318                     int missing;
6319                     call->flags &= ~RX_CALL_TQ_SOME_ACKED;
6320                     /* Some packets have received acks. If they all have, we can clear
6321                      * the transmit queue.
6322                      */
6323                     missing = 0;
6324                     for (opr_queue_ScanSafe(&call->tq, cursor, store)) {
6325                         struct rx_packet *p
6326                             = opr_queue_Entry(cursor, struct rx_packet, entry);
6327
6328                         if (p->header.seq < call->tfirst
6329                             && (p->flags & RX_PKTFLAG_ACKED)) {
6330                             opr_queue_Remove(&p->entry);
6331 #ifdef RX_TRACK_PACKETS
6332                             p->flags &= ~RX_PKTFLAG_TQ;
6333 #endif
6334 #ifdef RXDEBUG_PACKET
6335                             call->tqc--;
6336 #endif
6337                             rxi_FreePacket(p);
6338                         } else
6339                             missing = 1;
6340                     }
6341                     if (!missing)
6342                         call->flags |= RX_CALL_TQ_CLEARME;
6343                 }
6344                 if (call->flags & RX_CALL_TQ_CLEARME)
6345                     rxi_ClearTransmitQueue(call, 1);
6346             } while (call->flags & RX_CALL_NEED_START);
6347             /*
6348              * TQ references no longer protected by this flag; they must remain
6349              * protected by the call lock.
6350              */
6351             call->flags &= ~RX_CALL_TQ_BUSY;
6352             rxi_WakeUpTransmitQueue(call);
6353         } else {
6354             call->flags |= RX_CALL_NEED_START;
6355         }
6356 #endif /* RX_ENABLE_LOCKS */
6357     } else {
6358         rxi_rto_cancel(call);
6359     }
6360 }
6361
6362 /* Also adjusts the keep alive parameters for the call, to reflect
6363  * that we have just sent a packet (so keep alives aren't sent
6364  * immediately) */
6365 void
6366 rxi_Send(struct rx_call *call, struct rx_packet *p,
6367          int istack)
6368 {
6369     int code;
6370     struct rx_connection *conn = call->conn;
6371
6372     /* Stamp each packet with the user supplied status */
6373     p->header.userStatus = call->localStatus;
6374
6375     /* Allow the security object controlling this call's security to
6376      * make any last-minute changes to the packet */
6377     code = RXS_SendPacket(conn->securityObject, call, p);
6378     if (code) {
6379         MUTEX_EXIT(&call->lock);
6380         CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6381         rxi_ConnectionError(conn, code);
6382         CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6383         MUTEX_ENTER(&call->lock);
6384         return;
6385     }
6386
6387     /* Since we're about to send SOME sort of packet to the peer, it's
6388      * safe to nuke any scheduled end-of-packets ack */
6389     rxi_CancelDelayedAckEvent(call);
6390
6391     /* Actually send the packet, filling in more connection-specific fields */
6392     MUTEX_EXIT(&call->lock);
6393     CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6394     rxi_SendPacket(call, conn, p, istack);
6395     CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6396     MUTEX_ENTER(&call->lock);
6397
6398     /* Update last send time for this call (for keep-alive
6399      * processing), and for the connection (so that we can discover
6400      * idle connections) */
6401     if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6402         (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
6403         (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
6404     {
6405         conn->lastSendTime = call->lastSendTime = clock_Sec();
6406     }
6407 }
6408
6409 /* Check if a call needs to be destroyed.  Called by keep-alive code to ensure
6410  * that things are fine.  Also called periodically to guarantee that nothing
6411  * falls through the cracks (e.g. (error + dally) connections have keepalive
6412  * turned off.  Returns 0 if conn is well, -1 otherwise.  If otherwise, call
6413  *  may be freed!
6414  * haveCTLock Set if calling from rxi_ReapConnections
6415  */
6416 static int
6417 rxi_CheckCall(struct rx_call *call, int haveCTLock)
6418 {
6419     struct rx_connection *conn = call->conn;
6420     afs_uint32 now;
6421     afs_uint32 deadTime, idleDeadTime = 0, hardDeadTime = 0;
6422     afs_uint32 fudgeFactor;
6423     int cerror = 0;
6424     int newmtu = 0;
6425     int idle_timeout = 0;
6426     afs_int32  clock_diff = 0;
6427
6428     if (rxi_CheckPeerDead(call)) {
6429         return -1;
6430     }
6431
6432     now = clock_Sec();
6433
6434     /* Large swings in the clock can have a significant impact on
6435      * the performance of RX call processing.  Forward clock shifts
6436      * will result in premature event triggering or timeouts.
6437      * Backward shifts can result in calls not completing until
6438      * the clock catches up with the original start clock value.
6439      *
6440      * If a backward clock shift of more than five minutes is noticed,
6441      * just fail the call.
6442      */
6443     if (now < call->lastSendTime)
6444         clock_diff = call->lastSendTime - now;
6445     if (now < call->startWait)
6446         clock_diff = MAX(clock_diff, call->startWait - now);
6447     if (now < call->lastReceiveTime)
6448         clock_diff = MAX(clock_diff, call->lastReceiveTime - now);
6449     if (clock_diff > 5 * 60)
6450     {
6451         if (call->state == RX_STATE_ACTIVE)
6452             rxi_CallError(call, RX_CALL_TIMEOUT);
6453         return -1;
6454     }
6455
6456 #ifdef RX_ENABLE_LOCKS
6457     if (call->flags & RX_CALL_TQ_BUSY) {
6458         /* Call is active and will be reset by rxi_Start if it's
6459          * in an error state.
6460          */
6461         return 0;
6462     }
6463 #endif
6464     /* RTT + 8*MDEV, rounded up to the next second. */
6465     fudgeFactor = (((afs_uint32) call->rtt >> 3) +
6466                    ((afs_uint32) call->rtt_dev << 1) + 1023) >> 10;
6467
6468     deadTime = conn->secondsUntilDead + fudgeFactor;
6469     /* These are computed to the second (+- 1 second).  But that's
6470      * good enough for these values, which should be a significant
6471      * number of seconds. */
6472     if (now > (call->lastReceiveTime + deadTime)) {
6473         if (call->state == RX_STATE_ACTIVE) {
6474             cerror = RX_CALL_DEAD;
6475             goto mtuout;
6476         } else {
6477 #ifdef RX_ENABLE_LOCKS
6478             /* Cancel pending events */
6479             rxi_CancelDelayedAckEvent(call);
6480             rxi_rto_cancel(call);
6481             rxi_CancelKeepAliveEvent(call);
6482             rxi_CancelGrowMTUEvent(call);
6483             MUTEX_ENTER(&rx_refcnt_mutex);
6484             /* if rxi_FreeCall returns 1 it has freed the call */
6485             if (call->refCount == 0 &&
6486                 rxi_FreeCall(call, haveCTLock))
6487             {
6488                 MUTEX_EXIT(&rx_refcnt_mutex);
6489                 return -2;
6490             }
6491             MUTEX_EXIT(&rx_refcnt_mutex);
6492             return -1;
6493 #else /* RX_ENABLE_LOCKS */
6494             rxi_FreeCall(call, 0);
6495             return -2;
6496 #endif /* RX_ENABLE_LOCKS */
6497         }
6498         /* Non-active calls are destroyed if they are not responding
6499          * to pings; active calls are simply flagged in error, so the
6500          * attached process can die reasonably gracefully. */
6501     }
6502
6503     if (conn->idleDeadTime) {
6504         idleDeadTime = conn->idleDeadTime + fudgeFactor;
6505     }
6506
6507     if (idleDeadTime) {
6508         /* see if we have a non-activity timeout */
6509         if (call->startWait && ((call->startWait + idleDeadTime) < now)) {
6510             if (call->state == RX_STATE_ACTIVE) {
6511                 cerror = RX_CALL_TIMEOUT;
6512                 goto mtuout;
6513             }
6514         }
6515     }
6516
6517     if (conn->hardDeadTime) {
6518         hardDeadTime = conn->hardDeadTime + fudgeFactor;
6519     }
6520
6521     /* see if we have a hard timeout */
6522     if (hardDeadTime
6523         && (now > (hardDeadTime + call->startTime.sec))) {
6524         if (call->state == RX_STATE_ACTIVE)
6525             rxi_CallError(call, RX_CALL_TIMEOUT);
6526         return -1;
6527     }
6528     return 0;
6529 mtuout:
6530     if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT && !idle_timeout &&
6531         call->lastReceiveTime) {
6532         int oldMTU = conn->peer->ifMTU;
6533
6534         /* If we thought we could send more, perhaps things got worse.
6535          * Shrink by 128 bytes and try again. */
6536         if (conn->peer->maxPacketSize < conn->lastPacketSize)
6537             /* maxPacketSize will be cleared in rxi_SetPeerMtu */
6538             newmtu = MAX(conn->peer->maxPacketSize + RX_HEADER_SIZE,
6539                          conn->lastPacketSize - 128 + RX_HEADER_SIZE);
6540         else
6541             newmtu = conn->lastPacketSize - 128 + RX_HEADER_SIZE;
6542
6543         /* minimum capped in SetPeerMtu */
6544         rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6545
6546         /* clean up */
6547         conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
6548
6549         /* needed so ResetCall doesn't clobber us. */
6550         call->MTU = conn->peer->ifMTU;
6551
6552         /* if we never succeeded, let the error pass out as-is */
6553         if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6554             cerror = conn->msgsizeRetryErr;
6555
6556     }
6557     rxi_CallError(call, cerror);
6558     return -1;
6559 }
6560
6561 void
6562 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1,
6563                       void *dummy, int dummy2)
6564 {
6565     struct rx_connection *conn = arg1;
6566     struct rx_header theader;
6567     char tbuffer[1 + sizeof(struct rx_header)];
6568     struct sockaddr_in taddr;
6569     char *tp;
6570     char a[1] = { 0 };
6571     int resched = 0;
6572     struct iovec tmpiov[2];
6573     osi_socket socket =
6574         (conn->type ==
6575          RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6576
6577
6578     tp = &tbuffer[sizeof(struct rx_header)];
6579     taddr.sin_family = AF_INET;
6580     taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6581     taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6582     memset(&taddr.sin_zero, 0, sizeof(taddr.sin_zero));
6583 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6584     taddr.sin_len = sizeof(struct sockaddr_in);
6585 #endif
6586     memset(&theader, 0, sizeof(theader));
6587     theader.epoch = htonl(999);
6588     theader.cid = 0;
6589     theader.callNumber = 0;
6590     theader.seq = 0;
6591     theader.serial = 0;
6592     theader.type = RX_PACKET_TYPE_VERSION;
6593     theader.flags = RX_LAST_PACKET;
6594     theader.serviceId = 0;
6595
6596     memcpy(tbuffer, &theader, sizeof(theader));
6597     memcpy(tp, &a, sizeof(a));
6598     tmpiov[0].iov_base = tbuffer;
6599     tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6600
6601     rxi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6602
6603     MUTEX_ENTER(&conn->conn_data_lock);
6604     /* We ran, so the handle is no longer needed to try to cancel ourselves. */
6605     if (event == conn->natKeepAliveEvent)
6606         rxevent_Put(&conn->natKeepAliveEvent);
6607     MUTEX_ENTER(&rx_refcnt_mutex);
6608     /* Only reschedule ourselves if the connection would not be destroyed */
6609     if (conn->refCount > 1)
6610         resched = 1;
6611     if (conn->refCount <= 0) {
6612 #ifdef RX_REFCOUNT_CHECK
6613         osi_Assert(conn->refCount == 0);
6614 #endif
6615         if (rx_stats_active) {
6616             MUTEX_ENTER(&rx_stats_mutex);
6617             rxi_lowConnRefCount++;
6618             MUTEX_EXIT(&rx_stats_mutex);
6619         }
6620     }
6621     MUTEX_EXIT(&rx_refcnt_mutex);
6622     if (resched)
6623         rxi_ScheduleNatKeepAliveEvent(conn);
6624     MUTEX_EXIT(&conn->conn_data_lock);
6625     putConnection(conn);
6626 }
6627
6628 static void
6629 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6630 {
6631     MUTEX_ASSERT(&conn->conn_data_lock);
6632     if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6633         struct clock when, now;
6634         clock_GetTime(&now);
6635         when = now;
6636         when.sec += conn->secondsUntilNatPing;
6637         rx_GetConnection(conn);
6638         conn->natKeepAliveEvent =
6639             rxevent_Post(&when, &now, rxi_NatKeepAliveEvent, conn, NULL, 0);
6640     }
6641 }
6642
6643 void
6644 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6645 {
6646     MUTEX_ENTER(&conn->conn_data_lock);
6647     conn->secondsUntilNatPing = seconds;
6648     if (seconds != 0) {
6649         if (!(conn->flags & RX_CONN_ATTACHWAIT))
6650             rxi_ScheduleNatKeepAliveEvent(conn);
6651         else
6652             conn->flags |= RX_CONN_NAT_PING;
6653     }
6654     MUTEX_EXIT(&conn->conn_data_lock);
6655 }
6656
6657 /* When a call is in progress, this routine is called occasionally to
6658  * make sure that some traffic has arrived (or been sent to) the peer.
6659  * If nothing has arrived in a reasonable amount of time, the call is
6660  * declared dead; if nothing has been sent for a while, we send a
6661  * keep-alive packet (if we're actually trying to keep the call alive)
6662  */
6663 void
6664 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy,
6665                    int dummy2)
6666 {
6667     struct rx_call *call = arg1;
6668     struct rx_connection *conn;
6669     afs_uint32 now;
6670
6671     MUTEX_ENTER(&call->lock);
6672
6673     if (event == call->keepAliveEvent)
6674         rxevent_Put(&call->keepAliveEvent);
6675
6676     now = clock_Sec();
6677
6678     if (rxi_CheckCall(call, 0)) {
6679         MUTEX_EXIT(&call->lock);
6680         CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6681         return;
6682     }
6683
6684     /* Don't try to keep alive dallying calls */
6685     if (call->state == RX_STATE_DALLY) {
6686         MUTEX_EXIT(&call->lock);
6687         CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6688         return;
6689     }
6690
6691     conn = call->conn;
6692     if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6693         /* Don't try to send keepalives if there is unacknowledged data */
6694         /* the rexmit code should be good enough, this little hack
6695          * doesn't quite work XXX */
6696         (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6697     }
6698     rxi_ScheduleKeepAliveEvent(call);
6699     MUTEX_EXIT(&call->lock);
6700     CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6701 }
6702
6703 /* Does what's on the nameplate. */
6704 void
6705 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy, int dummy2)
6706 {
6707     struct rx_call *call = arg1;
6708     struct rx_connection *conn;
6709
6710     MUTEX_ENTER(&call->lock);
6711
6712     if (event == call->growMTUEvent)
6713         rxevent_Put(&call->growMTUEvent);
6714
6715     if (rxi_CheckCall(call, 0))
6716         goto out;
6717
6718     /* Don't bother with dallying calls */
6719     if (call->state == RX_STATE_DALLY)
6720         goto out;
6721
6722     conn = call->conn;
6723
6724     /*
6725      * keep being scheduled, just don't do anything if we're at peak,
6726      * or we're not set up to be properly handled (idle timeout required)
6727      */
6728     if ((conn->peer->maxPacketSize != 0) &&
6729         (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6730         conn->idleDeadTime)
6731         (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6732     rxi_ScheduleGrowMTUEvent(call, 0);
6733 out:
6734     MUTEX_EXIT(&call->lock);
6735     CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6736 }
6737
6738 static void
6739 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6740 {
6741     MUTEX_ASSERT(&call->lock);
6742     if (!call->keepAliveEvent) {
6743         struct clock when, now;
6744         clock_GetTime(&now);
6745         when = now;
6746         when.sec += call->conn->secondsUntilPing;
6747         CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6748         call->keepAliveEvent =
6749             rxevent_Post(&when, &now, rxi_KeepAliveEvent, call, NULL, 0);
6750     }
6751 }
6752
6753 static void
6754 rxi_CancelKeepAliveEvent(struct rx_call *call) {
6755     MUTEX_ASSERT(&call->lock);
6756     if (rxevent_Cancel(&call->keepAliveEvent))
6757         CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6758 }
6759
6760 static void
6761 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6762 {
6763     MUTEX_ASSERT(&call->lock);
6764     if (!call->growMTUEvent) {
6765         struct clock when, now;
6766
6767         clock_GetTime(&now);
6768         when = now;
6769         if (!secs) {
6770             if (call->conn->secondsUntilPing)
6771                 secs = (6*call->conn->secondsUntilPing)-1;
6772
6773             if (call->conn->secondsUntilDead)
6774                 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6775         }
6776
6777         when.sec += secs;
6778         CALL_HOLD(call, RX_CALL_REFCOUNT_MTU);
6779         call->growMTUEvent =
6780             rxevent_Post(&when, &now, rxi_GrowMTUEvent, call, NULL, 0);
6781     }
6782 }
6783
6784 static void
6785 rxi_CancelGrowMTUEvent(struct rx_call *call)
6786 {
6787     MUTEX_ASSERT(&call->lock);
6788     if (rxevent_Cancel(&call->growMTUEvent))
6789         CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6790 }
6791
6792 /*
6793  * Increment the counter for the next connection ID.
6794  * Wrapping on unsigned integer overflow is the intended behavior.
6795  */
6796 static void
6797 update_nextCid(void)
6798 {
6799     rx_nextCid += 1 << RX_CIDSHIFT;
6800 }
6801
6802 static void
6803 rxi_KeepAliveOn(struct rx_call *call)
6804 {
6805     /* Pretend last packet received was received now--i.e. if another
6806      * packet isn't received within the keep alive time, then the call
6807      * will die; Initialize last send time to the current time--even
6808      * if a packet hasn't been sent yet.  This will guarantee that a
6809      * keep-alive is sent within the ping time */
6810     call->lastReceiveTime = call->lastSendTime = clock_Sec();
6811     rxi_ScheduleKeepAliveEvent(call);
6812 }
6813
6814 static void
6815 rxi_GrowMTUOn(struct rx_call *call)
6816 {
6817     struct rx_connection *conn = call->conn;
6818     MUTEX_ENTER(&conn->conn_data_lock);
6819     conn->lastPingSizeSer = conn->lastPingSize = 0;
6820     MUTEX_EXIT(&conn->conn_data_lock);
6821     rxi_ScheduleGrowMTUEvent(call, 1);
6822 }
6823
6824 /* This routine is called to send connection abort messages
6825  * that have been delayed to throttle looping clients. */
6826 static void
6827 rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1, void *unused,
6828                          int unused2)
6829 {
6830     struct rx_connection *conn = arg1;
6831
6832     afs_int32 error;
6833     struct rx_packet *packet;
6834
6835     MUTEX_ENTER(&conn->conn_data_lock);
6836     if (event == conn->delayedAbortEvent)
6837         rxevent_Put(&conn->delayedAbortEvent);
6838     error = htonl(conn->error);
6839     conn->abortCount++;
6840     MUTEX_EXIT(&conn->conn_data_lock);
6841     packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6842     if (packet) {
6843         packet =
6844             rxi_SendSpecial((struct rx_call *)0, conn, packet,
6845                             RX_PACKET_TYPE_ABORT, (char *)&error,
6846                             sizeof(error), 0);
6847         rxi_FreePacket(packet);
6848     }
6849     putConnection(conn);
6850 }
6851
6852 /* This routine is called to send call abort messages
6853  * that have been delayed to throttle looping clients. */
6854 static void
6855 rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1, void *dummy,
6856                          int dummy2)
6857 {
6858     struct rx_call *call = arg1;
6859
6860     afs_int32 error;
6861     struct rx_packet *packet;
6862
6863     MUTEX_ENTER(&call->lock);
6864     if (event == call->delayedAbortEvent)
6865         rxevent_Put(&call->delayedAbortEvent);
6866     error = htonl(call->error);
6867     call->abortCount++;
6868     packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6869     if (packet) {
6870         packet =
6871             rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6872                             (char *)&error, sizeof(error), 0);
6873         rxi_FreePacket(packet);
6874     }
6875     MUTEX_EXIT(&call->lock);
6876     CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6877 }
6878
6879 /*
6880  * This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6881  * seconds) to ask the client to authenticate itself.  The routine
6882  * issues a challenge to the client, which is obtained from the
6883  * security object associated with the connection
6884  *
6885  * This routine is both an event handler and a function called directly;
6886  * when called directly the passed |event| is NULL and the
6887  * conn->conn->data>lock must must not be held.  Also, when called as an
6888  * an event handler, we must putConnection before we exit; but when called
6889  * directly (the first challenge), we must NOT putConnection.
6890  */
6891 static void
6892 rxi_ChallengeEvent(struct rxevent *event,
6893                    void *arg0, void *arg1, int tries)
6894 {
6895     struct rx_connection *conn = arg0;
6896     int event_raised = 0;       /* assume we were called directly */
6897
6898     MUTEX_ENTER(&conn->conn_data_lock);
6899     if (event != NULL && event == conn->challengeEvent) {
6900         event_raised = 1;       /* called as an event */
6901         rxevent_Put(&conn->challengeEvent);
6902     }
6903     MUTEX_EXIT(&conn->conn_data_lock);
6904
6905     /* If there are no active calls it is not worth re-issuing the
6906      * challenge.  If the client issues another call on this connection
6907      * the challenge can be requested at that time.
6908      */
6909     if (!rxi_HasActiveCalls(conn))
6910         goto done;
6911
6912     if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6913         struct rx_packet *packet;
6914         struct clock when, now;
6915
6916         if (tries <= 0) {
6917             /* We've failed to authenticate for too long.
6918              * Reset any calls waiting for authentication;
6919              * they are all in RX_STATE_PRECALL.
6920              */
6921             int i;
6922
6923             MUTEX_ENTER(&conn->conn_call_lock);
6924             for (i = 0; i < RX_MAXCALLS; i++) {
6925                 struct rx_call *call = conn->call[i];
6926                 if (call) {
6927                     MUTEX_ENTER(&call->lock);
6928                     if (call->state == RX_STATE_PRECALL) {
6929                         rxi_CallError(call, RX_CALL_DEAD);
6930                         rxi_SendCallAbort(call, NULL, 0, 0);
6931                     }
6932                     MUTEX_EXIT(&call->lock);
6933                 }
6934             }
6935             MUTEX_EXIT(&conn->conn_call_lock);
6936             goto done;
6937         }
6938
6939         packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6940         if (packet) {
6941             int code;
6942             code = RXS_GetChallenge(conn->securityObject, conn, packet);
6943             if (code && event_raised) {
6944                 /*
6945                  * We can only rxi_ConnectionError the connection if we are
6946                  * running as an event. Otherwise, the caller may have our call
6947                  * locked, and so we cannot call rxi_ConnectionError (since it
6948                  * tries to lock each call in the conn).
6949                  */
6950                 rxi_FreePacket(packet);
6951                 rxi_ConnectionError(conn, code);
6952                 goto done;
6953             }
6954             if (code == 0) {
6955                 /* Only send a challenge packet if we were able to allocate a
6956                  * packet, and the security layer successfully populated the
6957                  * challenge. */
6958                 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6959                                 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6960                 conn->securityChallengeSent = 1;
6961             }
6962             rxi_FreePacket(packet);
6963         }
6964         clock_GetTime(&now);
6965         when = now;
6966         when.sec += RX_CHALLENGE_TIMEOUT;
6967         MUTEX_ENTER(&conn->conn_data_lock);
6968         /* Only reschedule ourselves if not already pending. */
6969         if (conn->challengeEvent == NULL) {
6970             rx_GetConnection(conn);
6971             conn->challengeEvent =
6972                 rxevent_Post(&when, &now, rxi_ChallengeEvent, conn, 0,
6973                              (tries - 1));
6974         }
6975         MUTEX_EXIT(&conn->conn_data_lock);
6976     }
6977  done:
6978     if (event_raised)
6979         putConnection(conn);
6980 }
6981
6982 /* Call this routine to start requesting the client to authenticate
6983  * itself.  This will continue until authentication is established,
6984  * the call times out, or an invalid response is returned.  The
6985  * security object associated with the connection is asked to create
6986  * the challenge at this time. */
6987 static int
6988 rxi_ChallengeOn(struct rx_connection *conn)
6989 {
6990     int start = 0;
6991     MUTEX_ENTER(&conn->conn_data_lock);
6992     if (!conn->challengeEvent)
6993         start = 1;
6994     MUTEX_EXIT(&conn->conn_data_lock);
6995     if (start) {
6996         int code;
6997         code = RXS_CreateChallenge(conn->securityObject, conn);
6998         if (code) {
6999             return code;
7000         }
7001         rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
7002     }
7003     return 0;
7004 }
7005
7006
7007 /* rxi_ComputeRoundTripTime is called with peer locked. */
7008 /* peer may be null */
7009 static void
7010 rxi_ComputeRoundTripTime(struct rx_packet *p,
7011                          struct rx_ackPacket *ack,
7012                          struct rx_call *call,
7013                          struct rx_peer *peer,
7014                          struct clock *now)
7015 {
7016     struct clock thisRtt, *sentp;
7017     int rtt_timeout;
7018     int serial;
7019
7020     /* If the ACK is delayed, then do nothing */
7021     if (ack->reason == RX_ACK_DELAY)
7022         return;
7023
7024     /* On the wire, jumbograms are a single UDP packet. We shouldn't count
7025      * their RTT multiple times, so only include the RTT of the last packet
7026      * in a jumbogram */
7027     if (p->flags & RX_JUMBO_PACKET)
7028         return;
7029
7030     /* Use the serial number to determine which transmission the ACK is for,
7031      * and set the sent time to match this. If we have no serial number, then
7032      * only use the ACK for RTT calculations if the packet has not been
7033      * retransmitted
7034      */
7035
7036     serial = ntohl(ack->serial);
7037     if (serial) {
7038         if (serial == p->header.serial) {
7039             sentp = &p->timeSent;
7040         } else if (serial == p->firstSerial) {
7041             sentp = &p->firstSent;
7042         } else if (clock_Eq(&p->timeSent, &p->firstSent)) {
7043             sentp = &p->firstSent;
7044         } else
7045             return;
7046     } else {
7047         if (clock_Eq(&p->timeSent, &p->firstSent)) {
7048             sentp = &p->firstSent;
7049         } else
7050             return;
7051     }
7052
7053     thisRtt = *now;
7054
7055     if (clock_Lt(&thisRtt, sentp))
7056         return;                 /* somebody set the clock back, don't count this time. */
7057
7058     clock_Sub(&thisRtt, sentp);
7059     dpf(("rxi_ComputeRoundTripTime(call=%d packet=%p rttp=%d.%06d sec)\n",
7060           p->header.callNumber, p, thisRtt.sec, thisRtt.usec));
7061
7062     if (clock_IsZero(&thisRtt)) {
7063         /*
7064          * The actual round trip time is shorter than the
7065          * clock_GetTime resolution.  It is most likely 1ms or 100ns.
7066          * Since we can't tell which at the moment we will assume 1ms.
7067          */
7068         thisRtt.usec = 1000;
7069     }
7070
7071     if (rx_stats_active) {
7072         MUTEX_ENTER(&rx_stats_mutex);
7073         if (clock_Lt(&thisRtt, &rx_stats.minRtt))
7074             rx_stats.minRtt = thisRtt;
7075         if (clock_Gt(&thisRtt, &rx_stats.maxRtt)) {
7076             if (thisRtt.sec > 60) {
7077                 MUTEX_EXIT(&rx_stats_mutex);
7078                 return;         /* somebody set the clock ahead */
7079             }
7080             rx_stats.maxRtt = thisRtt;
7081         }
7082         clock_Add(&rx_stats.totalRtt, &thisRtt);
7083         rx_atomic_inc(&rx_stats.nRttSamples);
7084         MUTEX_EXIT(&rx_stats_mutex);
7085     }
7086
7087     /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
7088
7089     /* Apply VanJacobson round-trip estimations */
7090     if (call->rtt) {
7091         int delta;
7092
7093         /*
7094          * srtt (call->rtt) is in units of one-eighth-milliseconds.
7095          * srtt is stored as fixed point with 3 bits after the binary
7096          * point (i.e., scaled by 8). The following magic is
7097          * equivalent to the smoothing algorithm in rfc793 with an
7098          * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
7099          * srtt'*8 = rtt + srtt*7
7100          * srtt'*8 = srtt*8 + rtt - srtt
7101          * srtt' = srtt + rtt/8 - srtt/8
7102          * srtt' = srtt + (rtt - srtt)/8
7103          */
7104
7105         delta = _8THMSEC(&thisRtt) - call->rtt;
7106         call->rtt += (delta >> 3);
7107
7108         /*
7109          * We accumulate a smoothed rtt variance (actually, a smoothed
7110          * mean difference), then set the retransmit timer to smoothed
7111          * rtt + 4 times the smoothed variance (was 2x in van's original
7112          * paper, but 4x works better for me, and apparently for him as
7113          * well).
7114          * rttvar is stored as
7115          * fixed point with 2 bits after the binary point (scaled by
7116          * 4).  The following is equivalent to rfc793 smoothing with
7117          * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
7118          *   rttvar'*4 = rttvar*3 + |delta|
7119          *   rttvar'*4 = rttvar*4 + |delta| - rttvar
7120          *   rttvar' = rttvar + |delta|/4 - rttvar/4
7121          *   rttvar' = rttvar + (|delta| - rttvar)/4
7122          * This replaces rfc793's wired-in beta.
7123          * dev*4 = dev*4 + (|actual - expected| - dev)
7124          */
7125
7126         if (delta < 0)
7127             delta = -delta;
7128
7129         delta -= (call->rtt_dev << 1);
7130         call->rtt_dev += (delta >> 3);
7131     } else {
7132         /* I don't have a stored RTT so I start with this value.  Since I'm
7133          * probably just starting a call, and will be pushing more data down
7134          * this, I expect congestion to increase rapidly.  So I fudge a
7135          * little, and I set deviance to half the rtt.  In practice,
7136          * deviance tends to approach something a little less than
7137          * half the smoothed rtt. */
7138         call->rtt = _8THMSEC(&thisRtt) + 8;
7139         call->rtt_dev = call->rtt >> 2; /* rtt/2: they're scaled differently */
7140     }
7141     /* the smoothed RTT time is RTT + 4*MDEV
7142      *
7143      * We allow a user specified minimum to be set for this, to allow clamping
7144      * at a minimum value in the same way as TCP. In addition, we have to allow
7145      * for the possibility that this packet is answered by a delayed ACK, so we
7146      * add on a fixed 200ms to account for that timer expiring.
7147      */
7148
7149     rtt_timeout = MAX(((call->rtt >> 3) + call->rtt_dev),
7150                       rx_minPeerTimeout) + 200;
7151     clock_Zero(&call->rto);
7152     clock_Addmsec(&call->rto, rtt_timeout);
7153
7154     /* Update the peer, so any new calls start with our values */
7155     peer->rtt_dev = call->rtt_dev;
7156     peer->rtt = call->rtt;
7157
7158     dpf(("rxi_ComputeRoundTripTime(call=%d packet=%p rtt=%d ms, srtt=%d ms, "
7159          "rtt_dev=%d ms, timeout=%d.%06d sec)\n",
7160          p->header.callNumber, p, MSEC(&thisRtt), call->rtt >> 3,
7161          call->rtt_dev >> 2, (call->rto.sec), (call->rto.usec)));
7162 }
7163
7164
7165 /* Find all server connections that have not been active for a long time, and
7166  * toss them */
7167 static void
7168 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2,
7169                     int unused3)
7170 {
7171     struct clock now, when;
7172     struct rxevent *event;
7173     clock_GetTime(&now);
7174
7175     /* Find server connection structures that haven't been used for
7176      * greater than rx_idleConnectionTime */
7177     {
7178         struct rx_connection **conn_ptr, **conn_end;
7179         int i, havecalls = 0;
7180         MUTEX_ENTER(&rx_connHashTable_lock);
7181         for (conn_ptr = &rx_connHashTable[0], conn_end =
7182              &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
7183              conn_ptr++) {
7184             struct rx_connection *conn, *next;
7185             struct rx_call *call;
7186             int result;
7187
7188           rereap:
7189             for (conn = *conn_ptr; conn; conn = next) {
7190                 /* XXX -- Shouldn't the connection be locked? */
7191                 next = conn->next;
7192                 havecalls = 0;
7193                 for (i = 0; i < RX_MAXCALLS; i++) {
7194                     call = conn->call[i];
7195                     if (call) {
7196                         int code;
7197                         havecalls = 1;
7198                         code = MUTEX_TRYENTER(&call->lock);
7199                         if (!code)
7200                             continue;
7201                         result = rxi_CheckCall(call, 1);
7202                         MUTEX_EXIT(&call->lock);
7203                         if (result == -2) {
7204                             /* If CheckCall freed the call, it might
7205                              * have destroyed  the connection as well,
7206                              * which screws up the linked lists.
7207                              */
7208                             goto rereap;
7209                         }
7210                     }
7211                 }
7212                 if (conn->type == RX_SERVER_CONNECTION) {
7213                     /* This only actually destroys the connection if
7214                      * there are no outstanding calls */
7215                     MUTEX_ENTER(&conn->conn_data_lock);
7216                     MUTEX_ENTER(&rx_refcnt_mutex);
7217                     if (!havecalls && !conn->refCount
7218                         && ((conn->lastSendTime + rx_idleConnectionTime) <
7219                             now.sec)) {
7220                         conn->refCount++;       /* it will be decr in rx_DestroyConn */
7221                         MUTEX_EXIT(&rx_refcnt_mutex);
7222                         MUTEX_EXIT(&conn->conn_data_lock);
7223 #ifdef RX_ENABLE_LOCKS
7224                         rxi_DestroyConnectionNoLock(conn);
7225 #else /* RX_ENABLE_LOCKS */
7226                         rxi_DestroyConnection(conn);
7227 #endif /* RX_ENABLE_LOCKS */
7228                     }
7229 #ifdef RX_ENABLE_LOCKS
7230                     else {
7231                         MUTEX_EXIT(&rx_refcnt_mutex);
7232                         MUTEX_EXIT(&conn->conn_data_lock);
7233                     }
7234 #endif /* RX_ENABLE_LOCKS */
7235                 }
7236             }
7237         }
7238 #ifdef RX_ENABLE_LOCKS
7239         while (rx_connCleanup_list) {
7240             struct rx_connection *conn;
7241             conn = rx_connCleanup_list;
7242             rx_connCleanup_list = rx_connCleanup_list->next;
7243             MUTEX_EXIT(&rx_connHashTable_lock);
7244             rxi_CleanupConnection(conn);
7245             MUTEX_ENTER(&rx_connHashTable_lock);
7246         }
7247         MUTEX_EXIT(&rx_connHashTable_lock);
7248 #endif /* RX_ENABLE_LOCKS */
7249     }
7250
7251     /* Find any peer structures that haven't been used (haven't had an
7252      * associated connection) for greater than rx_idlePeerTime */
7253     {
7254         struct rx_peer **peer_ptr, **peer_end;
7255         int code;
7256
7257         /*
7258          * Why do we need to hold the rx_peerHashTable_lock across
7259          * the incrementing of peer_ptr since the rx_peerHashTable
7260          * array is not changing?  We don't.
7261          *
7262          * By dropping the lock periodically we can permit other
7263          * activities to be performed while a rxi_ReapConnections
7264          * call is in progress.  The goal of reap connections
7265          * is to clean up quickly without causing large amounts
7266          * of contention.  Therefore, it is important that global
7267          * mutexes not be held for extended periods of time.
7268          */
7269         for (peer_ptr = &rx_peerHashTable[0], peer_end =
7270              &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7271              peer_ptr++) {
7272             struct rx_peer *peer, *next, *prev;
7273
7274             MUTEX_ENTER(&rx_peerHashTable_lock);
7275             for (prev = peer = *peer_ptr; peer; peer = next) {
7276                 next = peer->next;
7277                 code = MUTEX_TRYENTER(&peer->peer_lock);
7278                 if ((code) && (peer->refCount == 0)
7279                     && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
7280                     struct opr_queue *cursor, *store;
7281                     size_t space;
7282
7283                     /*
7284                      * now know that this peer object is one to be
7285                      * removed from the hash table.  Once it is removed
7286                      * it can't be referenced by other threads.
7287                      * Lets remove it first and decrement the struct
7288                      * nPeerStructs count.
7289                      */
7290                     if (peer == *peer_ptr) {
7291                         *peer_ptr = next;
7292                         prev = next;
7293                     } else
7294                         prev->next = next;
7295
7296                     if (rx_stats_active)
7297                         rx_atomic_dec(&rx_stats.nPeerStructs);
7298
7299                     /*
7300                      * Now if we hold references on 'prev' and 'next'
7301                      * we can safely drop the rx_peerHashTable_lock
7302                      * while we destroy this 'peer' object.
7303                      */
7304                     if (next)
7305                         next->refCount++;
7306                     if (prev)
7307                         prev->refCount++;
7308                     MUTEX_EXIT(&rx_peerHashTable_lock);
7309
7310                     MUTEX_EXIT(&peer->peer_lock);
7311                     MUTEX_DESTROY(&peer->peer_lock);
7312
7313                     for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
7314                         unsigned int num_funcs;
7315                         struct rx_interface_stat *rpc_stat
7316                             = opr_queue_Entry(cursor, struct rx_interface_stat,
7317                                              entry);
7318                         if (!rpc_stat)
7319                             break;
7320
7321                         opr_queue_Remove(&rpc_stat->entry);
7322                         opr_queue_Remove(&rpc_stat->entryPeers);
7323
7324                         num_funcs = rpc_stat->stats[0].func_total;
7325                         space =
7326                             sizeof(rx_interface_stat_t) +
7327                             rpc_stat->stats[0].func_total *
7328                             sizeof(rx_function_entry_v1_t);
7329
7330                         rxi_Free(rpc_stat, space);
7331
7332                         MUTEX_ENTER(&rx_rpc_stats);
7333                         rxi_rpc_peer_stat_cnt -= num_funcs;
7334                         MUTEX_EXIT(&rx_rpc_stats);
7335                     }
7336                     rxi_FreePeer(peer);
7337
7338                     /*
7339                      * Regain the rx_peerHashTable_lock and
7340                      * decrement the reference count on 'prev'
7341                      * and 'next'.
7342                      */
7343                     MUTEX_ENTER(&rx_peerHashTable_lock);
7344                     if (next)
7345                         next->refCount--;
7346                     if (prev)
7347                         prev->refCount--;
7348                 } else {
7349                     if (code) {
7350                         MUTEX_EXIT(&peer->peer_lock);
7351                     }
7352                     prev = peer;
7353                 }
7354             }
7355             MUTEX_EXIT(&rx_peerHashTable_lock);
7356         }
7357     }
7358
7359     /* THIS HACK IS A TEMPORARY HACK.  The idea is that the race condition in
7360      * rxi_AllocSendPacket, if it hits, will be handled at the next conn
7361      * GC, just below.  Really, we shouldn't have to keep moving packets from
7362      * one place to another, but instead ought to always know if we can
7363      * afford to hold onto a packet in its particular use.  */
7364     MUTEX_ENTER(&rx_freePktQ_lock);
7365     if (rx_waitingForPackets) {
7366         rx_waitingForPackets = 0;
7367 #ifdef  RX_ENABLE_LOCKS
7368         CV_BROADCAST(&rx_waitingForPackets_cv);
7369 #else
7370         osi_rxWakeup(&rx_waitingForPackets);
7371 #endif
7372     }
7373     MUTEX_EXIT(&rx_freePktQ_lock);
7374
7375     when = now;
7376     when.sec += RX_REAP_TIME;   /* Check every RX_REAP_TIME seconds */
7377     event = rxevent_Post(&when, &now, rxi_ReapConnections, 0, NULL, 0);
7378     rxevent_Put(&event);
7379 }
7380
7381
7382 /* rxs_Release - This isn't strictly necessary but, since the macro name from
7383  * rx.h is sort of strange this is better.  This is called with a security
7384  * object before it is discarded.  Each connection using a security object has
7385  * its own refcount to the object so it won't actually be freed until the last
7386  * connection is destroyed.
7387  *
7388  * This is the only rxs module call.  A hold could also be written but no one
7389  * needs it. */
7390
7391 int
7392 rxs_Release(struct rx_securityClass *aobj)
7393 {
7394     return RXS_Close(aobj);
7395 }
7396
7397 void
7398 rxi_DebugInit(void)
7399 {
7400 #ifdef RXDEBUG
7401 #ifdef AFS_NT40_ENV
7402 #define TRACE_OPTION_RX_DEBUG 16
7403     HKEY parmKey;
7404     DWORD dummyLen;
7405     DWORD TraceOption;
7406     long code;
7407
7408     rxdebug_active = 0;
7409
7410     code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
7411                          0, KEY_QUERY_VALUE, &parmKey);
7412     if (code != ERROR_SUCCESS)
7413         return;
7414
7415     dummyLen = sizeof(TraceOption);
7416     code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
7417                            (BYTE *) &TraceOption, &dummyLen);
7418     if (code == ERROR_SUCCESS) {
7419         rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
7420     }
7421     RegCloseKey (parmKey);
7422 #endif /* AFS_NT40_ENV */
7423 #endif
7424 }
7425
7426 void
7427 rx_DebugOnOff(int on)
7428 {
7429 #ifdef RXDEBUG
7430 #ifdef AFS_NT40_ENV
7431     rxdebug_active = on;
7432 #endif
7433 #endif
7434 }
7435
7436 void
7437 rx_StatsOnOff(int on)
7438 {
7439     rx_stats_active = on;
7440 }
7441
7442
7443 /* Don't call this debugging routine directly; use dpf */
7444 void
7445 rxi_DebugPrint(char *format, ...)
7446 {
7447 #ifdef RXDEBUG
7448     va_list ap;
7449 #ifdef AFS_NT40_ENV
7450     char msg[512];
7451     char tformat[256];
7452     size_t len;
7453
7454     va_start(ap, format);
7455
7456     len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7457
7458     if (len > 0) {
7459         len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7460         if (len > 0)
7461             OutputDebugString(msg);
7462     }
7463     va_end(ap);
7464 #else
7465     struct clock now;
7466
7467     va_start(ap, format);
7468
7469     clock_GetTime(&now);
7470     fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7471             (unsigned int)now.usec);
7472     vfprintf(rx_Log, format, ap);
7473     va_end(ap);
7474 #endif
7475 #endif
7476 }
7477
7478 #ifndef KERNEL
7479 /*
7480  * This function is used to process the rx_stats structure that is local
7481  * to a process as well as an rx_stats structure received from a remote
7482  * process (via rxdebug).  Therefore, it needs to do minimal version
7483  * checking.
7484  */
7485 void
7486 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7487                    afs_int32 freePackets, char version)
7488 {
7489     int i;
7490
7491     if (size != sizeof(struct rx_statistics)) {
7492         fprintf(file,
7493                 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7494                 size, sizeof(struct rx_statistics));
7495     }
7496
7497     fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7498             s->packetRequests);
7499
7500     if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7501         fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7502                 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7503                 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7504                 s->specialPktAllocFailures);
7505     } else {
7506         fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7507                 s->receivePktAllocFailures, s->sendPktAllocFailures,
7508                 s->specialPktAllocFailures);
7509     }
7510
7511     fprintf(file,
7512             "   greedy %u, " "bogusReads %u (last from host %x), "
7513             "noPackets %u, " "noBuffers %u, " "selects %u, "
7514             "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7515             s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7516             s->selects, s->sendSelects);
7517
7518     fprintf(file, "   packets read: ");
7519     for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7520         fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7521     }
7522     fprintf(file, "\n");
7523
7524     fprintf(file,
7525             "   other read counters: data %u, " "ack %u, " "dup %u "
7526             "spurious %u " "dally %u\n", s->dataPacketsRead,
7527             s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7528             s->ignorePacketDally);
7529
7530     fprintf(file, "   packets sent: ");
7531     for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7532         fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7533     }
7534     fprintf(file, "\n");
7535
7536     fprintf(file,
7537             "   other send counters: ack %u, " "data %u (not resends), "
7538             "resends %u, " "pushed %u, " "acked&ignored %u\n",
7539             s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7540             s->dataPacketsPushed, s->ignoreAckedPacket);
7541
7542     fprintf(file,
7543             "   \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7544             s->netSendFailures, (int)s->fatalErrors);
7545
7546     if (s->nRttSamples) {
7547         fprintf(file, "   Average rtt is %0.3f, with %d samples\n",
7548                 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7549
7550         fprintf(file, "   Minimum rtt is %0.3f, maximum is %0.3f\n",
7551                 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7552     }
7553
7554     fprintf(file,
7555             "   %d server connections, " "%d client connections, "
7556             "%d peer structs, " "%d call structs, " "%d free call structs\n",
7557             s->nServerConns, s->nClientConns, s->nPeerStructs,
7558             s->nCallStructs, s->nFreeCallStructs);
7559
7560 #if     !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7561     fprintf(file, "   %d clock updates\n", clock_nUpdates);
7562 #endif
7563 }
7564
7565 /* for backward compatibility */
7566 void
7567 rx_PrintStats(FILE * file)
7568 {
7569     MUTEX_ENTER(&rx_stats_mutex);
7570     rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7571                        sizeof(rx_stats), rx_nFreePackets,
7572                        RX_DEBUGI_VERSION);
7573     MUTEX_EXIT(&rx_stats_mutex);
7574 }
7575
7576 void
7577 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7578 {
7579     fprintf(file, "Peer %x.%d.\n",
7580             ntohl(peer->host), (int)ntohs(peer->port));
7581
7582     fprintf(file,
7583             "   Rtt %d, " "total sent %d, " "resent %d\n",
7584             peer->rtt, peer->nSent, peer->reSends);
7585
7586     fprintf(file, "   Packet size %d\n", peer->ifMTU);
7587 }
7588 #endif
7589
7590 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7591 /*
7592  * This mutex protects the following static variables:
7593  * counter
7594  */
7595
7596 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7597 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7598 #else
7599 #define LOCK_RX_DEBUG
7600 #define UNLOCK_RX_DEBUG
7601 #endif /* AFS_PTHREAD_ENV */
7602
7603 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7604 static int
7605 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7606               u_char type, void *inputData, size_t inputLength,
7607               void *outputData, size_t outputLength)
7608 {
7609     static afs_int32 counter = 100;
7610     time_t waitTime, waitCount;
7611     struct rx_header theader;
7612     char tbuffer[1500];
7613     afs_int32 code;
7614     struct timeval tv_now, tv_wake, tv_delta;
7615     struct sockaddr_in taddr, faddr;
7616 #ifdef AFS_NT40_ENV
7617     int faddrLen;
7618 #else
7619     socklen_t faddrLen;
7620 #endif
7621     fd_set imask;
7622     char *tp;
7623
7624     waitTime = 1;
7625     waitCount = 5;
7626     LOCK_RX_DEBUG;
7627     counter++;
7628     UNLOCK_RX_DEBUG;
7629     tp = &tbuffer[sizeof(struct rx_header)];
7630     taddr.sin_family = AF_INET;
7631     taddr.sin_port = remotePort;
7632     taddr.sin_addr.s_addr = remoteAddr;
7633     memset(&taddr.sin_zero, 0, sizeof(taddr.sin_zero));
7634 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7635     taddr.sin_len = sizeof(struct sockaddr_in);
7636 #endif
7637     while (1) {
7638         memset(&theader, 0, sizeof(theader));
7639         theader.epoch = htonl(999);
7640         theader.cid = 0;
7641         theader.callNumber = htonl(counter);
7642         theader.seq = 0;
7643         theader.serial = 0;
7644         theader.type = type;
7645         theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7646         theader.serviceId = 0;
7647
7648         memcpy(tbuffer, &theader, sizeof(theader));
7649         memcpy(tp, inputData, inputLength);
7650         code =
7651             sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7652                    (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7653
7654         /* see if there's a packet available */
7655         gettimeofday(&tv_wake, NULL);
7656         tv_wake.tv_sec += waitTime;
7657         for (;;) {
7658             FD_ZERO(&imask);
7659             FD_SET(socket, &imask);
7660             tv_delta.tv_sec = tv_wake.tv_sec;
7661             tv_delta.tv_usec = tv_wake.tv_usec;
7662             gettimeofday(&tv_now, NULL);
7663
7664             if (tv_delta.tv_usec < tv_now.tv_usec) {
7665                 /* borrow */
7666                 tv_delta.tv_usec += 1000000;
7667                 tv_delta.tv_sec--;
7668             }
7669             tv_delta.tv_usec -= tv_now.tv_usec;
7670
7671             if (tv_delta.tv_sec < tv_now.tv_sec) {
7672                 /* time expired */
7673                 break;
7674             }
7675             tv_delta.tv_sec -= tv_now.tv_sec;
7676
7677 #ifdef AFS_NT40_ENV
7678             code = select(0, &imask, 0, 0, &tv_delta);
7679 #else /* AFS_NT40_ENV */
7680             code = select(socket + 1, &imask, 0, 0, &tv_delta);
7681 #endif /* AFS_NT40_ENV */
7682             if (code == 1 && FD_ISSET(socket, &imask)) {
7683                 /* now receive a packet */
7684                 faddrLen = sizeof(struct sockaddr_in);
7685                 code =
7686                     recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7687                              (struct sockaddr *)&faddr, &faddrLen);
7688
7689                 if (code > 0) {
7690                     memcpy(&theader, tbuffer, sizeof(struct rx_header));
7691                     if (counter == ntohl(theader.callNumber))
7692                         goto success;
7693                     continue;
7694                 }
7695             }
7696             break;
7697         }
7698
7699         /* see if we've timed out */
7700         if (!--waitCount) {
7701             return -1;
7702         }
7703         waitTime <<= 1;
7704     }
7705
7706  success:
7707     code -= sizeof(struct rx_header);
7708     if (code > outputLength)
7709         code = outputLength;
7710     memcpy(outputData, tp, code);
7711     return code;
7712 }
7713 #endif /* RXDEBUG */
7714
7715 afs_int32
7716 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7717                   afs_uint16 remotePort, struct rx_debugStats * stat,
7718                   afs_uint32 * supportedValues)
7719 {
7720 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7721     afs_int32 rc = 0;
7722     struct rx_debugIn in;
7723
7724     *supportedValues = 0;
7725     in.type = htonl(RX_DEBUGI_GETSTATS);
7726     in.index = 0;
7727
7728     rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7729                        &in, sizeof(in), stat, sizeof(*stat));
7730
7731     /*
7732      * If the call was successful, fixup the version and indicate
7733      * what contents of the stat structure are valid.
7734      * Also do net to host conversion of fields here.
7735      */
7736
7737     if (rc >= 0) {
7738         if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7739             *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7740         }
7741         if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7742             *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7743         }
7744         if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7745             *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7746         }
7747         if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7748             *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7749         }
7750         if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7751             *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7752         }
7753         if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7754             *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7755         }
7756         if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7757             *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7758         }
7759         if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7760             *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7761         }
7762         if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7763             *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7764         }
7765         stat->nFreePackets = ntohl(stat->nFreePackets);
7766         stat->packetReclaims = ntohl(stat->packetReclaims);
7767         stat->callsExecuted = ntohl(stat->callsExecuted);
7768         stat->nWaiting = ntohl(stat->nWaiting);
7769         stat->idleThreads = ntohl(stat->idleThreads);
7770         stat->nWaited = ntohl(stat->nWaited);
7771         stat->nPackets = ntohl(stat->nPackets);
7772     }
7773 #else
7774     afs_int32 rc = -1;
7775 #endif
7776     return rc;
7777 }
7778
7779 afs_int32
7780 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7781                   afs_uint16 remotePort, struct rx_statistics * stat,
7782                   afs_uint32 * supportedValues)
7783 {
7784 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7785     afs_int32 rc = 0;
7786     struct rx_debugIn in;
7787     afs_int32 *lp = (afs_int32 *) stat;
7788     int i;
7789
7790     /*
7791      * supportedValues is currently unused, but added to allow future
7792      * versioning of this function.
7793      */
7794
7795     *supportedValues = 0;
7796     in.type = htonl(RX_DEBUGI_RXSTATS);
7797     in.index = 0;
7798     memset(stat, 0, sizeof(*stat));
7799
7800     rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7801                        &in, sizeof(in), stat, sizeof(*stat));
7802
7803     if (rc >= 0) {
7804
7805         /*
7806          * Do net to host conversion here
7807          */
7808
7809         for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7810             *lp = ntohl(*lp);
7811         }
7812     }
7813 #else
7814     afs_int32 rc = -1;
7815 #endif
7816     return rc;
7817 }
7818
7819 afs_int32
7820 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7821                     afs_uint16 remotePort, size_t version_length,
7822                     char *version)
7823 {
7824 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7825     char a[1] = { 0 };
7826     return MakeDebugCall(socket, remoteAddr, remotePort,
7827                          RX_PACKET_TYPE_VERSION, a, 1, version,
7828                          version_length);
7829 #else
7830     return -1;
7831 #endif
7832 }
7833
7834 afs_int32
7835 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7836                         afs_uint16 remotePort, afs_int32 * nextConnection,
7837                         int allConnections, afs_uint32 debugSupportedValues,
7838                         struct rx_debugConn * conn,
7839                         afs_uint32 * supportedValues)
7840 {
7841 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7842     afs_int32 rc = 0;
7843     struct rx_debugIn in;
7844     int i;
7845
7846     /*
7847      * supportedValues is currently unused, but added to allow future
7848      * versioning of this function.
7849      */
7850
7851     *supportedValues = 0;
7852     if (allConnections) {
7853         in.type = htonl(RX_DEBUGI_GETALLCONN);
7854     } else {
7855         in.type = htonl(RX_DEBUGI_GETCONN);
7856     }
7857     in.index = htonl(*nextConnection);
7858     memset(conn, 0, sizeof(*conn));
7859
7860     rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7861                        &in, sizeof(in), conn, sizeof(*conn));
7862
7863     if (rc >= 0) {
7864         *nextConnection += 1;
7865
7866         /*
7867          * Convert old connection format to new structure.
7868          */
7869
7870         if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7871             struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7872 #define MOVEvL(a) (conn->a = vL->a)
7873
7874             /* any old or unrecognized version... */
7875             for (i = 0; i < RX_MAXCALLS; i++) {
7876                 MOVEvL(callState[i]);
7877                 MOVEvL(callMode[i]);
7878                 MOVEvL(callFlags[i]);
7879                 MOVEvL(callOther[i]);
7880             }
7881             if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7882                 MOVEvL(secStats.type);
7883                 MOVEvL(secStats.level);
7884                 MOVEvL(secStats.flags);
7885                 MOVEvL(secStats.expires);
7886                 MOVEvL(secStats.packetsReceived);
7887                 MOVEvL(secStats.packetsSent);
7888                 MOVEvL(secStats.bytesReceived);
7889                 MOVEvL(secStats.bytesSent);
7890             }
7891         }
7892
7893         /*
7894          * Do net to host conversion here
7895          * NOTE:
7896          *    I don't convert host or port since we are most likely
7897          *    going to want these in NBO.
7898          */
7899         conn->cid = ntohl(conn->cid);
7900         conn->serial = ntohl(conn->serial);
7901         for (i = 0; i < RX_MAXCALLS; i++) {
7902             conn->callNumber[i] = ntohl(conn->callNumber[i]);
7903         }
7904         conn->error = ntohl(conn->error);
7905         conn->secStats.flags = ntohl(conn->secStats.flags);
7906         conn->secStats.expires = ntohl(conn->secStats.expires);
7907         conn->secStats.packetsReceived =
7908             ntohl(conn->secStats.packetsReceived);
7909         conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7910         conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7911         conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7912         conn->epoch = ntohl(conn->epoch);
7913         conn->natMTU = ntohl(conn->natMTU);
7914     }
7915 #else
7916     afs_int32 rc = -1;
7917 #endif
7918     return rc;
7919 }
7920
7921 afs_int32
7922 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7923                   afs_uint16 remotePort, afs_int32 * nextPeer,
7924                   afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7925                   afs_uint32 * supportedValues)
7926 {
7927 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7928     afs_int32 rc = 0;
7929     struct rx_debugIn in;
7930
7931     /*
7932      * supportedValues is currently unused, but added to allow future
7933      * versioning of this function.
7934      */
7935
7936     *supportedValues = 0;
7937     in.type = htonl(RX_DEBUGI_GETPEER);
7938     in.index = htonl(*nextPeer);
7939     memset(peer, 0, sizeof(*peer));
7940
7941     rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7942                        &in, sizeof(in), peer, sizeof(*peer));
7943
7944     if (rc >= 0) {
7945         *nextPeer += 1;
7946
7947         /*
7948          * Do net to host conversion here
7949          * NOTE:
7950          *    I don't convert host or port since we are most likely
7951          *    going to want these in NBO.
7952          */
7953         peer->ifMTU = ntohs(peer->ifMTU);
7954         peer->idleWhen = ntohl(peer->idleWhen);
7955         peer->refCount = ntohs(peer->refCount);
7956         peer->rtt = ntohl(peer->rtt);
7957         peer->rtt_dev = ntohl(peer->rtt_dev);
7958         peer->timeout.sec = 0;
7959         peer->timeout.usec = 0;
7960         peer->nSent = ntohl(peer->nSent);
7961         peer->reSends = ntohl(peer->reSends);
7962         peer->natMTU = ntohs(peer->natMTU);
7963         peer->maxMTU = ntohs(peer->maxMTU);
7964         peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7965         peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7966         peer->MTU = ntohs(peer->MTU);
7967         peer->cwind = ntohs(peer->cwind);
7968         peer->nDgramPackets = ntohs(peer->nDgramPackets);
7969         peer->congestSeq = ntohs(peer->congestSeq);
7970         peer->bytesSent.high = ntohl(peer->bytesSent.high);
7971         peer->bytesSent.low = ntohl(peer->bytesSent.low);
7972         peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7973         peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7974     }
7975 #else
7976     afs_int32 rc = -1;
7977 #endif
7978     return rc;
7979 }
7980
7981 afs_int32
7982 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7983                 struct rx_debugPeer * peerStats)
7984 {
7985         struct rx_peer *tp;
7986         afs_int32 error = 1; /* default to "did not succeed" */
7987         afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7988
7989         MUTEX_ENTER(&rx_peerHashTable_lock);
7990         for(tp = rx_peerHashTable[hashValue];
7991               tp != NULL; tp = tp->next) {
7992                 if (tp->host == peerHost)
7993                         break;
7994         }
7995
7996         if (tp) {
7997                 tp->refCount++;
7998                 MUTEX_EXIT(&rx_peerHashTable_lock);
7999
8000                 error = 0;
8001
8002                 MUTEX_ENTER(&tp->peer_lock);
8003                 peerStats->host = tp->host;
8004                 peerStats->port = tp->port;
8005                 peerStats->ifMTU = tp->ifMTU;
8006                 peerStats->idleWhen = tp->idleWhen;
8007                 peerStats->refCount = tp->refCount;
8008                 peerStats->burstSize = 0;
8009                 peerStats->burst = 0;
8010                 peerStats->burstWait.sec = 0;
8011                 peerStats->burstWait.usec = 0;
8012                 peerStats->rtt = tp->rtt;
8013                 peerStats->rtt_dev = tp->rtt_dev;
8014                 peerStats->timeout.sec = 0;
8015                 peerStats->timeout.usec = 0;
8016                 peerStats->nSent = tp->nSent;
8017                 peerStats->reSends = tp->reSends;
8018                 peerStats->natMTU = tp->natMTU;
8019                 peerStats->maxMTU = tp->maxMTU;
8020                 peerStats->maxDgramPackets = tp->maxDgramPackets;
8021                 peerStats->ifDgramPackets = tp->ifDgramPackets;
8022                 peerStats->MTU = tp->MTU;
8023                 peerStats->cwind = tp->cwind;
8024                 peerStats->nDgramPackets = tp->nDgramPackets;
8025                 peerStats->congestSeq = tp->congestSeq;
8026                 peerStats->bytesSent.high = tp->bytesSent >> 32;
8027                 peerStats->bytesSent.low = tp->bytesSent & MAX_AFS_UINT32;
8028                 peerStats->bytesReceived.high = tp->bytesReceived >> 32;
8029                 peerStats->bytesReceived.low
8030                                 = tp->bytesReceived & MAX_AFS_UINT32;
8031                 MUTEX_EXIT(&tp->peer_lock);
8032
8033                 MUTEX_ENTER(&rx_peerHashTable_lock);
8034                 tp->refCount--;
8035         }
8036         MUTEX_EXIT(&rx_peerHashTable_lock);
8037
8038         return error;
8039 }
8040
8041 void
8042 shutdown_rx(void)
8043 {
8044     struct rx_serverQueueEntry *np;
8045     int i, j;
8046 #ifndef KERNEL
8047     struct rx_call *call;
8048     struct rx_serverQueueEntry *sq;
8049 #endif /* KERNEL */
8050
8051     LOCK_RX_INIT;
8052     if (!rxi_IsRunning()) {
8053         UNLOCK_RX_INIT;
8054         return;                 /* Already shutdown. */
8055     }
8056     rx_atomic_set(&rxi_running, 0);
8057 #ifndef KERNEL
8058     rx_port = 0;
8059 #ifndef AFS_PTHREAD_ENV
8060     FD_ZERO(&rx_selectMask);
8061 #endif /* AFS_PTHREAD_ENV */
8062     rxi_dataQuota = RX_MAX_QUOTA;
8063 #ifndef AFS_PTHREAD_ENV
8064     rxi_StopListener();
8065 #endif /* AFS_PTHREAD_ENV */
8066     shutdown_rxevent();
8067     rx_epoch = 0;
8068 #ifndef AFS_PTHREAD_ENV
8069 #ifndef AFS_USE_GETTIMEOFDAY
8070     clock_UnInit();
8071 #endif /* AFS_USE_GETTIMEOFDAY */
8072 #endif /* AFS_PTHREAD_ENV */
8073
8074     while (!opr_queue_IsEmpty(&rx_freeCallQueue)) {
8075         call = opr_queue_First(&rx_freeCallQueue, struct rx_call, entry);
8076         opr_queue_Remove(&call->entry);
8077         rxi_Free(call, sizeof(struct rx_call));
8078     }
8079
8080     while (!opr_queue_IsEmpty(&rx_idleServerQueue)) {
8081         sq = opr_queue_First(&rx_idleServerQueue, struct rx_serverQueueEntry,
8082                             entry);
8083         opr_queue_Remove(&sq->entry);
8084     }
8085 #endif /* KERNEL */
8086
8087     {
8088         struct rx_peer **peer_ptr, **peer_end;
8089         for (peer_ptr = &rx_peerHashTable[0], peer_end =
8090              &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
8091              peer_ptr++) {
8092             struct rx_peer *peer, *next;
8093
8094             MUTEX_ENTER(&rx_peerHashTable_lock);
8095             for (peer = *peer_ptr; peer; peer = next) {
8096                 struct opr_queue *cursor, *store;
8097                 size_t space;
8098
8099                 MUTEX_ENTER(&rx_rpc_stats);
8100                 MUTEX_ENTER(&peer->peer_lock);
8101                 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
8102                     unsigned int num_funcs;
8103                     struct rx_interface_stat *rpc_stat
8104                         = opr_queue_Entry(cursor, struct rx_interface_stat,
8105                                          entry);
8106                     if (!rpc_stat)
8107                         break;
8108                     opr_queue_Remove(&rpc_stat->entry);
8109                     opr_queue_Remove(&rpc_stat->entryPeers);
8110                     num_funcs = rpc_stat->stats[0].func_total;
8111                     space =
8112                         sizeof(rx_interface_stat_t) +
8113                         rpc_stat->stats[0].func_total *
8114                         sizeof(rx_function_entry_v1_t);
8115
8116                     rxi_Free(rpc_stat, space);
8117
8118                     /* rx_rpc_stats must be held */
8119                     rxi_rpc_peer_stat_cnt -= num_funcs;
8120                 }
8121                 MUTEX_EXIT(&peer->peer_lock);
8122                 MUTEX_EXIT(&rx_rpc_stats);
8123
8124                 next = peer->next;
8125                 rxi_FreePeer(peer);
8126                 if (rx_stats_active)
8127                     rx_atomic_dec(&rx_stats.nPeerStructs);
8128             }
8129             MUTEX_EXIT(&rx_peerHashTable_lock);
8130         }
8131     }
8132     for (i = 0; i < RX_MAX_SERVICES; i++) {
8133         if (rx_services[i])
8134             rxi_Free(rx_services[i], sizeof(*rx_services[i]));
8135     }
8136     for (i = 0; i < rx_hashTableSize; i++) {
8137         struct rx_connection *tc, *ntc;
8138         MUTEX_ENTER(&rx_connHashTable_lock);
8139         for (tc = rx_connHashTable[i]; tc; tc = ntc) {
8140             ntc = tc->next;
8141             for (j = 0; j < RX_MAXCALLS; j++) {
8142                 if (tc->call[j]) {
8143                     rxi_Free(tc->call[j], sizeof(*tc->call[j]));
8144                 }
8145             }
8146             rxi_Free(tc, sizeof(*tc));
8147         }
8148         MUTEX_EXIT(&rx_connHashTable_lock);
8149     }
8150
8151     MUTEX_ENTER(&freeSQEList_lock);
8152
8153     while (!opr_queue_IsEmpty(&rx_freeServerQueue)) {
8154         np = opr_queue_First(&rx_freeServerQueue, struct rx_serverQueueEntry,
8155                              entry);
8156         opr_queue_Remove(&np->entry);
8157         MUTEX_DESTROY(&np->lock);
8158         rxi_Free(np, sizeof(*np));
8159     }
8160
8161     MUTEX_EXIT(&freeSQEList_lock);
8162     MUTEX_DESTROY(&freeSQEList_lock);
8163     MUTEX_DESTROY(&rx_freeCallQueue_lock);
8164     MUTEX_DESTROY(&rx_connHashTable_lock);
8165     MUTEX_DESTROY(&rx_peerHashTable_lock);
8166     MUTEX_DESTROY(&rx_serverPool_lock);
8167
8168     osi_Free(rx_connHashTable,
8169              rx_hashTableSize * sizeof(struct rx_connection *));
8170     osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
8171
8172     UNPIN(rx_connHashTable,
8173           rx_hashTableSize * sizeof(struct rx_connection *));
8174     UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
8175
8176     MUTEX_ENTER(&rx_quota_mutex);
8177     rxi_dataQuota = RX_MAX_QUOTA;
8178     rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
8179     MUTEX_EXIT(&rx_quota_mutex);
8180     UNLOCK_RX_INIT;
8181 }
8182
8183 #ifndef KERNEL
8184
8185 /*
8186  * Routines to implement connection specific data.
8187  */
8188
8189 int
8190 rx_KeyCreate(rx_destructor_t rtn)
8191 {
8192     int key;
8193     MUTEX_ENTER(&rxi_keyCreate_lock);
8194     key = rxi_keyCreate_counter++;
8195     rxi_keyCreate_destructor = (rx_destructor_t *)
8196         realloc((void *)rxi_keyCreate_destructor,
8197                 (key + 1) * sizeof(rx_destructor_t));
8198     rxi_keyCreate_destructor[key] = rtn;
8199     MUTEX_EXIT(&rxi_keyCreate_lock);
8200     return key;
8201 }
8202
8203 void
8204 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
8205 {
8206     int i;
8207     MUTEX_ENTER(&conn->conn_data_lock);
8208     if (!conn->specific) {
8209         conn->specific = malloc((key + 1) * sizeof(void *));
8210         for (i = 0; i < key; i++)
8211             conn->specific[i] = NULL;
8212         conn->nSpecific = key + 1;
8213         conn->specific[key] = ptr;
8214     } else if (key >= conn->nSpecific) {
8215         conn->specific = (void **)
8216             realloc(conn->specific, (key + 1) * sizeof(void *));
8217         for (i = conn->nSpecific; i < key; i++)
8218             conn->specific[i] = NULL;
8219         conn->nSpecific = key + 1;
8220         conn->specific[key] = ptr;
8221     } else {
8222         if (conn->specific[key] && rxi_keyCreate_destructor[key])
8223             (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
8224         conn->specific[key] = ptr;
8225     }
8226     MUTEX_EXIT(&conn->conn_data_lock);
8227 }
8228
8229 void
8230 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
8231 {
8232     int i;
8233     MUTEX_ENTER(&svc->svc_data_lock);
8234     if (!svc->specific) {
8235         svc->specific = malloc((key + 1) * sizeof(void *));
8236         for (i = 0; i < key; i++)
8237             svc->specific[i] = NULL;
8238         svc->nSpecific = key + 1;
8239         svc->specific[key] = ptr;
8240     } else if (key >= svc->nSpecific) {
8241         svc->specific = (void **)
8242             realloc(svc->specific, (key + 1) * sizeof(void *));
8243         for (i = svc->nSpecific; i < key; i++)
8244             svc->specific[i] = NULL;
8245         svc->nSpecific = key + 1;
8246         svc->specific[key] = ptr;
8247     } else {
8248         if (svc->specific[key] && rxi_keyCreate_destructor[key])
8249             (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
8250         svc->specific[key] = ptr;
8251     }
8252     MUTEX_EXIT(&svc->svc_data_lock);
8253 }
8254
8255 void *
8256 rx_GetSpecific(struct rx_connection *conn, int key)
8257 {
8258     void *ptr;
8259     MUTEX_ENTER(&conn->conn_data_lock);
8260     if (key >= conn->nSpecific)
8261         ptr = NULL;
8262     else
8263         ptr = conn->specific[key];
8264     MUTEX_EXIT(&conn->conn_data_lock);
8265     return ptr;
8266 }
8267
8268 void *
8269 rx_GetServiceSpecific(struct rx_service *svc, int key)
8270 {
8271     void *ptr;
8272     MUTEX_ENTER(&svc->svc_data_lock);
8273     if (key >= svc->nSpecific)
8274         ptr = NULL;
8275     else
8276         ptr = svc->specific[key];
8277     MUTEX_EXIT(&svc->svc_data_lock);
8278     return ptr;
8279 }
8280
8281
8282 #endif /* !KERNEL */
8283
8284 /*
8285  * processStats is a queue used to store the statistics for the local
8286  * process.  Its contents are similar to the contents of the rpcStats
8287  * queue on a rx_peer structure, but the actual data stored within
8288  * this queue contains totals across the lifetime of the process (assuming
8289  * the stats have not been reset) - unlike the per peer structures
8290  * which can come and go based upon the peer lifetime.
8291  */
8292
8293 static struct opr_queue processStats = { &processStats, &processStats };
8294
8295 /*
8296  * peerStats is a queue used to store the statistics for all peer structs.
8297  * Its contents are the union of all the peer rpcStats queues.
8298  */
8299
8300 static struct opr_queue peerStats = { &peerStats, &peerStats };
8301
8302 /*
8303  * rxi_monitor_processStats is used to turn process wide stat collection
8304  * on and off
8305  */
8306
8307 static int rxi_monitor_processStats = 0;
8308
8309 /*
8310  * rxi_monitor_peerStats is used to turn per peer stat collection on and off
8311  */
8312
8313 static int rxi_monitor_peerStats = 0;
8314
8315
8316 void
8317 rxi_ClearRPCOpStat(rx_function_entry_v1_p rpc_stat)
8318 {
8319     rpc_stat->invocations = 0;
8320     rpc_stat->bytes_sent = 0;
8321     rpc_stat->bytes_rcvd = 0;
8322     rpc_stat->queue_time_sum.sec = 0;
8323     rpc_stat->queue_time_sum.usec = 0;
8324     rpc_stat->queue_time_sum_sqr.sec = 0;
8325     rpc_stat->queue_time_sum_sqr.usec = 0;
8326     rpc_stat->queue_time_min.sec = 9999999;
8327     rpc_stat->queue_time_min.usec = 9999999;
8328     rpc_stat->queue_time_max.sec = 0;
8329     rpc_stat->queue_time_max.usec = 0;
8330     rpc_stat->execution_time_sum.sec = 0;
8331     rpc_stat->execution_time_sum.usec = 0;
8332     rpc_stat->execution_time_sum_sqr.sec = 0;
8333     rpc_stat->execution_time_sum_sqr.usec = 0;
8334     rpc_stat->execution_time_min.sec = 9999999;
8335     rpc_stat->execution_time_min.usec = 9999999;
8336     rpc_stat->execution_time_max.sec = 0;
8337     rpc_stat->execution_time_max.usec = 0;
8338 }
8339
8340 /*!
8341  * Given all of the information for a particular rpc
8342  * call, find or create (if requested) the stat structure for the rpc.
8343  *
8344  * @param stats
8345  *      the queue of stats that will be updated with the new value
8346  *
8347  * @param rxInterface
8348  *      a unique number that identifies the rpc interface
8349  *
8350  * @param totalFunc
8351  *      the total number of functions in this interface. this is only
8352  *      required if create is true
8353  *
8354  * @param isServer
8355  *      if true, this invocation was made to a server
8356  *
8357  * @param remoteHost
8358  *      the ip address of the remote host. this is only required if create
8359  *      and addToPeerList are true
8360  *
8361  * @param remotePort
8362  *      the port of the remote host. this is only required if create
8363  *      and addToPeerList are true
8364  *
8365  * @param addToPeerList
8366  *      if != 0, add newly created stat to the global peer list
8367  *
8368  * @param counter
8369  *      if a new stats structure is allocated, the counter will
8370  *      be updated with the new number of allocated stat structures.
8371  *      only required if create is true
8372  *
8373  * @param create
8374  *      if no stats structure exists, allocate one
8375  *
8376  */
8377
8378 static rx_interface_stat_p
8379 rxi_FindRpcStat(struct opr_queue *stats, afs_uint32 rxInterface,
8380                 afs_uint32 totalFunc, int isServer, afs_uint32 remoteHost,
8381                 afs_uint32 remotePort, int addToPeerList,
8382                 unsigned int *counter, int create)
8383 {
8384     rx_interface_stat_p rpc_stat = NULL;
8385     struct opr_queue *cursor;
8386
8387     /*
8388      * See if there's already a structure for this interface
8389      */
8390
8391     for (opr_queue_Scan(stats, cursor)) {
8392         rpc_stat = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8393
8394         if ((rpc_stat->stats[0].interfaceId == rxInterface)
8395             && (rpc_stat->stats[0].remote_is_server == isServer))
8396             break;
8397     }
8398
8399     /* if they didn't ask us to create, we're done */
8400     if (!create) {
8401         if (opr_queue_IsEnd(stats, cursor))
8402             return NULL;
8403         else
8404             return rpc_stat;
8405     }
8406
8407     /* can't proceed without these */
8408     if (!totalFunc || !counter)
8409         return NULL;
8410
8411     /*
8412      * Didn't find a match so allocate a new structure and add it to the
8413      * queue.
8414      */
8415
8416     if (opr_queue_IsEnd(stats, cursor) || (rpc_stat == NULL)
8417         || (rpc_stat->stats[0].interfaceId != rxInterface)
8418         || (rpc_stat->stats[0].remote_is_server != isServer)) {
8419         int i;
8420         size_t space;
8421
8422         space =
8423             sizeof(rx_interface_stat_t) +
8424             totalFunc * sizeof(rx_function_entry_v1_t);
8425
8426         rpc_stat = rxi_Alloc(space);
8427         if (rpc_stat == NULL)
8428             return NULL;
8429
8430         *counter += totalFunc;
8431         for (i = 0; i < totalFunc; i++) {
8432             rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8433             rpc_stat->stats[i].remote_peer = remoteHost;
8434             rpc_stat->stats[i].remote_port = remotePort;
8435             rpc_stat->stats[i].remote_is_server = isServer;
8436             rpc_stat->stats[i].interfaceId = rxInterface;
8437             rpc_stat->stats[i].func_total = totalFunc;
8438             rpc_stat->stats[i].func_index = i;
8439         }
8440         opr_queue_Prepend(stats, &rpc_stat->entry);
8441         if (addToPeerList) {
8442             opr_queue_Prepend(&peerStats, &rpc_stat->entryPeers);
8443         }
8444     }
8445     return rpc_stat;
8446 }
8447
8448 void
8449 rx_ClearProcessRPCStats(afs_int32 rxInterface)
8450 {
8451     rx_interface_stat_p rpc_stat;
8452     int totalFunc, i;
8453
8454     if (rxInterface == -1)
8455         return;
8456
8457     MUTEX_ENTER(&rx_rpc_stats);
8458     rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8459                                0, 0, 0, 0, 0);
8460     if (rpc_stat) {
8461         totalFunc = rpc_stat->stats[0].func_total;
8462         for (i = 0; i < totalFunc; i++)
8463             rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8464     }
8465     MUTEX_EXIT(&rx_rpc_stats);
8466     return;
8467 }
8468
8469 void
8470 rx_ClearPeerRPCStats(afs_int32 rxInterface, afs_uint32 peerHost, afs_uint16 peerPort)
8471 {
8472     rx_interface_stat_p rpc_stat;
8473     int totalFunc, i;
8474     struct rx_peer * peer;
8475
8476     if (rxInterface == -1)
8477         return;
8478
8479     peer = rxi_FindPeer(peerHost, peerPort, 0);
8480     if (!peer)
8481         return;
8482
8483     MUTEX_ENTER(&rx_rpc_stats);
8484     rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8485                                0, 0, 0, 0, 0);
8486     if (rpc_stat) {
8487         totalFunc = rpc_stat->stats[0].func_total;
8488         for (i = 0; i < totalFunc; i++)
8489             rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8490     }
8491     MUTEX_EXIT(&rx_rpc_stats);
8492     return;
8493 }
8494
8495 void *
8496 rx_CopyProcessRPCStats(afs_uint64 op)
8497 {
8498     rx_interface_stat_p rpc_stat;
8499     rx_function_entry_v1_p rpcop_stat =
8500         rxi_Alloc(sizeof(rx_function_entry_v1_t));
8501     int currentFunc = (op & MAX_AFS_UINT32);
8502     afs_int32 rxInterface = (op >> 32);
8503
8504     if (!rxi_monitor_processStats)
8505         return NULL;
8506
8507     if (rxInterface == -1)
8508         return NULL;
8509
8510     if (rpcop_stat == NULL)
8511         return NULL;
8512
8513     MUTEX_ENTER(&rx_rpc_stats);
8514     rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8515                                0, 0, 0, 0, 0);
8516     if (rpc_stat)
8517         memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8518                sizeof(rx_function_entry_v1_t));
8519     MUTEX_EXIT(&rx_rpc_stats);
8520     if (!rpc_stat) {
8521         rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8522         return NULL;
8523     }
8524     return rpcop_stat;
8525 }
8526
8527 void *
8528 rx_CopyPeerRPCStats(afs_uint64 op, afs_uint32 peerHost, afs_uint16 peerPort)
8529 {
8530     rx_interface_stat_p rpc_stat;
8531     rx_function_entry_v1_p rpcop_stat =
8532         rxi_Alloc(sizeof(rx_function_entry_v1_t));
8533     int currentFunc = (op & MAX_AFS_UINT32);
8534     afs_int32 rxInterface = (op >> 32);
8535     struct rx_peer *peer;
8536
8537     if (!rxi_monitor_peerStats)
8538         return NULL;
8539
8540     if (rxInterface == -1)
8541         return NULL;
8542
8543     if (rpcop_stat == NULL)
8544         return NULL;
8545
8546     peer = rxi_FindPeer(peerHost, peerPort, 0);
8547     if (!peer)
8548         return NULL;
8549
8550     MUTEX_ENTER(&rx_rpc_stats);
8551     rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8552                                0, 0, 0, 0, 0);
8553     if (rpc_stat)
8554         memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8555                sizeof(rx_function_entry_v1_t));
8556     MUTEX_EXIT(&rx_rpc_stats);
8557     if (!rpc_stat) {
8558         rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8559         return NULL;
8560     }
8561     return rpcop_stat;
8562 }
8563
8564 void
8565 rx_ReleaseRPCStats(void *stats)
8566 {
8567     if (stats)
8568         rxi_Free(stats, sizeof(rx_function_entry_v1_t));
8569 }
8570
8571 /*!
8572  * Given all of the information for a particular rpc
8573  * call, create (if needed) and update the stat totals for the rpc.
8574  *
8575  * @param stats
8576  *      the queue of stats that will be updated with the new value
8577  *
8578  * @param rxInterface
8579  *      a unique number that identifies the rpc interface
8580  *
8581  * @param currentFunc
8582  *      the index of the function being invoked
8583  *
8584  * @param totalFunc
8585  *      the total number of functions in this interface
8586  *
8587  * @param queueTime
8588  *      the amount of time this function waited for a thread
8589  *
8590  * @param execTime
8591  *      the amount of time this function invocation took to execute
8592  *
8593  * @param bytesSent
8594  *      the number bytes sent by this invocation
8595  *
8596  * @param bytesRcvd
8597  *      the number bytes received by this invocation
8598  *
8599  * @param isServer
8600  *      if true, this invocation was made to a server
8601  *
8602  * @param remoteHost
8603  *      the ip address of the remote host
8604  *
8605  * @param remotePort
8606  *      the port of the remote host
8607  *
8608  * @param addToPeerList
8609  *      if != 0, add newly created stat to the global peer list
8610  *
8611  * @param counter
8612  *      if a new stats structure is allocated, the counter will
8613  *      be updated with the new number of allocated stat structures
8614  *
8615  */
8616
8617 static int
8618 rxi_AddRpcStat(struct opr_queue *stats, afs_uint32 rxInterface,
8619                afs_uint32 currentFunc, afs_uint32 totalFunc,
8620                struct clock *queueTime, struct clock *execTime,
8621                afs_uint64 bytesSent, afs_uint64 bytesRcvd, int isServer,
8622                afs_uint32 remoteHost, afs_uint32 remotePort,
8623                int addToPeerList, unsigned int *counter)
8624 {
8625     int rc = 0;
8626     rx_interface_stat_p rpc_stat;
8627
8628     rpc_stat = rxi_FindRpcStat(stats, rxInterface, totalFunc, isServer,
8629                                remoteHost, remotePort, addToPeerList, counter,
8630                                1);
8631     if (!rpc_stat) {
8632         rc = -1;
8633         goto fail;
8634     }
8635
8636     /*
8637      * Increment the stats for this function
8638      */
8639
8640     rpc_stat->stats[currentFunc].invocations++;
8641     rpc_stat->stats[currentFunc].bytes_sent += bytesSent;
8642     rpc_stat->stats[currentFunc].bytes_rcvd += bytesRcvd;
8643     clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8644     clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8645     if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8646         rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8647     }
8648     if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8649         rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8650     }
8651     clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8652     clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8653                 execTime);
8654     if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8655         rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8656     }
8657     if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8658         rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8659     }
8660
8661   fail:
8662     return rc;
8663 }
8664
8665 void
8666 rxi_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8667                           afs_uint32 currentFunc, afs_uint32 totalFunc,
8668                           struct clock *queueTime, struct clock *execTime,
8669                           afs_uint64 bytesSent, afs_uint64 bytesRcvd,
8670                           int isServer)
8671 {
8672
8673     if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8674         return;
8675
8676     MUTEX_ENTER(&rx_rpc_stats);
8677
8678     if (rxi_monitor_peerStats) {
8679         MUTEX_ENTER(&peer->peer_lock);
8680         rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8681                        queueTime, execTime, bytesSent, bytesRcvd, isServer,
8682                        peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8683         MUTEX_EXIT(&peer->peer_lock);
8684     }
8685
8686     if (rxi_monitor_processStats) {
8687         rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8688                        queueTime, execTime, bytesSent, bytesRcvd, isServer,
8689                        0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8690     }
8691
8692     MUTEX_EXIT(&rx_rpc_stats);
8693 }
8694
8695 /*!
8696  * Increment the times and count for a particular rpc function.
8697  *
8698  * Traditionally this call was invoked from rxgen stubs. Modern stubs
8699  * call rx_RecordCallStatistics instead, so the public version of this
8700  * function is left purely for legacy callers.
8701  *
8702  * @param peer
8703  *      The peer who invoked the rpc
8704  *
8705  * @param rxInterface
8706  *      A unique number that identifies the rpc interface
8707  *
8708  * @param currentFunc
8709  *      The index of the function being invoked
8710  *
8711  * @param totalFunc
8712  *      The total number of functions in this interface
8713  *
8714  * @param queueTime
8715  *      The amount of time this function waited for a thread
8716  *
8717  * @param execTime
8718  *      The amount of time this function invocation took to execute
8719  *
8720  * @param bytesSent
8721  *      The number bytes sent by this invocation
8722  *
8723  * @param bytesRcvd
8724  *      The number bytes received by this invocation
8725  *
8726  * @param isServer
8727  *      If true, this invocation was made to a server
8728  *
8729  */
8730 void
8731 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8732                          afs_uint32 currentFunc, afs_uint32 totalFunc,
8733                          struct clock *queueTime, struct clock *execTime,
8734                          afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8735                          int isServer)
8736 {
8737     afs_uint64 sent64;
8738     afs_uint64 rcvd64;
8739
8740     sent64 = ((afs_uint64)bytesSent->high << 32) + bytesSent->low;
8741     rcvd64 = ((afs_uint64)bytesRcvd->high << 32) + bytesRcvd->low;
8742
8743     rxi_IncrementTimeAndCount(peer, rxInterface, currentFunc, totalFunc,
8744                               queueTime, execTime, sent64, rcvd64,
8745                               isServer);
8746 }
8747
8748
8749
8750 /*
8751  * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8752  *
8753  * PARAMETERS
8754  *
8755  * IN callerVersion - the rpc stat version of the caller.
8756  *
8757  * IN count - the number of entries to marshall.
8758  *
8759  * IN stats - pointer to stats to be marshalled.
8760  *
8761  * OUT ptr - Where to store the marshalled data.
8762  *
8763  * RETURN CODES
8764  *
8765  * Returns void.
8766  */
8767 void
8768 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8769                            rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8770 {
8771     int i;
8772     afs_uint32 *ptr;
8773
8774     /*
8775      * We only support the first version
8776      */
8777     for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8778         *(ptr++) = stats->remote_peer;
8779         *(ptr++) = stats->remote_port;
8780         *(ptr++) = stats->remote_is_server;
8781         *(ptr++) = stats->interfaceId;
8782         *(ptr++) = stats->func_total;
8783         *(ptr++) = stats->func_index;
8784         *(ptr++) = stats->invocations >> 32;
8785         *(ptr++) = stats->invocations & MAX_AFS_UINT32;
8786         *(ptr++) = stats->bytes_sent >> 32;
8787         *(ptr++) = stats->bytes_sent & MAX_AFS_UINT32;
8788         *(ptr++) = stats->bytes_rcvd >> 32;
8789         *(ptr++) = stats->bytes_rcvd & MAX_AFS_UINT32;
8790         *(ptr++) = stats->queue_time_sum.sec;
8791         *(ptr++) = stats->queue_time_sum.usec;
8792         *(ptr++) = stats->queue_time_sum_sqr.sec;
8793         *(ptr++) = stats->queue_time_sum_sqr.usec;
8794         *(ptr++) = stats->queue_time_min.sec;
8795         *(ptr++) = stats->queue_time_min.usec;
8796         *(ptr++) = stats->queue_time_max.sec;
8797         *(ptr++) = stats->queue_time_max.usec;
8798         *(ptr++) = stats->execution_time_sum.sec;
8799         *(ptr++) = stats->execution_time_sum.usec;
8800         *(ptr++) = stats->execution_time_sum_sqr.sec;
8801         *(ptr++) = stats->execution_time_sum_sqr.usec;
8802         *(ptr++) = stats->execution_time_min.sec;
8803         *(ptr++) = stats->execution_time_min.usec;
8804         *(ptr++) = stats->execution_time_max.sec;
8805         *(ptr++) = stats->execution_time_max.usec;
8806     }
8807     *ptrP = ptr;
8808 }
8809
8810 /*
8811  * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8812  * this process
8813  *
8814  * PARAMETERS
8815  *
8816  * IN callerVersion - the rpc stat version of the caller
8817  *
8818  * OUT myVersion - the rpc stat version of this function
8819  *
8820  * OUT clock_sec - local time seconds
8821  *
8822  * OUT clock_usec - local time microseconds
8823  *
8824  * OUT allocSize - the number of bytes allocated to contain stats
8825  *
8826  * OUT statCount - the number stats retrieved from this process.
8827  *
8828  * OUT stats - the actual stats retrieved from this process.
8829  *
8830  * RETURN CODES
8831  *
8832  * Returns void.  If successful, stats will != NULL.
8833  */
8834
8835 int
8836 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8837                            afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8838                            size_t * allocSize, afs_uint32 * statCount,
8839                            afs_uint32 ** stats)
8840 {
8841     size_t space = 0;
8842     afs_uint32 *ptr;
8843     struct clock now;
8844     int rc = 0;
8845
8846     *stats = 0;
8847     *allocSize = 0;
8848     *statCount = 0;
8849     *myVersion = RX_STATS_RETRIEVAL_VERSION;
8850
8851     /*
8852      * Check to see if stats are enabled
8853      */
8854
8855     MUTEX_ENTER(&rx_rpc_stats);
8856     if (!rxi_monitor_processStats) {
8857         MUTEX_EXIT(&rx_rpc_stats);
8858         return rc;
8859     }
8860
8861     clock_GetTime(&now);
8862     *clock_sec = now.sec;
8863     *clock_usec = now.usec;
8864
8865     /*
8866      * Allocate the space based upon the caller version
8867      *
8868      * If the client is at an older version than we are,
8869      * we return the statistic data in the older data format, but
8870      * we still return our version number so the client knows we
8871      * are maintaining more data than it can retrieve.
8872      */
8873
8874     if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8875         space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8876         *statCount = rxi_rpc_process_stat_cnt;
8877     } else {
8878         /*
8879          * This can't happen yet, but in the future version changes
8880          * can be handled by adding additional code here
8881          */
8882     }
8883
8884     if (space > (size_t) 0) {
8885         *allocSize = space;
8886         ptr = *stats = rxi_Alloc(space);
8887
8888         if (ptr != NULL) {
8889             struct opr_queue *cursor;
8890
8891             for (opr_queue_Scan(&processStats, cursor)) {
8892                 struct rx_interface_stat *rpc_stat = 
8893                     opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8894                 /*
8895                  * Copy the data based upon the caller version
8896                  */
8897                 rx_MarshallProcessRPCStats(callerVersion,
8898                                            rpc_stat->stats[0].func_total,
8899                                            rpc_stat->stats, &ptr);
8900             }
8901         } else {
8902             rc = ENOMEM;
8903         }
8904     }
8905     MUTEX_EXIT(&rx_rpc_stats);
8906     return rc;
8907 }
8908
8909 /*
8910  * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8911  *
8912  * PARAMETERS
8913  *
8914  * IN callerVersion - the rpc stat version of the caller
8915  *
8916  * OUT myVersion - the rpc stat version of this function
8917  *
8918  * OUT clock_sec - local time seconds
8919  *
8920  * OUT clock_usec - local time microseconds
8921  *
8922  * OUT allocSize - the number of bytes allocated to contain stats
8923  *
8924  * OUT statCount - the number of stats retrieved from the individual
8925  * peer structures.
8926  *
8927  * OUT stats - the actual stats retrieved from the individual peer structures.
8928  *
8929  * RETURN CODES
8930  *
8931  * Returns void.  If successful, stats will != NULL.
8932  */
8933
8934 int
8935 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8936                         afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8937                         size_t * allocSize, afs_uint32 * statCount,
8938                         afs_uint32 ** stats)
8939 {
8940     size_t space = 0;
8941     afs_uint32 *ptr;
8942     struct clock now;
8943     int rc = 0;
8944
8945     *stats = 0;
8946     *statCount = 0;
8947     *allocSize = 0;
8948     *myVersion = RX_STATS_RETRIEVAL_VERSION;
8949
8950     /*
8951      * Check to see if stats are enabled
8952      */
8953
8954     MUTEX_ENTER(&rx_rpc_stats);
8955     if (!rxi_monitor_peerStats) {
8956         MUTEX_EXIT(&rx_rpc_stats);
8957         return rc;
8958     }
8959
8960     clock_GetTime(&now);
8961     *clock_sec = now.sec;
8962     *clock_usec = now.usec;
8963
8964     /*
8965      * Allocate the space based upon the caller version
8966      *
8967      * If the client is at an older version than we are,
8968      * we return the statistic data in the older data format, but
8969      * we still return our version number so the client knows we
8970      * are maintaining more data than it can retrieve.
8971      */
8972
8973     if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8974         space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8975         *statCount = rxi_rpc_peer_stat_cnt;
8976     } else {
8977         /*
8978          * This can't happen yet, but in the future version changes
8979          * can be handled by adding additional code here
8980          */
8981     }
8982
8983     if (space > (size_t) 0) {
8984         *allocSize = space;
8985         ptr = *stats = rxi_Alloc(space);
8986
8987         if (ptr != NULL) {
8988             struct opr_queue *cursor;
8989
8990             for (opr_queue_Scan(&peerStats, cursor)) {
8991                 struct rx_interface_stat *rpc_stat
8992                     = opr_queue_Entry(cursor, struct rx_interface_stat,
8993                                      entryPeers);
8994
8995                 /*
8996                  * Copy the data based upon the caller version
8997                  */
8998                 rx_MarshallProcessRPCStats(callerVersion,
8999                                            rpc_stat->stats[0].func_total,
9000                                            rpc_stat->stats, &ptr);
9001             }
9002         } else {
9003             rc = ENOMEM;
9004         }
9005     }
9006     MUTEX_EXIT(&rx_rpc_stats);
9007     return rc;
9008 }
9009
9010 /*
9011  * rx_FreeRPCStats - free memory allocated by
9012  *                   rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
9013  *
9014  * PARAMETERS
9015  *
9016  * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
9017  * rx_RetrievePeerRPCStats
9018  *
9019  * IN allocSize - the number of bytes in stats.
9020  *
9021  * RETURN CODES
9022  *
9023  * Returns void.
9024  */
9025
9026 void
9027 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
9028 {
9029     rxi_Free(stats, allocSize);
9030 }
9031
9032 /*
9033  * rx_queryProcessRPCStats - see if process rpc stat collection is
9034  * currently enabled.
9035  *
9036  * PARAMETERS
9037  *
9038  * RETURN CODES
9039  *
9040  * Returns 0 if stats are not enabled != 0 otherwise
9041  */
9042
9043 int
9044 rx_queryProcessRPCStats(void)
9045 {
9046     int rc;
9047     MUTEX_ENTER(&rx_rpc_stats);
9048     rc = rxi_monitor_processStats;
9049     MUTEX_EXIT(&rx_rpc_stats);
9050     return rc;
9051 }
9052
9053 /*
9054  * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
9055  *
9056  * PARAMETERS
9057  *
9058  * RETURN CODES
9059  *
9060  * Returns 0 if stats are not enabled != 0 otherwise
9061  */
9062
9063 int
9064 rx_queryPeerRPCStats(void)
9065 {
9066     int rc;
9067     MUTEX_ENTER(&rx_rpc_stats);
9068     rc = rxi_monitor_peerStats;
9069     MUTEX_EXIT(&rx_rpc_stats);
9070     return rc;
9071 }
9072
9073 /*
9074  * rx_enableProcessRPCStats - begin rpc stat collection for entire process
9075  *
9076  * PARAMETERS
9077  *
9078  * RETURN CODES
9079  *
9080  * Returns void.
9081  */
9082
9083 void
9084 rx_enableProcessRPCStats(void)
9085 {
9086     MUTEX_ENTER(&rx_rpc_stats);
9087     rx_enable_stats = 1;
9088     rxi_monitor_processStats = 1;
9089     MUTEX_EXIT(&rx_rpc_stats);
9090 }
9091
9092 /*
9093  * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
9094  *
9095  * PARAMETERS
9096  *
9097  * RETURN CODES
9098  *
9099  * Returns void.
9100  */
9101
9102 void
9103 rx_enablePeerRPCStats(void)
9104 {
9105     MUTEX_ENTER(&rx_rpc_stats);
9106     rx_enable_stats = 1;
9107     rxi_monitor_peerStats = 1;
9108     MUTEX_EXIT(&rx_rpc_stats);
9109 }
9110
9111 /*
9112  * rx_disableProcessRPCStats - stop rpc stat collection for entire process
9113  *
9114  * PARAMETERS
9115  *
9116  * RETURN CODES
9117  *
9118  * Returns void.
9119  */
9120
9121 void
9122 rx_disableProcessRPCStats(void)
9123 {
9124     struct opr_queue *cursor, *store;
9125     size_t space;
9126
9127     MUTEX_ENTER(&rx_rpc_stats);
9128
9129     /*
9130      * Turn off process statistics and if peer stats is also off, turn
9131      * off everything
9132      */
9133
9134     rxi_monitor_processStats = 0;
9135     if (rxi_monitor_peerStats == 0) {
9136         rx_enable_stats = 0;
9137     }
9138
9139     for (opr_queue_ScanSafe(&processStats, cursor, store)) {
9140         unsigned int num_funcs = 0;
9141         struct rx_interface_stat *rpc_stat
9142             = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
9143
9144         opr_queue_Remove(&rpc_stat->entry);
9145
9146         num_funcs = rpc_stat->stats[0].func_total;
9147         space =
9148             sizeof(rx_interface_stat_t) +
9149             rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
9150
9151         rxi_Free(rpc_stat, space);
9152         rxi_rpc_process_stat_cnt -= num_funcs;
9153     }
9154     MUTEX_EXIT(&rx_rpc_stats);
9155 }
9156
9157 /*
9158  * rx_disablePeerRPCStats - stop rpc stat collection for peers
9159  *
9160  * PARAMETERS
9161  *
9162  * RETURN CODES
9163  *
9164  * Returns void.
9165  */
9166
9167 void
9168 rx_disablePeerRPCStats(void)
9169 {
9170     struct rx_peer **peer_ptr, **peer_end;
9171     int code;
9172
9173     /*
9174      * Turn off peer statistics and if process stats is also off, turn
9175      * off everything
9176      */
9177
9178     rxi_monitor_peerStats = 0;
9179     if (rxi_monitor_processStats == 0) {
9180         rx_enable_stats = 0;
9181     }
9182
9183     for (peer_ptr = &rx_peerHashTable[0], peer_end =
9184          &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
9185          peer_ptr++) {
9186         struct rx_peer *peer, *next, *prev;
9187
9188         MUTEX_ENTER(&rx_peerHashTable_lock);
9189         MUTEX_ENTER(&rx_rpc_stats);
9190         for (prev = peer = *peer_ptr; peer; peer = next) {
9191             next = peer->next;
9192             code = MUTEX_TRYENTER(&peer->peer_lock);
9193             if (code) {
9194                 size_t space;
9195                 struct opr_queue *cursor, *store;
9196
9197                 if (prev == *peer_ptr) {
9198                     *peer_ptr = next;
9199                     prev = next;
9200                 } else
9201                     prev->next = next;
9202
9203                 if (next)
9204                     next->refCount++;
9205                 if (prev)
9206                     prev->refCount++;
9207                 peer->refCount++;
9208                 MUTEX_EXIT(&rx_peerHashTable_lock);
9209
9210                 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
9211                     unsigned int num_funcs = 0;
9212                     struct rx_interface_stat *rpc_stat
9213                         = opr_queue_Entry(cursor, struct rx_interface_stat,
9214                                          entry);
9215
9216                     opr_queue_Remove(&rpc_stat->entry);
9217                     opr_queue_Remove(&rpc_stat->entryPeers);
9218                     num_funcs = rpc_stat->stats[0].func_total;
9219                     space =
9220                         sizeof(rx_interface_stat_t) +
9221                         rpc_stat->stats[0].func_total *
9222                         sizeof(rx_function_entry_v1_t);
9223
9224                     rxi_Free(rpc_stat, space);
9225                     rxi_rpc_peer_stat_cnt -= num_funcs;
9226                 }
9227                 MUTEX_EXIT(&peer->peer_lock);
9228
9229                 MUTEX_ENTER(&rx_peerHashTable_lock);
9230                 if (next)
9231                     next->refCount--;
9232                 if (prev)
9233                     prev->refCount--;
9234                 peer->refCount--;
9235             } else {
9236                 prev = peer;
9237             }
9238         }
9239         MUTEX_EXIT(&rx_rpc_stats);
9240         MUTEX_EXIT(&rx_peerHashTable_lock);
9241     }
9242 }
9243
9244 /*
9245  * rx_clearProcessRPCStats - clear the contents of the rpc stats according
9246  * to clearFlag
9247  *
9248  * PARAMETERS
9249  *
9250  * IN clearFlag - flag indicating which stats to clear
9251  *
9252  * RETURN CODES
9253  *
9254  * Returns void.
9255  */
9256
9257 void
9258 rx_clearProcessRPCStats(afs_uint32 clearFlag)
9259 {
9260     struct opr_queue *cursor;
9261
9262     MUTEX_ENTER(&rx_rpc_stats);
9263
9264     for (opr_queue_Scan(&processStats, cursor)) {
9265         unsigned int num_funcs = 0, i;
9266         struct rx_interface_stat *rpc_stat
9267              = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
9268
9269         num_funcs = rpc_stat->stats[0].func_total;
9270         for (i = 0; i < num_funcs; i++) {
9271             if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9272                 rpc_stat->stats[i].invocations = 0;
9273             }
9274             if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9275                 rpc_stat->stats[i].bytes_sent = 0;
9276             }
9277             if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9278                 rpc_stat->stats[i].bytes_rcvd = 0;
9279             }
9280             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9281                 rpc_stat->stats[i].queue_time_sum.sec = 0;
9282                 rpc_stat->stats[i].queue_time_sum.usec = 0;
9283             }
9284             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9285                 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9286                 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9287             }
9288             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9289                 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9290                 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9291             }
9292             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9293                 rpc_stat->stats[i].queue_time_max.sec = 0;
9294                 rpc_stat->stats[i].queue_time_max.usec = 0;
9295             }
9296             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9297                 rpc_stat->stats[i].execution_time_sum.sec = 0;
9298                 rpc_stat->stats[i].execution_time_sum.usec = 0;
9299             }
9300             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9301                 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9302                 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9303             }
9304             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9305                 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9306                 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9307             }
9308             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9309                 rpc_stat->stats[i].execution_time_max.sec = 0;
9310                 rpc_stat->stats[i].execution_time_max.usec = 0;
9311             }
9312         }
9313     }
9314
9315     MUTEX_EXIT(&rx_rpc_stats);
9316 }
9317
9318 /*
9319  * rx_clearPeerRPCStats - clear the contents of the rpc stats according
9320  * to clearFlag
9321  *
9322  * PARAMETERS
9323  *
9324  * IN clearFlag - flag indicating which stats to clear
9325  *
9326  * RETURN CODES
9327  *
9328  * Returns void.
9329  */
9330
9331 void
9332 rx_clearPeerRPCStats(afs_uint32 clearFlag)
9333 {
9334     struct opr_queue *cursor;
9335
9336     MUTEX_ENTER(&rx_rpc_stats);
9337
9338     for (opr_queue_Scan(&peerStats, cursor)) {
9339         unsigned int num_funcs, i;
9340         struct rx_interface_stat *rpc_stat
9341             = opr_queue_Entry(cursor, struct rx_interface_stat, entryPeers);
9342
9343         num_funcs = rpc_stat->stats[0].func_total;
9344         for (i = 0; i < num_funcs; i++) {
9345             if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9346                 rpc_stat->stats[i].invocations = 0;
9347             }
9348             if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9349                 rpc_stat->stats[i].bytes_sent = 0;
9350             }
9351             if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9352                 rpc_stat->stats[i].bytes_rcvd = 0;
9353             }
9354             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9355                 rpc_stat->stats[i].queue_time_sum.sec = 0;
9356                 rpc_stat->stats[i].queue_time_sum.usec = 0;
9357             }
9358             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9359                 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9360                 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9361             }
9362             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9363                 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9364                 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9365             }
9366             if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9367                 rpc_stat->stats[i].queue_time_max.sec = 0;
9368                 rpc_stat->stats[i].queue_time_max.usec = 0;
9369             }
9370             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9371                 rpc_stat->stats[i].execution_time_sum.sec = 0;
9372                 rpc_stat->stats[i].execution_time_sum.usec = 0;
9373             }
9374             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9375                 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9376                 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9377             }
9378             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9379                 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9380                 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9381             }
9382             if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9383                 rpc_stat->stats[i].execution_time_max.sec = 0;
9384                 rpc_stat->stats[i].execution_time_max.usec = 0;
9385             }
9386         }
9387     }
9388
9389     MUTEX_EXIT(&rx_rpc_stats);
9390 }
9391
9392 /*
9393  * rxi_rxstat_userok points to a routine that returns 1 if the caller
9394  * is authorized to enable/disable/clear RX statistics.
9395  */
9396 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
9397
9398 void
9399 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
9400 {
9401     rxi_rxstat_userok = proc;
9402 }
9403
9404 int
9405 rx_RxStatUserOk(struct rx_call *call)
9406 {
9407     if (!rxi_rxstat_userok)
9408         return 0;
9409     return rxi_rxstat_userok(call);
9410 }
9411
9412 #ifdef AFS_NT40_ENV
9413 /*
9414  * DllMain() -- Entry-point function called by the DllMainCRTStartup()
9415  *     function in the MSVC runtime DLL (msvcrt.dll).
9416  *
9417  *     Note: the system serializes calls to this function.
9418  */
9419 BOOL WINAPI
9420 DllMain(HINSTANCE dllInstHandle,        /* instance handle for this DLL module */
9421         DWORD reason,                   /* reason function is being called */
9422         LPVOID reserved)                /* reserved for future use */
9423 {
9424     switch (reason) {
9425     case DLL_PROCESS_ATTACH:
9426         /* library is being attached to a process */
9427         INIT_PTHREAD_LOCKS;
9428         return TRUE;
9429
9430     case DLL_PROCESS_DETACH:
9431         return TRUE;
9432
9433     default:
9434         return FALSE;
9435     }
9436 }
9437 #endif /* AFS_NT40_ENV */
9438
9439 #ifndef KERNEL
9440 int rx_DumpCalls(FILE *outputFile, char *cookie)
9441 {
9442 #ifdef RXDEBUG_PACKET
9443 #ifdef KDUMP_RX_LOCK
9444     struct rx_call_rx_lock *c;
9445 #else
9446     struct rx_call *c;
9447 #endif
9448 #ifdef AFS_NT40_ENV
9449     int zilch;
9450     char output[2048];
9451 #define RXDPRINTF sprintf
9452 #define RXDPRINTOUT output
9453 #else
9454 #define RXDPRINTF fprintf
9455 #define RXDPRINTOUT outputFile
9456 #endif
9457
9458     RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
9459 #ifdef AFS_NT40_ENV
9460     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9461 #endif
9462
9463     for (c = rx_allCallsp; c; c = c->allNextp) {
9464         u_short rqc, tqc, iovqc;
9465
9466         MUTEX_ENTER(&c->lock);
9467         rqc = opr_queue_Count(&c->rq);
9468         tqc = opr_queue_Count(&c->tq);
9469         iovqc = opr_queue_Count(&c->app.iovq);
9470
9471         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, "
9472                 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
9473                 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
9474                 "resendEvent=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
9475                 "lastSendTime=%u, lastRecvTime=%u"
9476 #ifdef RX_ENABLE_LOCKS
9477                 ", refCount=%u"
9478 #endif
9479 #ifdef RX_REFCOUNT_CHECK
9480                 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
9481                 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
9482 #endif
9483                 "\r\n",
9484                 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,
9485                 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
9486                 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
9487                 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
9488                 c->resendEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
9489                 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime
9490 #ifdef RX_ENABLE_LOCKS
9491                 , (afs_uint32)c->refCount
9492 #endif
9493 #ifdef RX_REFCOUNT_CHECK
9494                 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
9495 #endif
9496                 );
9497         MUTEX_EXIT(&c->lock);
9498
9499 #ifdef AFS_NT40_ENV
9500         WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9501 #endif
9502     }
9503     RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
9504 #ifdef AFS_NT40_ENV
9505     WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9506 #endif
9507 #endif /* RXDEBUG_PACKET */
9508     return 0;
9509 }
9510 #endif
9511
9512 #ifdef AFS_RXERRQ_ENV
9513 void
9514 rxi_HandleSocketErrors(osi_socket sock)
9515 {
9516     size_t cmsgbuf_len = 256;
9517     void *cmsgbuf;
9518 # ifndef KERNEL
9519     int errno_save = errno;
9520 # endif
9521
9522     cmsgbuf = rxi_Alloc(cmsgbuf_len);
9523     if (cmsgbuf == NULL) {
9524         goto done;
9525     }
9526
9527     while (osi_HandleSocketError(sock, cmsgbuf, cmsgbuf_len))
9528         ;
9529
9530     rxi_Free(cmsgbuf, cmsgbuf_len);
9531
9532  done:
9533 # ifndef KERNEL
9534     errno = errno_save;
9535 # endif
9536     return;
9537 }
9538
9539 static int
9540 NetSend_retry(osi_socket sock, void *addr, struct iovec *dvec, int nvecs,
9541               int length, int istack)
9542 {
9543     int code;
9544     int safety;
9545     /*
9546      * If an ICMP error comes in for any peer, sendmsg() can return -1 with an
9547      * errno of EHOSTUNREACH, ENETUNREACH, etc. There may be no problem with
9548      * sending this packet (an error is returned just to indicate we need to
9549      * read in pending errors), but the packet wasn't actually sent.
9550      *
9551      * It's difficult to determine in general whether sendmsg() is returning an
9552      * error due to a received ICMP error, or we're getting an actual error for
9553      * this specific sendmsg() call, since there may be other threads running
9554      * sendmsg/recvmsg/rxi_HandleSocketErrors at the same time. So, just retry
9555      * the sendmsg a few times; make sure not to retry forever, in case we are
9556      * getting an actual error from this sendmsg() call.
9557      *
9558      * Also note that if we accidentally drop a packet here that we didn't need
9559      * to, it's not the end of the world. Packets get dropped, and we should be
9560      * able to recover.
9561      */
9562     for (safety = 0; safety < RXI_SENDMSG_RETRY; safety++) {
9563         code = osi_NetSend(sock, addr, dvec, nvecs, length, istack);
9564         if (code == 0) {
9565             return 0;
9566         }
9567         rxi_HandleSocketErrors(sock);
9568     }
9569     return code;
9570
9571 }
9572 #endif
9573
9574 int
9575 rxi_NetSend(osi_socket socket, void *addr, struct iovec *dvec,
9576             int nvecs, int length, int istack)
9577 {
9578     if (rxi_IsRunning()) {
9579 #ifdef AFS_RXERRQ_ENV
9580         return NetSend_retry(socket, addr, dvec, nvecs, length, istack);
9581 #else
9582         return osi_NetSend(socket, addr, dvec, nvecs, length, istack);
9583 #endif
9584     }
9585 #ifdef AFS_NT40_ENV
9586     return WSAESHUTDOWN;
9587 #else
9588     return ESHUTDOWN;
9589 #endif
9590 }