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