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