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