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