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