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