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