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