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