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