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