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