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