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