2 * Copyright 2000, International Business Machines Corporation and others.
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
10 /* RX: Extended Remote Procedure Call */
12 #include <afsconfig.h>
13 #include <afs/param.h>
16 # include "afs/sysincludes.h"
17 # include "afsincludes.h"
22 # ifdef AFS_LINUX20_ENV
23 # include "h/socket.h"
25 # include "netinet/in.h"
27 # include "netinet/ip6.h"
28 # include "inet/common.h"
30 # include "inet/ip_ire.h"
32 # include "afs/afs_args.h"
33 # include "afs/afs_osi.h"
34 # ifdef RX_KERNEL_TRACE
35 # include "rx_kcommon.h"
37 # if defined(AFS_AIX_ENV)
41 # undef RXDEBUG /* turn off debugging */
43 # if defined(AFS_SGI_ENV)
44 # include "sys/debug.h"
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;
58 # include "sys/lockl.h"
59 # include "sys/lock_def.h"
60 # endif /* AFS_AIX41_ENV */
61 # include "afs/rxgen_consts.h"
66 # include <afs/afsutil.h>
67 # include <WINNT\afsreg.h>
75 #include <opr/queue.h>
76 #include <hcrypto/rand.h>
80 #include "rx_atomic.h"
81 #include "rx_globals.h"
83 #include "rx_internal.h"
90 #include "rx_packet.h"
91 #include "rx_server.h"
93 #include <afs/rxgen_consts.h>
96 #ifdef AFS_PTHREAD_ENV
98 int (*registerProgram) (pid_t, char *) = 0;
99 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
102 int (*registerProgram) (PROCESS, char *) = 0;
103 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
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 *,
112 static void rxi_Resend(struct rxevent *event, void *arg0, void *arg1,
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,
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 int 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);
164 static void rxi_Finalize_locked(void);
165 #elif defined(UKERNEL)
166 # define rxi_Finalize_locked() do { } while (0)
169 #ifdef RX_ENABLE_LOCKS
171 rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
172 rx_atomic_t rxi_start_in_error;
174 #endif /* RX_ENABLE_LOCKS */
176 /* Constant delay time before sending an acknowledge of the last packet
177 * received. This is to avoid sending an extra acknowledge when the
178 * client is about to make another call, anyway, or the server is
181 * The lastAckDelay may not exceeed 400ms without causing peers to
182 * unecessarily timeout.
184 struct clock rx_lastAckDelay = {0, 400000};
186 /* Constant delay time before sending a soft ack when none was requested.
187 * This is to make sure we send soft acks before the sender times out,
188 * Normally we wait and send a hard ack when the receiver consumes the packet
190 * This value has been 100ms in all shipping versions of OpenAFS. Changing it
191 * will require changes to the peer's RTT calculations.
193 struct clock rx_softAckDelay = {0, 100000};
196 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
197 * currently allocated within rx. This number is used to allocate the
198 * memory required to return the statistics when queried.
199 * Protected by the rx_rpc_stats mutex.
202 static unsigned int rxi_rpc_peer_stat_cnt;
205 * rxi_rpc_process_stat_cnt counts the total number of local process stat
206 * structures currently allocated within rx. The number is used to allocate
207 * the memory required to return the statistics when queried.
208 * Protected by the rx_rpc_stats mutex.
211 static unsigned int rxi_rpc_process_stat_cnt;
213 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
214 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
216 /* Incoming calls wait on this queue when there are no available
217 * server processes */
218 struct opr_queue rx_incomingCallQueue;
220 /* Server processes wait on this queue when there are no appropriate
221 * calls to process */
222 struct opr_queue rx_idleServerQueue;
224 /* List of free rx_serverQueueEntry structs */
225 struct opr_queue rx_freeServerQueue;
227 #if !defined(offsetof)
228 #include <stddef.h> /* for definition of offsetof() */
231 #ifdef RX_ENABLE_LOCKS
232 afs_kmutex_t rx_atomic_mutex;
233 static afs_kmutex_t freeSQEList_lock;
236 /* Forward prototypes */
237 static struct rx_call * rxi_NewCall(struct rx_connection *, int);
240 putConnection (struct rx_connection *conn) {
241 MUTEX_ENTER(&rx_refcnt_mutex);
243 MUTEX_EXIT(&rx_refcnt_mutex);
246 #ifdef AFS_PTHREAD_ENV
249 * Use procedural initialization of mutexes/condition variables
253 extern afs_kmutex_t rx_quota_mutex;
254 extern afs_kmutex_t rx_pthread_mutex;
255 extern afs_kmutex_t rx_packets_mutex;
256 extern afs_kmutex_t rx_refcnt_mutex;
257 extern afs_kmutex_t des_init_mutex;
258 extern afs_kmutex_t des_random_mutex;
260 extern afs_kmutex_t rx_clock_mutex;
261 extern afs_kmutex_t rxi_connCacheMutex;
262 extern afs_kmutex_t event_handler_mutex;
263 extern afs_kmutex_t listener_mutex;
264 extern afs_kmutex_t rx_if_init_mutex;
265 extern afs_kmutex_t rx_if_mutex;
267 extern afs_kcondvar_t rx_event_handler_cond;
268 extern afs_kcondvar_t rx_listener_cond;
271 static afs_kmutex_t epoch_mutex;
272 static afs_kmutex_t rx_init_mutex;
273 static afs_kmutex_t rx_debug_mutex;
274 static afs_kmutex_t rx_rpc_stats;
277 rxi_InitPthread(void)
279 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
280 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
281 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
282 MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
284 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
285 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
286 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
287 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
288 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
289 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
291 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
292 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
293 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
294 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
295 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
298 CV_INIT(&rx_event_handler_cond, "evhand", CV_DEFAULT, 0);
299 CV_INIT(&rx_listener_cond, "rxlisten", CV_DEFAULT, 0);
302 osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
303 osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
305 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
306 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
307 MUTEX_INIT(&rx_mallocedPktQ_lock, "rx_mallocedPktQ_lock", MUTEX_DEFAULT,
310 #ifdef RX_ENABLE_LOCKS
313 #endif /* RX_LOCKS_DB */
314 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
315 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
317 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
319 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
321 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
323 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
325 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
327 #endif /* RX_ENABLE_LOCKS */
330 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
331 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
333 * The rx_stats_mutex mutex protects the following global variables:
334 * rxi_lowConnRefCount
335 * rxi_lowPeerRefCount
344 * The rx_quota_mutex mutex protects the following global variables:
352 * The rx_freePktQ_lock protects the following global variables:
357 * The rx_packets_mutex mutex protects the following global variables:
365 * The rx_pthread_mutex mutex protects the following global variables:
366 * rxi_fcfs_thread_num
369 #define INIT_PTHREAD_LOCKS
373 /* Variables for handling the minProcs implementation. availProcs gives the
374 * number of threads available in the pool at this moment (not counting dudes
375 * executing right now). totalMin gives the total number of procs required
376 * for handling all minProcs requests. minDeficit is a dynamic variable
377 * tracking the # of procs required to satisfy all of the remaining minProcs
379 * For fine grain locking to work, the quota check and the reservation of
380 * a server thread has to come while rxi_availProcs and rxi_minDeficit
381 * are locked. To this end, the code has been modified under #ifdef
382 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
383 * same time. A new function, ReturnToServerPool() returns the allocation.
385 * A call can be on several queue's (but only one at a time). When
386 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
387 * that no one else is touching the queue. To this end, we store the address
388 * of the queue lock in the call structure (under the call lock) when we
389 * put the call on a queue, and we clear the call_queue_lock when the
390 * call is removed from a queue (once the call lock has been obtained).
391 * This allows rxi_ResetCall to safely synchronize with others wishing
392 * to manipulate the queue.
395 #if defined(RX_ENABLE_LOCKS)
396 static afs_kmutex_t rx_rpc_stats;
399 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
400 ** pretty good that the next packet coming in is from the same connection
401 ** as the last packet, since we're send multiple packets in a transmit window.
403 struct rx_connection *rxLastConn = 0;
405 #ifdef RX_ENABLE_LOCKS
406 /* The locking hierarchy for rx fine grain locking is composed of these
409 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
410 * also protects updates to rx_nextCid
411 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
412 * call->lock - locks call data fields.
413 * These are independent of each other:
414 * rx_freeCallQueue_lock
419 * serverQueueEntry->lock
420 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
422 * peer->lock - locks peer data fields.
423 * conn_data_lock - that more than one thread is not updating a conn data
424 * field at the same time.
435 * Do we need a lock to protect the peer field in the conn structure?
436 * conn->peer was previously a constant for all intents and so has no
437 * lock protecting this field. The multihomed client delta introduced
438 * a RX code change : change the peer field in the connection structure
439 * to that remote interface from which the last packet for this
440 * connection was sent out. This may become an issue if further changes
443 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
444 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
446 /* rxdb_fileID is used to identify the lock location, along with line#. */
447 static int rxdb_fileID = RXDB_FILE_RX;
448 #endif /* RX_LOCKS_DB */
449 #else /* RX_ENABLE_LOCKS */
450 #define SET_CALL_QUEUE_LOCK(C, L)
451 #define CLEAR_CALL_QUEUE_LOCK(C)
452 #endif /* RX_ENABLE_LOCKS */
453 struct rx_serverQueueEntry *rx_waitForPacket = 0;
456 * This mutex serializes calls to our initialization and shutdown routines
457 * (rx_InitHost, rx_Finalize and shutdown_rx). Only one thread can be running
458 * these at any time; all other threads must wait for it to finish running, and
459 * then examine the value of rxi_running afterwards.
461 #ifdef AFS_PTHREAD_ENV
462 # define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
463 # define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
465 # define LOCK_RX_INIT
466 # define UNLOCK_RX_INIT
469 /* ------------Exported Interfaces------------- */
471 static rx_atomic_t rxi_running = RX_ATOMIC_INIT(0);
475 return rx_atomic_read(&rxi_running);
478 /* Initialize rx. A port number may be mentioned, in which case this
479 * becomes the default port number for any service installed later.
480 * If 0 is provided for the port number, a random port will be chosen
481 * by the kernel. Whether this will ever overlap anything in
482 * /etc/services is anybody's guess... Returns 0 on success, -1 on
485 rx_InitHost(u_int host, u_int port)
492 char *htable, *ptable;
498 if (rxi_IsRunning()) {
500 return 0; /* already started */
506 if (afs_winsockInit() < 0)
512 * Initialize anything necessary to provide a non-premptive threading
515 rxi_InitializeThreadSupport();
518 /* Allocate and initialize a socket for client and perhaps server
521 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
522 if (rx_socket == OSI_NULLSOCKET) {
525 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
528 #endif /* RX_LOCKS_DB */
529 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
530 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
531 MUTEX_INIT(&rx_atomic_mutex, "rx_atomic_mutex", MUTEX_DEFAULT, 0);
532 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
533 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
534 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
535 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
536 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
537 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
538 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
540 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
542 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
544 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
546 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
547 MUTEX_INIT(&rx_mallocedPktQ_lock, "rx_mallocedPktQ_lock", MUTEX_DEFAULT,
550 #if defined(AFS_HPUX110_ENV)
552 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
553 #endif /* AFS_HPUX110_ENV */
554 #endif /* RX_ENABLE_LOCKS && KERNEL */
557 rx_connDeadTime = 12;
558 rx_tranquil = 0; /* reset flag */
559 rxi_ResetStatistics();
560 htable = osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
561 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
562 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
563 ptable = osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
564 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
565 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
567 /* Malloc up a bunch of packets & buffers */
569 opr_queue_Init(&rx_freePacketQueue);
570 rxi_NeedMorePackets = FALSE;
571 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
572 opr_queue_Init(&rx_mallocedPacketQueue);
574 /* enforce a minimum number of allocated packets */
575 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
576 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
578 /* allocate the initial free packet pool */
579 #ifdef RX_ENABLE_TSFPQ
580 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
581 #else /* RX_ENABLE_TSFPQ */
582 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
583 #endif /* RX_ENABLE_TSFPQ */
590 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
591 tv.tv_sec = clock_now.sec;
592 tv.tv_usec = clock_now.usec;
593 srand((unsigned int)tv.tv_usec);
600 #if defined(KERNEL) && !defined(UKERNEL)
601 /* Really, this should never happen in a real kernel */
604 struct sockaddr_in addr;
606 int addrlen = sizeof(addr);
608 socklen_t addrlen = sizeof(addr);
610 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
611 rxi_Finalize_locked();
612 osi_Free(htable, rx_hashTableSize * sizeof(struct rx_connection *));
615 rx_port = addr.sin_port;
618 rx_stats.minRtt.sec = 9999999;
619 if (RAND_bytes(&rx_epoch, sizeof(rx_epoch)) != 1)
621 rx_epoch = (rx_epoch & ~0x40000000) | 0x80000000;
622 if (RAND_bytes(&rx_nextCid, sizeof(rx_nextCid)) != 1)
624 rx_nextCid &= RX_CIDMASK;
625 MUTEX_ENTER(&rx_quota_mutex);
626 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
627 MUTEX_EXIT(&rx_quota_mutex);
628 /* *Slightly* random start time for the cid. This is just to help
629 * out with the hashing function at the peer */
630 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
631 rx_connHashTable = (struct rx_connection **)htable;
632 rx_peerHashTable = (struct rx_peer **)ptable;
634 rx_hardAckDelay.sec = 0;
635 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
637 rxevent_Init(20, rxi_ReScheduleEvents);
639 /* Initialize various global queues */
640 opr_queue_Init(&rx_idleServerQueue);
641 opr_queue_Init(&rx_freeServerQueue);
642 opr_queue_Init(&rx_incomingCallQueue);
643 opr_queue_Init(&rx_freeCallQueue);
645 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
646 /* Initialize our list of usable IP addresses. */
650 /* Start listener process (exact function is dependent on the
651 * implementation environment--kernel or user space) */
656 rx_atomic_set(&rxi_running, 1);
673 return rx_InitHost(htonl(INADDR_ANY), port);
679 * The rxi_rto functions implement a TCP (RFC2988) style algorithm for
680 * maintaing the round trip timer.
685 * Start a new RTT timer for a given call and packet.
687 * There must be no resendEvent already listed for this call, otherwise this
688 * will leak events - intended for internal use within the RTO code only
691 * the RX call to start the timer for
692 * @param[in] lastPacket
693 * a flag indicating whether the last packet has been sent or not
695 * @pre call must be locked before calling this function
699 rxi_rto_startTimer(struct rx_call *call, int lastPacket, int istack)
701 struct clock now, retryTime;
703 MUTEX_ASSERT(&call->lock);
707 clock_Add(&retryTime, &call->rto);
709 /* If we're sending the last packet, and we're the client, then the server
710 * may wait for an additional 400ms before returning the ACK, wait for it
711 * rather than hitting a timeout */
712 if (lastPacket && call->conn->type == RX_CLIENT_CONNECTION)
713 clock_Addmsec(&retryTime, 400);
715 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
716 call->resendEvent = rxevent_Post(&retryTime, &now, rxi_Resend,
721 * Cancel an RTT timer for a given call.
725 * the RX call to cancel the timer for
727 * @pre call must be locked before calling this function
732 rxi_rto_cancel(struct rx_call *call)
734 MUTEX_ASSERT(&call->lock);
735 if (rxevent_Cancel(&call->resendEvent))
736 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
740 * Tell the RTO timer that we have sent a packet.
742 * If the timer isn't already running, then start it. If the timer is running,
746 * the RX call that the packet has been sent on
747 * @param[in] lastPacket
748 * A flag which is true if this is the last packet for the call
750 * @pre The call must be locked before calling this function
755 rxi_rto_packet_sent(struct rx_call *call, int lastPacket, int istack)
757 if (call->resendEvent)
760 rxi_rto_startTimer(call, lastPacket, istack);
764 * Tell the RTO timer that we have received an new ACK message
766 * This function should be called whenever a call receives an ACK that
767 * acknowledges new packets. Whatever happens, we stop the current timer.
768 * If there are unacked packets in the queue which have been sent, then
769 * we restart the timer from now. Otherwise, we leave it stopped.
772 * the RX call that the ACK has been received on
776 rxi_rto_packet_acked(struct rx_call *call, int istack)
778 struct opr_queue *cursor;
780 rxi_rto_cancel(call);
782 if (opr_queue_IsEmpty(&call->tq))
785 for (opr_queue_Scan(&call->tq, cursor)) {
786 struct rx_packet *p = opr_queue_Entry(cursor, struct rx_packet, entry);
787 if (p->header.seq > call->tfirst + call->twind)
790 if (!(p->flags & RX_PKTFLAG_ACKED) && p->flags & RX_PKTFLAG_SENT) {
791 rxi_rto_startTimer(call, p->header.flags & RX_LAST_PACKET, istack);
799 * Set an initial round trip timeout for a peer connection
801 * @param[in] secs The timeout to set in seconds
805 rx_rto_setPeerTimeoutSecs(struct rx_peer *peer, int secs) {
806 peer->rtt = secs * 8000;
810 * Set a delayed ack event on the specified call for the given time
812 * @param[in] call - the call on which to set the event
813 * @param[in] offset - the delay from now after which the event fires
816 rxi_PostDelayedAckEvent(struct rx_call *call, struct clock *offset)
818 struct clock now, when;
820 MUTEX_ASSERT(&call->lock);
823 clock_Add(&when, offset);
825 if (clock_Gt(&call->delayedAckTime, &when) &&
826 rxevent_Cancel(&call->delayedAckEvent)) {
827 /* We successfully cancelled an event too far in the future to install
828 * our new one; we can reuse the reference on the call. */
829 call->delayedAckEvent = rxevent_Post(&when, &now, rxi_SendDelayedAck,
832 call->delayedAckTime = when;
833 } else if (call->delayedAckEvent == NULL) {
834 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
835 call->delayedAckEvent = rxevent_Post(&when, &now,
838 call->delayedAckTime = when;
843 rxi_CancelDelayedAckEvent(struct rx_call *call)
845 MUTEX_ASSERT(&call->lock);
846 /* Only drop the ref if we cancelled it before it could run. */
847 if (rxevent_Cancel(&call->delayedAckEvent))
848 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
851 /* called with unincremented nRequestsRunning to see if it is OK to start
852 * a new thread in this service. Could be "no" for two reasons: over the
853 * max quota, or would prevent others from reaching their min quota.
855 #ifdef RX_ENABLE_LOCKS
856 /* This verion of QuotaOK reserves quota if it's ok while the
857 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
860 QuotaOK(struct rx_service *aservice)
862 /* check if over max quota */
863 if (aservice->nRequestsRunning >= aservice->maxProcs) {
867 /* under min quota, we're OK */
868 /* otherwise, can use only if there are enough to allow everyone
869 * to go to their min quota after this guy starts.
872 MUTEX_ENTER(&rx_quota_mutex);
873 if ((aservice->nRequestsRunning < aservice->minProcs)
874 || (rxi_availProcs > rxi_minDeficit)) {
875 aservice->nRequestsRunning++;
876 /* just started call in minProcs pool, need fewer to maintain
878 if (aservice->nRequestsRunning <= aservice->minProcs)
881 MUTEX_EXIT(&rx_quota_mutex);
884 MUTEX_EXIT(&rx_quota_mutex);
890 ReturnToServerPool(struct rx_service *aservice)
892 aservice->nRequestsRunning--;
893 MUTEX_ENTER(&rx_quota_mutex);
894 if (aservice->nRequestsRunning < aservice->minProcs)
897 MUTEX_EXIT(&rx_quota_mutex);
900 #else /* RX_ENABLE_LOCKS */
902 QuotaOK(struct rx_service *aservice)
905 /* under min quota, we're OK */
906 if (aservice->nRequestsRunning < aservice->minProcs)
909 /* check if over max quota */
910 if (aservice->nRequestsRunning >= aservice->maxProcs)
913 /* otherwise, can use only if there are enough to allow everyone
914 * to go to their min quota after this guy starts.
916 MUTEX_ENTER(&rx_quota_mutex);
917 if (rxi_availProcs > rxi_minDeficit)
919 MUTEX_EXIT(&rx_quota_mutex);
922 #endif /* RX_ENABLE_LOCKS */
925 /* Called by rx_StartServer to start up lwp's to service calls.
926 NExistingProcs gives the number of procs already existing, and which
927 therefore needn't be created. */
929 rxi_StartServerProcs(int nExistingProcs)
931 struct rx_service *service;
936 /* For each service, reserve N processes, where N is the "minimum"
937 * number of processes that MUST be able to execute a request in parallel,
938 * at any time, for that process. Also compute the maximum difference
939 * between any service's maximum number of processes that can run
940 * (i.e. the maximum number that ever will be run, and a guarantee
941 * that this number will run if other services aren't running), and its
942 * minimum number. The result is the extra number of processes that
943 * we need in order to provide the latter guarantee */
944 for (i = 0; i < RX_MAX_SERVICES; i++) {
946 service = rx_services[i];
947 if (service == (struct rx_service *)0)
949 nProcs += service->minProcs;
950 diff = service->maxProcs - service->minProcs;
954 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
955 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
956 for (i = 0; i < nProcs; i++) {
957 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
963 /* This routine is only required on Windows */
965 rx_StartClientThread(void)
967 #ifdef AFS_PTHREAD_ENV
969 pid = pthread_self();
970 #endif /* AFS_PTHREAD_ENV */
972 #endif /* AFS_NT40_ENV */
974 /* This routine must be called if any services are exported. If the
975 * donateMe flag is set, the calling process is donated to the server
978 rx_StartServer(int donateMe)
980 struct rx_service *service;
986 /* Start server processes, if necessary (exact function is dependent
987 * on the implementation environment--kernel or user space). DonateMe
988 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
989 * case, one less new proc will be created rx_StartServerProcs.
991 rxi_StartServerProcs(donateMe);
993 /* count up the # of threads in minProcs, and add set the min deficit to
994 * be that value, too.
996 for (i = 0; i < RX_MAX_SERVICES; i++) {
997 service = rx_services[i];
998 if (service == (struct rx_service *)0)
1000 MUTEX_ENTER(&rx_quota_mutex);
1001 rxi_totalMin += service->minProcs;
1002 /* below works even if a thread is running, since minDeficit would
1003 * still have been decremented and later re-incremented.
1005 rxi_minDeficit += service->minProcs;
1006 MUTEX_EXIT(&rx_quota_mutex);
1009 /* Turn on reaping of idle server connections */
1010 rxi_ReapConnections(NULL, NULL, NULL, 0);
1015 #ifndef AFS_NT40_ENV
1019 #ifdef AFS_PTHREAD_ENV
1021 pid = afs_pointer_to_int(pthread_self());
1022 #else /* AFS_PTHREAD_ENV */
1024 LWP_CurrentProcess(&pid);
1025 #endif /* AFS_PTHREAD_ENV */
1027 sprintf(name, "srv_%d", ++nProcs);
1028 if (registerProgram)
1029 (*registerProgram) (pid, name);
1031 #endif /* AFS_NT40_ENV */
1032 rx_ServerProc(NULL); /* Never returns */
1034 #ifdef RX_ENABLE_TSFPQ
1035 /* no use leaving packets around in this thread's local queue if
1036 * it isn't getting donated to the server thread pool.
1038 rxi_FlushLocalPacketsTSFPQ();
1039 #endif /* RX_ENABLE_TSFPQ */
1043 /* Create a new client connection to the specified service, using the
1044 * specified security object to implement the security model for this
1046 struct rx_connection *
1047 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
1048 struct rx_securityClass *securityObject,
1049 int serviceSecurityIndex)
1052 struct rx_connection *conn;
1058 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
1059 "serviceSecurityIndex %d)\n",
1060 ntohl(shost), ntohs(sport), sservice, securityObject,
1061 serviceSecurityIndex));
1063 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
1064 * the case of kmem_alloc? */
1065 conn = rxi_AllocConnection();
1066 #ifdef RX_ENABLE_LOCKS
1067 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
1068 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
1069 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
1072 MUTEX_ENTER(&rx_connHashTable_lock);
1073 conn->type = RX_CLIENT_CONNECTION;
1074 conn->epoch = rx_epoch;
1075 conn->cid = rx_nextCid;
1077 conn->peer = rxi_FindPeer(shost, sport, 1);
1078 conn->serviceId = sservice;
1079 conn->securityObject = securityObject;
1080 conn->securityData = (void *) 0;
1081 conn->securityIndex = serviceSecurityIndex;
1082 rx_SetConnDeadTime(conn, rx_connDeadTime);
1083 rx_SetConnSecondsUntilNatPing(conn, 0);
1084 conn->ackRate = RX_FAST_ACK_RATE;
1085 conn->nSpecific = 0;
1086 conn->specific = NULL;
1087 conn->challengeEvent = NULL;
1088 conn->delayedAbortEvent = NULL;
1089 conn->abortCount = 0;
1091 for (i = 0; i < RX_MAXCALLS; i++) {
1092 conn->twind[i] = rx_initSendWindow;
1093 conn->rwind[i] = rx_initReceiveWindow;
1094 conn->lastBusy[i] = 0;
1097 code = RXS_NewConnection(securityObject, conn);
1099 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
1101 conn->refCount++; /* no lock required since only this thread knows... */
1102 conn->next = rx_connHashTable[hashindex];
1103 rx_connHashTable[hashindex] = conn;
1104 if (rx_stats_active)
1105 rx_atomic_inc(&rx_stats.nClientConns);
1106 MUTEX_EXIT(&rx_connHashTable_lock);
1109 rxi_ConnectionError(conn, code);
1115 * Ensure a connection's timeout values are valid.
1117 * @param[in] conn The connection to check
1119 * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
1120 * unless idleDeadTime and/or hardDeadTime are not set
1124 rxi_CheckConnTimeouts(struct rx_connection *conn)
1126 /* a connection's timeouts must have the relationship
1127 * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
1128 * total loss of network to a peer may cause an idle timeout instead of a
1129 * dead timeout, simply because the idle timeout gets hit first. Also set
1130 * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
1131 /* this logic is slightly complicated by the fact that
1132 * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
1134 conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
1135 if (conn->idleDeadTime) {
1136 conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
1138 if (conn->hardDeadTime) {
1139 if (conn->idleDeadTime) {
1140 conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
1142 conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
1148 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
1150 /* The idea is to set the dead time to a value that allows several
1151 * keepalives to be dropped without timing out the connection. */
1152 conn->secondsUntilDead = seconds;
1153 rxi_CheckConnTimeouts(conn);
1154 conn->secondsUntilPing = conn->secondsUntilDead / 6;
1158 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
1160 conn->hardDeadTime = seconds;
1161 rxi_CheckConnTimeouts(conn);
1165 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
1167 conn->idleDeadTime = seconds;
1168 rxi_CheckConnTimeouts(conn);
1171 int rxi_lowPeerRefCount = 0;
1172 int rxi_lowConnRefCount = 0;
1175 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
1176 * NOTE: must not be called with rx_connHashTable_lock held.
1179 rxi_CleanupConnection(struct rx_connection *conn)
1181 /* Notify the service exporter, if requested, that this connection
1182 * is being destroyed */
1183 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
1184 (*conn->service->destroyConnProc) (conn);
1186 /* Notify the security module that this connection is being destroyed */
1187 RXS_DestroyConnection(conn->securityObject, conn);
1189 /* If this is the last connection using the rx_peer struct, set its
1190 * idle time to now. rxi_ReapConnections will reap it if it's still
1191 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
1193 MUTEX_ENTER(&rx_peerHashTable_lock);
1194 if (conn->peer->refCount < 2) {
1195 conn->peer->idleWhen = clock_Sec();
1196 if (conn->peer->refCount < 1) {
1197 conn->peer->refCount = 1;
1198 if (rx_stats_active) {
1199 MUTEX_ENTER(&rx_stats_mutex);
1200 rxi_lowPeerRefCount++;
1201 MUTEX_EXIT(&rx_stats_mutex);
1205 conn->peer->refCount--;
1206 MUTEX_EXIT(&rx_peerHashTable_lock);
1208 if (rx_stats_active)
1210 if (conn->type == RX_SERVER_CONNECTION)
1211 rx_atomic_dec(&rx_stats.nServerConns);
1213 rx_atomic_dec(&rx_stats.nClientConns);
1216 if (conn->specific) {
1218 for (i = 0; i < conn->nSpecific; i++) {
1219 if (conn->specific[i] && rxi_keyCreate_destructor[i])
1220 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
1221 conn->specific[i] = NULL;
1223 free(conn->specific);
1225 conn->specific = NULL;
1226 conn->nSpecific = 0;
1227 #endif /* !KERNEL */
1229 MUTEX_DESTROY(&conn->conn_call_lock);
1230 MUTEX_DESTROY(&conn->conn_data_lock);
1231 CV_DESTROY(&conn->conn_call_cv);
1233 rxi_FreeConnection(conn);
1236 /* Destroy the specified connection */
1238 rxi_DestroyConnection(struct rx_connection *conn)
1240 MUTEX_ENTER(&rx_connHashTable_lock);
1241 rxi_DestroyConnectionNoLock(conn);
1242 /* conn should be at the head of the cleanup list */
1243 if (conn == rx_connCleanup_list) {
1244 rx_connCleanup_list = rx_connCleanup_list->next;
1245 MUTEX_EXIT(&rx_connHashTable_lock);
1246 rxi_CleanupConnection(conn);
1248 #ifdef RX_ENABLE_LOCKS
1250 MUTEX_EXIT(&rx_connHashTable_lock);
1252 #endif /* RX_ENABLE_LOCKS */
1256 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1258 struct rx_connection **conn_ptr;
1266 MUTEX_ENTER(&conn->conn_data_lock);
1267 MUTEX_ENTER(&rx_refcnt_mutex);
1268 if (conn->refCount > 0)
1271 #ifdef RX_REFCOUNT_CHECK
1272 osi_Assert(conn->refCount == 0);
1274 if (rx_stats_active) {
1275 MUTEX_ENTER(&rx_stats_mutex);
1276 rxi_lowConnRefCount++;
1277 MUTEX_EXIT(&rx_stats_mutex);
1281 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1282 /* Busy; wait till the last guy before proceeding */
1283 MUTEX_EXIT(&rx_refcnt_mutex);
1284 MUTEX_EXIT(&conn->conn_data_lock);
1289 /* If the client previously called rx_NewCall, but it is still
1290 * waiting, treat this as a running call, and wait to destroy the
1291 * connection later when the call completes. */
1292 if ((conn->type == RX_CLIENT_CONNECTION)
1293 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1294 conn->flags |= RX_CONN_DESTROY_ME;
1295 MUTEX_EXIT(&rx_refcnt_mutex);
1296 MUTEX_EXIT(&conn->conn_data_lock);
1300 MUTEX_EXIT(&rx_refcnt_mutex);
1301 MUTEX_EXIT(&conn->conn_data_lock);
1303 /* Check for extant references to this connection */
1304 MUTEX_ENTER(&conn->conn_call_lock);
1305 for (i = 0; i < RX_MAXCALLS; i++) {
1306 struct rx_call *call = conn->call[i];
1309 if (conn->type == RX_CLIENT_CONNECTION) {
1310 MUTEX_ENTER(&call->lock);
1311 if (call->delayedAckEvent) {
1312 /* Push the final acknowledgment out now--there
1313 * won't be a subsequent call to acknowledge the
1314 * last reply packets */
1315 rxi_CancelDelayedAckEvent(call);
1316 if (call->state == RX_STATE_PRECALL
1317 || call->state == RX_STATE_ACTIVE) {
1318 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1323 MUTEX_EXIT(&call->lock);
1327 MUTEX_EXIT(&conn->conn_call_lock);
1329 #ifdef RX_ENABLE_LOCKS
1331 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1332 MUTEX_EXIT(&conn->conn_data_lock);
1334 /* Someone is accessing a packet right now. */
1338 #endif /* RX_ENABLE_LOCKS */
1341 /* Don't destroy the connection if there are any call
1342 * structures still in use */
1343 MUTEX_ENTER(&conn->conn_data_lock);
1344 conn->flags |= RX_CONN_DESTROY_ME;
1345 MUTEX_EXIT(&conn->conn_data_lock);
1350 /* Remove from connection hash table before proceeding */
1352 &rx_connHashTable[CONN_HASH
1353 (peer->host, peer->port, conn->cid, conn->epoch,
1355 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1356 if (*conn_ptr == conn) {
1357 *conn_ptr = conn->next;
1361 /* if the conn that we are destroying was the last connection, then we
1362 * clear rxLastConn as well */
1363 if (rxLastConn == conn)
1366 /* Make sure the connection is completely reset before deleting it. */
1368 * Pending events hold a refcount, so we can't get here if they are
1370 osi_Assert(conn->challengeEvent == NULL);
1371 osi_Assert(conn->delayedAbortEvent == NULL);
1372 osi_Assert(conn->natKeepAliveEvent == NULL);
1373 osi_Assert(conn->checkReachEvent == NULL);
1375 /* Add the connection to the list of destroyed connections that
1376 * need to be cleaned up. This is necessary to avoid deadlocks
1377 * in the routines we call to inform others that this connection is
1378 * being destroyed. */
1379 conn->next = rx_connCleanup_list;
1380 rx_connCleanup_list = conn;
1383 /* Externally available version */
1385 rx_DestroyConnection(struct rx_connection *conn)
1390 rxi_DestroyConnection(conn);
1395 rx_GetConnection(struct rx_connection *conn)
1400 MUTEX_ENTER(&rx_refcnt_mutex);
1402 MUTEX_EXIT(&rx_refcnt_mutex);
1406 #ifdef RX_ENABLE_LOCKS
1407 /* Wait for the transmit queue to no longer be busy.
1408 * requires the call->lock to be held */
1410 rxi_WaitforTQBusy(struct rx_call *call) {
1411 while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1412 call->flags |= RX_CALL_TQ_WAIT;
1414 MUTEX_ASSERT(&call->lock);
1415 CV_WAIT(&call->cv_tq, &call->lock);
1417 if (call->tqWaiters == 0) {
1418 call->flags &= ~RX_CALL_TQ_WAIT;
1425 rxi_WakeUpTransmitQueue(struct rx_call *call)
1427 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1428 dpf(("call %p has %d waiters and flags %d\n",
1429 call, call->tqWaiters, call->flags));
1430 #ifdef RX_ENABLE_LOCKS
1431 MUTEX_ASSERT(&call->lock);
1432 CV_BROADCAST(&call->cv_tq);
1433 #else /* RX_ENABLE_LOCKS */
1434 osi_rxWakeup(&call->tq);
1435 #endif /* RX_ENABLE_LOCKS */
1439 /* Start a new rx remote procedure call, on the specified connection.
1440 * If wait is set to 1, wait for a free call channel; otherwise return
1441 * 0. Maxtime gives the maximum number of seconds this call may take,
1442 * after rx_NewCall returns. After this time interval, a call to any
1443 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1444 * For fine grain locking, we hold the conn_call_lock in order to
1445 * to ensure that we don't get signalle after we found a call in an active
1446 * state and before we go to sleep.
1449 rx_NewCall(struct rx_connection *conn)
1451 int i, wait, ignoreBusy = 1;
1452 struct rx_call *call;
1453 struct clock queueTime;
1454 afs_uint32 leastBusy = 0;
1458 dpf(("rx_NewCall(conn %p)\n", conn));
1461 clock_GetTime(&queueTime);
1463 * Check if there are others waiting for a new call.
1464 * If so, let them go first to avoid starving them.
1465 * This is a fairly simple scheme, and might not be
1466 * a complete solution for large numbers of waiters.
1468 * makeCallWaiters keeps track of the number of
1469 * threads waiting to make calls and the
1470 * RX_CONN_MAKECALL_WAITING flag bit is used to
1471 * indicate that there are indeed calls waiting.
1472 * The flag is set when the waiter is incremented.
1473 * It is only cleared when makeCallWaiters is 0.
1474 * This prevents us from accidently destroying the
1475 * connection while it is potentially about to be used.
1477 MUTEX_ENTER(&conn->conn_call_lock);
1478 MUTEX_ENTER(&conn->conn_data_lock);
1479 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1480 conn->flags |= RX_CONN_MAKECALL_WAITING;
1481 conn->makeCallWaiters++;
1482 MUTEX_EXIT(&conn->conn_data_lock);
1484 #ifdef RX_ENABLE_LOCKS
1485 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1489 MUTEX_ENTER(&conn->conn_data_lock);
1490 conn->makeCallWaiters--;
1491 if (conn->makeCallWaiters == 0)
1492 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1495 /* We are now the active thread in rx_NewCall */
1496 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1497 MUTEX_EXIT(&conn->conn_data_lock);
1502 for (i = 0; i < RX_MAXCALLS; i++) {
1503 call = conn->call[i];
1505 if (!ignoreBusy && conn->lastBusy[i] != leastBusy) {
1506 /* we're not ignoring busy call slots; only look at the
1507 * call slot that is the "least" busy */
1511 if (call->state == RX_STATE_DALLY) {
1512 MUTEX_ENTER(&call->lock);
1513 if (call->state == RX_STATE_DALLY) {
1514 if (ignoreBusy && conn->lastBusy[i]) {
1515 /* if we're ignoring busy call slots, skip any ones that
1516 * have lastBusy set */
1517 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1518 leastBusy = conn->lastBusy[i];
1520 MUTEX_EXIT(&call->lock);
1525 * We are setting the state to RX_STATE_RESET to
1526 * ensure that no one else will attempt to use this
1527 * call once we drop the conn->conn_call_lock and
1528 * call->lock. We must drop the conn->conn_call_lock
1529 * before calling rxi_ResetCall because the process
1530 * of clearing the transmit queue can block for an
1531 * extended period of time. If we block while holding
1532 * the conn->conn_call_lock, then all rx_EndCall
1533 * processing will block as well. This has a detrimental
1534 * effect on overall system performance.
1536 call->state = RX_STATE_RESET;
1537 (*call->callNumber)++;
1538 MUTEX_EXIT(&conn->conn_call_lock);
1539 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1540 rxi_ResetCall(call, 0);
1541 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1545 * If we failed to be able to safely obtain the
1546 * conn->conn_call_lock we will have to drop the
1547 * call->lock to avoid a deadlock. When the call->lock
1548 * is released the state of the call can change. If it
1549 * is no longer RX_STATE_RESET then some other thread is
1552 MUTEX_EXIT(&call->lock);
1553 MUTEX_ENTER(&conn->conn_call_lock);
1554 MUTEX_ENTER(&call->lock);
1556 if (call->state == RX_STATE_RESET)
1560 * If we get here it means that after dropping
1561 * the conn->conn_call_lock and call->lock that
1562 * the call is no longer ours. If we can't find
1563 * a free call in the remaining slots we should
1564 * not go immediately to RX_CONN_MAKECALL_WAITING
1565 * because by dropping the conn->conn_call_lock
1566 * we have given up synchronization with rx_EndCall.
1567 * Instead, cycle through one more time to see if
1568 * we can find a call that can call our own.
1570 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1573 MUTEX_EXIT(&call->lock);
1576 if (ignoreBusy && conn->lastBusy[i]) {
1577 /* if we're ignoring busy call slots, skip any ones that
1578 * have lastBusy set */
1579 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1580 leastBusy = conn->lastBusy[i];
1585 /* rxi_NewCall returns with mutex locked */
1586 call = rxi_NewCall(conn, i);
1587 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1591 if (i < RX_MAXCALLS) {
1592 conn->lastBusy[i] = 0;
1597 if (leastBusy && ignoreBusy) {
1598 /* we didn't find a useable call slot, but we did see at least one
1599 * 'busy' slot; look again and only use a slot with the 'least
1605 MUTEX_ENTER(&conn->conn_data_lock);
1606 conn->flags |= RX_CONN_MAKECALL_WAITING;
1607 conn->makeCallWaiters++;
1608 MUTEX_EXIT(&conn->conn_data_lock);
1610 #ifdef RX_ENABLE_LOCKS
1611 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1615 MUTEX_ENTER(&conn->conn_data_lock);
1616 conn->makeCallWaiters--;
1617 if (conn->makeCallWaiters == 0)
1618 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1619 MUTEX_EXIT(&conn->conn_data_lock);
1621 /* Client is initially in send mode */
1622 call->state = RX_STATE_ACTIVE;
1623 call->error = conn->error;
1625 call->app.mode = RX_MODE_ERROR;
1627 call->app.mode = RX_MODE_SENDING;
1629 #ifdef AFS_RXERRQ_ENV
1630 /* remember how many network errors the peer has when we started, so if
1631 * more errors are encountered after the call starts, we know the other endpoint won't be
1632 * responding to us */
1633 call->neterr_gen = rx_atomic_read(&conn->peer->neterrs);
1636 /* remember start time for call in case we have hard dead time limit */
1637 call->queueTime = queueTime;
1638 clock_GetTime(&call->startTime);
1639 call->app.bytesSent = 0;
1640 call->app.bytesRcvd = 0;
1642 /* Turn on busy protocol. */
1643 rxi_KeepAliveOn(call);
1645 /* Attempt MTU discovery */
1646 rxi_GrowMTUOn(call);
1649 * We are no longer the active thread in rx_NewCall
1651 MUTEX_ENTER(&conn->conn_data_lock);
1652 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1653 MUTEX_EXIT(&conn->conn_data_lock);
1656 * Wake up anyone else who might be giving us a chance to
1657 * run (see code above that avoids resource starvation).
1659 #ifdef RX_ENABLE_LOCKS
1660 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1661 osi_Panic("rx_NewCall call about to be used without an empty tq");
1664 CV_BROADCAST(&conn->conn_call_cv);
1668 MUTEX_EXIT(&conn->conn_call_lock);
1669 MUTEX_EXIT(&call->lock);
1672 dpf(("rx_NewCall(call %p)\n", call));
1677 rxi_HasActiveCalls(struct rx_connection *aconn)
1680 struct rx_call *tcall;
1684 for (i = 0; i < RX_MAXCALLS; i++) {
1685 if ((tcall = aconn->call[i])) {
1686 if ((tcall->state == RX_STATE_ACTIVE)
1687 || (tcall->state == RX_STATE_PRECALL)) {
1698 rxi_GetCallNumberVector(struct rx_connection *aconn,
1699 afs_int32 * aint32s)
1702 struct rx_call *tcall;
1706 MUTEX_ENTER(&aconn->conn_call_lock);
1707 for (i = 0; i < RX_MAXCALLS; i++) {
1708 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1709 aint32s[i] = aconn->callNumber[i] + 1;
1711 aint32s[i] = aconn->callNumber[i];
1713 MUTEX_EXIT(&aconn->conn_call_lock);
1719 rxi_SetCallNumberVector(struct rx_connection *aconn,
1720 afs_int32 * aint32s)
1723 struct rx_call *tcall;
1727 MUTEX_ENTER(&aconn->conn_call_lock);
1728 for (i = 0; i < RX_MAXCALLS; i++) {
1729 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1730 aconn->callNumber[i] = aint32s[i] - 1;
1732 aconn->callNumber[i] = aint32s[i];
1734 MUTEX_EXIT(&aconn->conn_call_lock);
1739 /* Advertise a new service. A service is named locally by a UDP port
1740 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1743 char *serviceName; Name for identification purposes (e.g. the
1744 service name might be used for probing for
1747 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1748 char *serviceName, struct rx_securityClass **securityObjects,
1749 int nSecurityObjects,
1750 afs_int32(*serviceProc) (struct rx_call * acall))
1752 osi_socket socket = OSI_NULLSOCKET;
1753 struct rx_service *tservice;
1759 if (serviceId == 0) {
1761 "rx_NewService: service id for service %s is not non-zero.\n",
1768 "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",
1776 tservice = rxi_AllocService();
1779 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1781 for (i = 0; i < RX_MAX_SERVICES; i++) {
1782 struct rx_service *service = rx_services[i];
1784 if (port == service->servicePort && host == service->serviceHost) {
1785 if (service->serviceId == serviceId) {
1786 /* The identical service has already been
1787 * installed; if the caller was intending to
1788 * change the security classes used by this
1789 * service, he/she loses. */
1791 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1792 serviceName, serviceId, service->serviceName);
1794 rxi_FreeService(tservice);
1797 /* Different service, same port: re-use the socket
1798 * which is bound to the same port */
1799 socket = service->socket;
1802 if (socket == OSI_NULLSOCKET) {
1803 /* If we don't already have a socket (from another
1804 * service on same port) get a new one */
1805 socket = rxi_GetHostUDPSocket(host, port);
1806 if (socket == OSI_NULLSOCKET) {
1808 rxi_FreeService(tservice);
1813 service->socket = socket;
1814 service->serviceHost = host;
1815 service->servicePort = port;
1816 service->serviceId = serviceId;
1817 service->serviceName = serviceName;
1818 service->nSecurityObjects = nSecurityObjects;
1819 service->securityObjects = securityObjects;
1820 service->minProcs = 0;
1821 service->maxProcs = 1;
1822 service->idleDeadTime = 60;
1823 service->connDeadTime = rx_connDeadTime;
1824 service->executeRequestProc = serviceProc;
1825 service->checkReach = 0;
1826 service->nSpecific = 0;
1827 service->specific = NULL;
1828 rx_services[i] = service; /* not visible until now */
1834 rxi_FreeService(tservice);
1835 (osi_Msg "rx_NewService: cannot support > %d services\n",
1840 /* Set configuration options for all of a service's security objects */
1843 rx_SetSecurityConfiguration(struct rx_service *service,
1844 rx_securityConfigVariables type,
1849 for (i = 0; i<service->nSecurityObjects; i++) {
1850 if (service->securityObjects[i]) {
1851 code = RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1862 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1863 struct rx_securityClass **securityObjects, int nSecurityObjects,
1864 afs_int32(*serviceProc) (struct rx_call * acall))
1866 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1869 /* Generic request processing loop. This routine should be called
1870 * by the implementation dependent rx_ServerProc. If socketp is
1871 * non-null, it will be set to the file descriptor that this thread
1872 * is now listening on. If socketp is null, this routine will never
1875 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1877 struct rx_call *call;
1879 struct rx_service *tservice = NULL;
1886 call = rx_GetCall(threadID, tservice, socketp);
1887 if (socketp && *socketp != OSI_NULLSOCKET) {
1888 /* We are now a listener thread */
1894 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1895 #ifdef RX_ENABLE_LOCKS
1897 #endif /* RX_ENABLE_LOCKS */
1898 afs_termState = AFSOP_STOP_AFS;
1899 afs_osi_Wakeup(&afs_termState);
1900 #ifdef RX_ENABLE_LOCKS
1902 #endif /* RX_ENABLE_LOCKS */
1907 /* if server is restarting( typically smooth shutdown) then do not
1908 * allow any new calls.
1911 if (rx_tranquil && (call != NULL)) {
1915 MUTEX_ENTER(&call->lock);
1917 rxi_CallError(call, RX_RESTARTING);
1918 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1920 MUTEX_EXIT(&call->lock);
1925 tservice = call->conn->service;
1927 if (tservice->beforeProc)
1928 (*tservice->beforeProc) (call);
1930 code = tservice->executeRequestProc(call);
1932 if (tservice->afterProc)
1933 (*tservice->afterProc) (call, code);
1935 rx_EndCall(call, code);
1937 if (tservice->postProc)
1938 (*tservice->postProc) (code);
1940 if (rx_stats_active) {
1941 MUTEX_ENTER(&rx_stats_mutex);
1943 MUTEX_EXIT(&rx_stats_mutex);
1950 rx_WakeupServerProcs(void)
1952 struct rx_serverQueueEntry *np;
1953 struct opr_queue *cursor;
1957 MUTEX_ENTER(&rx_serverPool_lock);
1959 #ifdef RX_ENABLE_LOCKS
1960 if (rx_waitForPacket)
1961 CV_BROADCAST(&rx_waitForPacket->cv);
1962 #else /* RX_ENABLE_LOCKS */
1963 if (rx_waitForPacket)
1964 osi_rxWakeup(rx_waitForPacket);
1965 #endif /* RX_ENABLE_LOCKS */
1966 MUTEX_ENTER(&freeSQEList_lock);
1967 for (opr_queue_Scan(&rx_freeServerQueue, cursor)) {
1968 np = opr_queue_Entry(cursor, struct rx_serverQueueEntry, entry);
1969 #ifdef RX_ENABLE_LOCKS
1970 CV_BROADCAST(&np->cv);
1971 #else /* RX_ENABLE_LOCKS */
1973 #endif /* RX_ENABLE_LOCKS */
1975 MUTEX_EXIT(&freeSQEList_lock);
1976 for (opr_queue_Scan(&rx_idleServerQueue, cursor)) {
1977 np = opr_queue_Entry(cursor, struct rx_serverQueueEntry, entry);
1978 #ifdef RX_ENABLE_LOCKS
1979 CV_BROADCAST(&np->cv);
1980 #else /* RX_ENABLE_LOCKS */
1982 #endif /* RX_ENABLE_LOCKS */
1984 MUTEX_EXIT(&rx_serverPool_lock);
1989 * One thing that seems to happen is that all the server threads get
1990 * tied up on some empty or slow call, and then a whole bunch of calls
1991 * arrive at once, using up the packet pool, so now there are more
1992 * empty calls. The most critical resources here are server threads
1993 * and the free packet pool. The "doreclaim" code seems to help in
1994 * general. I think that eventually we arrive in this state: there
1995 * are lots of pending calls which do have all their packets present,
1996 * so they won't be reclaimed, are multi-packet calls, so they won't
1997 * be scheduled until later, and thus are tying up most of the free
1998 * packet pool for a very long time.
2000 * 1. schedule multi-packet calls if all the packets are present.
2001 * Probably CPU-bound operation, useful to return packets to pool.
2002 * Do what if there is a full window, but the last packet isn't here?
2003 * 3. preserve one thread which *only* runs "best" calls, otherwise
2004 * it sleeps and waits for that type of call.
2005 * 4. Don't necessarily reserve a whole window for each thread. In fact,
2006 * the current dataquota business is badly broken. The quota isn't adjusted
2007 * to reflect how many packets are presently queued for a running call.
2008 * So, when we schedule a queued call with a full window of packets queued
2009 * up for it, that *should* free up a window full of packets for other 2d-class
2010 * calls to be able to use from the packet pool. But it doesn't.
2012 * NB. Most of the time, this code doesn't run -- since idle server threads
2013 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
2014 * as a new call arrives.
2016 /* Sleep until a call arrives. Returns a pointer to the call, ready
2017 * for an rx_Read. */
2018 #ifdef RX_ENABLE_LOCKS
2020 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2022 struct rx_serverQueueEntry *sq;
2023 struct rx_call *call = (struct rx_call *)0;
2024 struct rx_service *service = NULL;
2026 MUTEX_ENTER(&freeSQEList_lock);
2028 if (!opr_queue_IsEmpty(&rx_freeServerQueue)) {
2029 sq = opr_queue_First(&rx_freeServerQueue, struct rx_serverQueueEntry,
2031 opr_queue_Remove(&sq->entry);
2032 MUTEX_EXIT(&freeSQEList_lock);
2033 } else { /* otherwise allocate a new one and return that */
2034 MUTEX_EXIT(&freeSQEList_lock);
2035 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2036 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2037 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2040 MUTEX_ENTER(&rx_serverPool_lock);
2041 if (cur_service != NULL) {
2042 ReturnToServerPool(cur_service);
2045 if (!opr_queue_IsEmpty(&rx_incomingCallQueue)) {
2046 struct rx_call *tcall, *choice2 = NULL;
2047 struct opr_queue *cursor;
2049 /* Scan for eligible incoming calls. A call is not eligible
2050 * if the maximum number of calls for its service type are
2051 * already executing */
2052 /* One thread will process calls FCFS (to prevent starvation),
2053 * while the other threads may run ahead looking for calls which
2054 * have all their input data available immediately. This helps
2055 * keep threads from blocking, waiting for data from the client. */
2056 for (opr_queue_Scan(&rx_incomingCallQueue, cursor)) {
2057 tcall = opr_queue_Entry(cursor, struct rx_call, entry);
2059 service = tcall->conn->service;
2060 if (!QuotaOK(service)) {
2063 MUTEX_ENTER(&rx_pthread_mutex);
2064 if (tno == rxi_fcfs_thread_num
2065 || opr_queue_IsLast(&rx_incomingCallQueue, cursor)) {
2066 MUTEX_EXIT(&rx_pthread_mutex);
2067 /* If we're the fcfs thread , then we'll just use
2068 * this call. If we haven't been able to find an optimal
2069 * choice, and we're at the end of the list, then use a
2070 * 2d choice if one has been identified. Otherwise... */
2071 call = (choice2 ? choice2 : tcall);
2072 service = call->conn->service;
2074 MUTEX_EXIT(&rx_pthread_mutex);
2075 if (!opr_queue_IsEmpty(&tcall->rq)) {
2076 struct rx_packet *rp;
2077 rp = opr_queue_First(&tcall->rq, struct rx_packet,
2079 if (rp->header.seq == 1) {
2081 || (rp->header.flags & RX_LAST_PACKET)) {
2083 } else if (rxi_2dchoice && !choice2
2084 && !(tcall->flags & RX_CALL_CLEARED)
2085 && (tcall->rprev > rxi_HardAckRate)) {
2095 ReturnToServerPool(service);
2101 opr_queue_Remove(&call->entry);
2102 MUTEX_EXIT(&rx_serverPool_lock);
2103 MUTEX_ENTER(&call->lock);
2104 CLEAR_CALL_QUEUE_LOCK(call);
2106 if (call->flags & RX_CALL_WAIT_PROC) {
2107 call->flags &= ~RX_CALL_WAIT_PROC;
2108 rx_atomic_dec(&rx_nWaiting);
2111 if (call->state != RX_STATE_PRECALL || call->error) {
2112 MUTEX_EXIT(&call->lock);
2113 MUTEX_ENTER(&rx_serverPool_lock);
2114 ReturnToServerPool(service);
2119 if (opr_queue_IsEmpty(&call->rq)
2120 || opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq != 1)
2121 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2125 /* If there are no eligible incoming calls, add this process
2126 * to the idle server queue, to wait for one */
2130 *socketp = OSI_NULLSOCKET;
2132 sq->socketp = socketp;
2133 opr_queue_Append(&rx_idleServerQueue, &sq->entry);
2134 #ifndef AFS_AIX41_ENV
2135 rx_waitForPacket = sq;
2136 #endif /* AFS_AIX41_ENV */
2138 CV_WAIT(&sq->cv, &rx_serverPool_lock);
2140 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2144 } while (!(call = sq->newcall)
2145 && !(socketp && *socketp != OSI_NULLSOCKET));
2146 if (opr_queue_IsOnQueue(&sq->entry)) {
2147 opr_queue_Remove(&sq->entry);
2149 MUTEX_EXIT(&rx_serverPool_lock);
2151 MUTEX_ENTER(&call->lock);
2157 MUTEX_ENTER(&freeSQEList_lock);
2158 opr_queue_Prepend(&rx_freeServerQueue, &sq->entry);
2159 MUTEX_EXIT(&freeSQEList_lock);
2162 clock_GetTime(&call->startTime);
2163 call->state = RX_STATE_ACTIVE;
2164 call->app.mode = RX_MODE_RECEIVING;
2165 #ifdef RX_KERNEL_TRACE
2166 if (ICL_SETACTIVE(afs_iclSetp)) {
2167 int glockOwner = ISAFS_GLOCK();
2170 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2171 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2178 rxi_calltrace(RX_CALL_START, call);
2179 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2180 call->conn->service->servicePort, call->conn->service->serviceId,
2183 MUTEX_EXIT(&call->lock);
2184 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
2186 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2191 #else /* RX_ENABLE_LOCKS */
2193 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2195 struct rx_serverQueueEntry *sq;
2196 struct rx_call *call = (struct rx_call *)0, *choice2;
2197 struct rx_service *service = NULL;
2201 MUTEX_ENTER(&freeSQEList_lock);
2203 if (!opr_queue_IsEmpty(&rx_freeServerQueue)) {
2204 sq = opr_queue_First(&rx_freeServerQueue, struct rx_serverQueueEntry,
2206 opr_queue_Remove(&sq->entry);
2207 MUTEX_EXIT(&freeSQEList_lock);
2208 } else { /* otherwise allocate a new one and return that */
2209 MUTEX_EXIT(&freeSQEList_lock);
2210 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2211 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2212 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2214 MUTEX_ENTER(&sq->lock);
2216 if (cur_service != NULL) {
2217 cur_service->nRequestsRunning--;
2218 MUTEX_ENTER(&rx_quota_mutex);
2219 if (cur_service->nRequestsRunning < cur_service->minProcs)
2222 MUTEX_EXIT(&rx_quota_mutex);
2224 if (!opr_queue_IsEmpty(&rx_incomingCallQueue)) {
2225 struct rx_call *tcall;
2226 struct opr_queue *cursor;
2227 /* Scan for eligible incoming calls. A call is not eligible
2228 * if the maximum number of calls for its service type are
2229 * already executing */
2230 /* One thread will process calls FCFS (to prevent starvation),
2231 * while the other threads may run ahead looking for calls which
2232 * have all their input data available immediately. This helps
2233 * keep threads from blocking, waiting for data from the client. */
2234 choice2 = (struct rx_call *)0;
2235 for (opr_queue_Scan(&rx_incomingCallQueue, cursor)) {
2236 tcall = opr_queue_Entry(cursor, struct rx_call, entry);
2237 service = tcall->conn->service;
2238 if (QuotaOK(service)) {
2239 MUTEX_ENTER(&rx_pthread_mutex);
2240 if (tno == rxi_fcfs_thread_num
2241 || opr_queue_IsLast(&rx_incomingCallQueue, cursor)) {
2242 MUTEX_EXIT(&rx_pthread_mutex);
2243 /* If we're the fcfs thread, then we'll just use
2244 * this call. If we haven't been able to find an optimal
2245 * choice, and we're at the end of the list, then use a
2246 * 2d choice if one has been identified. Otherwise... */
2247 call = (choice2 ? choice2 : tcall);
2248 service = call->conn->service;
2250 MUTEX_EXIT(&rx_pthread_mutex);
2251 if (!opr_queue_IsEmpty(&tcall->rq)) {
2252 struct rx_packet *rp;
2253 rp = opr_queue_First(&tcall->rq, struct rx_packet,
2255 if (rp->header.seq == 1
2257 || (rp->header.flags & RX_LAST_PACKET))) {
2259 } else if (rxi_2dchoice && !choice2
2260 && !(tcall->flags & RX_CALL_CLEARED)
2261 && (tcall->rprev > rxi_HardAckRate)) {
2274 opr_queue_Remove(&call->entry);
2275 CLEAR_CALL_QUEUE_LOCK(call);
2276 /* we can't schedule a call if there's no data!!! */
2277 /* send an ack if there's no data, if we're missing the
2278 * first packet, or we're missing something between first
2279 * and last -- there's a "hole" in the incoming data. */
2280 if (opr_queue_IsEmpty(&call->rq)
2281 || opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq != 1
2282 || call->rprev != opr_queue_Last(&call->rq, struct rx_packet, entry)->header.seq)
2283 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2285 call->flags &= (~RX_CALL_WAIT_PROC);
2286 service->nRequestsRunning++;
2287 /* just started call in minProcs pool, need fewer to maintain
2289 MUTEX_ENTER(&rx_quota_mutex);
2290 if (service->nRequestsRunning <= service->minProcs)
2293 MUTEX_EXIT(&rx_quota_mutex);
2294 rx_atomic_dec(&rx_nWaiting);
2295 /* MUTEX_EXIT(&call->lock); */
2297 /* If there are no eligible incoming calls, add this process
2298 * to the idle server queue, to wait for one */
2301 *socketp = OSI_NULLSOCKET;
2303 sq->socketp = socketp;
2304 opr_queue_Append(&rx_idleServerQueue, &sq->entry);
2308 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2310 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2311 return (struct rx_call *)0;
2314 } while (!(call = sq->newcall)
2315 && !(socketp && *socketp != OSI_NULLSOCKET));
2317 MUTEX_EXIT(&sq->lock);
2319 MUTEX_ENTER(&freeSQEList_lock);
2320 opr_queue_Prepend(&rx_freeServerQueue, &sq->entry);
2321 MUTEX_EXIT(&freeSQEList_lock);
2324 clock_GetTime(&call->startTime);
2325 call->state = RX_STATE_ACTIVE;
2326 call->app.mode = RX_MODE_RECEIVING;
2327 #ifdef RX_KERNEL_TRACE
2328 if (ICL_SETACTIVE(afs_iclSetp)) {
2329 int glockOwner = ISAFS_GLOCK();
2332 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2333 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2340 rxi_calltrace(RX_CALL_START, call);
2341 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2342 call->conn->service->servicePort, call->conn->service->serviceId,
2345 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2352 #endif /* RX_ENABLE_LOCKS */
2356 /* Establish a procedure to be called when a packet arrives for a
2357 * call. This routine will be called at most once after each call,
2358 * and will also be called if there is an error condition on the or
2359 * the call is complete. Used by multi rx to build a selection
2360 * function which determines which of several calls is likely to be a
2361 * good one to read from.
2362 * NOTE: the way this is currently implemented it is probably only a
2363 * good idea to (1) use it immediately after a newcall (clients only)
2364 * and (2) only use it once. Other uses currently void your warranty
2367 rx_SetArrivalProc(struct rx_call *call,
2368 void (*proc) (struct rx_call * call,
2371 void * handle, int arg)
2373 call->arrivalProc = proc;
2374 call->arrivalProcHandle = handle;
2375 call->arrivalProcArg = arg;
2378 /* Call is finished (possibly prematurely). Return rc to the peer, if
2379 * appropriate, and return the final error code from the conversation
2383 rx_EndCall(struct rx_call *call, afs_int32 rc)
2385 struct rx_connection *conn = call->conn;
2389 dpf(("rx_EndCall(call %p rc %d error %d abortCode %d)\n",
2390 call, rc, call->error, call->abortCode));
2393 MUTEX_ENTER(&call->lock);
2395 if (rc == 0 && call->error == 0) {
2396 call->abortCode = 0;
2397 call->abortCount = 0;
2400 call->arrivalProc = NULL;
2401 if (rc && call->error == 0) {
2402 rxi_CallError(call, rc);
2403 call->app.mode = RX_MODE_ERROR;
2404 /* Send an abort message to the peer if this error code has
2405 * only just been set. If it was set previously, assume the
2406 * peer has already been sent the error code or will request it
2408 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2410 if (conn->type == RX_SERVER_CONNECTION) {
2411 /* Make sure reply or at least dummy reply is sent */
2412 if (call->app.mode == RX_MODE_RECEIVING) {
2413 MUTEX_EXIT(&call->lock);
2414 rxi_WriteProc(call, 0, 0);
2415 MUTEX_ENTER(&call->lock);
2417 if (call->app.mode == RX_MODE_SENDING) {
2418 rxi_FlushWriteLocked(call);
2420 rxi_calltrace(RX_CALL_END, call);
2421 /* Call goes to hold state until reply packets are acknowledged */
2422 if (call->tfirst + call->nSoftAcked < call->tnext) {
2423 call->state = RX_STATE_HOLD;
2425 call->state = RX_STATE_DALLY;
2426 rxi_ClearTransmitQueue(call, 0);
2427 rxi_rto_cancel(call);
2428 rxi_CancelKeepAliveEvent(call);
2430 } else { /* Client connection */
2432 /* Make sure server receives input packets, in the case where
2433 * no reply arguments are expected */
2435 if ((call->app.mode == RX_MODE_SENDING)
2436 || (call->app.mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2437 MUTEX_EXIT(&call->lock);
2438 (void)rxi_ReadProc(call, &dummy, 1);
2439 MUTEX_ENTER(&call->lock);
2442 /* If we had an outstanding delayed ack, be nice to the server
2443 * and force-send it now.
2445 if (call->delayedAckEvent) {
2446 rxi_CancelDelayedAckEvent(call);
2447 rxi_SendDelayedAck(NULL, call, NULL, 0);
2450 /* We need to release the call lock since it's lower than the
2451 * conn_call_lock and we don't want to hold the conn_call_lock
2452 * over the rx_ReadProc call. The conn_call_lock needs to be held
2453 * here for the case where rx_NewCall is perusing the calls on
2454 * the connection structure. We don't want to signal until
2455 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2456 * have checked this call, found it active and by the time it
2457 * goes to sleep, will have missed the signal.
2459 MUTEX_EXIT(&call->lock);
2460 MUTEX_ENTER(&conn->conn_call_lock);
2461 MUTEX_ENTER(&call->lock);
2464 /* While there are some circumstances where a call with an error is
2465 * obviously not on a "busy" channel, be conservative (clearing
2466 * lastBusy is just best-effort to possibly speed up rx_NewCall).
2467 * The call channel is definitely not busy if we just successfully
2468 * completed a call on it. */
2469 conn->lastBusy[call->channel] = 0;
2471 } else if (call->error == RX_CALL_TIMEOUT) {
2472 /* The call is still probably running on the server side, so try to
2473 * avoid this call channel in the future. */
2474 conn->lastBusy[call->channel] = clock_Sec();
2477 MUTEX_ENTER(&conn->conn_data_lock);
2478 conn->flags |= RX_CONN_BUSY;
2479 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2480 MUTEX_EXIT(&conn->conn_data_lock);
2481 #ifdef RX_ENABLE_LOCKS
2482 CV_BROADCAST(&conn->conn_call_cv);
2487 #ifdef RX_ENABLE_LOCKS
2489 MUTEX_EXIT(&conn->conn_data_lock);
2491 #endif /* RX_ENABLE_LOCKS */
2492 call->state = RX_STATE_DALLY;
2494 error = call->error;
2496 /* currentPacket, nLeft, and NFree must be zeroed here, because
2497 * ResetCall cannot: ResetCall may be called at splnet(), in the
2498 * kernel version, and may interrupt the macros rx_Read or
2499 * rx_Write, which run at normal priority for efficiency. */
2500 if (call->app.currentPacket) {
2501 #ifdef RX_TRACK_PACKETS
2502 call->app.currentPacket->flags &= ~RX_PKTFLAG_CP;
2504 rxi_FreePacket(call->app.currentPacket);
2505 call->app.currentPacket = (struct rx_packet *)0;
2508 call->app.nLeft = call->app.nFree = call->app.curlen = 0;
2510 /* Free any packets from the last call to ReadvProc/WritevProc */
2511 #ifdef RXDEBUG_PACKET
2513 #endif /* RXDEBUG_PACKET */
2514 rxi_FreePackets(0, &call->app.iovq);
2515 MUTEX_EXIT(&call->lock);
2517 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2518 if (conn->type == RX_CLIENT_CONNECTION) {
2519 MUTEX_ENTER(&conn->conn_data_lock);
2520 conn->flags &= ~RX_CONN_BUSY;
2521 MUTEX_EXIT(&conn->conn_data_lock);
2522 MUTEX_EXIT(&conn->conn_call_lock);
2526 * Map errors to the local host's errno.h format.
2528 error = ntoh_syserr_conv(error);
2530 /* If the caller said the call failed with some error, we had better
2531 * return an error code. */
2532 osi_Assert(!rc || error);
2536 #if !defined(KERNEL)
2538 /* Call this routine when shutting down a server or client (especially
2539 * clients). This will allow Rx to gracefully garbage collect server
2540 * connections, and reduce the number of retries that a server might
2541 * make to a dead client.
2542 * This is not quite right, since some calls may still be ongoing and
2543 * we can't lock them to destroy them. */
2549 if (!rxi_IsRunning()) {
2551 return; /* Already shutdown. */
2553 rxi_Finalize_locked();
2558 rxi_Finalize_locked(void)
2560 struct rx_connection **conn_ptr, **conn_end;
2561 rx_atomic_set(&rxi_running, 0);
2562 rxi_DeleteCachedConnections();
2563 if (rx_connHashTable) {
2564 MUTEX_ENTER(&rx_connHashTable_lock);
2565 for (conn_ptr = &rx_connHashTable[0], conn_end =
2566 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2568 struct rx_connection *conn, *next;
2569 for (conn = *conn_ptr; conn; conn = next) {
2571 if (conn->type == RX_CLIENT_CONNECTION) {
2572 rx_GetConnection(conn);
2573 #ifdef RX_ENABLE_LOCKS
2574 rxi_DestroyConnectionNoLock(conn);
2575 #else /* RX_ENABLE_LOCKS */
2576 rxi_DestroyConnection(conn);
2577 #endif /* RX_ENABLE_LOCKS */
2581 #ifdef RX_ENABLE_LOCKS
2582 while (rx_connCleanup_list) {
2583 struct rx_connection *conn;
2584 conn = rx_connCleanup_list;
2585 rx_connCleanup_list = rx_connCleanup_list->next;
2586 MUTEX_EXIT(&rx_connHashTable_lock);
2587 rxi_CleanupConnection(conn);
2588 MUTEX_ENTER(&rx_connHashTable_lock);
2590 MUTEX_EXIT(&rx_connHashTable_lock);
2591 #endif /* RX_ENABLE_LOCKS */
2596 afs_winsockCleanup();
2601 /* if we wakeup packet waiter too often, can get in loop with two
2602 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2604 rxi_PacketsUnWait(void)
2606 if (!rx_waitingForPackets) {
2610 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2611 return; /* still over quota */
2614 rx_waitingForPackets = 0;
2615 #ifdef RX_ENABLE_LOCKS
2616 CV_BROADCAST(&rx_waitingForPackets_cv);
2618 osi_rxWakeup(&rx_waitingForPackets);
2624 /* ------------------Internal interfaces------------------------- */
2626 /* Return this process's service structure for the
2627 * specified socket and service */
2628 static struct rx_service *
2629 rxi_FindService(osi_socket socket, u_short serviceId)
2631 struct rx_service **sp;
2632 for (sp = &rx_services[0]; *sp; sp++) {
2633 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2639 #ifdef RXDEBUG_PACKET
2640 #ifdef KDUMP_RX_LOCK
2641 static struct rx_call_rx_lock *rx_allCallsp = 0;
2643 static struct rx_call *rx_allCallsp = 0;
2645 #endif /* RXDEBUG_PACKET */
2647 /* Allocate a call structure, for the indicated channel of the
2648 * supplied connection. The mode and state of the call must be set by
2649 * the caller. Returns the call with mutex locked. */
2650 static struct rx_call *
2651 rxi_NewCall(struct rx_connection *conn, int channel)
2653 struct rx_call *call;
2654 #ifdef RX_ENABLE_LOCKS
2655 struct rx_call *cp; /* Call pointer temp */
2656 struct opr_queue *cursor;
2659 dpf(("rxi_NewCall(conn %p, channel %d)\n", conn, channel));
2661 /* Grab an existing call structure, or allocate a new one.
2662 * Existing call structures are assumed to have been left reset by
2664 MUTEX_ENTER(&rx_freeCallQueue_lock);
2666 #ifdef RX_ENABLE_LOCKS
2668 * EXCEPT that the TQ might not yet be cleared out.
2669 * Skip over those with in-use TQs.
2672 for (opr_queue_Scan(&rx_freeCallQueue, cursor)) {
2673 cp = opr_queue_Entry(cursor, struct rx_call, entry);
2674 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2680 #else /* RX_ENABLE_LOCKS */
2681 if (!opr_queue_IsEmpty(&rx_freeCallQueue)) {
2682 call = opr_queue_First(&rx_freeCallQueue, struct rx_call, entry);
2683 #endif /* RX_ENABLE_LOCKS */
2684 opr_queue_Remove(&call->entry);
2685 if (rx_stats_active)
2686 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2687 MUTEX_EXIT(&rx_freeCallQueue_lock);
2688 MUTEX_ENTER(&call->lock);
2689 CLEAR_CALL_QUEUE_LOCK(call);
2690 #ifdef RX_ENABLE_LOCKS
2691 /* Now, if TQ wasn't cleared earlier, do it now. */
2692 rxi_WaitforTQBusy(call);
2693 if (call->flags & RX_CALL_TQ_CLEARME) {
2694 rxi_ClearTransmitQueue(call, 1);
2695 /*queue_Init(&call->tq);*/
2697 #endif /* RX_ENABLE_LOCKS */
2698 /* Bind the call to its connection structure */
2700 rxi_ResetCall(call, 1);
2703 call = rxi_Alloc(sizeof(struct rx_call));
2704 #ifdef RXDEBUG_PACKET
2705 call->allNextp = rx_allCallsp;
2706 rx_allCallsp = call;
2708 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2709 #else /* RXDEBUG_PACKET */
2710 rx_atomic_inc(&rx_stats.nCallStructs);
2711 #endif /* RXDEBUG_PACKET */
2713 MUTEX_EXIT(&rx_freeCallQueue_lock);
2714 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2715 MUTEX_ENTER(&call->lock);
2716 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2717 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2718 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2720 /* Initialize once-only items */
2721 opr_queue_Init(&call->tq);
2722 opr_queue_Init(&call->rq);
2723 opr_queue_Init(&call->app.iovq);
2724 #ifdef RXDEBUG_PACKET
2725 call->rqc = call->tqc = call->iovqc = 0;
2726 #endif /* RXDEBUG_PACKET */
2727 /* Bind the call to its connection structure (prereq for reset) */
2729 rxi_ResetCall(call, 1);
2731 call->channel = channel;
2732 call->callNumber = &conn->callNumber[channel];
2733 call->rwind = conn->rwind[channel];
2734 call->twind = conn->twind[channel];
2735 /* Note that the next expected call number is retained (in
2736 * conn->callNumber[i]), even if we reallocate the call structure
2738 conn->call[channel] = call;
2739 /* if the channel's never been used (== 0), we should start at 1, otherwise
2740 * the call number is valid from the last time this channel was used */
2741 if (*call->callNumber == 0)
2742 *call->callNumber = 1;
2747 /* A call has been inactive long enough that so we can throw away
2748 * state, including the call structure, which is placed on the call
2751 * call->lock amd rx_refcnt_mutex are held upon entry.
2752 * haveCTLock is set when called from rxi_ReapConnections.
2754 * return 1 if the call is freed, 0 if not.
2757 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2759 int channel = call->channel;
2760 struct rx_connection *conn = call->conn;
2761 u_char state = call->state;
2764 * We are setting the state to RX_STATE_RESET to
2765 * ensure that no one else will attempt to use this
2766 * call once we drop the refcnt lock. We must drop
2767 * the refcnt lock before calling rxi_ResetCall
2768 * because it cannot be held across acquiring the
2769 * freepktQ lock. NewCall does the same.
2771 call->state = RX_STATE_RESET;
2772 MUTEX_EXIT(&rx_refcnt_mutex);
2773 rxi_ResetCall(call, 0);
2775 if (MUTEX_TRYENTER(&conn->conn_call_lock))
2777 if (state == RX_STATE_DALLY || state == RX_STATE_HOLD)
2778 (*call->callNumber)++;
2780 if (call->conn->call[channel] == call)
2781 call->conn->call[channel] = 0;
2782 MUTEX_EXIT(&conn->conn_call_lock);
2785 * We couldn't obtain the conn_call_lock so we can't
2786 * disconnect the call from the connection. Set the
2787 * call state to dally so that the call can be reused.
2789 MUTEX_ENTER(&rx_refcnt_mutex);
2790 call->state = RX_STATE_DALLY;
2794 MUTEX_ENTER(&rx_freeCallQueue_lock);
2795 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2796 #ifdef RX_ENABLE_LOCKS
2797 /* A call may be free even though its transmit queue is still in use.
2798 * Since we search the call list from head to tail, put busy calls at
2799 * the head of the list, and idle calls at the tail.
2801 if (call->flags & RX_CALL_TQ_BUSY)
2802 opr_queue_Prepend(&rx_freeCallQueue, &call->entry);
2804 opr_queue_Append(&rx_freeCallQueue, &call->entry);
2805 #else /* RX_ENABLE_LOCKS */
2806 opr_queue_Append(&rx_freeCallQueue, &call->entry);
2807 #endif /* RX_ENABLE_LOCKS */
2808 if (rx_stats_active)
2809 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2810 MUTEX_EXIT(&rx_freeCallQueue_lock);
2812 /* Destroy the connection if it was previously slated for
2813 * destruction, i.e. the Rx client code previously called
2814 * rx_DestroyConnection (client connections), or
2815 * rxi_ReapConnections called the same routine (server
2816 * connections). Only do this, however, if there are no
2817 * outstanding calls. Note that for fine grain locking, there appears
2818 * to be a deadlock in that rxi_FreeCall has a call locked and
2819 * DestroyConnectionNoLock locks each call in the conn. But note a
2820 * few lines up where we have removed this call from the conn.
2821 * If someone else destroys a connection, they either have no
2822 * call lock held or are going through this section of code.
2824 MUTEX_ENTER(&conn->conn_data_lock);
2825 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2826 rx_GetConnection(conn);
2827 MUTEX_EXIT(&conn->conn_data_lock);
2828 #ifdef RX_ENABLE_LOCKS
2830 rxi_DestroyConnectionNoLock(conn);
2832 rxi_DestroyConnection(conn);
2833 #else /* RX_ENABLE_LOCKS */
2834 rxi_DestroyConnection(conn);
2835 #endif /* RX_ENABLE_LOCKS */
2837 MUTEX_EXIT(&conn->conn_data_lock);
2839 MUTEX_ENTER(&rx_refcnt_mutex);
2843 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2844 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2847 rxi_Alloc(size_t size)
2851 if (rx_stats_active) {
2852 rx_atomic_add(&rxi_Allocsize, (int) size);
2853 rx_atomic_inc(&rxi_Alloccnt);
2857 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD_ENV)
2858 afs_osi_Alloc_NoSleep(size);
2863 osi_Panic("rxi_Alloc error");
2869 rxi_Free(void *addr, size_t size)
2874 if (rx_stats_active) {
2875 rx_atomic_sub(&rxi_Allocsize, (int) size);
2876 rx_atomic_dec(&rxi_Alloccnt);
2878 osi_Free(addr, size);
2882 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2884 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2885 struct rx_peer *next = NULL;
2889 MUTEX_ENTER(&rx_peerHashTable_lock);
2891 peer_ptr = &rx_peerHashTable[0];
2892 peer_end = &rx_peerHashTable[rx_hashTableSize];
2895 for ( ; peer_ptr < peer_end; peer_ptr++) {
2898 for ( ; peer; peer = next) {
2900 if (host == peer->host)
2905 hashIndex = PEER_HASH(host, port);
2906 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2907 if ((peer->host == host) && (peer->port == port))
2912 MUTEX_ENTER(&rx_peerHashTable_lock);
2917 MUTEX_EXIT(&rx_peerHashTable_lock);
2919 MUTEX_ENTER(&peer->peer_lock);
2920 /* We don't handle dropping below min, so don't */
2921 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2922 peer->ifMTU=MIN(mtu, peer->ifMTU);
2923 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2924 /* if we tweaked this down, need to tune our peer MTU too */
2925 peer->MTU = MIN(peer->MTU, peer->natMTU);
2926 /* if we discovered a sub-1500 mtu, degrade */
2927 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2928 peer->maxDgramPackets = 1;
2929 /* We no longer have valid peer packet information */
2930 if (peer->maxPacketSize + RX_HEADER_SIZE > peer->ifMTU)
2931 peer->maxPacketSize = 0;
2932 MUTEX_EXIT(&peer->peer_lock);
2934 MUTEX_ENTER(&rx_peerHashTable_lock);
2936 if (host && !port) {
2938 /* pick up where we left off */
2942 MUTEX_EXIT(&rx_peerHashTable_lock);
2945 #ifdef AFS_RXERRQ_ENV
2947 rxi_SetPeerDead(struct sock_extended_err *err, afs_uint32 host, afs_uint16 port)
2949 int hashIndex = PEER_HASH(host, port);
2950 struct rx_peer *peer;
2952 MUTEX_ENTER(&rx_peerHashTable_lock);
2954 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2955 if (peer->host == host && peer->port == port) {
2961 MUTEX_EXIT(&rx_peerHashTable_lock);
2964 rx_atomic_inc(&peer->neterrs);
2965 MUTEX_ENTER(&peer->peer_lock);
2966 peer->last_err_origin = RX_NETWORK_ERROR_ORIGIN_ICMP;
2967 peer->last_err_type = err->ee_type;
2968 peer->last_err_code = err->ee_code;
2969 MUTEX_EXIT(&peer->peer_lock);
2971 MUTEX_ENTER(&rx_peerHashTable_lock);
2973 MUTEX_EXIT(&rx_peerHashTable_lock);
2978 rxi_ProcessNetError(struct sock_extended_err *err, afs_uint32 addr, afs_uint16 port)
2980 # ifdef AFS_ADAPT_PMTU
2981 if (err->ee_errno == EMSGSIZE && err->ee_info >= 68) {
2982 rxi_SetPeerMtu(NULL, addr, port, err->ee_info - RX_IPUDP_SIZE);
2986 if (err->ee_origin == SO_EE_ORIGIN_ICMP && err->ee_type == ICMP_DEST_UNREACH) {
2987 switch (err->ee_code) {
2988 case ICMP_NET_UNREACH:
2989 case ICMP_HOST_UNREACH:
2990 case ICMP_PORT_UNREACH:
2993 rxi_SetPeerDead(err, addr, port);
3000 rxi_TranslateICMP(int type, int code)
3003 case ICMP_DEST_UNREACH:
3005 case ICMP_NET_UNREACH:
3006 return "Destination Net Unreachable";
3007 case ICMP_HOST_UNREACH:
3008 return "Destination Host Unreachable";
3009 case ICMP_PROT_UNREACH:
3010 return "Destination Protocol Unreachable";
3011 case ICMP_PORT_UNREACH:
3012 return "Destination Port Unreachable";
3014 return "Destination Net Prohibited";
3016 return "Destination Host Prohibited";
3022 #endif /* AFS_RXERRQ_ENV */
3025 * Get the last network error for a connection
3027 * A "network error" here means an error retrieved from ICMP, or some other
3028 * mechanism outside of Rx that informs us of errors in network reachability.
3030 * If a peer associated with the given Rx connection has received a network
3031 * error recently, this function allows the caller to know what error
3032 * specifically occurred. This can be useful to know, since e.g. ICMP errors
3033 * can cause calls to that peer to be quickly aborted. So, this function can
3034 * help see why a call was aborted due to network errors.
3036 * If we have received traffic from a peer since the last network error, we
3037 * treat that peer as if we had not received an network error for it.
3039 * @param[in] conn The Rx connection to examine
3040 * @param[out] err_origin The origin of the last network error (e.g. ICMP);
3041 * one of the RX_NETWORK_ERROR_ORIGIN_* constants
3042 * @param[out] err_type The type of the last error
3043 * @param[out] err_code The code of the last error
3044 * @param[out] msg Human-readable error message, if applicable; NULL otherwise
3046 * @return If we have an error
3047 * @retval -1 No error to get; 'out' params are undefined
3048 * @retval 0 We have an error; 'out' params contain the last error
3051 rx_GetNetworkError(struct rx_connection *conn, int *err_origin, int *err_type,
3052 int *err_code, const char **msg)
3054 #ifdef AFS_RXERRQ_ENV
3055 struct rx_peer *peer = conn->peer;
3056 if (rx_atomic_read(&peer->neterrs)) {
3057 MUTEX_ENTER(&peer->peer_lock);
3058 *err_origin = peer->last_err_origin;
3059 *err_type = peer->last_err_type;
3060 *err_code = peer->last_err_code;
3061 MUTEX_EXIT(&peer->peer_lock);
3064 if (*err_origin == RX_NETWORK_ERROR_ORIGIN_ICMP) {
3065 *msg = rxi_TranslateICMP(*err_type, *err_code);
3074 /* Find the peer process represented by the supplied (host,port)
3075 * combination. If there is no appropriate active peer structure, a
3076 * new one will be allocated and initialized
3079 rxi_FindPeer(afs_uint32 host, u_short port, int create)
3083 hashIndex = PEER_HASH(host, port);
3084 MUTEX_ENTER(&rx_peerHashTable_lock);
3085 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
3086 if ((pp->host == host) && (pp->port == port))
3091 pp = rxi_AllocPeer(); /* This bzero's *pp */
3092 pp->host = host; /* set here or in InitPeerParams is zero */
3094 #ifdef AFS_RXERRQ_ENV
3095 rx_atomic_set(&pp->neterrs, 0);
3097 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
3098 opr_queue_Init(&pp->rpcStats);
3099 pp->next = rx_peerHashTable[hashIndex];
3100 rx_peerHashTable[hashIndex] = pp;
3101 rxi_InitPeerParams(pp);
3102 if (rx_stats_active)
3103 rx_atomic_inc(&rx_stats.nPeerStructs);
3109 MUTEX_EXIT(&rx_peerHashTable_lock);
3114 /* Find the connection at (host, port) started at epoch, and with the
3115 * given connection id. Creates the server connection if necessary.
3116 * The type specifies whether a client connection or a server
3117 * connection is desired. In both cases, (host, port) specify the
3118 * peer's (host, pair) pair. Client connections are not made
3119 * automatically by this routine. The parameter socket gives the
3120 * socket descriptor on which the packet was received. This is used,
3121 * in the case of server connections, to check that *new* connections
3122 * come via a valid (port, serviceId). Finally, the securityIndex
3123 * parameter must match the existing index for the connection. If a
3124 * server connection is created, it will be created using the supplied
3125 * index, if the index is valid for this service */
3126 static struct rx_connection *
3127 rxi_FindConnection(osi_socket socket, afs_uint32 host,
3128 u_short port, u_short serviceId, afs_uint32 cid,
3129 afs_uint32 epoch, int type, u_int securityIndex,
3130 int *unknownService)
3132 int hashindex, flag, i;
3134 struct rx_connection *conn;
3135 *unknownService = 0;
3136 hashindex = CONN_HASH(host, port, cid, epoch, type);
3137 MUTEX_ENTER(&rx_connHashTable_lock);
3138 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
3139 rx_connHashTable[hashindex],
3142 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
3143 && (epoch == conn->epoch)) {
3144 struct rx_peer *pp = conn->peer;
3145 if (securityIndex != conn->securityIndex) {
3146 /* this isn't supposed to happen, but someone could forge a packet
3147 * like this, and there seems to be some CM bug that makes this
3148 * happen from time to time -- in which case, the fileserver
3150 MUTEX_EXIT(&rx_connHashTable_lock);
3151 return (struct rx_connection *)0;
3153 if (pp->host == host && pp->port == port)
3155 if (type == RX_CLIENT_CONNECTION && pp->port == port)
3157 /* So what happens when it's a callback connection? */
3158 if ( /*type == RX_CLIENT_CONNECTION && */
3159 (conn->epoch & 0x80000000))
3163 /* the connection rxLastConn that was used the last time is not the
3164 ** one we are looking for now. Hence, start searching in the hash */
3166 conn = rx_connHashTable[hashindex];
3171 struct rx_service *service;
3172 if (type == RX_CLIENT_CONNECTION) {
3173 MUTEX_EXIT(&rx_connHashTable_lock);
3174 return (struct rx_connection *)0;
3176 service = rxi_FindService(socket, serviceId);
3177 if (!service || (securityIndex >= service->nSecurityObjects)
3178 || (service->securityObjects[securityIndex] == 0)) {
3179 MUTEX_EXIT(&rx_connHashTable_lock);
3180 *unknownService = 1;
3181 return (struct rx_connection *)0;
3183 conn = rxi_AllocConnection(); /* This bzero's the connection */
3184 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
3185 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
3186 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
3187 conn->next = rx_connHashTable[hashindex];
3188 rx_connHashTable[hashindex] = conn;
3189 conn->peer = rxi_FindPeer(host, port, 1);
3190 conn->type = RX_SERVER_CONNECTION;
3191 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
3192 conn->epoch = epoch;
3193 conn->cid = cid & RX_CIDMASK;
3194 conn->ackRate = RX_FAST_ACK_RATE;
3195 conn->service = service;
3196 conn->serviceId = serviceId;
3197 conn->securityIndex = securityIndex;
3198 conn->securityObject = service->securityObjects[securityIndex];
3199 conn->nSpecific = 0;
3200 conn->specific = NULL;
3201 rx_SetConnDeadTime(conn, service->connDeadTime);
3202 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
3203 for (i = 0; i < RX_MAXCALLS; i++) {
3204 conn->twind[i] = rx_initSendWindow;
3205 conn->rwind[i] = rx_initReceiveWindow;
3207 /* Notify security object of the new connection */
3208 code = RXS_NewConnection(conn->securityObject, conn);
3209 /* XXXX Connection timeout? */
3210 if (service->newConnProc)
3211 (*service->newConnProc) (conn);
3212 if (rx_stats_active)
3213 rx_atomic_inc(&rx_stats.nServerConns);
3216 rx_GetConnection(conn);
3218 rxLastConn = conn; /* store this connection as the last conn used */
3219 MUTEX_EXIT(&rx_connHashTable_lock);
3221 rxi_ConnectionError(conn, code);
3227 * Abort the call if the server is over the busy threshold. This
3228 * can be used without requiring a call structure be initialised,
3229 * or connected to a particular channel
3232 rxi_AbortIfServerBusy(osi_socket socket, struct rx_connection *conn,
3233 struct rx_packet *np)
3237 if ((rx_BusyThreshold > 0) &&
3238 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3239 MUTEX_ENTER(&conn->conn_data_lock);
3240 serial = ++conn->serial;
3241 MUTEX_EXIT(&conn->conn_data_lock);
3242 rxi_SendRawAbort(socket, conn->peer->host, conn->peer->port,
3243 serial, rx_BusyError, np, 0);
3244 if (rx_stats_active)
3245 rx_atomic_inc(&rx_stats.nBusies);
3252 static_inline struct rx_call *
3253 rxi_ReceiveClientCall(struct rx_packet *np, struct rx_connection *conn)
3256 struct rx_call *call;
3258 channel = np->header.cid & RX_CHANNELMASK;
3259 MUTEX_ENTER(&conn->conn_call_lock);
3260 call = conn->call[channel];
3261 if (np->header.type == RX_PACKET_TYPE_BUSY) {
3262 conn->lastBusy[channel] = clock_Sec();
3264 if (!call || conn->callNumber[channel] != np->header.callNumber) {
3265 MUTEX_EXIT(&conn->conn_call_lock);
3266 if (rx_stats_active)
3267 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3271 MUTEX_ENTER(&call->lock);
3272 MUTEX_EXIT(&conn->conn_call_lock);
3274 if ((call->state == RX_STATE_DALLY)
3275 && np->header.type == RX_PACKET_TYPE_ACK) {
3276 if (rx_stats_active)
3277 rx_atomic_inc(&rx_stats.ignorePacketDally);
3278 MUTEX_EXIT(&call->lock);
3285 static_inline struct rx_call *
3286 rxi_ReceiveServerCall(osi_socket socket, struct rx_packet *np,
3287 struct rx_connection *conn)
3290 struct rx_call *call;
3292 channel = np->header.cid & RX_CHANNELMASK;
3293 MUTEX_ENTER(&conn->conn_call_lock);
3294 call = conn->call[channel];
3297 if (rxi_AbortIfServerBusy(socket, conn, np)) {
3298 MUTEX_EXIT(&conn->conn_call_lock);
3302 call = rxi_NewCall(conn, channel); /* returns locked call */
3303 *call->callNumber = np->header.callNumber;
3304 MUTEX_EXIT(&conn->conn_call_lock);
3306 call->state = RX_STATE_PRECALL;
3307 clock_GetTime(&call->queueTime);
3308 call->app.bytesSent = 0;
3309 call->app.bytesRcvd = 0;
3310 rxi_KeepAliveOn(call);
3315 if (np->header.callNumber == conn->callNumber[channel]) {
3316 MUTEX_ENTER(&call->lock);
3317 MUTEX_EXIT(&conn->conn_call_lock);
3321 if (np->header.callNumber < conn->callNumber[channel]) {
3322 MUTEX_EXIT(&conn->conn_call_lock);
3323 if (rx_stats_active)
3324 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3328 MUTEX_ENTER(&call->lock);
3329 MUTEX_EXIT(&conn->conn_call_lock);
3331 /* Wait until the transmit queue is idle before deciding
3332 * whether to reset the current call. Chances are that the
3333 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3336 #ifdef RX_ENABLE_LOCKS
3337 if (call->state == RX_STATE_ACTIVE && !call->error) {
3338 rxi_WaitforTQBusy(call);
3339 /* If we entered error state while waiting,
3340 * must call rxi_CallError to permit rxi_ResetCall
3341 * to processed when the tqWaiter count hits zero.
3344 rxi_CallError(call, call->error);
3345 MUTEX_EXIT(&call->lock);
3349 #endif /* RX_ENABLE_LOCKS */
3350 /* If the new call cannot be taken right now send a busy and set
3351 * the error condition in this call, so that it terminates as
3352 * quickly as possible */
3353 if (call->state == RX_STATE_ACTIVE) {
3354 rxi_CallError(call, RX_CALL_DEAD);
3355 rxi_SendSpecial(call, conn, NULL, RX_PACKET_TYPE_BUSY,
3357 MUTEX_EXIT(&call->lock);
3361 if (rxi_AbortIfServerBusy(socket, conn, np)) {
3362 MUTEX_EXIT(&call->lock);
3366 rxi_ResetCall(call, 0);
3367 /* The conn_call_lock is not held but no one else should be
3368 * using this call channel while we are processing this incoming
3369 * packet. This assignment should be safe.
3371 *call->callNumber = np->header.callNumber;
3372 call->state = RX_STATE_PRECALL;
3373 clock_GetTime(&call->queueTime);
3374 call->app.bytesSent = 0;
3375 call->app.bytesRcvd = 0;
3376 rxi_KeepAliveOn(call);
3382 /* There are two packet tracing routines available for testing and monitoring
3383 * Rx. One is called just after every packet is received and the other is
3384 * called just before every packet is sent. Received packets, have had their
3385 * headers decoded, and packets to be sent have not yet had their headers
3386 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
3387 * containing the network address. Both can be modified. The return value, if
3388 * non-zero, indicates that the packet should be dropped. */
3390 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
3391 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
3393 /* A packet has been received off the interface. Np is the packet, socket is
3394 * the socket number it was received from (useful in determining which service
3395 * this packet corresponds to), and (host, port) reflect the host,port of the
3396 * sender. This call returns the packet to the caller if it is finished with
3397 * it, rather than de-allocating it, just as a small performance hack */
3400 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
3401 afs_uint32 host, u_short port, int *tnop,
3402 struct rx_call **newcallp)
3404 struct rx_call *call;
3405 struct rx_connection *conn;
3407 int unknownService = 0;
3411 struct rx_packet *tnp;
3414 /* We don't print out the packet until now because (1) the time may not be
3415 * accurate enough until now in the lwp implementation (rx_Listener only gets
3416 * the time after the packet is read) and (2) from a protocol point of view,
3417 * this is the first time the packet has been seen */
3418 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
3419 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
3420 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %p\n",
3421 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
3422 np->header.epoch, np->header.cid, np->header.callNumber,
3423 np->header.seq, np->header.flags, np));
3426 /* Account for connectionless packets */
3427 if (rx_stats_active &&
3428 ((np->header.type == RX_PACKET_TYPE_VERSION) ||
3429 (np->header.type == RX_PACKET_TYPE_DEBUG))) {
3430 struct rx_peer *peer;
3432 /* Try to look up the peer structure, but don't create one */
3433 peer = rxi_FindPeer(host, port, 0);
3435 /* Since this may not be associated with a connection, it may have
3436 * no refCount, meaning we could race with ReapConnections
3439 if (peer && (peer->refCount > 0)) {
3440 #ifdef AFS_RXERRQ_ENV
3441 if (rx_atomic_read(&peer->neterrs)) {
3442 rx_atomic_set(&peer->neterrs, 0);
3445 MUTEX_ENTER(&peer->peer_lock);
3446 peer->bytesReceived += np->length;
3447 MUTEX_EXIT(&peer->peer_lock);
3451 if (np->header.type == RX_PACKET_TYPE_VERSION) {
3452 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
3455 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
3456 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
3459 /* If an input tracer function is defined, call it with the packet and
3460 * network address. Note this function may modify its arguments. */
3461 if (rx_justReceived) {
3462 struct sockaddr_in addr;
3464 addr.sin_family = AF_INET;
3465 addr.sin_port = port;
3466 addr.sin_addr.s_addr = host;
3467 memset(&addr.sin_zero, 0, sizeof(addr.sin_zero));
3468 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
3469 addr.sin_len = sizeof(addr);
3471 drop = (*rx_justReceived) (np, &addr);
3472 /* drop packet if return value is non-zero */
3475 port = addr.sin_port; /* in case fcn changed addr */
3476 host = addr.sin_addr.s_addr;
3480 /* If packet was not sent by the client, then *we* must be the client */
3481 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
3482 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
3484 /* Find the connection (or fabricate one, if we're the server & if
3485 * necessary) associated with this packet */
3487 rxi_FindConnection(socket, host, port, np->header.serviceId,
3488 np->header.cid, np->header.epoch, type,
3489 np->header.securityIndex, &unknownService);
3491 /* To avoid having 2 connections just abort at each other,
3492 don't abort an abort. */
3494 if (unknownService && (np->header.type != RX_PACKET_TYPE_ABORT))
3495 rxi_SendRawAbort(socket, host, port, 0, RX_INVALID_OPERATION,
3500 #ifdef AFS_RXERRQ_ENV
3501 if (rx_atomic_read(&conn->peer->neterrs)) {
3502 rx_atomic_set(&conn->peer->neterrs, 0);
3506 /* If we're doing statistics, then account for the incoming packet */
3507 if (rx_stats_active) {
3508 MUTEX_ENTER(&conn->peer->peer_lock);
3509 conn->peer->bytesReceived += np->length;
3510 MUTEX_EXIT(&conn->peer->peer_lock);
3513 /* If the connection is in an error state, send an abort packet and ignore
3514 * the incoming packet */
3516 /* Don't respond to an abort packet--we don't want loops! */
3517 MUTEX_ENTER(&conn->conn_data_lock);
3518 if (np->header.type != RX_PACKET_TYPE_ABORT)
3519 np = rxi_SendConnectionAbort(conn, np, 1, 0);
3520 putConnection(conn);
3521 MUTEX_EXIT(&conn->conn_data_lock);
3525 /* Check for connection-only requests (i.e. not call specific). */
3526 if (np->header.callNumber == 0) {
3527 switch (np->header.type) {
3528 case RX_PACKET_TYPE_ABORT: {
3529 /* What if the supplied error is zero? */
3530 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
3531 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
3532 rxi_ConnectionError(conn, errcode);
3533 putConnection(conn);
3536 case RX_PACKET_TYPE_CHALLENGE:
3537 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
3538 putConnection(conn);
3540 case RX_PACKET_TYPE_RESPONSE:
3541 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
3542 putConnection(conn);
3544 case RX_PACKET_TYPE_PARAMS:
3545 case RX_PACKET_TYPE_PARAMS + 1:
3546 case RX_PACKET_TYPE_PARAMS + 2:
3547 /* ignore these packet types for now */
3548 putConnection(conn);
3552 /* Should not reach here, unless the peer is broken: send an
3554 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
3555 MUTEX_ENTER(&conn->conn_data_lock);
3556 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
3557 putConnection(conn);
3558 MUTEX_EXIT(&conn->conn_data_lock);
3563 if (type == RX_SERVER_CONNECTION)
3564 call = rxi_ReceiveServerCall(socket, np, conn);
3566 call = rxi_ReceiveClientCall(np, conn);
3569 putConnection(conn);
3573 MUTEX_ASSERT(&call->lock);
3574 /* Set remote user defined status from packet */
3575 call->remoteStatus = np->header.userStatus;
3577 /* Now do packet type-specific processing */
3578 switch (np->header.type) {
3579 case RX_PACKET_TYPE_DATA:
3580 /* If we're a client, and receiving a response, then all the packets
3581 * we transmitted packets are implicitly acknowledged. */
3582 if (type == RX_CLIENT_CONNECTION && !opr_queue_IsEmpty(&call->tq))
3583 rxi_AckAllInTransmitQueue(call);
3585 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3588 case RX_PACKET_TYPE_ACK:
3589 /* Respond immediately to ack packets requesting acknowledgement
3591 if (np->header.flags & RX_REQUEST_ACK) {
3593 (void)rxi_SendCallAbort(call, 0, 1, 0);
3595 (void)rxi_SendAck(call, 0, np->header.serial,
3596 RX_ACK_PING_RESPONSE, 1);
3598 np = rxi_ReceiveAckPacket(call, np, 1);
3600 case RX_PACKET_TYPE_ABORT: {
3601 /* An abort packet: reset the call, passing the error up to the user. */
3602 /* What if error is zero? */
3603 /* What if the error is -1? the application will treat it as a timeout. */
3604 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3605 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3606 rxi_CallError(call, errdata);
3607 MUTEX_EXIT(&call->lock);
3608 putConnection(conn);
3609 return np; /* xmitting; drop packet */
3611 case RX_PACKET_TYPE_BUSY:
3612 /* Mostly ignore BUSY packets. We will update lastReceiveTime below,
3613 * so we don't think the endpoint is completely dead, but otherwise
3614 * just act as if we never saw anything. If all we get are BUSY packets
3615 * back, then we will eventually error out with RX_CALL_TIMEOUT if the
3616 * connection is configured with idle/hard timeouts. */
3619 case RX_PACKET_TYPE_ACKALL:
3620 /* All packets acknowledged, so we can drop all packets previously
3621 * readied for sending */
3622 rxi_AckAllInTransmitQueue(call);
3625 /* Should not reach here, unless the peer is broken: send an abort
3627 rxi_CallError(call, RX_PROTOCOL_ERROR);
3628 np = rxi_SendCallAbort(call, np, 1, 0);
3631 /* Note when this last legitimate packet was received, for keep-alive
3632 * processing. Note, we delay getting the time until now in the hope that
3633 * the packet will be delivered to the user before any get time is required
3634 * (if not, then the time won't actually be re-evaluated here). */
3635 call->lastReceiveTime = clock_Sec();
3636 MUTEX_EXIT(&call->lock);
3637 putConnection(conn);
3641 /* return true if this is an "interesting" connection from the point of view
3642 of someone trying to debug the system */
3644 rxi_IsConnInteresting(struct rx_connection *aconn)
3647 struct rx_call *tcall;
3649 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3652 for (i = 0; i < RX_MAXCALLS; i++) {
3653 tcall = aconn->call[i];
3655 if ((tcall->state == RX_STATE_PRECALL)
3656 || (tcall->state == RX_STATE_ACTIVE))
3658 if ((tcall->app.mode == RX_MODE_SENDING)
3659 || (tcall->app.mode == RX_MODE_RECEIVING))
3667 /* if this is one of the last few packets AND it wouldn't be used by the
3668 receiving call to immediately satisfy a read request, then drop it on
3669 the floor, since accepting it might prevent a lock-holding thread from
3670 making progress in its reading. If a call has been cleared while in
3671 the precall state then ignore all subsequent packets until the call
3672 is assigned to a thread. */
3675 TooLow(struct rx_packet *ap, struct rx_call *acall)
3679 MUTEX_ENTER(&rx_quota_mutex);
3680 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3681 && (acall->state == RX_STATE_PRECALL))
3682 || ((rx_nFreePackets < rxi_dataQuota + 2)
3683 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3684 && (acall->flags & RX_CALL_READER_WAIT)))) {
3687 MUTEX_EXIT(&rx_quota_mutex);
3693 * Clear the attach wait flag on a connection and proceed.
3695 * Any processing waiting for a connection to be attached should be
3696 * unblocked. We clear the flag and do any other needed tasks.
3699 * the conn to unmark waiting for attach
3701 * @pre conn's conn_data_lock must be locked before calling this function
3705 rxi_ConnClearAttachWait(struct rx_connection *conn)
3707 /* Indicate that rxi_CheckReachEvent is no longer running by
3708 * clearing the flag. Must be atomic under conn_data_lock to
3709 * avoid a new call slipping by: rxi_CheckConnReach holds
3710 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3712 conn->flags &= ~RX_CONN_ATTACHWAIT;
3713 if (conn->flags & RX_CONN_NAT_PING) {
3714 conn->flags &= ~RX_CONN_NAT_PING;
3715 rxi_ScheduleNatKeepAliveEvent(conn);
3720 * Event handler function for connection-specific events for checking
3721 * reachability. Also called directly from main code with |event| == NULL
3722 * in order to trigger the initial reachability check.
3724 * When |event| == NULL, must be called with the connection data lock held,
3725 * but returns with the lock unlocked.
3728 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2, int dummy)
3730 struct rx_connection *conn = arg1;
3731 struct rx_call *acall = arg2;
3732 struct rx_call *call = acall;
3733 struct clock when, now;
3737 MUTEX_ENTER(&conn->conn_data_lock);
3739 MUTEX_ASSERT(&conn->conn_data_lock);
3741 if (event != NULL && event == conn->checkReachEvent)
3742 rxevent_Put(&conn->checkReachEvent);
3743 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3744 MUTEX_EXIT(&conn->conn_data_lock);
3748 MUTEX_ENTER(&conn->conn_call_lock);
3749 MUTEX_ENTER(&conn->conn_data_lock);
3750 for (i = 0; i < RX_MAXCALLS; i++) {
3751 struct rx_call *tc = conn->call[i];
3752 if (tc && tc->state == RX_STATE_PRECALL) {
3758 rxi_ConnClearAttachWait(conn);
3759 MUTEX_EXIT(&conn->conn_data_lock);
3760 MUTEX_EXIT(&conn->conn_call_lock);
3765 MUTEX_ENTER(&call->lock);
3766 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3768 MUTEX_EXIT(&call->lock);
3770 clock_GetTime(&now);
3772 when.sec += RX_CHECKREACH_TIMEOUT;
3773 MUTEX_ENTER(&conn->conn_data_lock);
3774 if (!conn->checkReachEvent) {
3775 rx_GetConnection(conn);
3776 conn->checkReachEvent = rxevent_Post(&when, &now,
3777 rxi_CheckReachEvent, conn,