fa9c9a1f97a5c09dcbac77d1eb112247e07659e4
[openafs.git] / src / rx / rx.c
1 /*
2  * Copyright 2000, International Business Machines Corporation and others.
3  * All Rights Reserved.
4  *
5  * This software has been released under the terms of the IBM Public
6  * License.  For details, see the LICENSE file in the top-level source
7  * directory or online at http://www.openafs.org/dl/license10.html
8  */
9
10 /* RX:  Extended Remote Procedure Call */
11
12 #include <afsconfig.h>
13 #include "afs/param.h"
14
15 #ifdef KERNEL
16 # include "afs/sysincludes.h"
17 # include "afsincludes.h"
18 # ifndef UKERNEL
19 #  include "h/types.h"
20 #  include "h/time.h"
21 #  include "h/stat.h"
22 #  ifdef AFS_LINUX20_ENV
23 #   include "h/socket.h"
24 #  endif
25 #  include "netinet/in.h"
26 #  ifdef AFS_SUN58_ENV
27 #   include "netinet/ip6.h"
28 #  endif
29 #  ifdef AFS_SUN57_ENV
30 #   include "inet/common.h"
31 #   include "inet/ip.h"
32 #   include "inet/ip_ire.h"
33 #  endif
34 #  include "afs/afs_args.h"
35 #  include "afs/afs_osi.h"
36 #  ifdef RX_KERNEL_TRACE
37 #   include "rx_kcommon.h"
38 #  endif
39 #  if   defined(AFS_AIX_ENV)
40 #   include "h/systm.h"
41 #  endif
42 #  ifdef RXDEBUG
43 #   undef RXDEBUG                       /* turn off debugging */
44 #  endif /* RXDEBUG */
45 #  if defined(AFS_SGI_ENV)
46 #   include "sys/debug.h"
47 #  endif
48 # else /* !UKERNEL */
49 #  include "afs/sysincludes.h"
50 #  include "afsincludes.h"
51 # endif /* !UKERNEL */
52 # include "afs/lock.h"
53 # include "rx_kmutex.h"
54 # include "rx_kernel.h"
55 # define        AFSOP_STOP_RXCALLBACK   210     /* Stop CALLBACK process */
56 # define        AFSOP_STOP_AFS          211     /* Stop AFS process */
57 # define        AFSOP_STOP_BKG          212     /* Stop BKG process */
58 extern afs_int32 afs_termState;
59 # ifdef AFS_AIX41_ENV
60 #  include "sys/lockl.h"
61 #  include "sys/lock_def.h"
62 # endif /* AFS_AIX41_ENV */
63 # include "afs/rxgen_consts.h"
64 #else /* KERNEL */
65 # include <roken.h>
66 # include <sys/types.h>
67 # include <string.h>
68 # include <stdarg.h>
69 # include <errno.h>
70 # ifdef HAVE_STDINT_H
71 #  include <stdint.h>
72 # endif
73 # ifdef AFS_NT40_ENV
74 #  include <stdlib.h>
75 #  include <fcntl.h>
76 #  include <afs/afsutil.h>
77 #  include <WINNT\afsreg.h>
78 # else
79 #  include <sys/socket.h>
80 #  include <sys/file.h>
81 #  include <netdb.h>
82 #  include <sys/stat.h>
83 #  include <netinet/in.h>
84 #  include <sys/time.h>
85 # endif
86 # include "rx_user.h"
87 #endif /* KERNEL */
88
89 #include "rx.h"
90 #include "rx_clock.h"
91 #include "rx_queue.h"
92 #include "rx_atomic.h"
93 #include "rx_globals.h"
94 #include "rx_trace.h"
95 #include "rx_internal.h"
96 #include "rx_stats.h"
97
98 #include <afs/rxgen_consts.h>
99
100 #ifndef KERNEL
101 #ifdef AFS_PTHREAD_ENV
102 #ifndef AFS_NT40_ENV
103 int (*registerProgram) (pid_t, char *) = 0;
104 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
105 #endif
106 #else
107 int (*registerProgram) (PROCESS, char *) = 0;
108 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
109 #endif
110 #endif
111
112 /* Local static routines */
113 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
114 static void rxi_ComputeRoundTripTime(struct rx_packet *, struct rx_ackPacket *,
115                                      struct rx_peer *, struct clock *);
116
117 #ifdef RX_ENABLE_LOCKS
118 static void rxi_SetAcksInTransmitQueue(struct rx_call *call);
119 #endif
120
121 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
122 struct rx_tq_debug {
123     rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
124     rx_atomic_t rxi_start_in_error;
125 } rx_tq_debug;
126 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
127
128 /*
129  * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
130  * currently allocated within rx.  This number is used to allocate the
131  * memory required to return the statistics when queried.
132  * Protected by the rx_rpc_stats mutex.
133  */
134
135 static unsigned int rxi_rpc_peer_stat_cnt;
136
137 /*
138  * rxi_rpc_process_stat_cnt counts the total number of local process stat
139  * structures currently allocated within rx.  The number is used to allocate
140  * the memory required to return the statistics when queried.
141  * Protected by the rx_rpc_stats mutex.
142  */
143
144 static unsigned int rxi_rpc_process_stat_cnt;
145
146 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
147 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
148
149 #if !defined(offsetof)
150 #include <stddef.h>             /* for definition of offsetof() */
151 #endif
152
153 #ifdef RX_ENABLE_LOCKS
154 afs_kmutex_t rx_atomic_mutex;
155 #endif
156
157 #ifdef AFS_PTHREAD_ENV
158
159 /*
160  * Use procedural initialization of mutexes/condition variables
161  * to ease NT porting
162  */
163
164 extern afs_kmutex_t rx_quota_mutex;
165 extern afs_kmutex_t rx_pthread_mutex;
166 extern afs_kmutex_t rx_packets_mutex;
167 extern afs_kmutex_t rx_refcnt_mutex;
168 extern afs_kmutex_t des_init_mutex;
169 extern afs_kmutex_t des_random_mutex;
170 extern afs_kmutex_t rx_clock_mutex;
171 extern afs_kmutex_t rxi_connCacheMutex;
172 extern afs_kmutex_t rx_event_mutex;
173 extern afs_kmutex_t osi_malloc_mutex;
174 extern afs_kmutex_t event_handler_mutex;
175 extern afs_kmutex_t listener_mutex;
176 extern afs_kmutex_t rx_if_init_mutex;
177 extern afs_kmutex_t rx_if_mutex;
178 extern afs_kmutex_t rxkad_client_uid_mutex;
179 extern afs_kmutex_t rxkad_random_mutex;
180
181 extern afs_kcondvar_t rx_event_handler_cond;
182 extern afs_kcondvar_t rx_listener_cond;
183
184 static afs_kmutex_t epoch_mutex;
185 static afs_kmutex_t rx_init_mutex;
186 static afs_kmutex_t rx_debug_mutex;
187 static afs_kmutex_t rx_rpc_stats;
188
189 static void
190 rxi_InitPthread(void)
191 {
192     MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
193     MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
194     MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
195     MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
196     MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
197     MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
198     MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
199     MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
200     MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
201     MUTEX_INIT(&rx_event_mutex, "event", MUTEX_DEFAULT, 0);
202     MUTEX_INIT(&osi_malloc_mutex, "malloc", MUTEX_DEFAULT, 0);
203     MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
204     MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
205     MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
206     MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
207     MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
208     MUTEX_INIT(&rxkad_client_uid_mutex, "uid", MUTEX_DEFAULT, 0);
209     MUTEX_INIT(&rxkad_random_mutex, "rxkad random", MUTEX_DEFAULT, 0);
210     MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
211
212     CV_INIT(&rx_event_handler_cond, "evhand", CV_DEFAULT, 0);
213     CV_INIT(&rx_listener_cond, "rxlisten", CV_DEFAULT, 0);
214
215     osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
216     osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
217
218     rxkad_global_stats_init();
219
220     MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
221     MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
222 #ifdef  RX_ENABLE_LOCKS
223 #ifdef RX_LOCKS_DB
224     rxdb_init();
225 #endif /* RX_LOCKS_DB */
226     MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
227     MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
228                0);
229     CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
230             0);
231     MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
232                0);
233     MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
234                0);
235     MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
236     MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
237 #endif /* RX_ENABLE_LOCKS */
238 }
239
240 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
241 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
242 /*
243  * The rx_stats_mutex mutex protects the following global variables:
244  * rxi_lowConnRefCount
245  * rxi_lowPeerRefCount
246  * rxi_nCalls
247  * rxi_Alloccnt
248  * rxi_Allocsize
249  * rx_tq_debug
250  * rx_stats
251  */
252
253 /*
254  * The rx_quota_mutex mutex protects the following global variables:
255  * rxi_dataQuota
256  * rxi_minDeficit
257  * rxi_availProcs
258  * rxi_totalMin
259  */
260
261 /*
262  * The rx_freePktQ_lock protects the following global variables:
263  * rx_nFreePackets
264  */
265
266 /*
267  * The rx_packets_mutex mutex protects the following global variables:
268  * rx_nPackets
269  * rx_TSFPQLocalMax
270  * rx_TSFPQGlobSize
271  * rx_TSFPQMaxProcs
272  */
273
274 /*
275  * The rx_pthread_mutex mutex protects the following global variables:
276  * rxi_fcfs_thread_num
277  */
278 #else
279 #define INIT_PTHREAD_LOCKS
280 #endif
281
282
283 /* Variables for handling the minProcs implementation.  availProcs gives the
284  * number of threads available in the pool at this moment (not counting dudes
285  * executing right now).  totalMin gives the total number of procs required
286  * for handling all minProcs requests.  minDeficit is a dynamic variable
287  * tracking the # of procs required to satisfy all of the remaining minProcs
288  * demands.
289  * For fine grain locking to work, the quota check and the reservation of
290  * a server thread has to come while rxi_availProcs and rxi_minDeficit
291  * are locked. To this end, the code has been modified under #ifdef
292  * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
293  * same time. A new function, ReturnToServerPool() returns the allocation.
294  *
295  * A call can be on several queue's (but only one at a time). When
296  * rxi_ResetCall wants to remove the call from a queue, it has to ensure
297  * that no one else is touching the queue. To this end, we store the address
298  * of the queue lock in the call structure (under the call lock) when we
299  * put the call on a queue, and we clear the call_queue_lock when the
300  * call is removed from a queue (once the call lock has been obtained).
301  * This allows rxi_ResetCall to safely synchronize with others wishing
302  * to manipulate the queue.
303  */
304
305 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
306 static afs_kmutex_t rx_rpc_stats;
307 void rxi_StartUnlocked(struct rxevent *event, void *call,
308                        void *arg1, int istack);
309 #endif
310
311 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
312 ** pretty good that the next packet coming in is from the same connection
313 ** as the last packet, since we're send multiple packets in a transmit window.
314 */
315 struct rx_connection *rxLastConn = 0;
316
317 #ifdef RX_ENABLE_LOCKS
318 /* The locking hierarchy for rx fine grain locking is composed of these
319  * tiers:
320  *
321  * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
322  * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
323  * call->lock - locks call data fields.
324  * These are independent of each other:
325  *      rx_freeCallQueue_lock
326  *      rxi_keyCreate_lock
327  * rx_serverPool_lock
328  * freeSQEList_lock
329  *
330  * serverQueueEntry->lock
331  * rx_peerHashTable_lock - locked under rx_connHashTable_lock
332  * rx_rpc_stats
333  * peer->lock - locks peer data fields.
334  * conn_data_lock - that more than one thread is not updating a conn data
335  *                  field at the same time.
336  * rx_freePktQ_lock
337  *
338  * lowest level:
339  *      multi_handle->lock
340  *      rxevent_lock
341  *      rx_packets_mutex
342  *      rx_stats_mutex
343  *      rx_refcnt_mutex
344  *      rx_atomic_mutex
345  *
346  * Do we need a lock to protect the peer field in the conn structure?
347  *      conn->peer was previously a constant for all intents and so has no
348  *      lock protecting this field. The multihomed client delta introduced
349  *      a RX code change : change the peer field in the connection structure
350  *      to that remote interface from which the last packet for this
351  *      connection was sent out. This may become an issue if further changes
352  *      are made.
353  */
354 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
355 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
356 #ifdef RX_LOCKS_DB
357 /* rxdb_fileID is used to identify the lock location, along with line#. */
358 static int rxdb_fileID = RXDB_FILE_RX;
359 #endif /* RX_LOCKS_DB */
360 #else /* RX_ENABLE_LOCKS */
361 #define SET_CALL_QUEUE_LOCK(C, L)
362 #define CLEAR_CALL_QUEUE_LOCK(C)
363 #endif /* RX_ENABLE_LOCKS */
364 struct rx_serverQueueEntry *rx_waitForPacket = 0;
365 struct rx_serverQueueEntry *rx_waitingForPacket = 0;
366
367 /* ------------Exported Interfaces------------- */
368
369 /* This function allows rxkad to set the epoch to a suitably random number
370  * which rx_NewConnection will use in the future.  The principle purpose is to
371  * get rxnull connections to use the same epoch as the rxkad connections do, at
372  * least once the first rxkad connection is established.  This is important now
373  * that the host/port addresses aren't used in FindConnection: the uniqueness
374  * of epoch/cid matters and the start time won't do. */
375
376 #ifdef AFS_PTHREAD_ENV
377 /*
378  * This mutex protects the following global variables:
379  * rx_epoch
380  */
381
382 #define LOCK_EPOCH MUTEX_ENTER(&epoch_mutex)
383 #define UNLOCK_EPOCH MUTEX_EXIT(&epoch_mutex)
384 #else
385 #define LOCK_EPOCH
386 #define UNLOCK_EPOCH
387 #endif /* AFS_PTHREAD_ENV */
388
389 void
390 rx_SetEpoch(afs_uint32 epoch)
391 {
392     LOCK_EPOCH;
393     rx_epoch = epoch;
394     UNLOCK_EPOCH;
395 }
396
397 /* Initialize rx.  A port number may be mentioned, in which case this
398  * becomes the default port number for any service installed later.
399  * If 0 is provided for the port number, a random port will be chosen
400  * by the kernel.  Whether this will ever overlap anything in
401  * /etc/services is anybody's guess...  Returns 0 on success, -1 on
402  * error. */
403 #ifndef AFS_NT40_ENV
404 static
405 #endif
406 int rxinit_status = 1;
407 #ifdef AFS_PTHREAD_ENV
408 /*
409  * This mutex protects the following global variables:
410  * rxinit_status
411  */
412
413 #define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
414 #define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
415 #else
416 #define LOCK_RX_INIT
417 #define UNLOCK_RX_INIT
418 #endif
419
420 int
421 rx_InitHost(u_int host, u_int port)
422 {
423 #ifdef KERNEL
424     osi_timeval_t tv;
425 #else /* KERNEL */
426     struct timeval tv;
427 #endif /* KERNEL */
428     char *htable, *ptable;
429     int tmp_status;
430
431     SPLVAR;
432
433     INIT_PTHREAD_LOCKS;
434     LOCK_RX_INIT;
435     if (rxinit_status == 0) {
436         tmp_status = rxinit_status;
437         UNLOCK_RX_INIT;
438         return tmp_status;      /* Already started; return previous error code. */
439     }
440 #ifdef RXDEBUG
441     rxi_DebugInit();
442 #endif
443 #ifdef AFS_NT40_ENV
444     if (afs_winsockInit() < 0)
445         return -1;
446 #endif
447
448 #ifndef KERNEL
449     /*
450      * Initialize anything necessary to provide a non-premptive threading
451      * environment.
452      */
453     rxi_InitializeThreadSupport();
454 #endif
455
456     /* Allocate and initialize a socket for client and perhaps server
457      * connections. */
458
459     rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
460     if (rx_socket == OSI_NULLSOCKET) {
461         UNLOCK_RX_INIT;
462         return RX_ADDRINUSE;
463     }
464 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
465 #ifdef RX_LOCKS_DB
466     rxdb_init();
467 #endif /* RX_LOCKS_DB */
468     MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
469     MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
470     MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
471     MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
472     MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
473     MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
474     MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
475     MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
476     MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
477                0);
478     CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
479             0);
480     MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
481                0);
482     MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
483                0);
484     MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
485 #if defined(AFS_HPUX110_ENV)
486     if (!uniprocessor)
487         rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
488 #endif /* AFS_HPUX110_ENV */
489 #endif /* RX_ENABLE_LOCKS && KERNEL */
490
491     rxi_nCalls = 0;
492     rx_connDeadTime = 12;
493     rx_tranquil = 0;            /* reset flag */
494     rxi_ResetStatistics();
495     htable = (char *)
496         osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
497     PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *));     /* XXXXX */
498     memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
499     ptable = (char *)osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
500     PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *));   /* XXXXX */
501     memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
502
503     /* Malloc up a bunch of packets & buffers */
504     rx_nFreePackets = 0;
505     queue_Init(&rx_freePacketQueue);
506     rxi_NeedMorePackets = FALSE;
507     rx_nPackets = 0;    /* rx_nPackets is managed by rxi_MorePackets* */
508
509     /* enforce a minimum number of allocated packets */
510     if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
511         rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
512
513     /* allocate the initial free packet pool */
514 #ifdef RX_ENABLE_TSFPQ
515     rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
516 #else /* RX_ENABLE_TSFPQ */
517     rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2);        /* fudge */
518 #endif /* RX_ENABLE_TSFPQ */
519     rx_CheckPackets();
520
521     NETPRI;
522
523     clock_Init();
524
525 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
526     tv.tv_sec = clock_now.sec;
527     tv.tv_usec = clock_now.usec;
528     srand((unsigned int)tv.tv_usec);
529 #else
530     osi_GetTime(&tv);
531 #endif
532     if (port) {
533         rx_port = port;
534     } else {
535 #if defined(KERNEL) && !defined(UKERNEL)
536         /* Really, this should never happen in a real kernel */
537         rx_port = 0;
538 #else
539         struct sockaddr_in addr;
540 #ifdef AFS_NT40_ENV
541         int addrlen = sizeof(addr);
542 #else
543         socklen_t addrlen = sizeof(addr);
544 #endif
545         if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
546             rx_Finalize();
547             return -1;
548         }
549         rx_port = addr.sin_port;
550 #endif
551     }
552     rx_stats.minRtt.sec = 9999999;
553 #ifdef  KERNEL
554     rx_SetEpoch(tv.tv_sec | 0x80000000);
555 #else
556     rx_SetEpoch(tv.tv_sec);     /* Start time of this package, rxkad
557                                  * will provide a randomer value. */
558 #endif
559     MUTEX_ENTER(&rx_quota_mutex);
560     rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
561     MUTEX_EXIT(&rx_quota_mutex);
562     /* *Slightly* random start time for the cid.  This is just to help
563      * out with the hashing function at the peer */
564     rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
565     rx_connHashTable = (struct rx_connection **)htable;
566     rx_peerHashTable = (struct rx_peer **)ptable;
567
568     rx_lastAckDelay.sec = 0;
569     rx_lastAckDelay.usec = 400000;      /* 400 milliseconds */
570     rx_hardAckDelay.sec = 0;
571     rx_hardAckDelay.usec = 100000;      /* 100 milliseconds */
572     rx_softAckDelay.sec = 0;
573     rx_softAckDelay.usec = 100000;      /* 100 milliseconds */
574
575     rxevent_Init(20, rxi_ReScheduleEvents);
576
577     /* Initialize various global queues */
578     queue_Init(&rx_idleServerQueue);
579     queue_Init(&rx_incomingCallQueue);
580     queue_Init(&rx_freeCallQueue);
581
582 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
583     /* Initialize our list of usable IP addresses. */
584     rx_GetIFInfo();
585 #endif
586
587     /* Start listener process (exact function is dependent on the
588      * implementation environment--kernel or user space) */
589     rxi_StartListener();
590
591     USERPRI;
592     tmp_status = rxinit_status = 0;
593     UNLOCK_RX_INIT;
594     return tmp_status;
595 }
596
597 int
598 rx_Init(u_int port)
599 {
600     return rx_InitHost(htonl(INADDR_ANY), port);
601 }
602
603 /* called with unincremented nRequestsRunning to see if it is OK to start
604  * a new thread in this service.  Could be "no" for two reasons: over the
605  * max quota, or would prevent others from reaching their min quota.
606  */
607 #ifdef RX_ENABLE_LOCKS
608 /* This verion of QuotaOK reserves quota if it's ok while the
609  * rx_serverPool_lock is held.  Return quota using ReturnToServerPool().
610  */
611 static int
612 QuotaOK(struct rx_service *aservice)
613 {
614     /* check if over max quota */
615     if (aservice->nRequestsRunning >= aservice->maxProcs) {
616         return 0;
617     }
618
619     /* under min quota, we're OK */
620     /* otherwise, can use only if there are enough to allow everyone
621      * to go to their min quota after this guy starts.
622      */
623
624     MUTEX_ENTER(&rx_quota_mutex);
625     if ((aservice->nRequestsRunning < aservice->minProcs)
626         || (rxi_availProcs > rxi_minDeficit)) {
627         aservice->nRequestsRunning++;
628         /* just started call in minProcs pool, need fewer to maintain
629          * guarantee */
630         if (aservice->nRequestsRunning <= aservice->minProcs)
631             rxi_minDeficit--;
632         rxi_availProcs--;
633         MUTEX_EXIT(&rx_quota_mutex);
634         return 1;
635     }
636     MUTEX_EXIT(&rx_quota_mutex);
637
638     return 0;
639 }
640
641 static void
642 ReturnToServerPool(struct rx_service *aservice)
643 {
644     aservice->nRequestsRunning--;
645     MUTEX_ENTER(&rx_quota_mutex);
646     if (aservice->nRequestsRunning < aservice->minProcs)
647         rxi_minDeficit++;
648     rxi_availProcs++;
649     MUTEX_EXIT(&rx_quota_mutex);
650 }
651
652 #else /* RX_ENABLE_LOCKS */
653 static int
654 QuotaOK(struct rx_service *aservice)
655 {
656     int rc = 0;
657     /* under min quota, we're OK */
658     if (aservice->nRequestsRunning < aservice->minProcs)
659         return 1;
660
661     /* check if over max quota */
662     if (aservice->nRequestsRunning >= aservice->maxProcs)
663         return 0;
664
665     /* otherwise, can use only if there are enough to allow everyone
666      * to go to their min quota after this guy starts.
667      */
668     MUTEX_ENTER(&rx_quota_mutex);
669     if (rxi_availProcs > rxi_minDeficit)
670         rc = 1;
671     MUTEX_EXIT(&rx_quota_mutex);
672     return rc;
673 }
674 #endif /* RX_ENABLE_LOCKS */
675
676 #ifndef KERNEL
677 /* Called by rx_StartServer to start up lwp's to service calls.
678    NExistingProcs gives the number of procs already existing, and which
679    therefore needn't be created. */
680 void
681 rxi_StartServerProcs(int nExistingProcs)
682 {
683     struct rx_service *service;
684     int i;
685     int maxdiff = 0;
686     int nProcs = 0;
687
688     /* For each service, reserve N processes, where N is the "minimum"
689      * number of processes that MUST be able to execute a request in parallel,
690      * at any time, for that process.  Also compute the maximum difference
691      * between any service's maximum number of processes that can run
692      * (i.e. the maximum number that ever will be run, and a guarantee
693      * that this number will run if other services aren't running), and its
694      * minimum number.  The result is the extra number of processes that
695      * we need in order to provide the latter guarantee */
696     for (i = 0; i < RX_MAX_SERVICES; i++) {
697         int diff;
698         service = rx_services[i];
699         if (service == (struct rx_service *)0)
700             break;
701         nProcs += service->minProcs;
702         diff = service->maxProcs - service->minProcs;
703         if (diff > maxdiff)
704             maxdiff = diff;
705     }
706     nProcs += maxdiff;          /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
707     nProcs -= nExistingProcs;   /* Subtract the number of procs that were previously created for use as server procs */
708     for (i = 0; i < nProcs; i++) {
709         rxi_StartServerProc(rx_ServerProc, rx_stackSize);
710     }
711 }
712 #endif /* KERNEL */
713
714 #ifdef AFS_NT40_ENV
715 /* This routine is only required on Windows */
716 void
717 rx_StartClientThread(void)
718 {
719 #ifdef AFS_PTHREAD_ENV
720     pthread_t pid;
721     pid = pthread_self();
722 #endif /* AFS_PTHREAD_ENV */
723 }
724 #endif /* AFS_NT40_ENV */
725
726 /* This routine must be called if any services are exported.  If the
727  * donateMe flag is set, the calling process is donated to the server
728  * process pool */
729 void
730 rx_StartServer(int donateMe)
731 {
732     struct rx_service *service;
733     int i;
734     SPLVAR;
735     clock_NewTime();
736
737     NETPRI;
738     /* Start server processes, if necessary (exact function is dependent
739      * on the implementation environment--kernel or user space).  DonateMe
740      * will be 1 if there is 1 pre-existing proc, i.e. this one.  In this
741      * case, one less new proc will be created rx_StartServerProcs.
742      */
743     rxi_StartServerProcs(donateMe);
744
745     /* count up the # of threads in minProcs, and add set the min deficit to
746      * be that value, too.
747      */
748     for (i = 0; i < RX_MAX_SERVICES; i++) {
749         service = rx_services[i];
750         if (service == (struct rx_service *)0)
751             break;
752         MUTEX_ENTER(&rx_quota_mutex);
753         rxi_totalMin += service->minProcs;
754         /* below works even if a thread is running, since minDeficit would
755          * still have been decremented and later re-incremented.
756          */
757         rxi_minDeficit += service->minProcs;
758         MUTEX_EXIT(&rx_quota_mutex);
759     }
760
761     /* Turn on reaping of idle server connections */
762     rxi_ReapConnections(NULL, NULL, NULL);
763
764     USERPRI;
765
766     if (donateMe) {
767 #ifndef AFS_NT40_ENV
768 #ifndef KERNEL
769         char name[32];
770         static int nProcs;
771 #ifdef AFS_PTHREAD_ENV
772         pid_t pid;
773         pid = afs_pointer_to_int(pthread_self());
774 #else /* AFS_PTHREAD_ENV */
775         PROCESS pid;
776         LWP_CurrentProcess(&pid);
777 #endif /* AFS_PTHREAD_ENV */
778
779         sprintf(name, "srv_%d", ++nProcs);
780         if (registerProgram)
781             (*registerProgram) (pid, name);
782 #endif /* KERNEL */
783 #endif /* AFS_NT40_ENV */
784         rx_ServerProc(NULL);    /* Never returns */
785     }
786 #ifdef RX_ENABLE_TSFPQ
787     /* no use leaving packets around in this thread's local queue if
788      * it isn't getting donated to the server thread pool.
789      */
790     rxi_FlushLocalPacketsTSFPQ();
791 #endif /* RX_ENABLE_TSFPQ */
792     return;
793 }
794
795 /* Create a new client connection to the specified service, using the
796  * specified security object to implement the security model for this
797  * connection. */
798 struct rx_connection *
799 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
800                  struct rx_securityClass *securityObject,
801                  int serviceSecurityIndex)
802 {
803     int hashindex, i;
804     afs_int32 cid;
805     struct rx_connection *conn;
806
807     SPLVAR;
808
809     clock_NewTime();
810     dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
811          "serviceSecurityIndex %d)\n",
812          ntohl(shost), ntohs(sport), sservice, securityObject,
813          serviceSecurityIndex));
814
815     /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
816      * the case of kmem_alloc? */
817     conn = rxi_AllocConnection();
818 #ifdef  RX_ENABLE_LOCKS
819     MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
820     MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
821     CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
822 #endif
823     NETPRI;
824     MUTEX_ENTER(&rx_connHashTable_lock);
825     cid = (rx_nextCid += RX_MAXCALLS);
826     conn->type = RX_CLIENT_CONNECTION;
827     conn->cid = cid;
828     conn->epoch = rx_epoch;
829     conn->peer = rxi_FindPeer(shost, sport, 0, 1);
830     conn->serviceId = sservice;
831     conn->securityObject = securityObject;
832     conn->securityData = (void *) 0;
833     conn->securityIndex = serviceSecurityIndex;
834     rx_SetConnDeadTime(conn, rx_connDeadTime);
835     rx_SetConnSecondsUntilNatPing(conn, 0);
836     conn->ackRate = RX_FAST_ACK_RATE;
837     conn->nSpecific = 0;
838     conn->specific = NULL;
839     conn->challengeEvent = NULL;
840     conn->delayedAbortEvent = NULL;
841     conn->abortCount = 0;
842     conn->error = 0;
843     for (i = 0; i < RX_MAXCALLS; i++) {
844         conn->twind[i] = rx_initSendWindow;
845         conn->rwind[i] = rx_initReceiveWindow;
846         conn->lastBusy[i] = 0;
847     }
848
849     RXS_NewConnection(securityObject, conn);
850     hashindex =
851         CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
852
853     conn->refCount++;           /* no lock required since only this thread knows... */
854     conn->next = rx_connHashTable[hashindex];
855     rx_connHashTable[hashindex] = conn;
856     if (rx_stats_active)
857         rx_atomic_inc(&rx_stats.nClientConns);
858     MUTEX_EXIT(&rx_connHashTable_lock);
859     USERPRI;
860     return conn;
861 }
862
863 /**
864  * Ensure a connection's timeout values are valid.
865  *
866  * @param[in] conn The connection to check
867  *
868  * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
869  *       unless idleDeadTime and/or hardDeadTime are not set
870  * @internal
871  */
872 static void
873 rxi_CheckConnTimeouts(struct rx_connection *conn)
874 {
875     /* a connection's timeouts must have the relationship
876      * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
877      * total loss of network to a peer may cause an idle timeout instead of a
878      * dead timeout, simply because the idle timeout gets hit first. Also set
879      * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
880     /* this logic is slightly complicated by the fact that
881      * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
882      */
883     conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
884     if (conn->idleDeadTime) {
885         conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
886     }
887     if (conn->hardDeadTime) {
888         if (conn->idleDeadTime) {
889             conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
890         } else {
891             conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
892         }
893     }
894 }
895
896 void
897 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
898 {
899     /* The idea is to set the dead time to a value that allows several
900      * keepalives to be dropped without timing out the connection. */
901     conn->secondsUntilDead = seconds;
902     rxi_CheckConnTimeouts(conn);
903     conn->secondsUntilPing = conn->secondsUntilDead / 6;
904 }
905
906 void
907 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
908 {
909     conn->hardDeadTime = seconds;
910     rxi_CheckConnTimeouts(conn);
911 }
912
913 void
914 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
915 {
916     conn->idleDeadTime = seconds;
917     rxi_CheckConnTimeouts(conn);
918 }
919
920 int rxi_lowPeerRefCount = 0;
921 int rxi_lowConnRefCount = 0;
922
923 /*
924  * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
925  * NOTE: must not be called with rx_connHashTable_lock held.
926  */
927 void
928 rxi_CleanupConnection(struct rx_connection *conn)
929 {
930     /* Notify the service exporter, if requested, that this connection
931      * is being destroyed */
932     if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
933         (*conn->service->destroyConnProc) (conn);
934
935     /* Notify the security module that this connection is being destroyed */
936     RXS_DestroyConnection(conn->securityObject, conn);
937
938     /* If this is the last connection using the rx_peer struct, set its
939      * idle time to now. rxi_ReapConnections will reap it if it's still
940      * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
941      */
942     MUTEX_ENTER(&rx_peerHashTable_lock);
943     if (conn->peer->refCount < 2) {
944         conn->peer->idleWhen = clock_Sec();
945         if (conn->peer->refCount < 1) {
946             conn->peer->refCount = 1;
947             if (rx_stats_active) {
948                 MUTEX_ENTER(&rx_stats_mutex);
949                 rxi_lowPeerRefCount++;
950                 MUTEX_EXIT(&rx_stats_mutex);
951             }
952         }
953     }
954     conn->peer->refCount--;
955     MUTEX_EXIT(&rx_peerHashTable_lock);
956
957     if (rx_stats_active)
958     {
959         if (conn->type == RX_SERVER_CONNECTION)
960             rx_atomic_dec(&rx_stats.nServerConns);
961         else
962             rx_atomic_dec(&rx_stats.nClientConns);
963     }
964 #ifndef KERNEL
965     if (conn->specific) {
966         int i;
967         for (i = 0; i < conn->nSpecific; i++) {
968             if (conn->specific[i] && rxi_keyCreate_destructor[i])
969                 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
970             conn->specific[i] = NULL;
971         }
972         free(conn->specific);
973     }
974     conn->specific = NULL;
975     conn->nSpecific = 0;
976 #endif /* !KERNEL */
977
978     MUTEX_DESTROY(&conn->conn_call_lock);
979     MUTEX_DESTROY(&conn->conn_data_lock);
980     CV_DESTROY(&conn->conn_call_cv);
981
982     rxi_FreeConnection(conn);
983 }
984
985 /* Destroy the specified connection */
986 void
987 rxi_DestroyConnection(struct rx_connection *conn)
988 {
989     MUTEX_ENTER(&rx_connHashTable_lock);
990     rxi_DestroyConnectionNoLock(conn);
991     /* conn should be at the head of the cleanup list */
992     if (conn == rx_connCleanup_list) {
993         rx_connCleanup_list = rx_connCleanup_list->next;
994         MUTEX_EXIT(&rx_connHashTable_lock);
995         rxi_CleanupConnection(conn);
996     }
997 #ifdef RX_ENABLE_LOCKS
998     else {
999         MUTEX_EXIT(&rx_connHashTable_lock);
1000     }
1001 #endif /* RX_ENABLE_LOCKS */
1002 }
1003
1004 static void
1005 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1006 {
1007     struct rx_connection **conn_ptr;
1008     int havecalls = 0;
1009     struct rx_packet *packet;
1010     int i;
1011     SPLVAR;
1012
1013     clock_NewTime();
1014
1015     NETPRI;
1016     MUTEX_ENTER(&conn->conn_data_lock);
1017     MUTEX_ENTER(&rx_refcnt_mutex);
1018     if (conn->refCount > 0)
1019         conn->refCount--;
1020     else {
1021         if (rx_stats_active) {
1022             MUTEX_ENTER(&rx_stats_mutex);
1023             rxi_lowConnRefCount++;
1024             MUTEX_EXIT(&rx_stats_mutex);
1025         }
1026     }
1027
1028     if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1029         /* Busy; wait till the last guy before proceeding */
1030         MUTEX_EXIT(&rx_refcnt_mutex);
1031         MUTEX_EXIT(&conn->conn_data_lock);
1032         USERPRI;
1033         return;
1034     }
1035
1036     /* If the client previously called rx_NewCall, but it is still
1037      * waiting, treat this as a running call, and wait to destroy the
1038      * connection later when the call completes. */
1039     if ((conn->type == RX_CLIENT_CONNECTION)
1040         && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1041         conn->flags |= RX_CONN_DESTROY_ME;
1042         MUTEX_EXIT(&conn->conn_data_lock);
1043         USERPRI;
1044         return;
1045     }
1046     MUTEX_EXIT(&rx_refcnt_mutex);
1047     MUTEX_EXIT(&conn->conn_data_lock);
1048
1049     /* Check for extant references to this connection */
1050     for (i = 0; i < RX_MAXCALLS; i++) {
1051         struct rx_call *call = conn->call[i];
1052         if (call) {
1053             havecalls = 1;
1054             if (conn->type == RX_CLIENT_CONNECTION) {
1055                 MUTEX_ENTER(&call->lock);
1056                 if (call->delayedAckEvent) {
1057                     /* Push the final acknowledgment out now--there
1058                      * won't be a subsequent call to acknowledge the
1059                      * last reply packets */
1060                     rxevent_Cancel(call->delayedAckEvent, call,
1061                                    RX_CALL_REFCOUNT_DELAY);
1062                     if (call->state == RX_STATE_PRECALL
1063                         || call->state == RX_STATE_ACTIVE) {
1064                         rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1065                     } else {
1066                         rxi_AckAll(NULL, call, 0);
1067                     }
1068                 }
1069                 MUTEX_EXIT(&call->lock);
1070             }
1071         }
1072     }
1073 #ifdef RX_ENABLE_LOCKS
1074     if (!havecalls) {
1075         if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1076             MUTEX_EXIT(&conn->conn_data_lock);
1077         } else {
1078             /* Someone is accessing a packet right now. */
1079             havecalls = 1;
1080         }
1081     }
1082 #endif /* RX_ENABLE_LOCKS */
1083
1084     if (havecalls) {
1085         /* Don't destroy the connection if there are any call
1086          * structures still in use */
1087         MUTEX_ENTER(&conn->conn_data_lock);
1088         conn->flags |= RX_CONN_DESTROY_ME;
1089         MUTEX_EXIT(&conn->conn_data_lock);
1090         USERPRI;
1091         return;
1092     }
1093
1094     if (conn->natKeepAliveEvent) {
1095         rxi_NatKeepAliveOff(conn);
1096     }
1097
1098     if (conn->delayedAbortEvent) {
1099         rxevent_Cancel(conn->delayedAbortEvent, (struct rx_call *)0, 0);
1100         packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1101         if (packet) {
1102             MUTEX_ENTER(&conn->conn_data_lock);
1103             rxi_SendConnectionAbort(conn, packet, 0, 1);
1104             MUTEX_EXIT(&conn->conn_data_lock);
1105             rxi_FreePacket(packet);
1106         }
1107     }
1108
1109     /* Remove from connection hash table before proceeding */
1110     conn_ptr =
1111         &rx_connHashTable[CONN_HASH
1112                           (peer->host, peer->port, conn->cid, conn->epoch,
1113                            conn->type)];
1114     for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1115         if (*conn_ptr == conn) {
1116             *conn_ptr = conn->next;
1117             break;
1118         }
1119     }
1120     /* if the conn that we are destroying was the last connection, then we
1121      * clear rxLastConn as well */
1122     if (rxLastConn == conn)
1123         rxLastConn = 0;
1124
1125     /* Make sure the connection is completely reset before deleting it. */
1126     /* get rid of pending events that could zap us later */
1127     if (conn->challengeEvent)
1128         rxevent_Cancel(conn->challengeEvent, (struct rx_call *)0, 0);
1129     if (conn->checkReachEvent)
1130         rxevent_Cancel(conn->checkReachEvent, (struct rx_call *)0, 0);
1131     if (conn->natKeepAliveEvent)
1132         rxevent_Cancel(conn->natKeepAliveEvent, (struct rx_call *)0, 0);
1133
1134     /* Add the connection to the list of destroyed connections that
1135      * need to be cleaned up. This is necessary to avoid deadlocks
1136      * in the routines we call to inform others that this connection is
1137      * being destroyed. */
1138     conn->next = rx_connCleanup_list;
1139     rx_connCleanup_list = conn;
1140 }
1141
1142 /* Externally available version */
1143 void
1144 rx_DestroyConnection(struct rx_connection *conn)
1145 {
1146     SPLVAR;
1147
1148     NETPRI;
1149     rxi_DestroyConnection(conn);
1150     USERPRI;
1151 }
1152
1153 void
1154 rx_GetConnection(struct rx_connection *conn)
1155 {
1156     SPLVAR;
1157
1158     NETPRI;
1159     MUTEX_ENTER(&rx_refcnt_mutex);
1160     conn->refCount++;
1161     MUTEX_EXIT(&rx_refcnt_mutex);
1162     USERPRI;
1163 }
1164
1165 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
1166 /* Wait for the transmit queue to no longer be busy.
1167  * requires the call->lock to be held */
1168 void
1169 rxi_WaitforTQBusy(struct rx_call *call) {
1170     while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1171         call->flags |= RX_CALL_TQ_WAIT;
1172         call->tqWaiters++;
1173 #ifdef RX_ENABLE_LOCKS
1174         osirx_AssertMine(&call->lock, "rxi_WaitforTQ lock");
1175         CV_WAIT(&call->cv_tq, &call->lock);
1176 #else /* RX_ENABLE_LOCKS */
1177         osi_rxSleep(&call->tq);
1178 #endif /* RX_ENABLE_LOCKS */
1179         call->tqWaiters--;
1180         if (call->tqWaiters == 0) {
1181             call->flags &= ~RX_CALL_TQ_WAIT;
1182         }
1183     }
1184 }
1185 #endif
1186
1187 static void
1188 rxi_WakeUpTransmitQueue(struct rx_call *call)
1189 {
1190     if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1191         dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
1192              call, call->tqWaiters, call->flags));
1193 #ifdef RX_ENABLE_LOCKS
1194         osirx_AssertMine(&call->lock, "rxi_Start start");
1195         CV_BROADCAST(&call->cv_tq);
1196 #else /* RX_ENABLE_LOCKS */
1197         osi_rxWakeup(&call->tq);
1198 #endif /* RX_ENABLE_LOCKS */
1199     }
1200 }
1201
1202 /* Start a new rx remote procedure call, on the specified connection.
1203  * If wait is set to 1, wait for a free call channel; otherwise return
1204  * 0.  Maxtime gives the maximum number of seconds this call may take,
1205  * after rx_NewCall returns.  After this time interval, a call to any
1206  * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1207  * For fine grain locking, we hold the conn_call_lock in order to
1208  * to ensure that we don't get signalle after we found a call in an active
1209  * state and before we go to sleep.
1210  */
1211 struct rx_call *
1212 rx_NewCall(struct rx_connection *conn)
1213 {
1214     int i, wait, ignoreBusy = 1;
1215     struct rx_call *call;
1216     struct clock queueTime;
1217     afs_uint32 leastBusy = 0;
1218     SPLVAR;
1219
1220     clock_NewTime();
1221     dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1222
1223     NETPRI;
1224     clock_GetTime(&queueTime);
1225     /*
1226      * Check if there are others waiting for a new call.
1227      * If so, let them go first to avoid starving them.
1228      * This is a fairly simple scheme, and might not be
1229      * a complete solution for large numbers of waiters.
1230      *
1231      * makeCallWaiters keeps track of the number of
1232      * threads waiting to make calls and the
1233      * RX_CONN_MAKECALL_WAITING flag bit is used to
1234      * indicate that there are indeed calls waiting.
1235      * The flag is set when the waiter is incremented.
1236      * It is only cleared when makeCallWaiters is 0.
1237      * This prevents us from accidently destroying the
1238      * connection while it is potentially about to be used.
1239      */
1240     MUTEX_ENTER(&conn->conn_call_lock);
1241     MUTEX_ENTER(&conn->conn_data_lock);
1242     while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1243         conn->flags |= RX_CONN_MAKECALL_WAITING;
1244         conn->makeCallWaiters++;
1245         MUTEX_EXIT(&conn->conn_data_lock);
1246
1247 #ifdef  RX_ENABLE_LOCKS
1248         CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1249 #else
1250         osi_rxSleep(conn);
1251 #endif
1252         MUTEX_ENTER(&conn->conn_data_lock);
1253         conn->makeCallWaiters--;
1254         if (conn->makeCallWaiters == 0)
1255             conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1256     }
1257
1258     /* We are now the active thread in rx_NewCall */
1259     conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1260     MUTEX_EXIT(&conn->conn_data_lock);
1261
1262     for (;;) {
1263         wait = 1;
1264
1265         for (i = 0; i < RX_MAXCALLS; i++) {
1266             call = conn->call[i];
1267             if (call) {
1268                 if (!ignoreBusy && conn->lastBusy[i] != leastBusy) {
1269                     /* we're not ignoring busy call slots; only look at the
1270                      * call slot that is the "least" busy */
1271                     continue;
1272                 }
1273
1274                 if (call->state == RX_STATE_DALLY) {
1275                     MUTEX_ENTER(&call->lock);
1276                     if (call->state == RX_STATE_DALLY) {
1277                         if (ignoreBusy && conn->lastBusy[i]) {
1278                             /* if we're ignoring busy call slots, skip any ones that
1279                              * have lastBusy set */
1280                             if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1281                                 leastBusy = conn->lastBusy[i];
1282                             }
1283                             MUTEX_EXIT(&call->lock);
1284                             continue;
1285                         }
1286
1287                         /*
1288                          * We are setting the state to RX_STATE_RESET to
1289                          * ensure that no one else will attempt to use this
1290                          * call once we drop the conn->conn_call_lock and
1291                          * call->lock.  We must drop the conn->conn_call_lock
1292                          * before calling rxi_ResetCall because the process
1293                          * of clearing the transmit queue can block for an
1294                          * extended period of time.  If we block while holding
1295                          * the conn->conn_call_lock, then all rx_EndCall
1296                          * processing will block as well.  This has a detrimental
1297                          * effect on overall system performance.
1298                          */
1299                         call->state = RX_STATE_RESET;
1300                         MUTEX_EXIT(&conn->conn_call_lock);
1301                         MUTEX_ENTER(&rx_refcnt_mutex);
1302                         CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1303                         MUTEX_EXIT(&rx_refcnt_mutex);
1304                         rxi_ResetCall(call, 0);
1305                         (*call->callNumber)++;
1306                         if (MUTEX_TRYENTER(&conn->conn_call_lock))
1307                             break;
1308
1309                         /*
1310                          * If we failed to be able to safely obtain the
1311                          * conn->conn_call_lock we will have to drop the
1312                          * call->lock to avoid a deadlock.  When the call->lock
1313                          * is released the state of the call can change.  If it
1314                          * is no longer RX_STATE_RESET then some other thread is
1315                          * using the call.
1316                          */
1317                         MUTEX_EXIT(&call->lock);
1318                         MUTEX_ENTER(&conn->conn_call_lock);
1319                         MUTEX_ENTER(&call->lock);
1320
1321                         if (call->state == RX_STATE_RESET)
1322                             break;
1323
1324                         /*
1325                          * If we get here it means that after dropping
1326                          * the conn->conn_call_lock and call->lock that
1327                          * the call is no longer ours.  If we can't find
1328                          * a free call in the remaining slots we should
1329                          * not go immediately to RX_CONN_MAKECALL_WAITING
1330                          * because by dropping the conn->conn_call_lock
1331                          * we have given up synchronization with rx_EndCall.
1332                          * Instead, cycle through one more time to see if
1333                          * we can find a call that can call our own.
1334                          */
1335                         MUTEX_ENTER(&rx_refcnt_mutex);
1336                         CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1337                         MUTEX_EXIT(&rx_refcnt_mutex);
1338                         wait = 0;
1339                     }
1340                     MUTEX_EXIT(&call->lock);
1341                 }
1342             } else {
1343                 if (ignoreBusy && conn->lastBusy[i]) {
1344                     /* if we're ignoring busy call slots, skip any ones that
1345                      * have lastBusy set */
1346                     if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1347                         leastBusy = conn->lastBusy[i];
1348                     }
1349                     continue;
1350                 }
1351
1352                 /* rxi_NewCall returns with mutex locked */
1353                 call = rxi_NewCall(conn, i);
1354                 MUTEX_ENTER(&rx_refcnt_mutex);
1355                 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1356                 MUTEX_EXIT(&rx_refcnt_mutex);
1357                 break;
1358             }
1359         }
1360         if (i < RX_MAXCALLS) {
1361             conn->lastBusy[i] = 0;
1362             break;
1363         }
1364         if (!wait)
1365             continue;
1366         if (leastBusy && ignoreBusy) {
1367             /* we didn't find a useable call slot, but we did see at least one
1368              * 'busy' slot; look again and only use a slot with the 'least
1369              * busy time */
1370             ignoreBusy = 0;
1371             continue;
1372         }
1373
1374         MUTEX_ENTER(&conn->conn_data_lock);
1375         conn->flags |= RX_CONN_MAKECALL_WAITING;
1376         conn->makeCallWaiters++;
1377         MUTEX_EXIT(&conn->conn_data_lock);
1378
1379 #ifdef  RX_ENABLE_LOCKS
1380         CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1381 #else
1382         osi_rxSleep(conn);
1383 #endif
1384         MUTEX_ENTER(&conn->conn_data_lock);
1385         conn->makeCallWaiters--;
1386         if (conn->makeCallWaiters == 0)
1387             conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1388         MUTEX_EXIT(&conn->conn_data_lock);
1389     }
1390     /* Client is initially in send mode */
1391     call->state = RX_STATE_ACTIVE;
1392     call->error = conn->error;
1393     if (call->error)
1394         call->mode = RX_MODE_ERROR;
1395     else
1396         call->mode = RX_MODE_SENDING;
1397
1398     /* remember start time for call in case we have hard dead time limit */
1399     call->queueTime = queueTime;
1400     clock_GetTime(&call->startTime);
1401     hzero(call->bytesSent);
1402     hzero(call->bytesRcvd);
1403
1404     /* Turn on busy protocol. */
1405     rxi_KeepAliveOn(call);
1406
1407     /* Attempt MTU discovery */
1408     rxi_GrowMTUOn(call);
1409
1410     /*
1411      * We are no longer the active thread in rx_NewCall
1412      */
1413     MUTEX_ENTER(&conn->conn_data_lock);
1414     conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1415     MUTEX_EXIT(&conn->conn_data_lock);
1416
1417     /*
1418      * Wake up anyone else who might be giving us a chance to
1419      * run (see code above that avoids resource starvation).
1420      */
1421 #ifdef  RX_ENABLE_LOCKS
1422     CV_BROADCAST(&conn->conn_call_cv);
1423 #else
1424     osi_rxWakeup(conn);
1425 #endif
1426     MUTEX_EXIT(&conn->conn_call_lock);
1427
1428 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
1429     if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1430         osi_Panic("rx_NewCall call about to be used without an empty tq");
1431     }
1432 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
1433
1434     MUTEX_EXIT(&call->lock);
1435     USERPRI;
1436
1437     dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1438     return call;
1439 }
1440
1441 int
1442 rxi_HasActiveCalls(struct rx_connection *aconn)
1443 {
1444     int i;
1445     struct rx_call *tcall;
1446     SPLVAR;
1447
1448     NETPRI;
1449     for (i = 0; i < RX_MAXCALLS; i++) {
1450         if ((tcall = aconn->call[i])) {
1451             if ((tcall->state == RX_STATE_ACTIVE)
1452                 || (tcall->state == RX_STATE_PRECALL)) {
1453                 USERPRI;
1454                 return 1;
1455             }
1456         }
1457     }
1458     USERPRI;
1459     return 0;
1460 }
1461
1462 int
1463 rxi_GetCallNumberVector(struct rx_connection *aconn,
1464                         afs_int32 * aint32s)
1465 {
1466     int i;
1467     struct rx_call *tcall;
1468     SPLVAR;
1469
1470     NETPRI;
1471     for (i = 0; i < RX_MAXCALLS; i++) {
1472         if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1473             aint32s[i] = aconn->callNumber[i] + 1;
1474         else
1475             aint32s[i] = aconn->callNumber[i];
1476     }
1477     USERPRI;
1478     return 0;
1479 }
1480
1481 int
1482 rxi_SetCallNumberVector(struct rx_connection *aconn,
1483                         afs_int32 * aint32s)
1484 {
1485     int i;
1486     struct rx_call *tcall;
1487     SPLVAR;
1488
1489     NETPRI;
1490     for (i = 0; i < RX_MAXCALLS; i++) {
1491         if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1492             aconn->callNumber[i] = aint32s[i] - 1;
1493         else
1494             aconn->callNumber[i] = aint32s[i];
1495     }
1496     USERPRI;
1497     return 0;
1498 }
1499
1500 /* Advertise a new service.  A service is named locally by a UDP port
1501  * number plus a 16-bit service id.  Returns (struct rx_service *) 0
1502  * on a failure.
1503  *
1504      char *serviceName;  Name for identification purposes (e.g. the
1505                          service name might be used for probing for
1506                          statistics) */
1507 struct rx_service *
1508 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1509                   char *serviceName, struct rx_securityClass **securityObjects,
1510                   int nSecurityObjects,
1511                   afs_int32(*serviceProc) (struct rx_call * acall))
1512 {
1513     osi_socket socket = OSI_NULLSOCKET;
1514     struct rx_service *tservice;
1515     int i;
1516     SPLVAR;
1517
1518     clock_NewTime();
1519
1520     if (serviceId == 0) {
1521         (osi_Msg
1522          "rx_NewService:  service id for service %s is not non-zero.\n",
1523          serviceName);
1524         return 0;
1525     }
1526     if (port == 0) {
1527         if (rx_port == 0) {
1528             (osi_Msg
1529              "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",
1530              serviceName);
1531             return 0;
1532         }
1533         port = rx_port;
1534         socket = rx_socket;
1535     }
1536
1537     tservice = rxi_AllocService();
1538     NETPRI;
1539
1540 #ifdef  RX_ENABLE_LOCKS
1541     MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1542 #endif
1543
1544     for (i = 0; i < RX_MAX_SERVICES; i++) {
1545         struct rx_service *service = rx_services[i];
1546         if (service) {
1547             if (port == service->servicePort && host == service->serviceHost) {
1548                 if (service->serviceId == serviceId) {
1549                     /* The identical service has already been
1550                      * installed; if the caller was intending to
1551                      * change the security classes used by this
1552                      * service, he/she loses. */
1553                     (osi_Msg
1554                      "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1555                      serviceName, serviceId, service->serviceName);
1556                     USERPRI;
1557                     rxi_FreeService(tservice);
1558                     return service;
1559                 }
1560                 /* Different service, same port: re-use the socket
1561                  * which is bound to the same port */
1562                 socket = service->socket;
1563             }
1564         } else {
1565             if (socket == OSI_NULLSOCKET) {
1566                 /* If we don't already have a socket (from another
1567                  * service on same port) get a new one */
1568                 socket = rxi_GetHostUDPSocket(host, port);
1569                 if (socket == OSI_NULLSOCKET) {
1570                     USERPRI;
1571                     rxi_FreeService(tservice);
1572                     return 0;
1573                 }
1574             }
1575             service = tservice;
1576             service->socket = socket;
1577             service->serviceHost = host;
1578             service->servicePort = port;
1579             service->serviceId = serviceId;
1580             service->serviceName = serviceName;
1581             service->nSecurityObjects = nSecurityObjects;
1582             service->securityObjects = securityObjects;
1583             service->minProcs = 0;
1584             service->maxProcs = 1;
1585             service->idleDeadTime = 60;
1586             service->idleDeadErr = 0;
1587             service->connDeadTime = rx_connDeadTime;
1588             service->executeRequestProc = serviceProc;
1589             service->checkReach = 0;
1590             service->nSpecific = 0;
1591             service->specific = NULL;
1592             rx_services[i] = service;   /* not visible until now */
1593             USERPRI;
1594             return service;
1595         }
1596     }
1597     USERPRI;
1598     rxi_FreeService(tservice);
1599     (osi_Msg "rx_NewService: cannot support > %d services\n",
1600      RX_MAX_SERVICES);
1601     return 0;
1602 }
1603
1604 /* Set configuration options for all of a service's security objects */
1605
1606 afs_int32
1607 rx_SetSecurityConfiguration(struct rx_service *service,
1608                             rx_securityConfigVariables type,
1609                             void *value)
1610 {
1611     int i;
1612     for (i = 0; i<service->nSecurityObjects; i++) {
1613         if (service->securityObjects[i]) {
1614             RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1615                                  value, NULL);
1616         }
1617     }
1618     return 0;
1619 }
1620
1621 struct rx_service *
1622 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1623               struct rx_securityClass **securityObjects, int nSecurityObjects,
1624               afs_int32(*serviceProc) (struct rx_call * acall))
1625 {
1626     return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1627 }
1628
1629 /* Generic request processing loop. This routine should be called
1630  * by the implementation dependent rx_ServerProc. If socketp is
1631  * non-null, it will be set to the file descriptor that this thread
1632  * is now listening on. If socketp is null, this routine will never
1633  * returns. */
1634 void
1635 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1636 {
1637     struct rx_call *call;
1638     afs_int32 code;
1639     struct rx_service *tservice = NULL;
1640
1641     for (;;) {
1642         if (newcall) {
1643             call = newcall;
1644             newcall = NULL;
1645         } else {
1646             call = rx_GetCall(threadID, tservice, socketp);
1647             if (socketp && *socketp != OSI_NULLSOCKET) {
1648                 /* We are now a listener thread */
1649                 return;
1650             }
1651         }
1652
1653         /* if server is restarting( typically smooth shutdown) then do not
1654          * allow any new calls.
1655          */
1656
1657         if (rx_tranquil && (call != NULL)) {
1658             SPLVAR;
1659
1660             NETPRI;
1661             MUTEX_ENTER(&call->lock);
1662
1663             rxi_CallError(call, RX_RESTARTING);
1664             rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1665
1666             MUTEX_EXIT(&call->lock);
1667             USERPRI;
1668         }
1669 #ifdef  KERNEL
1670         if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1671 #ifdef RX_ENABLE_LOCKS
1672             AFS_GLOCK();
1673 #endif /* RX_ENABLE_LOCKS */
1674             afs_termState = AFSOP_STOP_AFS;
1675             afs_osi_Wakeup(&afs_termState);
1676 #ifdef RX_ENABLE_LOCKS
1677             AFS_GUNLOCK();
1678 #endif /* RX_ENABLE_LOCKS */
1679             return;
1680         }
1681 #endif
1682
1683         tservice = call->conn->service;
1684
1685         if (tservice->beforeProc)
1686             (*tservice->beforeProc) (call);
1687
1688         code = tservice->executeRequestProc(call);
1689
1690         if (tservice->afterProc)
1691             (*tservice->afterProc) (call, code);
1692
1693         rx_EndCall(call, code);
1694         if (rx_stats_active) {
1695             MUTEX_ENTER(&rx_stats_mutex);
1696             rxi_nCalls++;
1697             MUTEX_EXIT(&rx_stats_mutex);
1698         }
1699     }
1700 }
1701
1702
1703 void
1704 rx_WakeupServerProcs(void)
1705 {
1706     struct rx_serverQueueEntry *np, *tqp;
1707     SPLVAR;
1708
1709     NETPRI;
1710     MUTEX_ENTER(&rx_serverPool_lock);
1711
1712 #ifdef RX_ENABLE_LOCKS
1713     if (rx_waitForPacket)
1714         CV_BROADCAST(&rx_waitForPacket->cv);
1715 #else /* RX_ENABLE_LOCKS */
1716     if (rx_waitForPacket)
1717         osi_rxWakeup(rx_waitForPacket);
1718 #endif /* RX_ENABLE_LOCKS */
1719     MUTEX_ENTER(&freeSQEList_lock);
1720     for (np = rx_FreeSQEList; np; np = tqp) {
1721         tqp = *(struct rx_serverQueueEntry **)np;
1722 #ifdef RX_ENABLE_LOCKS
1723         CV_BROADCAST(&np->cv);
1724 #else /* RX_ENABLE_LOCKS */
1725         osi_rxWakeup(np);
1726 #endif /* RX_ENABLE_LOCKS */
1727     }
1728     MUTEX_EXIT(&freeSQEList_lock);
1729     for (queue_Scan(&rx_idleServerQueue, np, tqp, rx_serverQueueEntry)) {
1730 #ifdef RX_ENABLE_LOCKS
1731         CV_BROADCAST(&np->cv);
1732 #else /* RX_ENABLE_LOCKS */
1733         osi_rxWakeup(np);
1734 #endif /* RX_ENABLE_LOCKS */
1735     }
1736     MUTEX_EXIT(&rx_serverPool_lock);
1737     USERPRI;
1738 }
1739
1740 /* meltdown:
1741  * One thing that seems to happen is that all the server threads get
1742  * tied up on some empty or slow call, and then a whole bunch of calls
1743  * arrive at once, using up the packet pool, so now there are more
1744  * empty calls.  The most critical resources here are server threads
1745  * and the free packet pool.  The "doreclaim" code seems to help in
1746  * general.  I think that eventually we arrive in this state: there
1747  * are lots of pending calls which do have all their packets present,
1748  * so they won't be reclaimed, are multi-packet calls, so they won't
1749  * be scheduled until later, and thus are tying up most of the free
1750  * packet pool for a very long time.
1751  * future options:
1752  * 1.  schedule multi-packet calls if all the packets are present.
1753  * Probably CPU-bound operation, useful to return packets to pool.
1754  * Do what if there is a full window, but the last packet isn't here?
1755  * 3.  preserve one thread which *only* runs "best" calls, otherwise
1756  * it sleeps and waits for that type of call.
1757  * 4.  Don't necessarily reserve a whole window for each thread.  In fact,
1758  * the current dataquota business is badly broken.  The quota isn't adjusted
1759  * to reflect how many packets are presently queued for a running call.
1760  * So, when we schedule a queued call with a full window of packets queued
1761  * up for it, that *should* free up a window full of packets for other 2d-class
1762  * calls to be able to use from the packet pool.  But it doesn't.
1763  *
1764  * NB.  Most of the time, this code doesn't run -- since idle server threads
1765  * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1766  * as a new call arrives.
1767  */
1768 /* Sleep until a call arrives.  Returns a pointer to the call, ready
1769  * for an rx_Read. */
1770 #ifdef RX_ENABLE_LOCKS
1771 struct rx_call *
1772 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1773 {
1774     struct rx_serverQueueEntry *sq;
1775     struct rx_call *call = (struct rx_call *)0;
1776     struct rx_service *service = NULL;
1777     SPLVAR;
1778
1779     MUTEX_ENTER(&freeSQEList_lock);
1780
1781     if ((sq = rx_FreeSQEList)) {
1782         rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1783         MUTEX_EXIT(&freeSQEList_lock);
1784     } else {                    /* otherwise allocate a new one and return that */
1785         MUTEX_EXIT(&freeSQEList_lock);
1786         sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1787         MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1788         CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1789     }
1790
1791     MUTEX_ENTER(&rx_serverPool_lock);
1792     if (cur_service != NULL) {
1793         ReturnToServerPool(cur_service);
1794     }
1795     while (1) {
1796         if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1797             struct rx_call *tcall, *ncall, *choice2 = NULL;
1798
1799             /* Scan for eligible incoming calls.  A call is not eligible
1800              * if the maximum number of calls for its service type are
1801              * already executing */
1802             /* One thread will process calls FCFS (to prevent starvation),
1803              * while the other threads may run ahead looking for calls which
1804              * have all their input data available immediately.  This helps
1805              * keep threads from blocking, waiting for data from the client. */
1806             for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1807                 service = tcall->conn->service;
1808                 if (!QuotaOK(service)) {
1809                     continue;
1810                 }
1811                 MUTEX_ENTER(&rx_pthread_mutex);
1812                 if (tno == rxi_fcfs_thread_num
1813                     || !tcall->queue_item_header.next) {
1814                     MUTEX_EXIT(&rx_pthread_mutex);
1815                     /* If we're the fcfs thread , then  we'll just use
1816                      * this call. If we haven't been able to find an optimal
1817                      * choice, and we're at the end of the list, then use a
1818                      * 2d choice if one has been identified.  Otherwise... */
1819                     call = (choice2 ? choice2 : tcall);
1820                     service = call->conn->service;
1821                 } else {
1822                     MUTEX_EXIT(&rx_pthread_mutex);
1823                     if (!queue_IsEmpty(&tcall->rq)) {
1824                         struct rx_packet *rp;
1825                         rp = queue_First(&tcall->rq, rx_packet);
1826                         if (rp->header.seq == 1) {
1827                             if (!meltdown_1pkt
1828                                 || (rp->header.flags & RX_LAST_PACKET)) {
1829                                 call = tcall;
1830                             } else if (rxi_2dchoice && !choice2
1831                                        && !(tcall->flags & RX_CALL_CLEARED)
1832                                        && (tcall->rprev > rxi_HardAckRate)) {
1833                                 choice2 = tcall;
1834                             } else
1835                                 rxi_md2cnt++;
1836                         }
1837                     }
1838                 }
1839                 if (call) {
1840                     break;
1841                 } else {
1842                     ReturnToServerPool(service);
1843                 }
1844             }
1845         }
1846
1847         if (call) {
1848             queue_Remove(call);
1849             MUTEX_EXIT(&rx_serverPool_lock);
1850             MUTEX_ENTER(&call->lock);
1851
1852             if (call->flags & RX_CALL_WAIT_PROC) {
1853                 call->flags &= ~RX_CALL_WAIT_PROC;
1854                 rx_atomic_dec(&rx_nWaiting);
1855             }
1856
1857             if (call->state != RX_STATE_PRECALL || call->error) {
1858                 MUTEX_EXIT(&call->lock);
1859                 MUTEX_ENTER(&rx_serverPool_lock);
1860                 ReturnToServerPool(service);
1861                 call = NULL;
1862                 continue;
1863             }
1864
1865             if (queue_IsEmpty(&call->rq)
1866                 || queue_First(&call->rq, rx_packet)->header.seq != 1)
1867                 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1868
1869             CLEAR_CALL_QUEUE_LOCK(call);
1870             break;
1871         } else {
1872             /* If there are no eligible incoming calls, add this process
1873              * to the idle server queue, to wait for one */
1874             sq->newcall = 0;
1875             sq->tno = tno;
1876             if (socketp) {
1877                 *socketp = OSI_NULLSOCKET;
1878             }
1879             sq->socketp = socketp;
1880             queue_Append(&rx_idleServerQueue, sq);
1881 #ifndef AFS_AIX41_ENV
1882             rx_waitForPacket = sq;
1883 #else
1884             rx_waitingForPacket = sq;
1885 #endif /* AFS_AIX41_ENV */
1886             do {
1887                 CV_WAIT(&sq->cv, &rx_serverPool_lock);
1888 #ifdef  KERNEL
1889                 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1890                     MUTEX_EXIT(&rx_serverPool_lock);
1891                     return (struct rx_call *)0;
1892                 }
1893 #endif
1894             } while (!(call = sq->newcall)
1895                      && !(socketp && *socketp != OSI_NULLSOCKET));
1896             MUTEX_EXIT(&rx_serverPool_lock);
1897             if (call) {
1898                 MUTEX_ENTER(&call->lock);
1899             }
1900             break;
1901         }
1902     }
1903
1904     MUTEX_ENTER(&freeSQEList_lock);
1905     *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
1906     rx_FreeSQEList = sq;
1907     MUTEX_EXIT(&freeSQEList_lock);
1908
1909     if (call) {
1910         clock_GetTime(&call->startTime);
1911         call->state = RX_STATE_ACTIVE;
1912         call->mode = RX_MODE_RECEIVING;
1913 #ifdef RX_KERNEL_TRACE
1914         if (ICL_SETACTIVE(afs_iclSetp)) {
1915             int glockOwner = ISAFS_GLOCK();
1916             if (!glockOwner)
1917                 AFS_GLOCK();
1918             afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
1919                        __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
1920                        call);
1921             if (!glockOwner)
1922                 AFS_GUNLOCK();
1923         }
1924 #endif
1925
1926         rxi_calltrace(RX_CALL_START, call);
1927         dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
1928              call->conn->service->servicePort, call->conn->service->serviceId,
1929              call));
1930
1931         MUTEX_EXIT(&call->lock);
1932         MUTEX_ENTER(&rx_refcnt_mutex);
1933         CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1934         MUTEX_EXIT(&rx_refcnt_mutex);
1935     } else {
1936         dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
1937     }
1938
1939     return call;
1940 }
1941 #else /* RX_ENABLE_LOCKS */
1942 struct rx_call *
1943 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1944 {
1945     struct rx_serverQueueEntry *sq;
1946     struct rx_call *call = (struct rx_call *)0, *choice2;
1947     struct rx_service *service = NULL;
1948     SPLVAR;
1949
1950     NETPRI;
1951     MUTEX_ENTER(&freeSQEList_lock);
1952
1953     if ((sq = rx_FreeSQEList)) {
1954         rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1955         MUTEX_EXIT(&freeSQEList_lock);
1956     } else {                    /* otherwise allocate a new one and return that */
1957         MUTEX_EXIT(&freeSQEList_lock);
1958         sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1959         MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1960         CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1961     }
1962     MUTEX_ENTER(&sq->lock);
1963
1964     if (cur_service != NULL) {
1965         cur_service->nRequestsRunning--;
1966         MUTEX_ENTER(&rx_quota_mutex);
1967         if (cur_service->nRequestsRunning < cur_service->minProcs)
1968             rxi_minDeficit++;
1969         rxi_availProcs++;
1970         MUTEX_EXIT(&rx_quota_mutex);
1971     }
1972     if (queue_IsNotEmpty(&rx_incomingCallQueue)) {
1973         struct rx_call *tcall, *ncall;
1974         /* Scan for eligible incoming calls.  A call is not eligible
1975          * if the maximum number of calls for its service type are
1976          * already executing */
1977         /* One thread will process calls FCFS (to prevent starvation),
1978          * while the other threads may run ahead looking for calls which
1979          * have all their input data available immediately.  This helps
1980          * keep threads from blocking, waiting for data from the client. */
1981         choice2 = (struct rx_call *)0;
1982         for (queue_Scan(&rx_incomingCallQueue, tcall, ncall, rx_call)) {
1983             service = tcall->conn->service;
1984             if (QuotaOK(service)) {
1985                 MUTEX_ENTER(&rx_pthread_mutex);
1986                 if (tno == rxi_fcfs_thread_num
1987                     || !tcall->queue_item_header.next) {
1988                     MUTEX_EXIT(&rx_pthread_mutex);
1989                     /* If we're the fcfs thread, then  we'll just use
1990                      * this call. If we haven't been able to find an optimal
1991                      * choice, and we're at the end of the list, then use a
1992                      * 2d choice if one has been identified.  Otherwise... */
1993                     call = (choice2 ? choice2 : tcall);
1994                     service = call->conn->service;
1995                 } else {
1996                     MUTEX_EXIT(&rx_pthread_mutex);
1997                     if (!queue_IsEmpty(&tcall->rq)) {
1998                         struct rx_packet *rp;
1999                         rp = queue_First(&tcall->rq, rx_packet);
2000                         if (rp->header.seq == 1
2001                             && (!meltdown_1pkt
2002                                 || (rp->header.flags & RX_LAST_PACKET))) {
2003                             call = tcall;
2004                         } else if (rxi_2dchoice && !choice2
2005                                    && !(tcall->flags & RX_CALL_CLEARED)
2006                                    && (tcall->rprev > rxi_HardAckRate)) {
2007                             choice2 = tcall;
2008                         } else
2009                             rxi_md2cnt++;
2010                     }
2011                 }
2012             }
2013             if (call)
2014                 break;
2015         }
2016     }
2017
2018     if (call) {
2019         queue_Remove(call);
2020         /* we can't schedule a call if there's no data!!! */
2021         /* send an ack if there's no data, if we're missing the
2022          * first packet, or we're missing something between first
2023          * and last -- there's a "hole" in the incoming data. */
2024         if (queue_IsEmpty(&call->rq)
2025             || queue_First(&call->rq, rx_packet)->header.seq != 1
2026             || call->rprev != queue_Last(&call->rq, rx_packet)->header.seq)
2027             rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2028
2029         call->flags &= (~RX_CALL_WAIT_PROC);
2030         service->nRequestsRunning++;
2031         /* just started call in minProcs pool, need fewer to maintain
2032          * guarantee */
2033         MUTEX_ENTER(&rx_quota_mutex);
2034         if (service->nRequestsRunning <= service->minProcs)
2035             rxi_minDeficit--;
2036         rxi_availProcs--;
2037         MUTEX_EXIT(&rx_quota_mutex);
2038         rx_atomic_dec(&rx_nWaiting);
2039         /* MUTEX_EXIT(&call->lock); */
2040     } else {
2041         /* If there are no eligible incoming calls, add this process
2042          * to the idle server queue, to wait for one */
2043         sq->newcall = 0;
2044         if (socketp) {
2045             *socketp = OSI_NULLSOCKET;
2046         }
2047         sq->socketp = socketp;
2048         queue_Append(&rx_idleServerQueue, sq);
2049         do {
2050             osi_rxSleep(sq);
2051 #ifdef  KERNEL
2052             if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2053                 USERPRI;
2054                 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2055                 return (struct rx_call *)0;
2056             }
2057 #endif
2058         } while (!(call = sq->newcall)
2059                  && !(socketp && *socketp != OSI_NULLSOCKET));
2060     }
2061     MUTEX_EXIT(&sq->lock);
2062
2063     MUTEX_ENTER(&freeSQEList_lock);
2064     *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2065     rx_FreeSQEList = sq;
2066     MUTEX_EXIT(&freeSQEList_lock);
2067
2068     if (call) {
2069         clock_GetTime(&call->startTime);
2070         call->state = RX_STATE_ACTIVE;
2071         call->mode = RX_MODE_RECEIVING;
2072 #ifdef RX_KERNEL_TRACE
2073         if (ICL_SETACTIVE(afs_iclSetp)) {
2074             int glockOwner = ISAFS_GLOCK();
2075             if (!glockOwner)
2076                 AFS_GLOCK();
2077             afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2078                        __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2079                        call);
2080             if (!glockOwner)
2081                 AFS_GUNLOCK();
2082         }
2083 #endif
2084
2085         rxi_calltrace(RX_CALL_START, call);
2086         dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2087              call->conn->service->servicePort, call->conn->service->serviceId,
2088              call));
2089     } else {
2090         dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2091     }
2092
2093     USERPRI;
2094
2095     return call;
2096 }
2097 #endif /* RX_ENABLE_LOCKS */
2098
2099
2100
2101 /* Establish a procedure to be called when a packet arrives for a
2102  * call.  This routine will be called at most once after each call,
2103  * and will also be called if there is an error condition on the or
2104  * the call is complete.  Used by multi rx to build a selection
2105  * function which determines which of several calls is likely to be a
2106  * good one to read from.
2107  * NOTE: the way this is currently implemented it is probably only a
2108  * good idea to (1) use it immediately after a newcall (clients only)
2109  * and (2) only use it once.  Other uses currently void your warranty
2110  */
2111 void
2112 rx_SetArrivalProc(struct rx_call *call,
2113                   void (*proc) (struct rx_call * call,
2114                                         void * mh,
2115                                         int index),
2116                   void * handle, int arg)
2117 {
2118     call->arrivalProc = proc;
2119     call->arrivalProcHandle = handle;
2120     call->arrivalProcArg = arg;
2121 }
2122
2123 /* Call is finished (possibly prematurely).  Return rc to the peer, if
2124  * appropriate, and return the final error code from the conversation
2125  * to the caller */
2126
2127 afs_int32
2128 rx_EndCall(struct rx_call *call, afs_int32 rc)
2129 {
2130     struct rx_connection *conn = call->conn;
2131     afs_int32 error;
2132     SPLVAR;
2133
2134     dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2135           call, rc, call->error, call->abortCode));
2136
2137     NETPRI;
2138     MUTEX_ENTER(&call->lock);
2139
2140     if (rc == 0 && call->error == 0) {
2141         call->abortCode = 0;
2142         call->abortCount = 0;
2143     }
2144
2145     call->arrivalProc = (void (*)())0;
2146     if (rc && call->error == 0) {
2147         rxi_CallError(call, rc);
2148         call->mode = RX_MODE_ERROR;
2149         /* Send an abort message to the peer if this error code has
2150          * only just been set.  If it was set previously, assume the
2151          * peer has already been sent the error code or will request it
2152          */
2153         rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2154     }
2155     if (conn->type == RX_SERVER_CONNECTION) {
2156         /* Make sure reply or at least dummy reply is sent */
2157         if (call->mode == RX_MODE_RECEIVING) {
2158             MUTEX_EXIT(&call->lock);
2159             rxi_WriteProc(call, 0, 0);
2160             MUTEX_ENTER(&call->lock);
2161         }
2162         if (call->mode == RX_MODE_SENDING) {
2163             MUTEX_EXIT(&call->lock);
2164             rxi_FlushWrite(call);
2165             MUTEX_ENTER(&call->lock);
2166         }
2167         rxi_calltrace(RX_CALL_END, call);
2168         /* Call goes to hold state until reply packets are acknowledged */
2169         if (call->tfirst + call->nSoftAcked < call->tnext) {
2170             call->state = RX_STATE_HOLD;
2171         } else {
2172             call->state = RX_STATE_DALLY;
2173             rxi_ClearTransmitQueue(call, 0);
2174             rxevent_Cancel(call->resendEvent, call, RX_CALL_REFCOUNT_RESEND);
2175             rxevent_Cancel(call->keepAliveEvent, call,
2176                            RX_CALL_REFCOUNT_ALIVE);
2177         }
2178     } else {                    /* Client connection */
2179         char dummy;
2180         /* Make sure server receives input packets, in the case where
2181          * no reply arguments are expected */
2182         if ((call->mode == RX_MODE_SENDING)
2183             || (call->mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2184             MUTEX_EXIT(&call->lock);
2185             (void)rxi_ReadProc(call, &dummy, 1);
2186             MUTEX_ENTER(&call->lock);
2187         }
2188
2189         /* If we had an outstanding delayed ack, be nice to the server
2190          * and force-send it now.
2191          */
2192         if (call->delayedAckEvent) {
2193             rxevent_Cancel(call->delayedAckEvent, call,
2194                            RX_CALL_REFCOUNT_DELAY);
2195             call->delayedAckEvent = NULL;
2196             rxi_SendDelayedAck(NULL, call, NULL);
2197         }
2198
2199         /* We need to release the call lock since it's lower than the
2200          * conn_call_lock and we don't want to hold the conn_call_lock
2201          * over the rx_ReadProc call. The conn_call_lock needs to be held
2202          * here for the case where rx_NewCall is perusing the calls on
2203          * the connection structure. We don't want to signal until
2204          * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2205          * have checked this call, found it active and by the time it
2206          * goes to sleep, will have missed the signal.
2207          */
2208         MUTEX_EXIT(&call->lock);
2209         MUTEX_ENTER(&conn->conn_call_lock);
2210         MUTEX_ENTER(&call->lock);
2211
2212         if (!(call->flags & RX_CALL_PEER_BUSY)) {
2213             conn->lastBusy[call->channel] = 0;
2214         }
2215
2216         MUTEX_ENTER(&conn->conn_data_lock);
2217         conn->flags |= RX_CONN_BUSY;
2218         if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2219             MUTEX_EXIT(&conn->conn_data_lock);
2220 #ifdef  RX_ENABLE_LOCKS
2221             CV_BROADCAST(&conn->conn_call_cv);
2222 #else
2223             osi_rxWakeup(conn);
2224 #endif
2225         }
2226 #ifdef RX_ENABLE_LOCKS
2227         else {
2228             MUTEX_EXIT(&conn->conn_data_lock);
2229         }
2230 #endif /* RX_ENABLE_LOCKS */
2231         call->state = RX_STATE_DALLY;
2232     }
2233     error = call->error;
2234
2235     /* currentPacket, nLeft, and NFree must be zeroed here, because
2236      * ResetCall cannot: ResetCall may be called at splnet(), in the
2237      * kernel version, and may interrupt the macros rx_Read or
2238      * rx_Write, which run at normal priority for efficiency. */
2239     if (call->currentPacket) {
2240 #ifdef RX_TRACK_PACKETS
2241         call->currentPacket->flags &= ~RX_PKTFLAG_CP;
2242 #endif
2243         rxi_FreePacket(call->currentPacket);
2244         call->currentPacket = (struct rx_packet *)0;
2245     }
2246
2247     call->nLeft = call->nFree = call->curlen = 0;
2248
2249     /* Free any packets from the last call to ReadvProc/WritevProc */
2250 #ifdef RXDEBUG_PACKET
2251     call->iovqc -=
2252 #endif /* RXDEBUG_PACKET */
2253         rxi_FreePackets(0, &call->iovq);
2254     MUTEX_EXIT(&call->lock);
2255
2256     MUTEX_ENTER(&rx_refcnt_mutex);
2257     CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2258     MUTEX_EXIT(&rx_refcnt_mutex);
2259     if (conn->type == RX_CLIENT_CONNECTION) {
2260         MUTEX_ENTER(&conn->conn_data_lock);
2261         conn->flags &= ~RX_CONN_BUSY;
2262         MUTEX_EXIT(&conn->conn_data_lock);
2263         MUTEX_EXIT(&conn->conn_call_lock);
2264     }
2265     USERPRI;
2266     /*
2267      * Map errors to the local host's errno.h format.
2268      */
2269     error = ntoh_syserr_conv(error);
2270     return error;
2271 }
2272
2273 #if !defined(KERNEL)
2274
2275 /* Call this routine when shutting down a server or client (especially
2276  * clients).  This will allow Rx to gracefully garbage collect server
2277  * connections, and reduce the number of retries that a server might
2278  * make to a dead client.
2279  * This is not quite right, since some calls may still be ongoing and
2280  * we can't lock them to destroy them. */
2281 void
2282 rx_Finalize(void)
2283 {
2284     struct rx_connection **conn_ptr, **conn_end;
2285
2286     INIT_PTHREAD_LOCKS;
2287     LOCK_RX_INIT;
2288     if (rxinit_status == 1) {
2289         UNLOCK_RX_INIT;
2290         return;                 /* Already shutdown. */
2291     }
2292     rxi_DeleteCachedConnections();
2293     if (rx_connHashTable) {
2294         MUTEX_ENTER(&rx_connHashTable_lock);
2295         for (conn_ptr = &rx_connHashTable[0], conn_end =
2296              &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2297              conn_ptr++) {
2298             struct rx_connection *conn, *next;
2299             for (conn = *conn_ptr; conn; conn = next) {
2300                 next = conn->next;
2301                 if (conn->type == RX_CLIENT_CONNECTION) {
2302                     MUTEX_ENTER(&rx_refcnt_mutex);
2303                     conn->refCount++;
2304                     MUTEX_EXIT(&rx_refcnt_mutex);
2305 #ifdef RX_ENABLE_LOCKS
2306                     rxi_DestroyConnectionNoLock(conn);
2307 #else /* RX_ENABLE_LOCKS */
2308                     rxi_DestroyConnection(conn);
2309 #endif /* RX_ENABLE_LOCKS */
2310                 }
2311             }
2312         }
2313 #ifdef RX_ENABLE_LOCKS
2314         while (rx_connCleanup_list) {
2315             struct rx_connection *conn;
2316             conn = rx_connCleanup_list;
2317             rx_connCleanup_list = rx_connCleanup_list->next;
2318             MUTEX_EXIT(&rx_connHashTable_lock);
2319             rxi_CleanupConnection(conn);
2320             MUTEX_ENTER(&rx_connHashTable_lock);
2321         }
2322         MUTEX_EXIT(&rx_connHashTable_lock);
2323 #endif /* RX_ENABLE_LOCKS */
2324     }
2325     rxi_flushtrace();
2326
2327 #ifdef AFS_NT40_ENV
2328     afs_winsockCleanup();
2329 #endif
2330
2331     rxinit_status = 1;
2332     UNLOCK_RX_INIT;
2333 }
2334 #endif
2335
2336 /* if we wakeup packet waiter too often, can get in loop with two
2337     AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2338 void
2339 rxi_PacketsUnWait(void)
2340 {
2341     if (!rx_waitingForPackets) {
2342         return;
2343     }
2344 #ifdef KERNEL
2345     if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2346         return;                 /* still over quota */
2347     }
2348 #endif /* KERNEL */
2349     rx_waitingForPackets = 0;
2350 #ifdef  RX_ENABLE_LOCKS
2351     CV_BROADCAST(&rx_waitingForPackets_cv);
2352 #else
2353     osi_rxWakeup(&rx_waitingForPackets);
2354 #endif
2355     return;
2356 }
2357
2358
2359 /* ------------------Internal interfaces------------------------- */
2360
2361 /* Return this process's service structure for the
2362  * specified socket and service */
2363 struct rx_service *
2364 rxi_FindService(osi_socket socket, u_short serviceId)
2365 {
2366     struct rx_service **sp;
2367     for (sp = &rx_services[0]; *sp; sp++) {
2368         if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2369             return *sp;
2370     }
2371     return 0;
2372 }
2373
2374 #ifdef RXDEBUG_PACKET
2375 #ifdef KDUMP_RX_LOCK
2376 static struct rx_call_rx_lock *rx_allCallsp = 0;
2377 #else
2378 static struct rx_call *rx_allCallsp = 0;
2379 #endif
2380 #endif /* RXDEBUG_PACKET */
2381
2382 /* Allocate a call structure, for the indicated channel of the
2383  * supplied connection.  The mode and state of the call must be set by
2384  * the caller. Returns the call with mutex locked. */
2385 struct rx_call *
2386 rxi_NewCall(struct rx_connection *conn, int channel)
2387 {
2388     struct rx_call *call;
2389 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
2390     struct rx_call *cp; /* Call pointer temp */
2391     struct rx_call *nxp;        /* Next call pointer, for queue_Scan */
2392 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2393
2394     dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2395
2396     /* Grab an existing call structure, or allocate a new one.
2397      * Existing call structures are assumed to have been left reset by
2398      * rxi_FreeCall */
2399     MUTEX_ENTER(&rx_freeCallQueue_lock);
2400
2401 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
2402     /*
2403      * EXCEPT that the TQ might not yet be cleared out.
2404      * Skip over those with in-use TQs.
2405      */
2406     call = NULL;
2407     for (queue_Scan(&rx_freeCallQueue, cp, nxp, rx_call)) {
2408         if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2409             call = cp;
2410             break;
2411         }
2412     }
2413     if (call) {
2414 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2415     if (queue_IsNotEmpty(&rx_freeCallQueue)) {
2416         call = queue_First(&rx_freeCallQueue, rx_call);
2417 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2418         queue_Remove(call);
2419         if (rx_stats_active)
2420             rx_atomic_dec(&rx_stats.nFreeCallStructs);
2421         MUTEX_EXIT(&rx_freeCallQueue_lock);
2422         MUTEX_ENTER(&call->lock);
2423         CLEAR_CALL_QUEUE_LOCK(call);
2424 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
2425         /* Now, if TQ wasn't cleared earlier, do it now. */
2426         rxi_WaitforTQBusy(call);
2427         if (call->flags & RX_CALL_TQ_CLEARME) {
2428             rxi_ClearTransmitQueue(call, 1);
2429             /*queue_Init(&call->tq);*/
2430         }
2431 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2432         /* Bind the call to its connection structure */
2433         call->conn = conn;
2434         rxi_ResetCall(call, 1);
2435     } else {
2436
2437         call = rxi_Alloc(sizeof(struct rx_call));
2438 #ifdef RXDEBUG_PACKET
2439         call->allNextp = rx_allCallsp;
2440         rx_allCallsp = call;
2441         call->call_id =
2442             rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2443 #else /* RXDEBUG_PACKET */
2444         rx_atomic_inc(&rx_stats.nCallStructs);
2445 #endif /* RXDEBUG_PACKET */
2446
2447         MUTEX_EXIT(&rx_freeCallQueue_lock);
2448         MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2449         MUTEX_ENTER(&call->lock);
2450         CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2451         CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2452         CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2453
2454         /* Initialize once-only items */
2455         queue_Init(&call->tq);
2456         queue_Init(&call->rq);
2457         queue_Init(&call->iovq);
2458 #ifdef RXDEBUG_PACKET
2459         call->rqc = call->tqc = call->iovqc = 0;
2460 #endif /* RXDEBUG_PACKET */
2461         /* Bind the call to its connection structure (prereq for reset) */
2462         call->conn = conn;
2463         rxi_ResetCall(call, 1);
2464     }
2465     call->channel = channel;
2466     call->callNumber = &conn->callNumber[channel];
2467     call->rwind = conn->rwind[channel];
2468     call->twind = conn->twind[channel];
2469     /* Note that the next expected call number is retained (in
2470      * conn->callNumber[i]), even if we reallocate the call structure
2471      */
2472     conn->call[channel] = call;
2473     /* if the channel's never been used (== 0), we should start at 1, otherwise
2474      * the call number is valid from the last time this channel was used */
2475     if (*call->callNumber == 0)
2476         *call->callNumber = 1;
2477
2478     return call;
2479 }
2480
2481 /* A call has been inactive long enough that so we can throw away
2482  * state, including the call structure, which is placed on the call
2483  * free list.
2484  *
2485  * call->lock amd rx_refcnt_mutex are held upon entry.
2486  * haveCTLock is set when called from rxi_ReapConnections.
2487  */
2488 void
2489 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2490 {
2491     int channel = call->channel;
2492     struct rx_connection *conn = call->conn;
2493
2494
2495     if (call->state == RX_STATE_DALLY || call->state == RX_STATE_HOLD)
2496         (*call->callNumber)++;
2497     /*
2498      * We are setting the state to RX_STATE_RESET to
2499      * ensure that no one else will attempt to use this
2500      * call once we drop the refcnt lock. We must drop
2501      * the refcnt lock before calling rxi_ResetCall
2502      * because it cannot be held across acquiring the
2503      * freepktQ lock. NewCall does the same.
2504      */
2505     call->state = RX_STATE_RESET;
2506     MUTEX_EXIT(&rx_refcnt_mutex);
2507     rxi_ResetCall(call, 0);
2508     call->conn->call[channel] = (struct rx_call *)0;
2509
2510     MUTEX_ENTER(&rx_freeCallQueue_lock);
2511     SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2512 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
2513     /* A call may be free even though its transmit queue is still in use.
2514      * Since we search the call list from head to tail, put busy calls at
2515      * the head of the list, and idle calls at the tail.
2516      */
2517     if (call->flags & RX_CALL_TQ_BUSY)
2518         queue_Prepend(&rx_freeCallQueue, call);
2519     else
2520         queue_Append(&rx_freeCallQueue, call);
2521 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
2522     queue_Append(&rx_freeCallQueue, call);
2523 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
2524     if (rx_stats_active)
2525         rx_atomic_inc(&rx_stats.nFreeCallStructs);
2526     MUTEX_EXIT(&rx_freeCallQueue_lock);
2527
2528     /* Destroy the connection if it was previously slated for
2529      * destruction, i.e. the Rx client code previously called
2530      * rx_DestroyConnection (client connections), or
2531      * rxi_ReapConnections called the same routine (server
2532      * connections).  Only do this, however, if there are no
2533      * outstanding calls. Note that for fine grain locking, there appears
2534      * to be a deadlock in that rxi_FreeCall has a call locked and
2535      * DestroyConnectionNoLock locks each call in the conn. But note a
2536      * few lines up where we have removed this call from the conn.
2537      * If someone else destroys a connection, they either have no
2538      * call lock held or are going through this section of code.
2539      */
2540     MUTEX_ENTER(&conn->conn_data_lock);
2541     if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2542         MUTEX_ENTER(&rx_refcnt_mutex);
2543         conn->refCount++;
2544         MUTEX_EXIT(&rx_refcnt_mutex);
2545         MUTEX_EXIT(&conn->conn_data_lock);
2546 #ifdef RX_ENABLE_LOCKS
2547         if (haveCTLock)
2548             rxi_DestroyConnectionNoLock(conn);
2549         else
2550             rxi_DestroyConnection(conn);
2551 #else /* RX_ENABLE_LOCKS */
2552         rxi_DestroyConnection(conn);
2553 #endif /* RX_ENABLE_LOCKS */
2554     } else {
2555         MUTEX_EXIT(&conn->conn_data_lock);
2556     }
2557     MUTEX_ENTER(&rx_refcnt_mutex);
2558 }
2559
2560 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2561 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2562
2563 void *
2564 rxi_Alloc(size_t size)
2565 {
2566     char *p;
2567
2568     if (rx_stats_active) {
2569         rx_atomic_add(&rxi_Allocsize, (int) size);
2570         rx_atomic_inc(&rxi_Alloccnt);
2571     }
2572
2573 p = (char *)
2574 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2575   afs_osi_Alloc_NoSleep(size);
2576 #else
2577   osi_Alloc(size);
2578 #endif
2579     if (!p)
2580         osi_Panic("rxi_Alloc error");
2581     memset(p, 0, size);
2582     return p;
2583 }
2584
2585 void
2586 rxi_Free(void *addr, size_t size)
2587 {
2588     if (rx_stats_active) {
2589         rx_atomic_sub(&rxi_Allocsize, (int) size);
2590         rx_atomic_dec(&rxi_Alloccnt);
2591     }
2592     osi_Free(addr, size);
2593 }
2594
2595 void
2596 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2597 {
2598     struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2599     struct rx_peer *next = NULL;
2600     int hashIndex;
2601
2602     if (!peer) {
2603         MUTEX_ENTER(&rx_peerHashTable_lock);
2604         if (port == 0) {
2605             peer_ptr = &rx_peerHashTable[0];
2606             peer_end = &rx_peerHashTable[rx_hashTableSize];
2607             next = NULL;
2608         resume:
2609             for ( ; peer_ptr < peer_end; peer_ptr++) {
2610                 if (!peer)
2611                     peer = *peer_ptr;
2612                 for ( ; peer; peer = next) {
2613                     next = peer->next;
2614                     if (host == peer->host)
2615                         break;
2616                 }
2617             }
2618         } else {
2619             hashIndex = PEER_HASH(host, port);
2620             for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2621                 if ((peer->host == host) && (peer->port == port))
2622                     break;
2623             }
2624         }
2625     } else {
2626         MUTEX_ENTER(&rx_peerHashTable_lock);
2627     }
2628
2629     if (peer) {
2630         peer->refCount++;
2631         MUTEX_EXIT(&rx_peerHashTable_lock);
2632
2633         MUTEX_ENTER(&peer->peer_lock);
2634         /* We don't handle dropping below min, so don't */
2635         mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2636         peer->ifMTU=MIN(mtu, peer->ifMTU);
2637         peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2638         /* if we tweaked this down, need to tune our peer MTU too */
2639         peer->MTU = MIN(peer->MTU, peer->natMTU);
2640         /* if we discovered a sub-1500 mtu, degrade */
2641         if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2642             peer->maxDgramPackets = 1;
2643         /* We no longer have valid peer packet information */
2644         if (peer->maxPacketSize-RX_IPUDP_SIZE > peer->ifMTU)
2645             peer->maxPacketSize = 0;
2646         MUTEX_EXIT(&peer->peer_lock);
2647
2648         MUTEX_ENTER(&rx_peerHashTable_lock);
2649         peer->refCount--;
2650         if (host && !port) {
2651             peer = next;
2652             /* pick up where we left off */
2653             goto resume;
2654         }
2655     }
2656     MUTEX_EXIT(&rx_peerHashTable_lock);
2657 }
2658
2659 /* Find the peer process represented by the supplied (host,port)
2660  * combination.  If there is no appropriate active peer structure, a
2661  * new one will be allocated and initialized
2662  * The origPeer, if set, is a pointer to a peer structure on which the
2663  * refcount will be be decremented. This is used to replace the peer
2664  * structure hanging off a connection structure */
2665 struct rx_peer *
2666 rxi_FindPeer(afs_uint32 host, u_short port,
2667              struct rx_peer *origPeer, int create)
2668 {
2669     struct rx_peer *pp;
2670     int hashIndex;
2671     hashIndex = PEER_HASH(host, port);
2672     MUTEX_ENTER(&rx_peerHashTable_lock);
2673     for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
2674         if ((pp->host == host) && (pp->port == port))
2675             break;
2676     }
2677     if (!pp) {
2678         if (create) {
2679             pp = rxi_AllocPeer();       /* This bzero's *pp */
2680             pp->host = host;    /* set here or in InitPeerParams is zero */
2681             pp->port = port;
2682             MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
2683             queue_Init(&pp->congestionQueue);
2684             queue_Init(&pp->rpcStats);
2685             pp->next = rx_peerHashTable[hashIndex];
2686             rx_peerHashTable[hashIndex] = pp;
2687             rxi_InitPeerParams(pp);
2688             if (rx_stats_active)
2689                 rx_atomic_inc(&rx_stats.nPeerStructs);
2690         }
2691     }
2692     if (pp && create) {
2693         pp->refCount++;
2694     }
2695     if (origPeer)
2696         origPeer->refCount--;
2697     MUTEX_EXIT(&rx_peerHashTable_lock);
2698     return pp;
2699 }
2700
2701
2702 /* Find the connection at (host, port) started at epoch, and with the
2703  * given connection id.  Creates the server connection if necessary.
2704  * The type specifies whether a client connection or a server
2705  * connection is desired.  In both cases, (host, port) specify the
2706  * peer's (host, pair) pair.  Client connections are not made
2707  * automatically by this routine.  The parameter socket gives the
2708  * socket descriptor on which the packet was received.  This is used,
2709  * in the case of server connections, to check that *new* connections
2710  * come via a valid (port, serviceId).  Finally, the securityIndex
2711  * parameter must match the existing index for the connection.  If a
2712  * server connection is created, it will be created using the supplied
2713  * index, if the index is valid for this service */
2714 struct rx_connection *
2715 rxi_FindConnection(osi_socket socket, afs_uint32 host,
2716                    u_short port, u_short serviceId, afs_uint32 cid,
2717                    afs_uint32 epoch, int type, u_int securityIndex)
2718 {
2719     int hashindex, flag, i;
2720     struct rx_connection *conn;
2721     hashindex = CONN_HASH(host, port, cid, epoch, type);
2722     MUTEX_ENTER(&rx_connHashTable_lock);
2723     rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
2724                                                   rx_connHashTable[hashindex],
2725                                                   flag = 1);
2726     for (; conn;) {
2727         if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
2728             && (epoch == conn->epoch)) {
2729             struct rx_peer *pp = conn->peer;
2730             if (securityIndex != conn->securityIndex) {
2731                 /* this isn't supposed to happen, but someone could forge a packet
2732                  * like this, and there seems to be some CM bug that makes this
2733                  * happen from time to time -- in which case, the fileserver
2734                  * asserts. */
2735                 MUTEX_EXIT(&rx_connHashTable_lock);
2736                 return (struct rx_connection *)0;
2737             }
2738             if (pp->host == host && pp->port == port)
2739                 break;
2740             if (type == RX_CLIENT_CONNECTION && pp->port == port)
2741                 break;
2742             /* So what happens when it's a callback connection? */
2743             if (                /*type == RX_CLIENT_CONNECTION && */
2744                    (conn->epoch & 0x80000000))
2745                 break;
2746         }
2747         if (!flag) {
2748             /* the connection rxLastConn that was used the last time is not the
2749              ** one we are looking for now. Hence, start searching in the hash */
2750             flag = 1;
2751             conn = rx_connHashTable[hashindex];
2752         } else
2753             conn = conn->next;
2754     }
2755     if (!conn) {
2756         struct rx_service *service;
2757         if (type == RX_CLIENT_CONNECTION) {
2758             MUTEX_EXIT(&rx_connHashTable_lock);
2759             return (struct rx_connection *)0;
2760         }
2761         service = rxi_FindService(socket, serviceId);
2762         if (!service || (securityIndex >= service->nSecurityObjects)
2763             || (service->securityObjects[securityIndex] == 0)) {
2764             MUTEX_EXIT(&rx_connHashTable_lock);
2765             return (struct rx_connection *)0;
2766         }
2767         conn = rxi_AllocConnection();   /* This bzero's the connection */
2768         MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
2769         MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
2770         CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
2771         conn->next = rx_connHashTable[hashindex];
2772         rx_connHashTable[hashindex] = conn;
2773         conn->peer = rxi_FindPeer(host, port, 0, 1);
2774         conn->type = RX_SERVER_CONNECTION;
2775         conn->lastSendTime = clock_Sec();       /* don't GC immediately */
2776         conn->epoch = epoch;
2777         conn->cid = cid & RX_CIDMASK;
2778         /* conn->serial = conn->lastSerial = 0; */
2779         /* conn->timeout = 0; */
2780         conn->ackRate = RX_FAST_ACK_RATE;
2781         conn->service = service;
2782         conn->serviceId = serviceId;
2783         conn->securityIndex = securityIndex;
2784         conn->securityObject = service->securityObjects[securityIndex];
2785         conn->nSpecific = 0;
2786         conn->specific = NULL;
2787         rx_SetConnDeadTime(conn, service->connDeadTime);
2788         rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
2789         rx_SetServerConnIdleDeadErr(conn, service->idleDeadErr);
2790         for (i = 0; i < RX_MAXCALLS; i++) {
2791             conn->twind[i] = rx_initSendWindow;
2792             conn->rwind[i] = rx_initReceiveWindow;
2793         }
2794         /* Notify security object of the new connection */
2795         RXS_NewConnection(conn->securityObject, conn);
2796         /* XXXX Connection timeout? */
2797         if (service->newConnProc)
2798             (*service->newConnProc) (conn);
2799         if (rx_stats_active)
2800             rx_atomic_inc(&rx_stats.nServerConns);
2801     }
2802
2803     MUTEX_ENTER(&rx_refcnt_mutex);
2804     conn->refCount++;
2805     MUTEX_EXIT(&rx_refcnt_mutex);
2806
2807     rxLastConn = conn;          /* store this connection as the last conn used */
2808     MUTEX_EXIT(&rx_connHashTable_lock);
2809     return conn;
2810 }
2811
2812 /**
2813  * Timeout a call on a busy call channel if appropriate.
2814  *
2815  * @param[in] call The busy call.
2816  *
2817  * @pre 'call' is marked as busy (namely,
2818  *      call->conn->lastBusy[call->channel] != 0)
2819  *
2820  * @pre call->lock is held
2821  *
2822  * @note call->lock is dropped and reacquired
2823  */
2824 static void
2825 rxi_CheckBusy(struct rx_call *call)
2826 {
2827     struct rx_connection *conn = call->conn;
2828     int channel = call->channel;
2829     int freechannel = 0;
2830     int i;
2831     afs_uint32 callNumber = *call->callNumber;
2832
2833     MUTEX_EXIT(&call->lock);
2834
2835     MUTEX_ENTER(&conn->conn_call_lock);
2836
2837     /* Are there any other call slots on this conn that we should try? Look for
2838      * slots that are empty and are either non-busy, or were marked as busy
2839      * longer than conn->secondsUntilDead seconds before this call started. */
2840
2841     for (i = 0; i < RX_MAXCALLS && !freechannel; i++) {
2842         if (i == channel) {
2843             /* only look at channels that aren't us */
2844             continue;
2845         }
2846
2847         if (conn->lastBusy[i]) {
2848             /* if this channel looked busy too recently, don't look at it */
2849             if (conn->lastBusy[i] >= call->startTime.sec) {
2850                 continue;
2851             }
2852             if (call->startTime.sec - conn->lastBusy[i] < conn->secondsUntilDead) {
2853                 continue;
2854             }
2855         }
2856
2857         if (conn->call[i]) {
2858             struct rx_call *tcall = conn->call[i];
2859             MUTEX_ENTER(&tcall->lock);
2860             if (tcall->state == RX_STATE_DALLY) {
2861                 freechannel = 1;
2862             }
2863             MUTEX_EXIT(&tcall->lock);
2864         } else {
2865             freechannel = 1;
2866         }
2867     }
2868
2869     MUTEX_EXIT(&conn->conn_call_lock);
2870
2871     MUTEX_ENTER(&call->lock);
2872
2873     /* Since the call->lock and conn->conn_call_lock have been released it is
2874      * possible that (1) the call may no longer be busy and/or (2) the call may
2875      * have been reused by another waiting thread. Therefore, we must confirm
2876      * that the call state has not changed when deciding whether or not to
2877      * force this application thread to retry by forcing a Timeout error. */
2878
2879     if (freechannel && *call->callNumber == callNumber &&
2880         (call->flags & RX_CALL_PEER_BUSY)) {
2881         /* Since 'freechannel' is set, there exists another channel in this
2882          * rx_conn that the application thread might be able to use. We know
2883          * that we have the correct call since callNumber is unchanged, and we
2884          * know that the call is still busy. So, set the call error state to
2885          * RX_CALL_TIMEOUT so the application can retry the request, presumably
2886          * on a less-busy call channel. */
2887
2888         rxi_CallError(call, RX_CALL_TIMEOUT);
2889     }
2890 }
2891
2892 /* There are two packet tracing routines available for testing and monitoring
2893  * Rx.  One is called just after every packet is received and the other is
2894  * called just before every packet is sent.  Received packets, have had their
2895  * headers decoded, and packets to be sent have not yet had their headers
2896  * encoded.  Both take two parameters: a pointer to the packet and a sockaddr
2897  * containing the network address.  Both can be modified.  The return value, if
2898  * non-zero, indicates that the packet should be dropped.  */
2899
2900 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
2901 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
2902
2903 /* A packet has been received off the interface.  Np is the packet, socket is
2904  * the socket number it was received from (useful in determining which service
2905  * this packet corresponds to), and (host, port) reflect the host,port of the
2906  * sender.  This call returns the packet to the caller if it is finished with
2907  * it, rather than de-allocating it, just as a small performance hack */
2908
2909 struct rx_packet *
2910 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
2911                   afs_uint32 host, u_short port, int *tnop,
2912                   struct rx_call **newcallp)
2913 {
2914     struct rx_call *call;
2915     struct rx_connection *conn;
2916     int channel;
2917     afs_uint32 currentCallNumber;
2918     int type;
2919     int skew;
2920 #ifdef RXDEBUG
2921     char *packetType;
2922 #endif
2923     struct rx_packet *tnp;
2924
2925 #ifdef RXDEBUG
2926 /* We don't print out the packet until now because (1) the time may not be
2927  * accurate enough until now in the lwp implementation (rx_Listener only gets
2928  * the time after the packet is read) and (2) from a protocol point of view,
2929  * this is the first time the packet has been seen */
2930     packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
2931         ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
2932     dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT"\n",
2933          np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
2934          np->header.epoch, np->header.cid, np->header.callNumber,
2935          np->header.seq, np->header.flags, np));
2936 #endif
2937
2938     if (np->header.type == RX_PACKET_TYPE_VERSION) {
2939         return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
2940     }
2941
2942     if (np->header.type == RX_PACKET_TYPE_DEBUG) {
2943         return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
2944     }
2945 #ifdef RXDEBUG
2946     /* If an input tracer function is defined, call it with the packet and
2947      * network address.  Note this function may modify its arguments. */
2948     if (rx_justReceived) {
2949         struct sockaddr_in addr;
2950         int drop;
2951         addr.sin_family = AF_INET;
2952         addr.sin_port = port;
2953         addr.sin_addr.s_addr = host;
2954 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
2955         addr.sin_len = sizeof(addr);
2956 #endif /* AFS_OSF_ENV */
2957         drop = (*rx_justReceived) (np, &addr);
2958         /* drop packet if return value is non-zero */
2959         if (drop)
2960             return np;
2961         port = addr.sin_port;   /* in case fcn changed addr */
2962         host = addr.sin_addr.s_addr;
2963     }
2964 #endif
2965
2966     /* If packet was not sent by the client, then *we* must be the client */
2967     type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
2968         ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
2969
2970     /* Find the connection (or fabricate one, if we're the server & if
2971      * necessary) associated with this packet */
2972     conn =
2973         rxi_FindConnection(socket, host, port, np->header.serviceId,
2974                            np->header.cid, np->header.epoch, type,
2975                            np->header.securityIndex);
2976
2977     if (!conn) {
2978         /* If no connection found or fabricated, just ignore the packet.
2979          * (An argument could be made for sending an abort packet for
2980          * the conn) */
2981         return np;
2982     }
2983
2984     MUTEX_ENTER(&conn->conn_data_lock);
2985     if (conn->maxSerial < np->header.serial)
2986         conn->maxSerial = np->header.serial;
2987     MUTEX_EXIT(&conn->conn_data_lock);
2988
2989     /* If the connection is in an error state, send an abort packet and ignore
2990      * the incoming packet */
2991     if (conn->error) {
2992         /* Don't respond to an abort packet--we don't want loops! */
2993         MUTEX_ENTER(&conn->conn_data_lock);
2994         if (np->header.type != RX_PACKET_TYPE_ABORT)
2995             np = rxi_SendConnectionAbort(conn, np, 1, 0);
2996         MUTEX_ENTER(&rx_refcnt_mutex);
2997         conn->refCount--;
2998         MUTEX_EXIT(&rx_refcnt_mutex);
2999         MUTEX_EXIT(&conn->conn_data_lock);
3000         return np;
3001     }
3002
3003     /* Check for connection-only requests (i.e. not call specific). */
3004     if (np->header.callNumber == 0) {
3005         switch (np->header.type) {
3006         case RX_PACKET_TYPE_ABORT: {
3007             /* What if the supplied error is zero? */
3008             afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
3009             dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
3010             rxi_ConnectionError(conn, errcode);
3011             MUTEX_ENTER(&rx_refcnt_mutex);
3012             conn->refCount--;
3013             MUTEX_EXIT(&rx_refcnt_mutex);
3014             return np;
3015         }
3016         case RX_PACKET_TYPE_CHALLENGE:
3017             tnp = rxi_ReceiveChallengePacket(conn, np, 1);
3018             MUTEX_ENTER(&rx_refcnt_mutex);
3019             conn->refCount--;
3020             MUTEX_EXIT(&rx_refcnt_mutex);
3021             return tnp;
3022         case RX_PACKET_TYPE_RESPONSE:
3023             tnp = rxi_ReceiveResponsePacket(conn, np, 1);
3024             MUTEX_ENTER(&rx_refcnt_mutex);
3025             conn->refCount--;
3026             MUTEX_EXIT(&rx_refcnt_mutex);
3027             return tnp;
3028         case RX_PACKET_TYPE_PARAMS:
3029         case RX_PACKET_TYPE_PARAMS + 1:
3030         case RX_PACKET_TYPE_PARAMS + 2:
3031             /* ignore these packet types for now */
3032             MUTEX_ENTER(&rx_refcnt_mutex);
3033             conn->refCount--;
3034             MUTEX_EXIT(&rx_refcnt_mutex);
3035             return np;
3036
3037
3038         default:
3039             /* Should not reach here, unless the peer is broken: send an
3040              * abort packet */
3041             rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
3042             MUTEX_ENTER(&conn->conn_data_lock);
3043             tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
3044             MUTEX_ENTER(&rx_refcnt_mutex);
3045             conn->refCount--;
3046             MUTEX_EXIT(&rx_refcnt_mutex);
3047             MUTEX_EXIT(&conn->conn_data_lock);
3048             return tnp;
3049         }
3050     }
3051
3052     channel = np->header.cid & RX_CHANNELMASK;
3053     call = conn->call[channel];
3054 #ifdef  RX_ENABLE_LOCKS
3055     if (call)
3056         MUTEX_ENTER(&call->lock);
3057     /* Test to see if call struct is still attached to conn. */
3058     if (call != conn->call[channel]) {
3059         if (call)
3060             MUTEX_EXIT(&call->lock);
3061         if (type == RX_SERVER_CONNECTION) {
3062             call = conn->call[channel];
3063             /* If we started with no call attached and there is one now,
3064              * another thread is also running this routine and has gotten
3065              * the connection channel. We should drop this packet in the tests
3066              * below. If there was a call on this connection and it's now
3067              * gone, then we'll be making a new call below.
3068              * If there was previously a call and it's now different then
3069              * the old call was freed and another thread running this routine
3070              * has created a call on this channel. One of these two threads
3071              * has a packet for the old call and the code below handles those
3072              * cases.
3073              */
3074             if (call)
3075                 MUTEX_ENTER(&call->lock);
3076         } else {
3077             /* This packet can't be for this call. If the new call address is
3078              * 0 then no call is running on this channel. If there is a call
3079              * then, since this is a client connection we're getting data for
3080              * it must be for the previous call.
3081              */
3082             if (rx_stats_active)
3083                 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3084             MUTEX_ENTER(&rx_refcnt_mutex);
3085             conn->refCount--;
3086             MUTEX_EXIT(&rx_refcnt_mutex);
3087             return np;
3088         }
3089     }
3090 #endif
3091     currentCallNumber = conn->callNumber[channel];
3092
3093     if (type == RX_SERVER_CONNECTION) { /* We're the server */
3094         if (np->header.callNumber < currentCallNumber) {
3095             if (rx_stats_active)
3096                 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3097 #ifdef  RX_ENABLE_LOCKS
3098             if (call)
3099                 MUTEX_EXIT(&call->lock);
3100 #endif
3101             MUTEX_ENTER(&rx_refcnt_mutex);
3102             conn->refCount--;
3103             MUTEX_EXIT(&rx_refcnt_mutex);
3104             return np;
3105         }
3106         if (!call) {
3107             MUTEX_ENTER(&conn->conn_call_lock);
3108             call = rxi_NewCall(conn, channel);
3109             MUTEX_EXIT(&conn->conn_call_lock);
3110             *call->callNumber = np->header.callNumber;
3111 #ifdef RXDEBUG
3112             if (np->header.callNumber == 0)
3113                 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",
3114                       np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3115                       np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3116                       np->header.flags, np, np->retryTime.sec, np->retryTime.usec / 1000, np->length));
3117 #endif
3118             call->state = RX_STATE_PRECALL;
3119             clock_GetTime(&call->queueTime);
3120             hzero(call->bytesSent);
3121             hzero(call->bytesRcvd);
3122             /*
3123              * If the number of queued calls exceeds the overload
3124              * threshold then abort this call.
3125              */
3126             if ((rx_BusyThreshold > 0) &&
3127                 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3128                 struct rx_packet *tp;
3129
3130                 rxi_CallError(call, rx_BusyError);
3131                 tp = rxi_SendCallAbort(call, np, 1, 0);
3132                 MUTEX_EXIT(&call->lock);
3133                 MUTEX_ENTER(&rx_refcnt_mutex);
3134                 conn->refCount--;
3135                 MUTEX_EXIT(&rx_refcnt_mutex);
3136                 if (rx_stats_active)
3137                     rx_atomic_inc(&rx_stats.nBusies);
3138                 return tp;
3139             }
3140             rxi_KeepAliveOn(call);
3141         } else if (np->header.callNumber != currentCallNumber) {
3142             /* Wait until the transmit queue is idle before deciding
3143              * whether to reset the current call. Chances are that the
3144              * call will be in ether DALLY or HOLD state once the TQ_BUSY
3145              * flag is cleared.
3146              */
3147 #ifdef AFS_GLOBAL_RXLOCK_KERNEL
3148             if (call->state == RX_STATE_ACTIVE) {
3149                 rxi_WaitforTQBusy(call);
3150                 /*
3151                  * If we entered error state while waiting,
3152                  * must call rxi_CallError to permit rxi_ResetCall
3153                  * to processed when the tqWaiter count hits zero.
3154                  */
3155                 if (call->error) {
3156                     rxi_CallError(call, call->error);
3157                     MUTEX_EXIT(&call->lock);
3158                     MUTEX_ENTER(&rx_refcnt_mutex);
3159                     conn->refCount--;
3160                     MUTEX_EXIT(&rx_refcnt_mutex);
3161                     return np;
3162                 }
3163             }
3164 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3165             /* If the new call cannot be taken right now send a busy and set
3166              * the error condition in this call, so that it terminates as
3167              * quickly as possible */
3168             if (call->state == RX_STATE_ACTIVE) {
3169                 struct rx_packet *tp;
3170
3171                 rxi_CallError(call, RX_CALL_DEAD);
3172                 tp = rxi_SendSpecial(call, conn, np, RX_PACKET_TYPE_BUSY,
3173                                      NULL, 0, 1);
3174                 MUTEX_EXIT(&call->lock);
3175                 MUTEX_ENTER(&rx_refcnt_mutex);
3176                 conn->refCount--;
3177                 MUTEX_EXIT(&rx_refcnt_mutex);
3178                 return tp;
3179             }
3180             rxi_ResetCall(call, 0);
3181             *call->callNumber = np->header.callNumber;
3182 #ifdef RXDEBUG
3183             if (np->header.callNumber == 0)
3184                 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",
3185                       np->header.serial, rx_packetTypes[np->header.type - 1], ntohl(conn->peer->host), ntohs(conn->peer->port),
3186                       np->header.serial, np->header.epoch, np->header.cid, np->header.callNumber, np->header.seq,
3187                       np->header.flags, np, np->retryTime.sec, np->retryTime.usec, np->length));
3188 #endif
3189             call->state = RX_STATE_PRECALL;
3190             clock_GetTime(&call->queueTime);
3191             hzero(call->bytesSent);
3192             hzero(call->bytesRcvd);
3193             /*
3194              * If the number of queued calls exceeds the overload
3195              * threshold then abort this call.
3196              */
3197             if ((rx_BusyThreshold > 0) &&
3198                 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3199                 struct rx_packet *tp;
3200
3201                 rxi_CallError(call, rx_BusyError);
3202                 tp = rxi_SendCallAbort(call, np, 1, 0);
3203                 MUTEX_EXIT(&call->lock);
3204                 MUTEX_ENTER(&rx_refcnt_mutex);
3205                 conn->refCount--;
3206                 MUTEX_EXIT(&rx_refcnt_mutex);
3207                 if (rx_stats_active)
3208                     rx_atomic_inc(&rx_stats.nBusies);
3209                 return tp;
3210             }
3211             rxi_KeepAliveOn(call);
3212         } else {
3213             /* Continuing call; do nothing here. */
3214         }
3215     } else {                    /* we're the client */
3216         /* Ignore all incoming acknowledgements for calls in DALLY state */
3217         if (call && (call->state == RX_STATE_DALLY)
3218             && (np->header.type == RX_PACKET_TYPE_ACK)) {
3219             if (rx_stats_active)
3220                 rx_atomic_inc(&rx_stats.ignorePacketDally);
3221 #ifdef  RX_ENABLE_LOCKS
3222             if (call) {
3223                 MUTEX_EXIT(&call->lock);
3224             }
3225 #endif
3226             MUTEX_ENTER(&rx_refcnt_mutex);
3227             conn->refCount--;
3228             MUTEX_EXIT(&rx_refcnt_mutex);
3229             return np;
3230         }
3231
3232         /* Ignore anything that's not relevant to the current call.  If there
3233          * isn't a current call, then no packet is relevant. */
3234         if (!call || (np->header.callNumber != currentCallNumber)) {
3235             if (rx_stats_active)
3236                 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3237 #ifdef  RX_ENABLE_LOCKS
3238             if (call) {
3239                 MUTEX_EXIT(&call->lock);
3240             }
3241 #endif
3242             MUTEX_ENTER(&rx_refcnt_mutex);
3243             conn->refCount--;
3244             MUTEX_EXIT(&rx_refcnt_mutex);
3245             return np;
3246         }
3247         /* If the service security object index stamped in the packet does not
3248          * match the connection's security index, ignore the packet */
3249         if (np->header.securityIndex != conn->securityIndex) {
3250 #ifdef  RX_ENABLE_LOCKS
3251             MUTEX_EXIT(&call->lock);
3252 #endif
3253             MUTEX_ENTER(&rx_refcnt_mutex);
3254             conn->refCount--;
3255             MUTEX_EXIT(&rx_refcnt_mutex);
3256             return np;
3257         }
3258
3259         /* If we're receiving the response, then all transmit packets are
3260          * implicitly acknowledged.  Get rid of them. */
3261         if (np->header.type == RX_PACKET_TYPE_DATA) {
3262 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
3263             /* XXX Hack. Because we must release the global rx lock when
3264              * sending packets (osi_NetSend) we drop all acks while we're
3265              * traversing the tq in rxi_Start sending packets out because
3266              * packets may move to the freePacketQueue as result of being here!
3267              * So we drop these packets until we're safely out of the
3268              * traversing. Really ugly!
3269              * For fine grain RX locking, we set the acked field in the
3270              * packets and let rxi_Start remove them from the transmit queue.
3271              */
3272             if (call->flags & RX_CALL_TQ_BUSY) {
3273 #ifdef  RX_ENABLE_LOCKS
3274                 rxi_SetAcksInTransmitQueue(call);
3275 #else
3276                 MUTEX_ENTER(&rx_refcnt_mutex);
3277                 conn->refCount--;
3278                 MUTEX_EXIT(&rx_refcnt_mutex);
3279                 return np;      /* xmitting; drop packet */
3280 #endif
3281             } else {
3282                 rxi_ClearTransmitQueue(call, 0);
3283             }
3284 #else /* AFS_GLOBAL_RXLOCK_KERNEL */
3285             rxi_ClearTransmitQueue(call, 0);
3286 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3287         } else {
3288             if (np->header.type == RX_PACKET_TYPE_ACK) {
3289                 /* now check to see if this is an ack packet acknowledging that the
3290                  * server actually *lost* some hard-acked data.  If this happens we
3291                  * ignore this packet, as it may indicate that the server restarted in
3292                  * the middle of a call.  It is also possible that this is an old ack
3293                  * packet.  We don't abort the connection in this case, because this
3294                  * *might* just be an old ack packet.  The right way to detect a server
3295                  * restart in the midst of a call is to notice that the server epoch
3296                  * changed, btw.  */
3297                 /* XXX I'm not sure this is exactly right, since tfirst **IS**
3298                  * XXX unacknowledged.  I think that this is off-by-one, but
3299                  * XXX I don't dare change it just yet, since it will
3300                  * XXX interact badly with the server-restart detection
3301                  * XXX code in receiveackpacket.  */
3302                 if (ntohl(rx_GetInt32(np, FIRSTACKOFFSET)) < call->tfirst) {
3303                     if (rx_stats_active)
3304                         rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3305                     MUTEX_EXIT(&call->lock);
3306                     MUTEX_ENTER(&rx_refcnt_mutex);
3307                     conn->refCount--;
3308                     MUTEX_EXIT(&rx_refcnt_mutex);
3309                     return np;
3310                 }
3311             }
3312         }                       /* else not a data packet */
3313     }
3314
3315     osirx_AssertMine(&call->lock, "rxi_ReceivePacket middle");
3316     /* Set remote user defined status from packet */
3317     call->remoteStatus = np->header.userStatus;
3318
3319     /* Note the gap between the expected next packet and the actual
3320      * packet that arrived, when the new packet has a smaller serial number
3321      * than expected.  Rioses frequently reorder packets all by themselves,
3322      * so this will be quite important with very large window sizes.
3323      * Skew is checked against 0 here to avoid any dependence on the type of
3324      * inPacketSkew (which may be unsigned).  In C, -1 > (unsigned) 0 is always
3325      * true!
3326      * The inPacketSkew should be a smoothed running value, not just a maximum.  MTUXXX
3327      * see CalculateRoundTripTime for an example of how to keep smoothed values.
3328      * I think using a beta of 1/8 is probably appropriate.  93.04.21
3329      */
3330     MUTEX_ENTER(&conn->conn_data_lock);
3331     skew = conn->lastSerial - np->header.serial;
3332     conn->lastSerial = np->header.serial;
3333     MUTEX_EXIT(&conn->conn_data_lock);
3334     if (skew > 0) {
3335         struct rx_peer *peer;
3336         peer = conn->peer;
3337         if (skew > peer->inPacketSkew) {
3338             dpf(("*** In skew changed from %d to %d\n",
3339                   peer->inPacketSkew, skew));
3340             peer->inPacketSkew = skew;
3341         }
3342     }
3343
3344     /* Now do packet type-specific processing */
3345     switch (np->header.type) {
3346     case RX_PACKET_TYPE_DATA:
3347         np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3348                                    newcallp);
3349         break;
3350     case RX_PACKET_TYPE_ACK:
3351         /* Respond immediately to ack packets requesting acknowledgement
3352          * (ping packets) */
3353         if (np->header.flags & RX_REQUEST_ACK) {
3354             if (call->error)
3355                 (void)rxi_SendCallAbort(call, 0, 1, 0);
3356             else
3357                 (void)rxi_SendAck(call, 0, np->header.serial,
3358                                   RX_ACK_PING_RESPONSE, 1);
3359         }
3360         np = rxi_ReceiveAckPacket(call, np, 1);
3361         break;
3362     case RX_PACKET_TYPE_ABORT: {
3363         /* An abort packet: reset the call, passing the error up to the user. */
3364         /* What if error is zero? */
3365         /* What if the error is -1? the application will treat it as a timeout. */
3366         afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3367         dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3368         rxi_CallError(call, errdata);
3369         MUTEX_EXIT(&call->lock);
3370         MUTEX_ENTER(&rx_refcnt_mutex);
3371         conn->refCount--;
3372         MUTEX_EXIT(&rx_refcnt_mutex);
3373         return np;              /* xmitting; drop packet */
3374     }
3375     case RX_PACKET_TYPE_BUSY: {
3376         struct clock busyTime;
3377         clock_NewTime();
3378         clock_GetTime(&busyTime);
3379
3380         MUTEX_EXIT(&call->lock);
3381
3382         MUTEX_ENTER(&conn->conn_call_lock);
3383         MUTEX_ENTER(&call->lock);
3384         conn->lastBusy[call->channel] = busyTime.sec;
3385         call->flags |= RX_CALL_PEER_BUSY;
3386         MUTEX_EXIT(&call->lock);
3387         MUTEX_EXIT(&conn->conn_call_lock);
3388
3389         MUTEX_ENTER(&rx_refcnt_mutex);
3390         conn->refCount--;
3391         MUTEX_EXIT(&rx_refcnt_mutex);
3392         return np;
3393     }
3394
3395     case RX_PACKET_TYPE_ACKALL:
3396         /* All packets acknowledged, so we can drop all packets previously
3397          * readied for sending */
3398 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
3399         /* XXX Hack. We because we can't release the global rx lock when
3400          * sending packets (osi_NetSend) we drop all ack pkts while we're
3401          * traversing the tq in rxi_Start sending packets out because
3402          * packets may move to the freePacketQueue as result of being
3403          * here! So we drop these packets until we're safely out of the
3404          * traversing. Really ugly!
3405          * For fine grain RX locking, we set the acked field in the packets
3406          * and let rxi_Start remove the packets from the transmit queue.
3407          */
3408         if (call->flags & RX_CALL_TQ_BUSY) {
3409 #ifdef  RX_ENABLE_LOCKS
3410             rxi_SetAcksInTransmitQueue(call);
3411             break;
3412 #else /* RX_ENABLE_LOCKS */
3413             MUTEX_EXIT(&call->lock);
3414             MUTEX_ENTER(&rx_refcnt_mutex);
3415             conn->refCount--;
3416             MUTEX_EXIT(&rx_refcnt_mutex);
3417             return np;          /* xmitting; drop packet */
3418 #endif /* RX_ENABLE_LOCKS */
3419         }
3420 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
3421         rxi_ClearTransmitQueue(call, 0);
3422         rxevent_Cancel(call->keepAliveEvent, call, RX_CALL_REFCOUNT_ALIVE);
3423         break;
3424     default:
3425         /* Should not reach here, unless the peer is broken: send an abort
3426          * packet */
3427         rxi_CallError(call, RX_PROTOCOL_ERROR);
3428         np = rxi_SendCallAbort(call, np, 1, 0);
3429         break;
3430     };
3431     /* Note when this last legitimate packet was received, for keep-alive
3432      * processing.  Note, we delay getting the time until now in the hope that
3433      * the packet will be delivered to the user before any get time is required
3434      * (if not, then the time won't actually be re-evaluated here). */
3435     call->lastReceiveTime = clock_Sec();
3436     /* we've received a legit packet, so the channel is not busy */
3437     call->flags &= ~RX_CALL_PEER_BUSY;
3438     MUTEX_EXIT(&call->lock);
3439     MUTEX_ENTER(&rx_refcnt_mutex);
3440     conn->refCount--;
3441     MUTEX_EXIT(&rx_refcnt_mutex);
3442     return np;
3443 }
3444
3445 /* return true if this is an "interesting" connection from the point of view
3446     of someone trying to debug the system */
3447 int
3448 rxi_IsConnInteresting(struct rx_connection *aconn)
3449 {
3450     int i;
3451     struct rx_call *tcall;
3452
3453     if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3454         return 1;
3455
3456     for (i = 0; i < RX_MAXCALLS; i++) {
3457         tcall = aconn->call[i];
3458         if (tcall) {
3459             if ((tcall->state == RX_STATE_PRECALL)
3460                 || (tcall->state == RX_STATE_ACTIVE))
3461                 return 1;
3462             if ((tcall->mode == RX_MODE_SENDING)
3463                 || (tcall->mode == RX_MODE_RECEIVING))
3464                 return 1;
3465         }
3466     }
3467     return 0;
3468 }
3469
3470 #ifdef KERNEL
3471 /* if this is one of the last few packets AND it wouldn't be used by the
3472    receiving call to immediately satisfy a read request, then drop it on
3473    the floor, since accepting it might prevent a lock-holding thread from
3474    making progress in its reading. If a call has been cleared while in
3475    the precall state then ignore all subsequent packets until the call
3476    is assigned to a thread. */
3477
3478 static int
3479 TooLow(struct rx_packet *ap, struct rx_call *acall)
3480 {
3481     int rc = 0;
3482
3483     MUTEX_ENTER(&rx_quota_mutex);
3484     if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3485          && (acall->state == RX_STATE_PRECALL))
3486         || ((rx_nFreePackets < rxi_dataQuota + 2)
3487             && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3488                  && (acall->flags & RX_CALL_READER_WAIT)))) {
3489         rc = 1;
3490     }
3491     MUTEX_EXIT(&rx_quota_mutex);
3492     return rc;
3493 }
3494 #endif /* KERNEL */
3495
3496 static void
3497 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2)
3498 {
3499     struct rx_connection *conn = arg1;
3500     struct rx_call *acall = arg2;
3501     struct rx_call *call = acall;
3502     struct clock when, now;
3503     int i, waiting;
3504
3505     MUTEX_ENTER(&conn->conn_data_lock);
3506     conn->checkReachEvent = NULL;
3507     waiting = conn->flags & RX_CONN_ATTACHWAIT;
3508     if (event) {
3509         MUTEX_ENTER(&rx_refcnt_mutex);
3510         conn->refCount--;
3511         MUTEX_EXIT(&rx_refcnt_mutex);
3512     }
3513     MUTEX_EXIT(&conn->conn_data_lock);
3514
3515     if (waiting) {
3516         if (!call) {
3517             MUTEX_ENTER(&conn->conn_call_lock);
3518             MUTEX_ENTER(&conn->conn_data_lock);
3519             for (i = 0; i < RX_MAXCALLS; i++) {
3520                 struct rx_call *tc = conn->call[i];
3521                 if (tc && tc->state == RX_STATE_PRECALL) {
3522                     call = tc;
3523                     break;
3524                 }
3525             }
3526             if (!call)
3527                 /* Indicate that rxi_CheckReachEvent is no longer running by
3528                  * clearing the flag.  Must be atomic under conn_data_lock to
3529                  * avoid a new call slipping by: rxi_CheckConnReach holds
3530                  * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3531                  */
3532                 conn->flags &= ~RX_CONN_ATTACHWAIT;
3533             MUTEX_EXIT(&conn->conn_data_lock);
3534             MUTEX_EXIT(&conn->conn_call_lock);
3535         }
3536
3537         if (call) {
3538             if (call != acall)
3539                 MUTEX_ENTER(&call->lock);
3540             rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3541             if (call != acall)
3542                 MUTEX_EXIT(&call->lock);
3543
3544             clock_GetTime(&now);
3545             when = now;
3546             when.sec += RX_CHECKREACH_TIMEOUT;
3547             MUTEX_ENTER(&conn->conn_data_lock);
3548             if (!conn->checkReachEvent) {
3549                 MUTEX_ENTER(&rx_refcnt_mutex);
3550                 conn->refCount++;
3551                 MUTEX_EXIT(&rx_refcnt_mutex);
3552                 conn->checkReachEvent =
3553                     rxevent_PostNow(&when, &now, rxi_CheckReachEvent, conn,
3554                                     NULL);
3555             }
3556             MUTEX_EXIT(&conn->conn_data_lock);
3557         }
3558     }
3559 }
3560
3561 static int
3562 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3563 {
3564     struct rx_service *service = conn->service;
3565     struct rx_peer *peer = conn->peer;
3566     afs_uint32 now, lastReach;
3567
3568     if (service->checkReach == 0)
3569         return 0;
3570
3571     now = clock_Sec();
3572     MUTEX_ENTER(&peer->peer_lock);
3573     lastReach = peer->lastReachTime;
3574     MUTEX_EXIT(&peer->peer_lock);
3575     if (now - lastReach < RX_CHECKREACH_TTL)
3576         return 0;
3577
3578     MUTEX_ENTER(&conn->conn_data_lock);
3579     if (conn->flags & RX_CONN_ATTACHWAIT) {
3580         MUTEX_EXIT(&conn->conn_data_lock);
3581         return 1;
3582     }
3583     conn->flags |= RX_CONN_ATTACHWAIT;
3584     MUTEX_EXIT(&conn->conn_data_lock);
3585     if (!conn->checkReachEvent)
3586         rxi_CheckReachEvent(NULL, conn, call);
3587
3588     return 1;
3589 }
3590
3591 /* try to attach call, if authentication is complete */
3592 static void
3593 TryAttach(struct rx_call *acall, osi_socket socket,
3594           int *tnop, struct rx_call **newcallp,
3595           int reachOverride)
3596 {
3597     struct rx_connection *conn = acall->conn;
3598
3599     if (conn->type == RX_SERVER_CONNECTION
3600         && acall->state == RX_STATE_PRECALL) {
3601         /* Don't attach until we have any req'd. authentication. */
3602         if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3603             if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3604                 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3605             /* Note:  this does not necessarily succeed; there
3606              * may not any proc available
3607              */
3608         } else {
3609             rxi_ChallengeOn(acall->conn);
3610         }
3611     }
3612 }
3613
3614 /* A data packet has been received off the interface.  This packet is
3615  * appropriate to the call (the call is in the right state, etc.).  This
3616  * routine can return a packet to the caller, for re-use */
3617
3618 struct rx_packet *
3619 rxi_ReceiveDataPacket(struct rx_call *call,
3620                       struct rx_packet *np, int istack,
3621                       osi_socket socket, afs_uint32 host, u_short port,
3622                       int *tnop, struct rx_call **newcallp)
3623 {
3624     int ackNeeded = 0;          /* 0 means no, otherwise ack_reason */
3625     int newPackets = 0;
3626     int didHardAck = 0;
3627     int haveLast = 0;
3628     afs_uint32 seq;
3629     afs_uint32 serial=0, flags=0;
3630     int isFirst;
3631     struct rx_packet *tnp;
3632     struct clock when, now;
3633     if (rx_stats_active)
3634         rx_atomic_inc(&rx_stats.dataPacketsRead);
3635
3636 #ifdef KERNEL
3637     /* If there are no packet buffers, drop this new packet, unless we can find
3638      * packet buffers from inactive calls */
3639     if (!call->error
3640         && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3641         MUTEX_ENTER(&rx_freePktQ_lock);
3642         rxi_NeedMorePackets = TRUE;
3643         MUTEX_EXIT(&rx_freePktQ_lock);
3644         if (rx_stats_active)
3645             rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3646         call->rprev = np->header.serial;
3647         rxi_calltrace(RX_TRACE_DROP, call);
3648         dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems\n", np));
3649         if (rxi_doreclaim)
3650             rxi_ClearReceiveQueue(call);
3651         clock_GetTime(&now);
3652         when = now;
3653         clock_Add(&when, &rx_softAckDelay);
3654         if (!call->delayedAckEvent
3655             || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3656             rxevent_Cancel(call->delayedAckEvent, call,
3657                            RX_CALL_REFCOUNT_DELAY);
3658             MUTEX_ENTER(&rx_refcnt_mutex);
3659             CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3660             MUTEX_EXIT(&rx_refcnt_mutex);
3661
3662             call->delayedAckEvent =
3663                 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3664         }
3665         /* we've damaged this call already, might as well do it in. */
3666         return np;
3667     }
3668 #endif /* KERNEL */
3669
3670     /*
3671      * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3672      * packet is one of several packets transmitted as a single
3673      * datagram. Do not send any soft or hard acks until all packets
3674      * in a jumbogram have been processed. Send negative acks right away.
3675      */
3676     for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3677         /* tnp is non-null when there are more packets in the
3678          * current jumbo gram */
3679         if (tnp) {
3680             if (np)
3681                 rxi_FreePacket(np);
3682             np = tnp;
3683         }
3684
3685         seq = np->header.seq;
3686         serial = np->header.serial;
3687         flags = np->header.flags;
3688
3689         /* If the call is in an error state, send an abort message */
3690         if (call->error)
3691             return rxi_SendCallAbort(call, np, istack, 0);
3692
3693         /* The RX_JUMBO_PACKET is set in all but the last packet in each
3694          * AFS 3.5 jumbogram. */
3695         if (flags & RX_JUMBO_PACKET) {
3696             tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3697         } else {
3698             tnp = NULL;
3699         }
3700
3701         if (np->header.spare != 0) {
3702             MUTEX_ENTER(&call->conn->conn_data_lock);
3703             call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3704             MUTEX_EXIT(&call->conn->conn_data_lock);
3705         }
3706
3707         /* The usual case is that this is the expected next packet */
3708         if (seq == call->rnext) {
3709
3710             /* Check to make sure it is not a duplicate of one already queued */
3711             if (queue_IsNotEmpty(&call->rq)
3712                 && queue_First(&call->rq, rx_packet)->header.seq == seq) {
3713                 if (rx_stats_active)
3714                     rx_atomic_inc(&rx_stats.dupPacketsRead);
3715                 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate\n", np));
3716                 rxevent_Cancel(call->delayedAckEvent, call,
3717                                RX_CALL_REFCOUNT_DELAY);
3718                 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3719                 ackNeeded = 0;
3720                 call->rprev = seq;
3721                 continue;
3722             }
3723
3724             /* It's the next packet. Stick it on the receive queue
3725              * for this call. Set newPackets to make sure we wake
3726              * the reader once all packets have been processed */
3727 #ifdef RX_TRACK_PACKETS
3728             np->flags |= RX_PKTFLAG_RQ;
3729 #endif
3730             queue_Prepend(&call->rq, np);
3731 #ifdef RXDEBUG_PACKET
3732             call->rqc++;
3733 #endif /* RXDEBUG_PACKET */
3734             call->nSoftAcks++;
3735             np = NULL;          /* We can't use this anymore */
3736             newPackets = 1;
3737
3738             /* If an ack is requested then set a flag to make sure we
3739              * send an acknowledgement for this packet */
3740             if (flags & RX_REQUEST_ACK) {
3741                 ackNeeded = RX_ACK_REQUESTED;
3742             }
3743
3744             /* Keep track of whether we have received the last packet */
3745             if (flags & RX_LAST_PACKET) {
3746                 call->flags |= RX_CALL_HAVE_LAST;
3747                 haveLast = 1;
3748             }
3749
3750             /* Check whether we have all of the packets for this call */
3751             if (call->flags & RX_CALL_HAVE_LAST) {
3752                 afs_uint32 tseq;        /* temporary sequence number */
3753                 struct rx_packet *tp;   /* Temporary packet pointer */
3754                 struct rx_packet *nxp;  /* Next pointer, for queue_Scan */
3755
3756                 for (tseq = seq, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3757                     if (tseq != tp->header.seq)
3758                         break;
3759                     if (tp->header.flags & RX_LAST_PACKET) {
3760                         call->flags |= RX_CALL_RECEIVE_DONE;
3761                         break;
3762                     }
3763                     tseq++;
3764                 }
3765             }
3766
3767             /* Provide asynchronous notification for those who want it
3768              * (e.g. multi rx) */
3769             if (call->arrivalProc) {
3770                 (*call->arrivalProc) (call, call->arrivalProcHandle,
3771                                       call->arrivalProcArg);
3772                 call->arrivalProc = (void (*)())0;
3773             }
3774
3775             /* Update last packet received */
3776             call->rprev = seq;
3777
3778             /* If there is no server process serving this call, grab
3779              * one, if available. We only need to do this once. If a
3780              * server thread is available, this thread becomes a server
3781              * thread and the server thread becomes a listener thread. */
3782             if (isFirst) {
3783                 TryAttach(call, socket, tnop, newcallp, 0);
3784             }
3785         }
3786         /* This is not the expected next packet. */
3787         else {
3788             /* Determine whether this is a new or old packet, and if it's
3789              * a new one, whether it fits into the current receive window.
3790              * Also figure out whether the packet was delivered in sequence.
3791              * We use the prev variable to determine whether the new packet
3792              * is the successor of its immediate predecessor in the
3793              * receive queue, and the missing flag to determine whether
3794              * any of this packets predecessors are missing.  */
3795
3796             afs_uint32 prev;    /* "Previous packet" sequence number */
3797             struct rx_packet *tp;       /* Temporary packet pointer */
3798             struct rx_packet *nxp;      /* Next pointer, for queue_Scan */
3799             int missing;        /* Are any predecessors missing? */
3800
3801             /* If the new packet's sequence number has been sent to the
3802              * application already, then this is a duplicate */
3803             if (seq < call->rnext) {
3804                 if (rx_stats_active)
3805                     rx_atomic_inc(&rx_stats.dupPacketsRead);
3806                 rxevent_Cancel(call->delayedAckEvent, call,
3807                                RX_CALL_REFCOUNT_DELAY);
3808                 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3809                 ackNeeded = 0;
3810                 call->rprev = seq;
3811                 continue;
3812             }
3813
3814             /* If the sequence number is greater than what can be
3815              * accomodated by the current window, then send a negative
3816              * acknowledge and drop the packet */
3817             if ((call->rnext + call->rwind) <= seq) {
3818                 rxevent_Cancel(call->delayedAckEvent, call,
3819                                RX_CALL_REFCOUNT_DELAY);
3820                 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3821                                  istack);
3822                 ackNeeded = 0;
3823                 call->rprev = seq;
3824                 continue;
3825             }
3826
3827             /* Look for the packet in the queue of old received packets */
3828             for (prev = call->rnext - 1, missing =
3829                  0, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3830                 /*Check for duplicate packet */
3831                 if (seq == tp->header.seq) {
3832                     if (rx_stats_active)
3833                         rx_atomic_inc(&rx_stats.dupPacketsRead);
3834                     rxevent_Cancel(call->delayedAckEvent, call,
3835                                    RX_CALL_REFCOUNT_DELAY);
3836                     np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3837                                      istack);
3838                     ackNeeded = 0;
3839                     call->rprev = seq;
3840                     goto nextloop;
3841                 }
3842                 /* If we find a higher sequence packet, break out and
3843                  * insert the new packet here. */
3844                 if (seq < tp->header.seq)
3845                     break;
3846                 /* Check for missing packet */
3847                 if (tp->header.seq != prev + 1) {
3848                     missing = 1;
3849                 }
3850
3851                 prev = tp->header.seq;
3852             }
3853
3854             /* Keep track of whether we have received the last packet. */
3855             if (flags & RX_LAST_PACKET) {
3856                 call->flags |= RX_CALL_HAVE_LAST;
3857             }
3858
3859             /* It's within the window: add it to the the receive queue.
3860              * tp is left by the previous loop either pointing at the
3861              * packet before which to insert the new packet, or at the
3862              * queue head if the queue is empty or the packet should be
3863              * appended. */
3864 #ifdef RX_TRACK_PACKETS
3865             np->flags |= RX_PKTFLAG_RQ;
3866 #endif
3867 #ifdef RXDEBUG_PACKET
3868             call->rqc++;
3869 #endif /* RXDEBUG_PACKET */
3870             queue_InsertBefore(tp, np);
3871             call->nSoftAcks++;
3872             np = NULL;
3873
3874             /* Check whether we have all of the packets for this call */
3875             if ((call->flags & RX_CALL_HAVE_LAST)
3876                 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
3877                 afs_uint32 tseq;        /* temporary sequence number */
3878
3879                 for (tseq =
3880                      call->rnext, queue_Scan(&call->rq, tp, nxp, rx_packet)) {
3881                     if (tseq != tp->header.seq)
3882                         break;
3883                     if (tp->header.flags & RX_LAST_PACKET) {
3884                         call->flags |= RX_CALL_RECEIVE_DONE;
3885                         break;
3886                     }
3887                     tseq++;
3888                 }
3889             }
3890
3891             /* We need to send an ack of the packet is out of sequence,
3892              * or if an ack was requested by the peer. */
3893             if (seq != prev + 1 || missing) {
3894                 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
3895             } else if (flags & RX_REQUEST_ACK) {
3896                 ackNeeded = RX_ACK_REQUESTED;
3897             }
3898
3899             /* Acknowledge the last packet for each call */
3900             if (flags & RX_LAST_PACKET) {
3901                 haveLast = 1;
3902             }
3903
3904             call->rprev = seq;
3905         }
3906       nextloop:;
3907     }
3908
3909     if (newPackets) {
3910         /*
3911          * If the receiver is waiting for an iovec, fill the iovec
3912          * using the data from the receive queue */
3913         if (call->flags & RX_CALL_IOVEC_WAIT) {
3914             didHardAck = rxi_FillReadVec(call, serial);
3915             /* the call may have been aborted */
3916             if (call->error) {
3917                 return NULL;
3918             }
3919             if (didHardAck) {
3920                 ackNeeded = 0;
3921             }
3922         }
3923
3924         /* Wakeup the reader if any */
3925         if ((call->flags & RX_CALL_READER_WAIT)
3926             && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
3927                 || (call->iovNext >= call->iovMax)
3928                 || (call->flags & RX_CALL_RECEIVE_DONE))) {
3929             call->flags &= ~RX_CALL_READER_WAIT;
3930 #ifdef  RX_ENABLE_LOCKS
3931             CV_BROADCAST(&call->cv_rq);
3932 #else
3933             osi_rxWakeup(&call->rq);
3934 #endif
3935         }
3936     }
3937
3938     /*
3939      * Send an ack when requested by the peer, or once every
3940      * rxi_SoftAckRate packets until the last packet has been
3941      * received. Always send a soft ack for the last packet in
3942      * the server's reply.
3943      *
3944      * If we have received all of the packets for the call
3945      * immediately send an RX_PACKET_TYPE_ACKALL packet so that
3946      * the peer can empty its packet queue and cancel all resend
3947      * events.
3948      */
3949     if (call->flags & RX_CALL_RECEIVE_DONE) {
3950         rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3951         rxi_AckAll(NULL, call, 0);
3952     } else if (ackNeeded) {
3953         rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3954         np = rxi_SendAck(call, np, serial, ackNeeded, istack);
3955     } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
3956         rxevent_Cancel(call->delayedAckEvent, call, RX_CALL_REFCOUNT_DELAY);
3957         np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
3958     } else if (call->nSoftAcks) {
3959         clock_GetTime(&now);
3960         when = now;
3961         if (haveLast && !(flags & RX_CLIENT_INITIATED)) {
3962             clock_Add(&when, &rx_lastAckDelay);
3963         } else {
3964             clock_Add(&when, &rx_softAckDelay);
3965         }
3966         if (!call->delayedAckEvent
3967             || clock_Gt(&call->delayedAckEvent->eventTime, &when)) {
3968             rxevent_Cancel(call->delayedAckEvent, call,
3969                            RX_CALL_REFCOUNT_DELAY);
3970             MUTEX_ENTER(&rx_refcnt_mutex);
3971             CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
3972             MUTEX_EXIT(&rx_refcnt_mutex);
3973             call->delayedAckEvent =
3974                 rxevent_PostNow(&when, &now, rxi_SendDelayedAck, call, 0);
3975         }
3976     }
3977
3978     return np;
3979 }
3980
3981 #ifdef  ADAPT_WINDOW
3982 static void rxi_ComputeRate();
3983 #endif
3984
3985 static void
3986 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
3987 {
3988     struct rx_peer *peer = conn->peer;
3989
3990     MUTEX_ENTER(&peer->peer_lock);
3991     peer->lastReachTime = clock_Sec();
3992     MUTEX_EXIT(&peer->peer_lock);
3993
3994     MUTEX_ENTER(&conn->conn_data_lock);
3995     if (conn->flags & RX_CONN_ATTACHWAIT) {
3996         int i;
3997
3998         conn->flags &= ~RX_CONN_ATTACHWAIT;
3999         MUTEX_EXIT(&conn->conn_data_lock);
4000
4001         for (i = 0; i < RX_MAXCALLS; i++) {
4002             struct rx_call *call = conn->call[i];
4003             if (call) {
4004                 if (call != acall)
4005                     MUTEX_ENTER(&call->lock);
4006                 /* tnop can be null if newcallp is null */
4007                 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
4008                 if (call != acall)
4009                     MUTEX_EXIT(&call->lock);
4010             }
4011         }
4012     } else
4013         MUTEX_EXIT(&conn->conn_data_lock);
4014 }
4015
4016 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
4017 static const char *
4018 rx_ack_reason(int reason)
4019 {
4020     switch (reason) {
4021     case RX_ACK_REQUESTED:
4022         return "requested";
4023     case RX_ACK_DUPLICATE:
4024         return "duplicate";
4025     case RX_ACK_OUT_OF_SEQUENCE:
4026         return "sequence";
4027     case RX_ACK_EXCEEDS_WINDOW:
4028         return "window";
4029     case RX_ACK_NOSPACE:
4030         return "nospace";
4031     case RX_ACK_PING:
4032         return "ping";
4033     case RX_ACK_PING_RESPONSE:
4034         return "response";
4035     case RX_ACK_DELAY:
4036         return "delay";
4037     case RX_ACK_IDLE:
4038         return "idle";
4039     default:
4040         return "unknown!!";
4041     }
4042 }
4043 #endif
4044
4045
4046 /* The real smarts of the whole thing.  */
4047 struct rx_packet *
4048 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
4049                      int istack)
4050 {
4051     struct rx_ackPacket *ap;
4052     int nAcks;
4053     struct rx_packet *tp;
4054     struct rx_packet *nxp;      /* Next packet pointer for queue_Scan */
4055     struct rx_connection *conn = call->conn;
4056     struct rx_peer *peer = conn->peer;
4057     struct clock now;           /* Current time, for RTT calculations */
4058     afs_uint32 first;
4059     afs_uint32 prev;
4060     afs_uint32 serial;
4061     /* because there are CM's that are bogus, sending weird values for this. */
4062     afs_uint32 skew = 0;
4063     int nbytes;
4064     int missing;
4065     int acked;
4066     int nNacked = 0;
4067     int newAckCount = 0;
4068     int maxDgramPackets = 0;    /* Set if peer supports AFS 3.5 jumbo datagrams */
4069     int pktsize = 0;            /* Set if we need to update the peer mtu */
4070     int conn_data_locked = 0;
4071
4072     if (rx_stats_active)
4073         rx_atomic_inc(&rx_stats.ackPacketsRead);
4074     ap = (struct rx_ackPacket *)rx_DataOf(np);
4075     nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
4076     if (nbytes < 0)
4077         return np;              /* truncated ack packet */
4078
4079     /* depends on ack packet struct */
4080     nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
4081     first = ntohl(ap->firstPacket);
4082     prev = ntohl(ap->previousPacket);
4083     serial = ntohl(ap->serial);
4084     /* temporarily disabled -- needs to degrade over time
4085      * skew = ntohs(ap->maxSkew); */
4086
4087     /* Ignore ack packets received out of order */
4088     if (first < call->tfirst ||
4089         (first == call->tfirst && prev < call->tprev)) {
4090         return np;
4091     }
4092
4093     call->tprev = prev;
4094
4095     if (np->header.flags & RX_SLOW_START_OK) {
4096         call->flags |= RX_CALL_SLOW_START_OK;
4097     }
4098
4099     if (ap->reason == RX_ACK_PING_RESPONSE)
4100         rxi_UpdatePeerReach(conn, call);
4101
4102     if (conn->lastPacketSizeSeq) {
4103         MUTEX_ENTER(&conn->conn_data_lock);
4104         conn_data_locked = 1;
4105         if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
4106             pktsize = conn->lastPacketSize;
4107             conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
4108         }
4109     }
4110     if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
4111         if (!conn_data_locked) {
4112             MUTEX_ENTER(&conn->conn_data_lock);
4113             conn_data_locked = 1;
4114         }
4115         if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
4116             /* process mtu ping ack */
4117             pktsize = conn->lastPingSize;
4118             conn->lastPingSizeSer = conn->lastPingSize = 0;
4119         }
4120     }
4121
4122     if (conn_data_locked) {
4123         MUTEX_EXIT(&conn->conn_data_lock);
4124         conn_data_locked = 0;
4125     }
4126 #ifdef RXDEBUG
4127 #ifdef AFS_NT40_ENV
4128     if (rxdebug_active) {
4129         char msg[512];
4130         size_t len;
4131
4132         len = _snprintf(msg, sizeof(msg),
4133                         "tid[%d] RACK: reason %s serial %u previous %u seq %u skew %d first %u acks %u space %u ",
4134                          GetCurrentThreadId(), rx_ack_reason(ap->reason),
4135                          ntohl(ap->serial), ntohl(ap->previousPacket),
4136                          (unsigned int)np->header.seq, (unsigned int)skew,
4137                          ntohl(ap->firstPacket), ap->nAcks, ntohs(ap->bufferSpace) );
4138         if (nAcks) {
4139             int offset;
4140
4141             for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
4142                 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4143         }
4144         msg[len++]='\n';
4145         msg[len] = '\0';
4146         OutputDebugString(msg);
4147     }
4148 #else /* AFS_NT40_ENV */
4149     if (rx_Log) {
4150         fprintf(rx_Log,
4151                 "RACK: reason %x previous %u seq %u serial %u skew %d first %u",
4152                 ap->reason, ntohl(ap->previousPacket),
4153                 (unsigned int)np->header.seq, (unsigned int)serial,
4154                 (unsigned int)skew, ntohl(ap->firstPacket));
4155         if (nAcks) {
4156             int offset;
4157             for (offset = 0; offset < nAcks; offset++)
4158                 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4159                      rx_Log);
4160         }
4161         putc('\n', rx_Log);
4162     }
4163 #endif /* AFS_NT40_ENV */
4164 #endif
4165
4166     MUTEX_ENTER(&peer->peer_lock);
4167     if (pktsize) {
4168         /*
4169          * Start somewhere. Can't assume we can send what we can receive,
4170          * but we are clearly receiving.
4171          */
4172         if (!peer->maxPacketSize)
4173             peer->maxPacketSize = RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE;
4174
4175         if (pktsize > peer->maxPacketSize) {
4176             peer->maxPacketSize = pktsize;
4177             if ((pktsize-RX_IPUDP_SIZE > peer->ifMTU)) {
4178                 peer->ifMTU=pktsize-RX_IPUDP_SIZE;
4179                 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4180                 rxi_ScheduleGrowMTUEvent(call, 1);
4181             }
4182         }
4183     }
4184
4185     /* Update the outgoing packet skew value to the latest value of
4186      * the peer's incoming packet skew value.  The ack packet, of
4187      * course, could arrive out of order, but that won't affect things
4188      * much */
4189     peer->outPacketSkew = skew;
4190
4191     /* Check for packets that no longer need to be transmitted, and
4192      * discard them.  This only applies to packets positively
4193      * acknowledged as having been sent to the peer's upper level.
4194      * All other packets must be retained.  So only packets with
4195      * sequence numbers < ap->firstPacket are candidates. */
4196
4197     clock_GetTime(&now);
4198
4199     for (queue_Scan(&call->tq, tp, nxp, rx_packet)) {
4200         if (tp->header.seq >= first)
4201             break;
4202         call->tfirst = tp->header.seq + 1;
4203
4204         if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4205             newAckCount++;
4206
4207             rxi_ComputeRoundTripTime(tp, ap, call->conn->peer, &now);
4208         }
4209
4210 #ifdef ADAPT_WINDOW
4211         rxi_ComputeRate(call->conn->peer, call, p, np, ap->reason);
4212 #endif
4213
4214 #ifdef  AFS_GLOBAL_RXLOCK_KERNEL
4215         /* XXX Hack. Because we have to release the global rx lock when sending
4216          * packets (osi_NetSend) we drop all acks while we're traversing the tq
4217          * in rxi_Start sending packets out because packets may move to the
4218          * freePacketQueue as result of being here! So we drop these packets until
4219          * we're safely out of the traversing. Really ugly!
4220          * To make it even uglier, if we're using fine grain locking, we can
4221          * set the ack bits in the packets and have rxi_Start remove the packets
4222          * when it's done transmitting.
4223          */
4224         if (call->flags & RX_CALL_TQ_BUSY) {
4225 #ifdef RX_ENABLE_LOCKS
4226             tp->flags |= RX_PKTFLAG_ACKED;
4227             call->flags |= RX_CALL_TQ_SOME_ACKED;
4228 #else /* RX_ENABLE_LOCKS */
4229             break;
4230 #endif /* RX_ENABLE_LOCKS */
4231         } else
4232 #endif /* AFS_GLOBAL_RXLOCK_KERNEL */
4233         {
4234             queue_Remove(tp);
4235 #ifdef RX_TRACK_PACKETS
4236             tp->flags &= ~RX_PKTFLAG_TQ;
4237 #endif
4238 #ifdef RXDEBUG_PACKET
4239             call->tqc--;
4240 #endif /* RXDEBUG_PACKET */
4241             rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4242         }
4243     }
4244
4245 #ifdef ADAPT_WINDOW
4246     /* Give rate detector a chance to respond to ping requests */
4247     if (ap->reason == RX_ACK_PING_RESPONSE) {
4248         rxi_ComputeRate(peer, call, 0, np, ap->reason);
4249     }
4250 #endif
4251
4252     /* N.B. we don't turn off any timers here.  They'll go away by themselves, anyway */
4253
4254     /* Now go through explicit acks/nacks and record the results in
4255      * the waiting packets.  These are packets that can't be released
4256      * yet, even with a positive acknowledge.  This positive
4257      * acknowledge only means the packet has been received by the
4258      * peer, not that it will be retained long enough to be sent to
4259      * the peer's upper level.  In addition, reset the transmit timers
4260      * of any missing packets (those packets that must be missing
4261      * because this packet was out of sequence) */
4262
4263     call->nSoftAcked = 0;
4264     for (missing = 0, queue_Scan(&call->tq, tp, nxp, rx_packet)) {
4265
4266         /* Set the acknowledge flag per packet based on the
4267          * information in the ack packet. An acknowlegded packet can
4268          * be downgraded when the server has discarded a packet it
4269          * soacked previously, or when an ack packet is received
4270          * out of sequence. */
4271         if (tp->header.seq < first) {
4272             /* Implicit ack information */
4273             if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4274                 newAckCount++;
4275             }
4276             tp->flags |= RX_PKTFLAG_ACKED;
4277         } else if (tp->header.seq < first + nAcks) {
4278             /* Explicit ack information:  set it in the packet appropriately */
4279             if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4280                 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4281                     newAckCount++;
4282                     tp->flags |= RX_PKTFLAG_ACKED;
4283
4284                     rxi_ComputeRoundTripTime(tp, ap, call->conn->peer, &now);
4285 #ifdef ADAPT_WINDOW
4286                     rxi_ComputeRate(call->conn->peer, call, tp, np,
4287                                     ap->reason);
4288 #endif
4289                 }
4290                 if (missing) {
4291                     nNacked++;
4292                 } else {
4293                     call->nSoftAcked++;
4294                 }
4295             } else /* RX_ACK_TYPE_NACK */ {
4296                 tp->flags &= ~RX_PKTFLAG_ACKED;
4297                 missing = 1;
4298             }
4299         } else {
4300             if (tp->flags & RX_PKTFLAG_ACKED) {
4301                 tp->flags &= ~RX_PKTFLAG_ACKED;
4302                 missing = 1;
4303             }
4304         }
4305
4306         /*
4307          * Following the suggestion of Phil Kern, we back off the peer's
4308          * timeout value for future packets until a successful response
4309          * is received for an initial transmission.
4310          */
4311         if (missing && !peer->backedOff) {
4312             struct clock c = peer->timeout;
4313             struct clock max_to = {3, 0};
4314
4315             clock_Add(&peer->timeout, &c);
4316             if (clock_Gt(&peer->timeout, &max_to))
4317                 peer->timeout = max_to;
4318             peer->backedOff = 1;
4319         }
4320
4321         /* If packet isn't yet acked, and it has been transmitted at least
4322          * once, reset retransmit time using latest timeout
4323          * ie, this should readjust the retransmit timer for all outstanding
4324          * packets...  So we don't just retransmit when we should know better*/
4325
4326         if (!(tp->flags & RX_PKTFLAG_ACKED) && !clock_IsZero(&tp->retryTime)) {
4327             tp->retryTime = tp->timeSent;
4328             clock_Add(&tp->retryTime, &peer->timeout);
4329             /* shift by eight because one quarter-sec ~ 256 milliseconds */
4330             clock_Addmsec(&(tp->retryTime), ((afs_uint32) tp->backoff) << 8);
4331         }
4332     }
4333
4334     /* If the window has been extended by this acknowledge packet,
4335      * then wakeup a sender waiting in alloc for window space, or try
4336      * sending packets now, if he's been sitting on packets due to
4337      * lack of window space */
4338     if (call->tnext < (call->tfirst + call->twind)) {
4339 #ifdef  RX_ENABLE_LOCKS
4340         CV_SIGNAL(&call->cv_twind);
4341 #else
4342         if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4343             call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4344             osi_rxWakeup(&call->twind);
4345         }
4346 #endif
4347         if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4348             call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4349         }
4350     }
4351
4352     /* if the ack packet has a receivelen field hanging off it,
4353      * update our state */
4354     if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4355         afs_uint32 tSize;
4356
4357         /* If the ack packet has a "recommended" size that is less than
4358          * what I am using now, reduce my size to match */
4359         rx_packetread(np, rx_AckDataSize(ap->nAcks) + (in