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