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