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