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