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