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