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