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 int *tnop, struct rx_call **newcallp);
135 static struct rx_packet
136 *rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
137 int istack, int *a_invalid);
138 static struct rx_packet
139 *rxi_ReceiveResponsePacket(struct rx_connection *conn,
140 struct rx_packet *np, int istack);
141 static struct rx_packet
142 *rxi_ReceiveChallengePacket(struct rx_connection *conn,
143 struct rx_packet *np, int istack);
144 static void rxi_AttachServerProc(struct rx_call *call, osi_socket socket,
145 int *tnop, struct rx_call **newcallp);
146 static void rxi_ClearTransmitQueue(struct rx_call *call, int force);
147 static void rxi_ClearReceiveQueue(struct rx_call *call);
148 static void rxi_ResetCall(struct rx_call *call, int newcall);
149 static void rxi_ScheduleKeepAliveEvent(struct rx_call *call);
150 static void rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn);
151 static void rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs);
152 static void rxi_KeepAliveOn(struct rx_call *call);
153 static void rxi_GrowMTUOn(struct rx_call *call);
154 static int rxi_ChallengeOn(struct rx_connection *conn);
155 static int rxi_CheckCall(struct rx_call *call, int haveCTLock);
156 static void rxi_AckAllInTransmitQueue(struct rx_call *call);
157 static void rxi_CancelKeepAliveEvent(struct rx_call *call);
158 static void rxi_CancelDelayedAbortEvent(struct rx_call *call);
159 static void rxi_CancelGrowMTUEvent(struct rx_call *call);
160 static void update_nextCid(void);
163 static void rxi_Finalize_locked(void);
164 #elif defined(UKERNEL)
165 # define rxi_Finalize_locked() do { } while (0)
168 #ifdef RX_ENABLE_LOCKS
170 rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
171 rx_atomic_t rxi_start_in_error;
173 #endif /* RX_ENABLE_LOCKS */
175 /* Constant delay time before sending an acknowledge of the last packet
176 * received. This is to avoid sending an extra acknowledge when the
177 * client is about to make another call, anyway, or the server is
180 * The lastAckDelay may not exceeed 400ms without causing peers to
181 * unecessarily timeout.
183 struct clock rx_lastAckDelay = {0, 400000};
185 /* Constant delay time before sending a soft ack when none was requested.
186 * This is to make sure we send soft acks before the sender times out,
187 * Normally we wait and send a hard ack when the receiver consumes the packet
189 * This value has been 100ms in all shipping versions of OpenAFS. Changing it
190 * will require changes to the peer's RTT calculations.
192 struct clock rx_softAckDelay = {0, 100000};
195 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
196 * currently allocated within rx. This number is used to allocate the
197 * memory required to return the statistics when queried.
198 * Protected by the rx_rpc_stats mutex.
201 static unsigned int rxi_rpc_peer_stat_cnt;
204 * rxi_rpc_process_stat_cnt counts the total number of local process stat
205 * structures currently allocated within rx. The number is used to allocate
206 * the memory required to return the statistics when queried.
207 * Protected by the rx_rpc_stats mutex.
210 static unsigned int rxi_rpc_process_stat_cnt;
212 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
213 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
215 /* Incoming calls wait on this queue when there are no available
216 * server processes */
217 struct opr_queue rx_incomingCallQueue;
219 /* Server processes wait on this queue when there are no appropriate
220 * calls to process */
221 struct opr_queue rx_idleServerQueue;
223 /* List of free rx_serverQueueEntry structs */
224 struct opr_queue rx_freeServerQueue;
226 #if !defined(offsetof)
227 #include <stddef.h> /* for definition of offsetof() */
230 #ifdef RX_ENABLE_LOCKS
231 afs_kmutex_t rx_atomic_mutex;
232 static afs_kmutex_t freeSQEList_lock;
235 /* Forward prototypes */
236 static struct rx_call * rxi_NewCall(struct rx_connection *, int);
239 putConnection (struct rx_connection *conn) {
240 MUTEX_ENTER(&rx_refcnt_mutex);
242 MUTEX_EXIT(&rx_refcnt_mutex);
245 #ifdef AFS_PTHREAD_ENV
248 * Use procedural initialization of mutexes/condition variables
252 extern afs_kmutex_t rx_quota_mutex;
253 extern afs_kmutex_t rx_pthread_mutex;
254 extern afs_kmutex_t rx_packets_mutex;
255 extern afs_kmutex_t rx_refcnt_mutex;
256 extern afs_kmutex_t des_init_mutex;
257 extern afs_kmutex_t des_random_mutex;
259 extern afs_kmutex_t rx_clock_mutex;
260 extern afs_kmutex_t rxi_connCacheMutex;
261 extern afs_kmutex_t event_handler_mutex;
262 extern afs_kmutex_t listener_mutex;
263 extern afs_kmutex_t rx_if_init_mutex;
264 extern afs_kmutex_t rx_if_mutex;
266 extern afs_kcondvar_t rx_event_handler_cond;
267 extern afs_kcondvar_t rx_listener_cond;
270 static afs_kmutex_t epoch_mutex;
271 static afs_kmutex_t rx_init_mutex;
272 static afs_kmutex_t rx_debug_mutex;
273 static afs_kmutex_t rx_rpc_stats;
276 rxi_InitPthread(void)
278 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
279 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
280 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
281 MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
283 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
284 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
285 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
286 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
287 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
288 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
290 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
291 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
292 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
293 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
294 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
297 CV_INIT(&rx_event_handler_cond, "evhand", CV_DEFAULT, 0);
298 CV_INIT(&rx_listener_cond, "rxlisten", CV_DEFAULT, 0);
301 osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
302 osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
304 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
305 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
306 MUTEX_INIT(&rx_mallocedPktQ_lock, "rx_mallocedPktQ_lock", MUTEX_DEFAULT,
309 #ifdef RX_ENABLE_LOCKS
312 #endif /* RX_LOCKS_DB */
313 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
314 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
316 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
318 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
320 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
322 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
324 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
326 #endif /* RX_ENABLE_LOCKS */
329 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
330 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
332 * The rx_stats_mutex mutex protects the following global variables:
333 * rxi_lowConnRefCount
334 * rxi_lowPeerRefCount
343 * The rx_quota_mutex mutex protects the following global variables:
351 * The rx_freePktQ_lock protects the following global variables:
356 * The rx_packets_mutex mutex protects the following global variables:
364 * The rx_pthread_mutex mutex protects the following global variables:
365 * rxi_fcfs_thread_num
368 #define INIT_PTHREAD_LOCKS
372 /* Variables for handling the minProcs implementation. availProcs gives the
373 * number of threads available in the pool at this moment (not counting dudes
374 * executing right now). totalMin gives the total number of procs required
375 * for handling all minProcs requests. minDeficit is a dynamic variable
376 * tracking the # of procs required to satisfy all of the remaining minProcs
378 * For fine grain locking to work, the quota check and the reservation of
379 * a server thread has to come while rxi_availProcs and rxi_minDeficit
380 * are locked. To this end, the code has been modified under #ifdef
381 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
382 * same time. A new function, ReturnToServerPool() returns the allocation.
384 * A call can be on several queue's (but only one at a time). When
385 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
386 * that no one else is touching the queue. To this end, we store the address
387 * of the queue lock in the call structure (under the call lock) when we
388 * put the call on a queue, and we clear the call_queue_lock when the
389 * call is removed from a queue (once the call lock has been obtained).
390 * This allows rxi_ResetCall to safely synchronize with others wishing
391 * to manipulate the queue.
394 #if defined(RX_ENABLE_LOCKS)
395 static afs_kmutex_t rx_rpc_stats;
398 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
399 ** pretty good that the next packet coming in is from the same connection
400 ** as the last packet, since we're send multiple packets in a transmit window.
402 struct rx_connection *rxLastConn = 0;
404 #ifdef RX_ENABLE_LOCKS
405 /* The locking hierarchy for rx fine grain locking is composed of these
408 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
409 * also protects updates to rx_nextCid
410 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
411 * call->lock - locks call data fields.
412 * These are independent of each other:
413 * rx_freeCallQueue_lock
418 * serverQueueEntry->lock
419 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
421 * peer->lock - locks peer data fields.
422 * conn_data_lock - that more than one thread is not updating a conn data
423 * field at the same time.
434 * Do we need a lock to protect the peer field in the conn structure?
435 * conn->peer was previously a constant for all intents and so has no
436 * lock protecting this field. The multihomed client delta introduced
437 * a RX code change : change the peer field in the connection structure
438 * to that remote interface from which the last packet for this
439 * connection was sent out. This may become an issue if further changes
442 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
443 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
445 /* rxdb_fileID is used to identify the lock location, along with line#. */
446 static int rxdb_fileID = RXDB_FILE_RX;
447 #endif /* RX_LOCKS_DB */
448 #else /* RX_ENABLE_LOCKS */
449 #define SET_CALL_QUEUE_LOCK(C, L)
450 #define CLEAR_CALL_QUEUE_LOCK(C)
451 #endif /* RX_ENABLE_LOCKS */
452 struct rx_serverQueueEntry *rx_waitForPacket = 0;
455 * This mutex serializes calls to our initialization and shutdown routines
456 * (rx_InitHost, rx_Finalize and shutdown_rx). Only one thread can be running
457 * these at any time; all other threads must wait for it to finish running, and
458 * then examine the value of rxi_running afterwards.
460 #ifdef AFS_PTHREAD_ENV
461 # define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
462 # define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
464 # define LOCK_RX_INIT
465 # define UNLOCK_RX_INIT
468 /* ------------Exported Interfaces------------- */
470 static rx_atomic_t rxi_running = RX_ATOMIC_INIT(0);
474 return rx_atomic_read(&rxi_running);
477 /* Initialize rx. A port number may be mentioned, in which case this
478 * becomes the default port number for any service installed later.
479 * If 0 is provided for the port number, a random port will be chosen
480 * by the kernel. Whether this will ever overlap anything in
481 * /etc/services is anybody's guess... Returns 0 on success, -1 on
484 rx_InitHost(u_int host, u_int port)
491 char *htable, *ptable;
497 if (rxi_IsRunning()) {
499 return 0; /* already started */
505 if (afs_winsockInit() < 0)
511 * Initialize anything necessary to provide a non-premptive threading
514 rxi_InitializeThreadSupport();
517 /* Allocate and initialize a socket for client and perhaps server
520 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
521 if (rx_socket == OSI_NULLSOCKET) {
524 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
527 #endif /* RX_LOCKS_DB */
528 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
529 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
530 MUTEX_INIT(&rx_atomic_mutex, "rx_atomic_mutex", MUTEX_DEFAULT, 0);
531 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
532 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
533 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
534 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
535 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
536 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
537 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
539 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
541 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
543 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
545 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
546 MUTEX_INIT(&rx_mallocedPktQ_lock, "rx_mallocedPktQ_lock", MUTEX_DEFAULT,
549 #if defined(AFS_HPUX110_ENV)
551 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
552 #endif /* AFS_HPUX110_ENV */
553 #endif /* RX_ENABLE_LOCKS && KERNEL */
556 rx_connDeadTime = 12;
557 rx_tranquil = 0; /* reset flag */
558 rxi_ResetStatistics();
559 htable = osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
560 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
561 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
562 ptable = osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
563 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
564 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
566 /* Malloc up a bunch of packets & buffers */
568 opr_queue_Init(&rx_freePacketQueue);
569 rxi_NeedMorePackets = FALSE;
570 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
571 opr_queue_Init(&rx_mallocedPacketQueue);
573 /* enforce a minimum number of allocated packets */
574 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
575 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
577 /* allocate the initial free packet pool */
578 #ifdef RX_ENABLE_TSFPQ
579 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
580 #else /* RX_ENABLE_TSFPQ */
581 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
582 #endif /* RX_ENABLE_TSFPQ */
589 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
590 tv.tv_sec = clock_now.sec;
591 tv.tv_usec = clock_now.usec;
592 srand((unsigned int)tv.tv_usec);
599 #if defined(KERNEL) && !defined(UKERNEL)
600 /* Really, this should never happen in a real kernel */
603 struct sockaddr_in addr;
605 int addrlen = sizeof(addr);
607 socklen_t addrlen = sizeof(addr);
609 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
610 rxi_Finalize_locked();
611 osi_Free(htable, rx_hashTableSize * sizeof(struct rx_connection *));
614 rx_port = addr.sin_port;
617 rx_stats.minRtt.sec = 9999999;
618 if (RAND_bytes(&rx_epoch, sizeof(rx_epoch)) != 1)
620 rx_epoch = (rx_epoch & ~0x40000000) | 0x80000000;
621 if (RAND_bytes(&rx_nextCid, sizeof(rx_nextCid)) != 1)
623 rx_nextCid &= RX_CIDMASK;
624 MUTEX_ENTER(&rx_quota_mutex);
625 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
626 MUTEX_EXIT(&rx_quota_mutex);
627 rx_connHashTable = (struct rx_connection **)htable;
628 rx_peerHashTable = (struct rx_peer **)ptable;
630 rx_hardAckDelay.sec = 0;
631 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
633 rxevent_Init(20, rxi_ReScheduleEvents);
635 /* Initialize various global queues */
636 opr_queue_Init(&rx_idleServerQueue);
637 opr_queue_Init(&rx_freeServerQueue);
638 opr_queue_Init(&rx_incomingCallQueue);
639 opr_queue_Init(&rx_freeCallQueue);
641 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
642 /* Initialize our list of usable IP addresses. */
646 /* Start listener process (exact function is dependent on the
647 * implementation environment--kernel or user space) */
652 rx_atomic_set(&rxi_running, 1);
669 return rx_InitHost(htonl(INADDR_ANY), port);
675 * The rxi_rto functions implement a TCP (RFC2988) style algorithm for
676 * maintaing the round trip timer.
681 * Start a new RTT timer for a given call and packet.
683 * There must be no resendEvent already listed for this call, otherwise this
684 * will leak events - intended for internal use within the RTO code only
687 * the RX call to start the timer for
688 * @param[in] lastPacket
689 * a flag indicating whether the last packet has been sent or not
691 * @pre call must be locked before calling this function
695 rxi_rto_startTimer(struct rx_call *call, int lastPacket, int istack)
697 struct clock now, retryTime;
699 MUTEX_ASSERT(&call->lock);
703 clock_Add(&retryTime, &call->rto);
705 /* If we're sending the last packet, and we're the client, then the server
706 * may wait for an additional 400ms before returning the ACK, wait for it
707 * rather than hitting a timeout */
708 if (lastPacket && call->conn->type == RX_CLIENT_CONNECTION)
709 clock_Addmsec(&retryTime, 400);
711 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
712 call->resendEvent = rxevent_Post(&retryTime, &now, rxi_Resend,
717 * Cancel an RTT timer for a given call.
721 * the RX call to cancel the timer for
723 * @pre call must be locked before calling this function
728 rxi_rto_cancel(struct rx_call *call)
730 MUTEX_ASSERT(&call->lock);
731 if (rxevent_Cancel(&call->resendEvent))
732 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
736 * Tell the RTO timer that we have sent a packet.
738 * If the timer isn't already running, then start it. If the timer is running,
742 * the RX call that the packet has been sent on
743 * @param[in] lastPacket
744 * A flag which is true if this is the last packet for the call
746 * @pre The call must be locked before calling this function
751 rxi_rto_packet_sent(struct rx_call *call, int lastPacket, int istack)
753 if (call->resendEvent)
756 rxi_rto_startTimer(call, lastPacket, istack);
760 * Tell the RTO timer that we have received an new ACK message
762 * This function should be called whenever a call receives an ACK that
763 * acknowledges new packets. Whatever happens, we stop the current timer.
764 * If there are unacked packets in the queue which have been sent, then
765 * we restart the timer from now. Otherwise, we leave it stopped.
768 * the RX call that the ACK has been received on
772 rxi_rto_packet_acked(struct rx_call *call, int istack)
774 struct opr_queue *cursor;
776 rxi_rto_cancel(call);
778 if (opr_queue_IsEmpty(&call->tq))
781 for (opr_queue_Scan(&call->tq, cursor)) {
782 struct rx_packet *p = opr_queue_Entry(cursor, struct rx_packet, entry);
783 if (p->header.seq > call->tfirst + call->twind)
786 if (!(p->flags & RX_PKTFLAG_ACKED) && p->flags & RX_PKTFLAG_SENT) {
787 rxi_rto_startTimer(call, p->header.flags & RX_LAST_PACKET, istack);
795 * Set an initial round trip timeout for a peer connection
797 * @param[in] secs The timeout to set in seconds
801 rx_rto_setPeerTimeoutSecs(struct rx_peer *peer, int secs) {
802 peer->rtt = secs * 8000;
806 * Set a delayed ack event on the specified call for the given time
808 * @param[in] call - the call on which to set the event
809 * @param[in] offset - the delay from now after which the event fires
812 rxi_PostDelayedAckEvent(struct rx_call *call, struct clock *offset)
814 struct clock now, when;
816 MUTEX_ASSERT(&call->lock);
819 clock_Add(&when, offset);
821 if (clock_Gt(&call->delayedAckTime, &when) &&
822 rxevent_Cancel(&call->delayedAckEvent)) {
823 /* We successfully cancelled an event too far in the future to install
824 * our new one; we can reuse the reference on the call. */
825 call->delayedAckEvent = rxevent_Post(&when, &now, rxi_SendDelayedAck,
828 call->delayedAckTime = when;
829 } else if (call->delayedAckEvent == NULL) {
830 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
831 call->delayedAckEvent = rxevent_Post(&when, &now,
834 call->delayedAckTime = when;
839 rxi_CancelDelayedAckEvent(struct rx_call *call)
841 MUTEX_ASSERT(&call->lock);
842 /* Only drop the ref if we cancelled it before it could run. */
843 if (rxevent_Cancel(&call->delayedAckEvent))
844 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
847 /* called with unincremented nRequestsRunning to see if it is OK to start
848 * a new thread in this service. Could be "no" for two reasons: over the
849 * max quota, or would prevent others from reaching their min quota.
851 #ifdef RX_ENABLE_LOCKS
852 /* This verion of QuotaOK reserves quota if it's ok while the
853 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
856 QuotaOK(struct rx_service *aservice)
858 /* check if over max quota */
859 if (aservice->nRequestsRunning >= aservice->maxProcs) {
863 /* under min quota, we're OK */
864 /* otherwise, can use only if there are enough to allow everyone
865 * to go to their min quota after this guy starts.
868 MUTEX_ENTER(&rx_quota_mutex);
869 if ((aservice->nRequestsRunning < aservice->minProcs)
870 || (rxi_availProcs > rxi_minDeficit)) {
871 aservice->nRequestsRunning++;
872 /* just started call in minProcs pool, need fewer to maintain
874 if (aservice->nRequestsRunning <= aservice->minProcs)
877 MUTEX_EXIT(&rx_quota_mutex);
880 MUTEX_EXIT(&rx_quota_mutex);
886 ReturnToServerPool(struct rx_service *aservice)
888 aservice->nRequestsRunning--;
889 MUTEX_ENTER(&rx_quota_mutex);
890 if (aservice->nRequestsRunning < aservice->minProcs)
893 MUTEX_EXIT(&rx_quota_mutex);
896 #else /* RX_ENABLE_LOCKS */
898 QuotaOK(struct rx_service *aservice)
901 /* under min quota, we're OK */
902 if (aservice->nRequestsRunning < aservice->minProcs)
905 /* check if over max quota */
906 if (aservice->nRequestsRunning >= aservice->maxProcs)
909 /* otherwise, can use only if there are enough to allow everyone
910 * to go to their min quota after this guy starts.
912 MUTEX_ENTER(&rx_quota_mutex);
913 if (rxi_availProcs > rxi_minDeficit)
915 MUTEX_EXIT(&rx_quota_mutex);
918 #endif /* RX_ENABLE_LOCKS */
921 /* Called by rx_StartServer to start up lwp's to service calls.
922 NExistingProcs gives the number of procs already existing, and which
923 therefore needn't be created. */
925 rxi_StartServerProcs(int nExistingProcs)
927 struct rx_service *service;
932 /* For each service, reserve N processes, where N is the "minimum"
933 * number of processes that MUST be able to execute a request in parallel,
934 * at any time, for that process. Also compute the maximum difference
935 * between any service's maximum number of processes that can run
936 * (i.e. the maximum number that ever will be run, and a guarantee
937 * that this number will run if other services aren't running), and its
938 * minimum number. The result is the extra number of processes that
939 * we need in order to provide the latter guarantee */
940 for (i = 0; i < RX_MAX_SERVICES; i++) {
942 service = rx_services[i];
943 if (service == (struct rx_service *)0)
945 nProcs += service->minProcs;
946 diff = service->maxProcs - service->minProcs;
950 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
951 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
952 for (i = 0; i < nProcs; i++) {
953 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
959 /* This routine is only required on Windows */
961 rx_StartClientThread(void)
963 #ifdef AFS_PTHREAD_ENV
965 pid = pthread_self();
966 #endif /* AFS_PTHREAD_ENV */
968 #endif /* AFS_NT40_ENV */
970 /* This routine must be called if any services are exported. If the
971 * donateMe flag is set, the calling process is donated to the server
974 rx_StartServer(int donateMe)
976 struct rx_service *service;
982 /* Start server processes, if necessary (exact function is dependent
983 * on the implementation environment--kernel or user space). DonateMe
984 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
985 * case, one less new proc will be created rx_StartServerProcs.
987 rxi_StartServerProcs(donateMe);
989 /* count up the # of threads in minProcs, and add set the min deficit to
990 * be that value, too.
992 for (i = 0; i < RX_MAX_SERVICES; i++) {
993 service = rx_services[i];
994 if (service == (struct rx_service *)0)
996 MUTEX_ENTER(&rx_quota_mutex);
997 rxi_totalMin += service->minProcs;
998 /* below works even if a thread is running, since minDeficit would
999 * still have been decremented and later re-incremented.
1001 rxi_minDeficit += service->minProcs;
1002 MUTEX_EXIT(&rx_quota_mutex);
1005 /* Turn on reaping of idle server connections */
1006 rxi_ReapConnections(NULL, NULL, NULL, 0);
1011 #ifndef AFS_NT40_ENV
1015 #ifdef AFS_PTHREAD_ENV
1017 pid = afs_pointer_to_int(pthread_self());
1018 #else /* AFS_PTHREAD_ENV */
1020 LWP_CurrentProcess(&pid);
1021 #endif /* AFS_PTHREAD_ENV */
1023 sprintf(name, "srv_%d", ++nProcs);
1024 if (registerProgram)
1025 (*registerProgram) (pid, name);
1027 #endif /* AFS_NT40_ENV */
1028 rx_ServerProc(NULL); /* Never returns */
1030 #ifdef RX_ENABLE_TSFPQ
1031 /* no use leaving packets around in this thread's local queue if
1032 * it isn't getting donated to the server thread pool.
1034 rxi_FlushLocalPacketsTSFPQ();
1035 #endif /* RX_ENABLE_TSFPQ */
1039 /* Create a new client connection to the specified service, using the
1040 * specified security object to implement the security model for this
1042 struct rx_connection *
1043 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
1044 struct rx_securityClass *securityObject,
1045 int serviceSecurityIndex)
1048 struct rx_connection *conn;
1054 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
1055 "serviceSecurityIndex %d)\n",
1056 ntohl(shost), ntohs(sport), sservice, securityObject,
1057 serviceSecurityIndex));
1059 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
1060 * the case of kmem_alloc? */
1061 conn = rxi_AllocConnection();
1062 #ifdef RX_ENABLE_LOCKS
1063 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
1064 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
1065 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
1068 MUTEX_ENTER(&rx_connHashTable_lock);
1069 conn->type = RX_CLIENT_CONNECTION;
1070 conn->epoch = rx_epoch;
1071 conn->cid = rx_nextCid;
1073 conn->peer = rxi_FindPeer(shost, sport, 1);
1074 conn->serviceId = sservice;
1075 conn->securityObject = securityObject;
1076 conn->securityData = (void *) 0;
1077 conn->securityIndex = serviceSecurityIndex;
1078 rx_SetConnDeadTime(conn, rx_connDeadTime);
1079 rx_SetConnSecondsUntilNatPing(conn, 0);
1080 conn->ackRate = RX_FAST_ACK_RATE;
1081 conn->nSpecific = 0;
1082 conn->specific = NULL;
1083 conn->challengeEvent = NULL;
1084 conn->delayedAbortEvent = NULL;
1085 conn->abortCount = 0;
1087 for (i = 0; i < RX_MAXCALLS; i++) {
1088 conn->twind[i] = rx_initSendWindow;
1089 conn->rwind[i] = rx_initReceiveWindow;
1090 conn->lastBusy[i] = 0;
1093 code = RXS_NewConnection(securityObject, conn);
1095 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
1097 conn->refCount++; /* no lock required since only this thread knows... */
1098 conn->next = rx_connHashTable[hashindex];
1099 rx_connHashTable[hashindex] = conn;
1100 if (rx_stats_active)
1101 rx_atomic_inc(&rx_stats.nClientConns);
1102 MUTEX_EXIT(&rx_connHashTable_lock);
1105 rxi_ConnectionError(conn, code);
1111 * Ensure a connection's timeout values are valid.
1113 * @param[in] conn The connection to check
1115 * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
1116 * unless idleDeadTime and/or hardDeadTime are not set
1120 rxi_CheckConnTimeouts(struct rx_connection *conn)
1122 /* a connection's timeouts must have the relationship
1123 * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
1124 * total loss of network to a peer may cause an idle timeout instead of a
1125 * dead timeout, simply because the idle timeout gets hit first. Also set
1126 * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
1127 /* this logic is slightly complicated by the fact that
1128 * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
1130 conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
1131 if (conn->idleDeadTime) {
1132 conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
1134 if (conn->hardDeadTime) {
1135 if (conn->idleDeadTime) {
1136 conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
1138 conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
1144 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
1146 /* The idea is to set the dead time to a value that allows several
1147 * keepalives to be dropped without timing out the connection. */
1148 conn->secondsUntilDead = seconds;
1149 rxi_CheckConnTimeouts(conn);
1150 conn->secondsUntilPing = conn->secondsUntilDead / 6;
1154 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
1156 conn->hardDeadTime = seconds;
1157 rxi_CheckConnTimeouts(conn);
1161 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
1163 conn->idleDeadTime = seconds;
1164 rxi_CheckConnTimeouts(conn);
1167 int rxi_lowPeerRefCount = 0;
1168 int rxi_lowConnRefCount = 0;
1171 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
1172 * NOTE: must not be called with rx_connHashTable_lock held.
1175 rxi_CleanupConnection(struct rx_connection *conn)
1177 /* Notify the service exporter, if requested, that this connection
1178 * is being destroyed */
1179 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
1180 (*conn->service->destroyConnProc) (conn);
1182 /* Notify the security module that this connection is being destroyed */
1183 RXS_DestroyConnection(conn->securityObject, conn);
1185 /* If this is the last connection using the rx_peer struct, set its
1186 * idle time to now. rxi_ReapConnections will reap it if it's still
1187 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
1189 MUTEX_ENTER(&rx_peerHashTable_lock);
1190 if (conn->peer->refCount < 2) {
1191 conn->peer->idleWhen = clock_Sec();
1192 if (conn->peer->refCount < 1) {
1193 conn->peer->refCount = 1;
1194 if (rx_stats_active) {
1195 MUTEX_ENTER(&rx_stats_mutex);
1196 rxi_lowPeerRefCount++;
1197 MUTEX_EXIT(&rx_stats_mutex);
1201 conn->peer->refCount--;
1202 MUTEX_EXIT(&rx_peerHashTable_lock);
1204 if (rx_stats_active)
1206 if (conn->type == RX_SERVER_CONNECTION)
1207 rx_atomic_dec(&rx_stats.nServerConns);
1209 rx_atomic_dec(&rx_stats.nClientConns);
1212 if (conn->specific) {
1214 for (i = 0; i < conn->nSpecific; i++) {
1215 if (conn->specific[i] && rxi_keyCreate_destructor[i])
1216 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
1217 conn->specific[i] = NULL;
1219 free(conn->specific);
1221 conn->specific = NULL;
1222 conn->nSpecific = 0;
1223 #endif /* !KERNEL */
1225 MUTEX_DESTROY(&conn->conn_call_lock);
1226 MUTEX_DESTROY(&conn->conn_data_lock);
1227 CV_DESTROY(&conn->conn_call_cv);
1229 rxi_FreeConnection(conn);
1232 /* Destroy the specified connection */
1234 rxi_DestroyConnection(struct rx_connection *conn)
1236 MUTEX_ENTER(&rx_connHashTable_lock);
1237 rxi_DestroyConnectionNoLock(conn);
1238 /* conn should be at the head of the cleanup list */
1239 if (conn == rx_connCleanup_list) {
1240 rx_connCleanup_list = rx_connCleanup_list->next;
1241 MUTEX_EXIT(&rx_connHashTable_lock);
1242 rxi_CleanupConnection(conn);
1244 #ifdef RX_ENABLE_LOCKS
1246 MUTEX_EXIT(&rx_connHashTable_lock);
1248 #endif /* RX_ENABLE_LOCKS */
1252 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1254 struct rx_connection **conn_ptr;
1262 MUTEX_ENTER(&conn->conn_data_lock);
1263 MUTEX_ENTER(&rx_refcnt_mutex);
1264 if (conn->refCount > 0)
1267 #ifdef RX_REFCOUNT_CHECK
1268 osi_Assert(conn->refCount == 0);
1270 if (rx_stats_active) {
1271 MUTEX_ENTER(&rx_stats_mutex);
1272 rxi_lowConnRefCount++;
1273 MUTEX_EXIT(&rx_stats_mutex);
1277 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1278 /* Busy; wait till the last guy before proceeding */
1279 MUTEX_EXIT(&rx_refcnt_mutex);
1280 MUTEX_EXIT(&conn->conn_data_lock);
1285 /* If the client previously called rx_NewCall, but it is still
1286 * waiting, treat this as a running call, and wait to destroy the
1287 * connection later when the call completes. */
1288 if ((conn->type == RX_CLIENT_CONNECTION)
1289 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1290 conn->flags |= RX_CONN_DESTROY_ME;
1291 MUTEX_EXIT(&rx_refcnt_mutex);
1292 MUTEX_EXIT(&conn->conn_data_lock);
1296 MUTEX_EXIT(&rx_refcnt_mutex);
1297 MUTEX_EXIT(&conn->conn_data_lock);
1299 /* Check for extant references to this connection */
1300 MUTEX_ENTER(&conn->conn_call_lock);
1301 for (i = 0; i < RX_MAXCALLS; i++) {
1302 struct rx_call *call = conn->call[i];
1305 if (conn->type == RX_CLIENT_CONNECTION) {
1306 MUTEX_ENTER(&call->lock);
1307 if (call->delayedAckEvent) {
1308 /* Push the final acknowledgment out now--there
1309 * won't be a subsequent call to acknowledge the
1310 * last reply packets */
1311 rxi_CancelDelayedAckEvent(call);
1312 if (call->state == RX_STATE_PRECALL
1313 || call->state == RX_STATE_ACTIVE) {
1314 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1319 MUTEX_EXIT(&call->lock);
1323 MUTEX_EXIT(&conn->conn_call_lock);
1325 #ifdef RX_ENABLE_LOCKS
1327 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1328 MUTEX_EXIT(&conn->conn_data_lock);
1330 /* Someone is accessing a packet right now. */
1334 #endif /* RX_ENABLE_LOCKS */
1337 /* Don't destroy the connection if there are any call
1338 * structures still in use */
1339 MUTEX_ENTER(&conn->conn_data_lock);
1340 conn->flags |= RX_CONN_DESTROY_ME;
1341 MUTEX_EXIT(&conn->conn_data_lock);
1346 /* Remove from connection hash table before proceeding */
1348 &rx_connHashTable[CONN_HASH
1349 (peer->host, peer->port, conn->cid, conn->epoch,
1351 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1352 if (*conn_ptr == conn) {
1353 *conn_ptr = conn->next;
1357 /* if the conn that we are destroying was the last connection, then we
1358 * clear rxLastConn as well */
1359 if (rxLastConn == conn)
1362 /* Make sure the connection is completely reset before deleting it. */
1364 * Pending events hold a refcount, so we can't get here if they are
1366 osi_Assert(conn->challengeEvent == NULL);
1367 osi_Assert(conn->delayedAbortEvent == NULL);
1368 osi_Assert(conn->natKeepAliveEvent == NULL);
1369 osi_Assert(conn->checkReachEvent == NULL);
1371 /* Add the connection to the list of destroyed connections that
1372 * need to be cleaned up. This is necessary to avoid deadlocks
1373 * in the routines we call to inform others that this connection is
1374 * being destroyed. */
1375 conn->next = rx_connCleanup_list;
1376 rx_connCleanup_list = conn;
1379 /* Externally available version */
1381 rx_DestroyConnection(struct rx_connection *conn)
1386 rxi_DestroyConnection(conn);
1391 rx_GetConnection(struct rx_connection *conn)
1396 MUTEX_ENTER(&rx_refcnt_mutex);
1398 MUTEX_EXIT(&rx_refcnt_mutex);
1402 #ifdef RX_ENABLE_LOCKS
1403 /* Wait for the transmit queue to no longer be busy.
1404 * requires the call->lock to be held */
1406 rxi_WaitforTQBusy(struct rx_call *call) {
1407 while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1408 call->flags |= RX_CALL_TQ_WAIT;
1410 MUTEX_ASSERT(&call->lock);
1411 CV_WAIT(&call->cv_tq, &call->lock);
1413 if (call->tqWaiters == 0) {
1414 call->flags &= ~RX_CALL_TQ_WAIT;
1421 rxi_WakeUpTransmitQueue(struct rx_call *call)
1423 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1424 dpf(("call %p has %d waiters and flags %d\n",
1425 call, call->tqWaiters, call->flags));
1426 #ifdef RX_ENABLE_LOCKS
1427 MUTEX_ASSERT(&call->lock);
1428 CV_BROADCAST(&call->cv_tq);
1429 #else /* RX_ENABLE_LOCKS */
1430 osi_rxWakeup(&call->tq);
1431 #endif /* RX_ENABLE_LOCKS */
1435 /* Start a new rx remote procedure call, on the specified connection.
1436 * If wait is set to 1, wait for a free call channel; otherwise return
1437 * 0. Maxtime gives the maximum number of seconds this call may take,
1438 * after rx_NewCall returns. After this time interval, a call to any
1439 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1440 * For fine grain locking, we hold the conn_call_lock in order to
1441 * to ensure that we don't get signalle after we found a call in an active
1442 * state and before we go to sleep.
1445 rx_NewCall(struct rx_connection *conn)
1447 int i, wait, ignoreBusy = 1;
1448 struct rx_call *call;
1449 struct clock queueTime;
1450 afs_uint32 leastBusy = 0;
1454 dpf(("rx_NewCall(conn %p)\n", conn));
1457 clock_GetTime(&queueTime);
1459 * Check if there are others waiting for a new call.
1460 * If so, let them go first to avoid starving them.
1461 * This is a fairly simple scheme, and might not be
1462 * a complete solution for large numbers of waiters.
1464 * makeCallWaiters keeps track of the number of
1465 * threads waiting to make calls and the
1466 * RX_CONN_MAKECALL_WAITING flag bit is used to
1467 * indicate that there are indeed calls waiting.
1468 * The flag is set when the waiter is incremented.
1469 * It is only cleared when makeCallWaiters is 0.
1470 * This prevents us from accidently destroying the
1471 * connection while it is potentially about to be used.
1473 MUTEX_ENTER(&conn->conn_call_lock);
1474 MUTEX_ENTER(&conn->conn_data_lock);
1475 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1476 conn->flags |= RX_CONN_MAKECALL_WAITING;
1477 conn->makeCallWaiters++;
1478 MUTEX_EXIT(&conn->conn_data_lock);
1480 #ifdef RX_ENABLE_LOCKS
1481 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1485 MUTEX_ENTER(&conn->conn_data_lock);
1486 conn->makeCallWaiters--;
1487 if (conn->makeCallWaiters == 0)
1488 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1491 /* We are now the active thread in rx_NewCall */
1492 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1493 MUTEX_EXIT(&conn->conn_data_lock);
1498 for (i = 0; i < RX_MAXCALLS; i++) {
1499 call = conn->call[i];
1501 if (!ignoreBusy && conn->lastBusy[i] != leastBusy) {
1502 /* we're not ignoring busy call slots; only look at the
1503 * call slot that is the "least" busy */
1507 if (call->state == RX_STATE_DALLY) {
1508 MUTEX_ENTER(&call->lock);
1509 if (call->state == RX_STATE_DALLY) {
1510 if (ignoreBusy && conn->lastBusy[i]) {
1511 /* if we're ignoring busy call slots, skip any ones that
1512 * have lastBusy set */
1513 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1514 leastBusy = conn->lastBusy[i];
1516 MUTEX_EXIT(&call->lock);
1521 * We are setting the state to RX_STATE_RESET to
1522 * ensure that no one else will attempt to use this
1523 * call once we drop the conn->conn_call_lock and
1524 * call->lock. We must drop the conn->conn_call_lock
1525 * before calling rxi_ResetCall because the process
1526 * of clearing the transmit queue can block for an
1527 * extended period of time. If we block while holding
1528 * the conn->conn_call_lock, then all rx_EndCall
1529 * processing will block as well. This has a detrimental
1530 * effect on overall system performance.
1532 call->state = RX_STATE_RESET;
1533 (*call->callNumber)++;
1534 MUTEX_EXIT(&conn->conn_call_lock);
1535 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1536 rxi_ResetCall(call, 0);
1537 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1541 * If we failed to be able to safely obtain the
1542 * conn->conn_call_lock we will have to drop the
1543 * call->lock to avoid a deadlock. When the call->lock
1544 * is released the state of the call can change. If it
1545 * is no longer RX_STATE_RESET then some other thread is
1548 MUTEX_EXIT(&call->lock);
1549 MUTEX_ENTER(&conn->conn_call_lock);
1550 MUTEX_ENTER(&call->lock);
1552 if (call->state == RX_STATE_RESET)
1556 * If we get here it means that after dropping
1557 * the conn->conn_call_lock and call->lock that
1558 * the call is no longer ours. If we can't find
1559 * a free call in the remaining slots we should
1560 * not go immediately to RX_CONN_MAKECALL_WAITING
1561 * because by dropping the conn->conn_call_lock
1562 * we have given up synchronization with rx_EndCall.
1563 * Instead, cycle through one more time to see if
1564 * we can find a call that can call our own.
1566 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1569 MUTEX_EXIT(&call->lock);
1572 if (ignoreBusy && conn->lastBusy[i]) {
1573 /* if we're ignoring busy call slots, skip any ones that
1574 * have lastBusy set */
1575 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1576 leastBusy = conn->lastBusy[i];
1581 /* rxi_NewCall returns with mutex locked */
1582 call = rxi_NewCall(conn, i);
1583 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1587 if (i < RX_MAXCALLS) {
1588 conn->lastBusy[i] = 0;
1593 if (leastBusy && ignoreBusy) {
1594 /* we didn't find a useable call slot, but we did see at least one
1595 * 'busy' slot; look again and only use a slot with the 'least
1601 MUTEX_ENTER(&conn->conn_data_lock);
1602 conn->flags |= RX_CONN_MAKECALL_WAITING;
1603 conn->makeCallWaiters++;
1604 MUTEX_EXIT(&conn->conn_data_lock);
1606 #ifdef RX_ENABLE_LOCKS
1607 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1611 MUTEX_ENTER(&conn->conn_data_lock);
1612 conn->makeCallWaiters--;
1613 if (conn->makeCallWaiters == 0)
1614 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1615 MUTEX_EXIT(&conn->conn_data_lock);
1617 /* Client is initially in send mode */
1618 call->state = RX_STATE_ACTIVE;
1619 call->error = conn->error;
1621 call->app.mode = RX_MODE_ERROR;
1623 call->app.mode = RX_MODE_SENDING;
1625 #ifdef AFS_RXERRQ_ENV
1626 /* remember how many network errors the peer has when we started, so if
1627 * more errors are encountered after the call starts, we know the other endpoint won't be
1628 * responding to us */
1629 call->neterr_gen = rx_atomic_read(&conn->peer->neterrs);
1632 /* remember start time for call in case we have hard dead time limit */
1633 call->queueTime = queueTime;
1634 clock_GetTime(&call->startTime);
1635 call->app.bytesSent = 0;
1636 call->app.bytesRcvd = 0;
1638 /* Turn on busy protocol. */
1639 rxi_KeepAliveOn(call);
1641 /* Attempt MTU discovery */
1642 rxi_GrowMTUOn(call);
1645 * We are no longer the active thread in rx_NewCall
1647 MUTEX_ENTER(&conn->conn_data_lock);
1648 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1649 MUTEX_EXIT(&conn->conn_data_lock);
1652 * Wake up anyone else who might be giving us a chance to
1653 * run (see code above that avoids resource starvation).
1655 #ifdef RX_ENABLE_LOCKS
1656 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1657 osi_Panic("rx_NewCall call about to be used without an empty tq");
1660 CV_BROADCAST(&conn->conn_call_cv);
1664 MUTEX_EXIT(&conn->conn_call_lock);
1665 MUTEX_EXIT(&call->lock);
1668 dpf(("rx_NewCall(call %p)\n", call));
1673 rxi_HasActiveCalls(struct rx_connection *aconn)
1676 struct rx_call *tcall;
1680 for (i = 0; i < RX_MAXCALLS; i++) {
1681 if ((tcall = aconn->call[i])) {
1682 if ((tcall->state == RX_STATE_ACTIVE)
1683 || (tcall->state == RX_STATE_PRECALL)) {
1694 rxi_GetCallNumberVector(struct rx_connection *aconn,
1695 afs_int32 * aint32s)
1698 struct rx_call *tcall;
1702 MUTEX_ENTER(&aconn->conn_call_lock);
1703 for (i = 0; i < RX_MAXCALLS; i++) {
1704 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1705 aint32s[i] = aconn->callNumber[i] + 1;
1707 aint32s[i] = aconn->callNumber[i];
1709 MUTEX_EXIT(&aconn->conn_call_lock);
1715 rxi_SetCallNumberVector(struct rx_connection *aconn,
1716 afs_int32 * aint32s)
1719 struct rx_call *tcall;
1723 MUTEX_ENTER(&aconn->conn_call_lock);
1724 for (i = 0; i < RX_MAXCALLS; i++) {
1725 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1726 aconn->callNumber[i] = aint32s[i] - 1;
1728 aconn->callNumber[i] = aint32s[i];
1730 MUTEX_EXIT(&aconn->conn_call_lock);
1735 /* Advertise a new service. A service is named locally by a UDP port
1736 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1739 char *serviceName; Name for identification purposes (e.g. the
1740 service name might be used for probing for
1743 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1744 char *serviceName, struct rx_securityClass **securityObjects,
1745 int nSecurityObjects,
1746 afs_int32(*serviceProc) (struct rx_call * acall))
1748 osi_socket socket = OSI_NULLSOCKET;
1749 struct rx_service *tservice;
1755 if (serviceId == 0) {
1757 "rx_NewService: service id for service %s is not non-zero.\n",
1764 "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",
1772 tservice = rxi_AllocService();
1775 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1777 for (i = 0; i < RX_MAX_SERVICES; i++) {
1778 struct rx_service *service = rx_services[i];
1780 if (port == service->servicePort && host == service->serviceHost) {
1781 if (service->serviceId == serviceId) {
1782 /* The identical service has already been
1783 * installed; if the caller was intending to
1784 * change the security classes used by this
1785 * service, he/she loses. */
1787 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1788 serviceName, serviceId, service->serviceName);
1790 rxi_FreeService(tservice);
1793 /* Different service, same port: re-use the socket
1794 * which is bound to the same port */
1795 socket = service->socket;
1798 if (socket == OSI_NULLSOCKET) {
1799 /* If we don't already have a socket (from another
1800 * service on same port) get a new one */
1801 socket = rxi_GetHostUDPSocket(host, port);
1802 if (socket == OSI_NULLSOCKET) {
1804 rxi_FreeService(tservice);
1809 service->socket = socket;
1810 service->serviceHost = host;
1811 service->servicePort = port;
1812 service->serviceId = serviceId;
1813 service->serviceName = serviceName;
1814 service->nSecurityObjects = nSecurityObjects;
1815 service->securityObjects = securityObjects;
1816 service->minProcs = 0;
1817 service->maxProcs = 1;
1818 service->idleDeadTime = 60;
1819 service->connDeadTime = rx_connDeadTime;
1820 service->executeRequestProc = serviceProc;
1821 service->checkReach = 0;
1822 service->nSpecific = 0;
1823 service->specific = NULL;
1824 rx_services[i] = service; /* not visible until now */
1830 rxi_FreeService(tservice);
1831 (osi_Msg "rx_NewService: cannot support > %d services\n",
1836 /* Set configuration options for all of a service's security objects */
1839 rx_SetSecurityConfiguration(struct rx_service *service,
1840 rx_securityConfigVariables type,
1845 for (i = 0; i<service->nSecurityObjects; i++) {
1846 if (service->securityObjects[i]) {
1847 code = RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1858 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1859 struct rx_securityClass **securityObjects, int nSecurityObjects,
1860 afs_int32(*serviceProc) (struct rx_call * acall))
1862 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1865 /* Generic request processing loop. This routine should be called
1866 * by the implementation dependent rx_ServerProc. If socketp is
1867 * non-null, it will be set to the file descriptor that this thread
1868 * is now listening on. If socketp is null, this routine will never
1871 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1873 struct rx_call *call;
1875 struct rx_service *tservice = NULL;
1882 call = rx_GetCall(threadID, tservice, socketp);
1883 if (socketp && *socketp != OSI_NULLSOCKET) {
1884 /* We are now a listener thread */
1890 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1891 #ifdef RX_ENABLE_LOCKS
1893 #endif /* RX_ENABLE_LOCKS */
1894 afs_termState = AFSOP_STOP_AFS;
1895 afs_osi_Wakeup(&afs_termState);
1896 #ifdef RX_ENABLE_LOCKS
1898 #endif /* RX_ENABLE_LOCKS */
1903 /* if server is restarting( typically smooth shutdown) then do not
1904 * allow any new calls.
1907 if (rx_tranquil && (call != NULL)) {
1911 MUTEX_ENTER(&call->lock);
1913 rxi_CallError(call, RX_RESTARTING);
1914 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1916 MUTEX_EXIT(&call->lock);
1921 tservice = call->conn->service;
1923 if (tservice->beforeProc)
1924 (*tservice->beforeProc) (call);
1926 code = tservice->executeRequestProc(call);
1928 if (tservice->afterProc)
1929 (*tservice->afterProc) (call, code);
1931 rx_EndCall(call, code);
1933 if (tservice->postProc)
1934 (*tservice->postProc) (code);
1936 if (rx_stats_active) {
1937 MUTEX_ENTER(&rx_stats_mutex);
1939 MUTEX_EXIT(&rx_stats_mutex);
1946 rx_WakeupServerProcs(void)
1948 struct rx_serverQueueEntry *np;
1949 struct opr_queue *cursor;
1953 MUTEX_ENTER(&rx_serverPool_lock);
1955 #ifdef RX_ENABLE_LOCKS
1956 if (rx_waitForPacket)
1957 CV_BROADCAST(&rx_waitForPacket->cv);
1958 #else /* RX_ENABLE_LOCKS */
1959 if (rx_waitForPacket)
1960 osi_rxWakeup(rx_waitForPacket);
1961 #endif /* RX_ENABLE_LOCKS */
1962 MUTEX_ENTER(&freeSQEList_lock);
1963 for (opr_queue_Scan(&rx_freeServerQueue, cursor)) {
1964 np = opr_queue_Entry(cursor, struct rx_serverQueueEntry, entry);
1965 #ifdef RX_ENABLE_LOCKS
1966 CV_BROADCAST(&np->cv);
1967 #else /* RX_ENABLE_LOCKS */
1969 #endif /* RX_ENABLE_LOCKS */
1971 MUTEX_EXIT(&freeSQEList_lock);
1972 for (opr_queue_Scan(&rx_idleServerQueue, cursor)) {
1973 np = opr_queue_Entry(cursor, struct rx_serverQueueEntry, entry);
1974 #ifdef RX_ENABLE_LOCKS
1975 CV_BROADCAST(&np->cv);
1976 #else /* RX_ENABLE_LOCKS */
1978 #endif /* RX_ENABLE_LOCKS */
1980 MUTEX_EXIT(&rx_serverPool_lock);
1985 * One thing that seems to happen is that all the server threads get
1986 * tied up on some empty or slow call, and then a whole bunch of calls
1987 * arrive at once, using up the packet pool, so now there are more
1988 * empty calls. The most critical resources here are server threads
1989 * and the free packet pool. The "doreclaim" code seems to help in
1990 * general. I think that eventually we arrive in this state: there
1991 * are lots of pending calls which do have all their packets present,
1992 * so they won't be reclaimed, are multi-packet calls, so they won't
1993 * be scheduled until later, and thus are tying up most of the free
1994 * packet pool for a very long time.
1996 * 1. schedule multi-packet calls if all the packets are present.
1997 * Probably CPU-bound operation, useful to return packets to pool.
1998 * Do what if there is a full window, but the last packet isn't here?
1999 * 3. preserve one thread which *only* runs "best" calls, otherwise
2000 * it sleeps and waits for that type of call.
2001 * 4. Don't necessarily reserve a whole window for each thread. In fact,
2002 * the current dataquota business is badly broken. The quota isn't adjusted
2003 * to reflect how many packets are presently queued for a running call.
2004 * So, when we schedule a queued call with a full window of packets queued
2005 * up for it, that *should* free up a window full of packets for other 2d-class
2006 * calls to be able to use from the packet pool. But it doesn't.
2008 * NB. Most of the time, this code doesn't run -- since idle server threads
2009 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
2010 * as a new call arrives.
2012 /* Sleep until a call arrives. Returns a pointer to the call, ready
2013 * for an rx_Read. */
2014 #ifdef RX_ENABLE_LOCKS
2016 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2018 struct rx_serverQueueEntry *sq;
2019 struct rx_call *call = (struct rx_call *)0;
2020 struct rx_service *service = NULL;
2022 MUTEX_ENTER(&freeSQEList_lock);
2024 if (!opr_queue_IsEmpty(&rx_freeServerQueue)) {
2025 sq = opr_queue_First(&rx_freeServerQueue, struct rx_serverQueueEntry,
2027 opr_queue_Remove(&sq->entry);
2028 MUTEX_EXIT(&freeSQEList_lock);
2029 } else { /* otherwise allocate a new one and return that */
2030 MUTEX_EXIT(&freeSQEList_lock);
2031 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2032 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2033 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2036 MUTEX_ENTER(&rx_serverPool_lock);
2037 if (cur_service != NULL) {
2038 ReturnToServerPool(cur_service);
2041 if (!opr_queue_IsEmpty(&rx_incomingCallQueue)) {
2042 struct rx_call *tcall, *choice2 = NULL;
2043 struct opr_queue *cursor;
2045 /* Scan for eligible incoming calls. A call is not eligible
2046 * if the maximum number of calls for its service type are
2047 * already executing */
2048 /* One thread will process calls FCFS (to prevent starvation),
2049 * while the other threads may run ahead looking for calls which
2050 * have all their input data available immediately. This helps
2051 * keep threads from blocking, waiting for data from the client. */
2052 for (opr_queue_Scan(&rx_incomingCallQueue, cursor)) {
2053 tcall = opr_queue_Entry(cursor, struct rx_call, entry);
2055 service = tcall->conn->service;
2056 if (!QuotaOK(service)) {
2059 MUTEX_ENTER(&rx_pthread_mutex);
2060 if (tno == rxi_fcfs_thread_num
2061 || opr_queue_IsLast(&rx_incomingCallQueue, cursor)) {
2062 MUTEX_EXIT(&rx_pthread_mutex);
2063 /* If we're the fcfs thread , then we'll just use
2064 * this call. If we haven't been able to find an optimal
2065 * choice, and we're at the end of the list, then use a
2066 * 2d choice if one has been identified. Otherwise... */
2067 call = (choice2 ? choice2 : tcall);
2068 service = call->conn->service;
2070 MUTEX_EXIT(&rx_pthread_mutex);
2071 if (!opr_queue_IsEmpty(&tcall->rq)) {
2072 struct rx_packet *rp;
2073 rp = opr_queue_First(&tcall->rq, struct rx_packet,
2075 if (rp->header.seq == 1) {
2077 || (rp->header.flags & RX_LAST_PACKET)) {
2079 } else if (rxi_2dchoice && !choice2
2080 && !(tcall->flags & RX_CALL_CLEARED)
2081 && (tcall->rprev > rxi_HardAckRate)) {
2091 ReturnToServerPool(service);
2097 opr_queue_Remove(&call->entry);
2098 MUTEX_EXIT(&rx_serverPool_lock);
2099 MUTEX_ENTER(&call->lock);
2100 CLEAR_CALL_QUEUE_LOCK(call);
2102 if (call->flags & RX_CALL_WAIT_PROC) {
2103 call->flags &= ~RX_CALL_WAIT_PROC;
2104 rx_atomic_dec(&rx_nWaiting);
2107 if (call->state != RX_STATE_PRECALL || call->error) {
2108 MUTEX_EXIT(&call->lock);
2109 MUTEX_ENTER(&rx_serverPool_lock);
2110 ReturnToServerPool(service);
2115 if (opr_queue_IsEmpty(&call->rq)
2116 || opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq != 1)
2117 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2121 /* If there are no eligible incoming calls, add this process
2122 * to the idle server queue, to wait for one */
2126 *socketp = OSI_NULLSOCKET;
2128 sq->socketp = socketp;
2129 opr_queue_Append(&rx_idleServerQueue, &sq->entry);
2130 #ifndef AFS_AIX41_ENV
2131 rx_waitForPacket = sq;
2132 #endif /* AFS_AIX41_ENV */
2134 CV_WAIT(&sq->cv, &rx_serverPool_lock);
2136 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2140 } while (!(call = sq->newcall)
2141 && !(socketp && *socketp != OSI_NULLSOCKET));
2142 if (opr_queue_IsOnQueue(&sq->entry)) {
2143 opr_queue_Remove(&sq->entry);
2145 MUTEX_EXIT(&rx_serverPool_lock);
2147 MUTEX_ENTER(&call->lock);
2153 MUTEX_ENTER(&freeSQEList_lock);
2154 opr_queue_Prepend(&rx_freeServerQueue, &sq->entry);
2155 MUTEX_EXIT(&freeSQEList_lock);
2158 clock_GetTime(&call->startTime);
2159 call->state = RX_STATE_ACTIVE;
2160 call->app.mode = RX_MODE_RECEIVING;
2161 #ifdef RX_KERNEL_TRACE
2162 if (ICL_SETACTIVE(afs_iclSetp)) {
2163 int glockOwner = ISAFS_GLOCK();
2166 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2167 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2174 rxi_calltrace(RX_CALL_START, call);
2175 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2176 call->conn->service->servicePort, call->conn->service->serviceId,
2179 MUTEX_EXIT(&call->lock);
2180 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
2182 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2187 #else /* RX_ENABLE_LOCKS */
2189 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2191 struct rx_serverQueueEntry *sq;
2192 struct rx_call *call = (struct rx_call *)0, *choice2;
2193 struct rx_service *service = NULL;
2197 MUTEX_ENTER(&freeSQEList_lock);
2199 if (!opr_queue_IsEmpty(&rx_freeServerQueue)) {
2200 sq = opr_queue_First(&rx_freeServerQueue, struct rx_serverQueueEntry,
2202 opr_queue_Remove(&sq->entry);
2203 MUTEX_EXIT(&freeSQEList_lock);
2204 } else { /* otherwise allocate a new one and return that */
2205 MUTEX_EXIT(&freeSQEList_lock);
2206 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2207 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2208 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2210 MUTEX_ENTER(&sq->lock);
2212 if (cur_service != NULL) {
2213 cur_service->nRequestsRunning--;
2214 MUTEX_ENTER(&rx_quota_mutex);
2215 if (cur_service->nRequestsRunning < cur_service->minProcs)
2218 MUTEX_EXIT(&rx_quota_mutex);
2220 if (!opr_queue_IsEmpty(&rx_incomingCallQueue)) {
2221 struct rx_call *tcall;
2222 struct opr_queue *cursor;
2223 /* Scan for eligible incoming calls. A call is not eligible
2224 * if the maximum number of calls for its service type are
2225 * already executing */
2226 /* One thread will process calls FCFS (to prevent starvation),
2227 * while the other threads may run ahead looking for calls which
2228 * have all their input data available immediately. This helps
2229 * keep threads from blocking, waiting for data from the client. */
2230 choice2 = (struct rx_call *)0;
2231 for (opr_queue_Scan(&rx_incomingCallQueue, cursor)) {
2232 tcall = opr_queue_Entry(cursor, struct rx_call, entry);
2233 service = tcall->conn->service;
2234 if (QuotaOK(service)) {
2235 MUTEX_ENTER(&rx_pthread_mutex);
2236 if (tno == rxi_fcfs_thread_num
2237 || opr_queue_IsLast(&rx_incomingCallQueue, cursor)) {
2238 MUTEX_EXIT(&rx_pthread_mutex);
2239 /* If we're the fcfs thread, then we'll just use
2240 * this call. If we haven't been able to find an optimal
2241 * choice, and we're at the end of the list, then use a
2242 * 2d choice if one has been identified. Otherwise... */
2243 call = (choice2 ? choice2 : tcall);
2244 service = call->conn->service;
2246 MUTEX_EXIT(&rx_pthread_mutex);
2247 if (!opr_queue_IsEmpty(&tcall->rq)) {
2248 struct rx_packet *rp;
2249 rp = opr_queue_First(&tcall->rq, struct rx_packet,
2251 if (rp->header.seq == 1
2253 || (rp->header.flags & RX_LAST_PACKET))) {
2255 } else if (rxi_2dchoice && !choice2
2256 && !(tcall->flags & RX_CALL_CLEARED)
2257 && (tcall->rprev > rxi_HardAckRate)) {
2270 opr_queue_Remove(&call->entry);
2271 CLEAR_CALL_QUEUE_LOCK(call);
2272 /* we can't schedule a call if there's no data!!! */
2273 /* send an ack if there's no data, if we're missing the
2274 * first packet, or we're missing something between first
2275 * and last -- there's a "hole" in the incoming data. */
2276 if (opr_queue_IsEmpty(&call->rq)
2277 || opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq != 1
2278 || call->rprev != opr_queue_Last(&call->rq, struct rx_packet, entry)->header.seq)
2279 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2281 call->flags &= (~RX_CALL_WAIT_PROC);
2282 service->nRequestsRunning++;
2283 /* just started call in minProcs pool, need fewer to maintain
2285 MUTEX_ENTER(&rx_quota_mutex);
2286 if (service->nRequestsRunning <= service->minProcs)
2289 MUTEX_EXIT(&rx_quota_mutex);
2290 rx_atomic_dec(&rx_nWaiting);
2291 /* MUTEX_EXIT(&call->lock); */
2293 /* If there are no eligible incoming calls, add this process
2294 * to the idle server queue, to wait for one */
2297 *socketp = OSI_NULLSOCKET;
2299 sq->socketp = socketp;
2300 opr_queue_Append(&rx_idleServerQueue, &sq->entry);
2304 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2306 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2307 return (struct rx_call *)0;
2310 } while (!(call = sq->newcall)
2311 && !(socketp && *socketp != OSI_NULLSOCKET));
2313 MUTEX_EXIT(&sq->lock);
2315 MUTEX_ENTER(&freeSQEList_lock);
2316 opr_queue_Prepend(&rx_freeServerQueue, &sq->entry);
2317 MUTEX_EXIT(&freeSQEList_lock);
2320 clock_GetTime(&call->startTime);
2321 call->state = RX_STATE_ACTIVE;
2322 call->app.mode = RX_MODE_RECEIVING;
2323 #ifdef RX_KERNEL_TRACE
2324 if (ICL_SETACTIVE(afs_iclSetp)) {
2325 int glockOwner = ISAFS_GLOCK();
2328 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2329 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2336 rxi_calltrace(RX_CALL_START, call);
2337 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2338 call->conn->service->servicePort, call->conn->service->serviceId,
2341 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2348 #endif /* RX_ENABLE_LOCKS */
2352 /* Establish a procedure to be called when a packet arrives for a
2353 * call. This routine will be called at most once after each call,
2354 * and will also be called if there is an error condition on the or
2355 * the call is complete. Used by multi rx to build a selection
2356 * function which determines which of several calls is likely to be a
2357 * good one to read from.
2358 * NOTE: the way this is currently implemented it is probably only a
2359 * good idea to (1) use it immediately after a newcall (clients only)
2360 * and (2) only use it once. Other uses currently void your warranty
2363 rx_SetArrivalProc(struct rx_call *call,
2364 void (*proc) (struct rx_call * call,
2367 void * handle, int arg)
2369 call->arrivalProc = proc;
2370 call->arrivalProcHandle = handle;
2371 call->arrivalProcArg = arg;
2374 /* Call is finished (possibly prematurely). Return rc to the peer, if
2375 * appropriate, and return the final error code from the conversation
2379 rx_EndCall(struct rx_call *call, afs_int32 rc)
2381 struct rx_connection *conn = call->conn;
2385 dpf(("rx_EndCall(call %p rc %d error %d abortCode %d)\n",
2386 call, rc, call->error, call->abortCode));
2389 MUTEX_ENTER(&call->lock);
2391 if (rc == 0 && call->error == 0) {
2392 call->abortCode = 0;
2393 call->abortCount = 0;
2396 call->arrivalProc = NULL;
2397 if (rc && call->error == 0) {
2398 rxi_CallError(call, rc);
2399 call->app.mode = RX_MODE_ERROR;
2400 /* Send an abort message to the peer if this error code has
2401 * only just been set. If it was set previously, assume the
2402 * peer has already been sent the error code or will request it
2404 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2406 if (conn->type == RX_SERVER_CONNECTION) {
2407 /* Make sure reply or at least dummy reply is sent */
2408 if (call->app.mode == RX_MODE_RECEIVING) {
2409 MUTEX_EXIT(&call->lock);
2410 rxi_WriteProc(call, 0, 0);
2411 MUTEX_ENTER(&call->lock);
2413 if (call->app.mode == RX_MODE_SENDING) {
2414 rxi_FlushWriteLocked(call);
2416 rxi_calltrace(RX_CALL_END, call);
2417 /* Call goes to hold state until reply packets are acknowledged */
2418 if (call->tfirst + call->nSoftAcked < call->tnext) {
2419 call->state = RX_STATE_HOLD;
2421 call->state = RX_STATE_DALLY;
2422 rxi_ClearTransmitQueue(call, 0);
2423 rxi_rto_cancel(call);
2424 rxi_CancelKeepAliveEvent(call);
2426 } else { /* Client connection */
2428 /* Make sure server receives input packets, in the case where
2429 * no reply arguments are expected */
2431 if ((call->app.mode == RX_MODE_SENDING)
2432 || (call->app.mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2433 MUTEX_EXIT(&call->lock);
2434 (void)rxi_ReadProc(call, &dummy, 1);
2435 MUTEX_ENTER(&call->lock);
2438 /* If we had an outstanding delayed ack, be nice to the server
2439 * and force-send it now.
2441 if (call->delayedAckEvent) {
2442 rxi_CancelDelayedAckEvent(call);
2443 rxi_SendDelayedAck(NULL, call, NULL, 0);
2446 /* We need to release the call lock since it's lower than the
2447 * conn_call_lock and we don't want to hold the conn_call_lock
2448 * over the rx_ReadProc call. The conn_call_lock needs to be held
2449 * here for the case where rx_NewCall is perusing the calls on
2450 * the connection structure. We don't want to signal until
2451 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2452 * have checked this call, found it active and by the time it
2453 * goes to sleep, will have missed the signal.
2455 MUTEX_EXIT(&call->lock);
2456 MUTEX_ENTER(&conn->conn_call_lock);
2457 MUTEX_ENTER(&call->lock);
2460 /* While there are some circumstances where a call with an error is
2461 * obviously not on a "busy" channel, be conservative (clearing
2462 * lastBusy is just best-effort to possibly speed up rx_NewCall).
2463 * The call channel is definitely not busy if we just successfully
2464 * completed a call on it. */
2465 conn->lastBusy[call->channel] = 0;
2467 } else if (call->error == RX_CALL_TIMEOUT) {
2468 /* The call is still probably running on the server side, so try to
2469 * avoid this call channel in the future. */
2470 conn->lastBusy[call->channel] = clock_Sec();
2473 MUTEX_ENTER(&conn->conn_data_lock);
2474 conn->flags |= RX_CONN_BUSY;
2475 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2476 MUTEX_EXIT(&conn->conn_data_lock);
2477 #ifdef RX_ENABLE_LOCKS
2478 CV_BROADCAST(&conn->conn_call_cv);
2483 #ifdef RX_ENABLE_LOCKS
2485 MUTEX_EXIT(&conn->conn_data_lock);
2487 #endif /* RX_ENABLE_LOCKS */
2488 call->state = RX_STATE_DALLY;
2490 error = call->error;
2492 /* currentPacket, nLeft, and NFree must be zeroed here, because
2493 * ResetCall cannot: ResetCall may be called at splnet(), in the
2494 * kernel version, and may interrupt the macros rx_Read or
2495 * rx_Write, which run at normal priority for efficiency. */
2496 if (call->app.currentPacket) {
2497 #ifdef RX_TRACK_PACKETS
2498 call->app.currentPacket->flags &= ~RX_PKTFLAG_CP;
2500 rxi_FreePacket(call->app.currentPacket);
2501 call->app.currentPacket = (struct rx_packet *)0;
2504 call->app.nLeft = call->app.nFree = call->app.curlen = 0;
2506 /* Free any packets from the last call to ReadvProc/WritevProc */
2507 #ifdef RXDEBUG_PACKET
2509 #endif /* RXDEBUG_PACKET */
2510 rxi_FreePackets(0, &call->app.iovq);
2511 MUTEX_EXIT(&call->lock);
2513 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2514 if (conn->type == RX_CLIENT_CONNECTION) {
2515 MUTEX_ENTER(&conn->conn_data_lock);
2516 conn->flags &= ~RX_CONN_BUSY;
2517 MUTEX_EXIT(&conn->conn_data_lock);
2518 MUTEX_EXIT(&conn->conn_call_lock);
2522 * Map errors to the local host's errno.h format.
2524 error = ntoh_syserr_conv(error);
2526 /* If the caller said the call failed with some error, we had better
2527 * return an error code. */
2528 osi_Assert(!rc || error);
2532 #if !defined(KERNEL)
2534 /* Call this routine when shutting down a server or client (especially
2535 * clients). This will allow Rx to gracefully garbage collect server
2536 * connections, and reduce the number of retries that a server might
2537 * make to a dead client.
2538 * This is not quite right, since some calls may still be ongoing and
2539 * we can't lock them to destroy them. */
2545 if (!rxi_IsRunning()) {
2547 return; /* Already shutdown. */
2549 rxi_Finalize_locked();
2554 rxi_Finalize_locked(void)
2556 struct rx_connection **conn_ptr, **conn_end;
2557 rx_atomic_set(&rxi_running, 0);
2558 rxi_DeleteCachedConnections();
2559 if (rx_connHashTable) {
2560 MUTEX_ENTER(&rx_connHashTable_lock);
2561 for (conn_ptr = &rx_connHashTable[0], conn_end =
2562 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2564 struct rx_connection *conn, *next;
2565 for (conn = *conn_ptr; conn; conn = next) {
2567 if (conn->type == RX_CLIENT_CONNECTION) {
2568 rx_GetConnection(conn);
2569 #ifdef RX_ENABLE_LOCKS
2570 rxi_DestroyConnectionNoLock(conn);
2571 #else /* RX_ENABLE_LOCKS */
2572 rxi_DestroyConnection(conn);
2573 #endif /* RX_ENABLE_LOCKS */
2577 #ifdef RX_ENABLE_LOCKS
2578 while (rx_connCleanup_list) {
2579 struct rx_connection *conn;
2580 conn = rx_connCleanup_list;
2581 rx_connCleanup_list = rx_connCleanup_list->next;
2582 MUTEX_EXIT(&rx_connHashTable_lock);
2583 rxi_CleanupConnection(conn);
2584 MUTEX_ENTER(&rx_connHashTable_lock);
2586 MUTEX_EXIT(&rx_connHashTable_lock);
2587 #endif /* RX_ENABLE_LOCKS */
2592 afs_winsockCleanup();
2597 /* if we wakeup packet waiter too often, can get in loop with two
2598 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2600 rxi_PacketsUnWait(void)
2602 if (!rx_waitingForPackets) {
2606 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2607 return; /* still over quota */
2610 rx_waitingForPackets = 0;
2611 #ifdef RX_ENABLE_LOCKS
2612 CV_BROADCAST(&rx_waitingForPackets_cv);
2614 osi_rxWakeup(&rx_waitingForPackets);
2620 /* ------------------Internal interfaces------------------------- */
2622 /* Return this process's service structure for the
2623 * specified socket and service */
2624 static struct rx_service *
2625 rxi_FindService(osi_socket socket, u_short serviceId)
2627 struct rx_service **sp;
2628 for (sp = &rx_services[0]; *sp; sp++) {
2629 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2635 #ifdef RXDEBUG_PACKET
2636 #ifdef KDUMP_RX_LOCK
2637 static struct rx_call_rx_lock *rx_allCallsp = 0;
2639 static struct rx_call *rx_allCallsp = 0;
2641 #endif /* RXDEBUG_PACKET */
2643 /* Allocate a call structure, for the indicated channel of the
2644 * supplied connection. The mode and state of the call must be set by
2645 * the caller. Returns the call with mutex locked. */
2646 static struct rx_call *
2647 rxi_NewCall(struct rx_connection *conn, int channel)
2649 struct rx_call *call;
2650 #ifdef RX_ENABLE_LOCKS
2651 struct rx_call *cp; /* Call pointer temp */
2652 struct opr_queue *cursor;
2655 dpf(("rxi_NewCall(conn %p, channel %d)\n", conn, channel));
2657 /* Grab an existing call structure, or allocate a new one.
2658 * Existing call structures are assumed to have been left reset by
2660 MUTEX_ENTER(&rx_freeCallQueue_lock);
2662 #ifdef RX_ENABLE_LOCKS
2664 * EXCEPT that the TQ might not yet be cleared out.
2665 * Skip over those with in-use TQs.
2668 for (opr_queue_Scan(&rx_freeCallQueue, cursor)) {
2669 cp = opr_queue_Entry(cursor, struct rx_call, entry);
2670 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2676 #else /* RX_ENABLE_LOCKS */
2677 if (!opr_queue_IsEmpty(&rx_freeCallQueue)) {
2678 call = opr_queue_First(&rx_freeCallQueue, struct rx_call, entry);
2679 #endif /* RX_ENABLE_LOCKS */
2680 opr_queue_Remove(&call->entry);
2681 if (rx_stats_active)
2682 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2683 MUTEX_EXIT(&rx_freeCallQueue_lock);
2684 MUTEX_ENTER(&call->lock);
2685 CLEAR_CALL_QUEUE_LOCK(call);
2686 #ifdef RX_ENABLE_LOCKS
2687 /* Now, if TQ wasn't cleared earlier, do it now. */
2688 rxi_WaitforTQBusy(call);
2689 if (call->flags & RX_CALL_TQ_CLEARME) {
2690 rxi_ClearTransmitQueue(call, 1);
2691 /*queue_Init(&call->tq);*/
2693 #endif /* RX_ENABLE_LOCKS */
2694 /* Bind the call to its connection structure */
2696 rxi_ResetCall(call, 1);
2699 call = rxi_Alloc(sizeof(struct rx_call));
2700 #ifdef RXDEBUG_PACKET
2701 call->allNextp = rx_allCallsp;
2702 rx_allCallsp = call;
2704 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2705 #else /* RXDEBUG_PACKET */
2706 rx_atomic_inc(&rx_stats.nCallStructs);
2707 #endif /* RXDEBUG_PACKET */
2709 MUTEX_EXIT(&rx_freeCallQueue_lock);
2710 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2711 MUTEX_ENTER(&call->lock);
2712 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2713 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2714 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2716 /* Initialize once-only items */
2717 opr_queue_Init(&call->tq);
2718 opr_queue_Init(&call->rq);
2719 opr_queue_Init(&call->app.iovq);
2720 #ifdef RXDEBUG_PACKET
2721 call->rqc = call->tqc = call->iovqc = 0;
2722 #endif /* RXDEBUG_PACKET */
2723 /* Bind the call to its connection structure (prereq for reset) */
2725 rxi_ResetCall(call, 1);
2727 call->channel = channel;
2728 call->callNumber = &conn->callNumber[channel];
2729 call->rwind = conn->rwind[channel];
2730 call->twind = conn->twind[channel];
2731 /* Note that the next expected call number is retained (in
2732 * conn->callNumber[i]), even if we reallocate the call structure
2734 conn->call[channel] = call;
2735 /* if the channel's never been used (== 0), we should start at 1, otherwise
2736 * the call number is valid from the last time this channel was used */
2737 if (*call->callNumber == 0)
2738 *call->callNumber = 1;
2743 /* A call has been inactive long enough that so we can throw away
2744 * state, including the call structure, which is placed on the call
2747 * call->lock amd rx_refcnt_mutex are held upon entry.
2748 * haveCTLock is set when called from rxi_ReapConnections.
2750 * return 1 if the call is freed, 0 if not.
2753 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2755 int channel = call->channel;
2756 struct rx_connection *conn = call->conn;
2757 u_char state = call->state;
2760 * We are setting the state to RX_STATE_RESET to
2761 * ensure that no one else will attempt to use this
2762 * call once we drop the refcnt lock. We must drop
2763 * the refcnt lock before calling rxi_ResetCall
2764 * because it cannot be held across acquiring the
2765 * freepktQ lock. NewCall does the same.
2767 call->state = RX_STATE_RESET;
2768 MUTEX_EXIT(&rx_refcnt_mutex);
2769 rxi_ResetCall(call, 0);
2771 if (MUTEX_TRYENTER(&conn->conn_call_lock))
2773 if (state == RX_STATE_DALLY || state == RX_STATE_HOLD)
2774 (*call->callNumber)++;
2776 if (call->conn->call[channel] == call)
2777 call->conn->call[channel] = 0;
2778 MUTEX_EXIT(&conn->conn_call_lock);
2781 * We couldn't obtain the conn_call_lock so we can't
2782 * disconnect the call from the connection. Set the
2783 * call state to dally so that the call can be reused.
2785 MUTEX_ENTER(&rx_refcnt_mutex);
2786 call->state = RX_STATE_DALLY;
2790 MUTEX_ENTER(&rx_freeCallQueue_lock);
2791 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2792 #ifdef RX_ENABLE_LOCKS
2793 /* A call may be free even though its transmit queue is still in use.
2794 * Since we search the call list from head to tail, put busy calls at
2795 * the head of the list, and idle calls at the tail.
2797 if (call->flags & RX_CALL_TQ_BUSY)
2798 opr_queue_Prepend(&rx_freeCallQueue, &call->entry);
2800 opr_queue_Append(&rx_freeCallQueue, &call->entry);
2801 #else /* RX_ENABLE_LOCKS */
2802 opr_queue_Append(&rx_freeCallQueue, &call->entry);
2803 #endif /* RX_ENABLE_LOCKS */
2804 if (rx_stats_active)
2805 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2806 MUTEX_EXIT(&rx_freeCallQueue_lock);
2808 /* Destroy the connection if it was previously slated for
2809 * destruction, i.e. the Rx client code previously called
2810 * rx_DestroyConnection (client connections), or
2811 * rxi_ReapConnections called the same routine (server
2812 * connections). Only do this, however, if there are no
2813 * outstanding calls. Note that for fine grain locking, there appears
2814 * to be a deadlock in that rxi_FreeCall has a call locked and
2815 * DestroyConnectionNoLock locks each call in the conn. But note a
2816 * few lines up where we have removed this call from the conn.
2817 * If someone else destroys a connection, they either have no
2818 * call lock held or are going through this section of code.
2820 MUTEX_ENTER(&conn->conn_data_lock);
2821 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2822 rx_GetConnection(conn);
2823 MUTEX_EXIT(&conn->conn_data_lock);
2824 #ifdef RX_ENABLE_LOCKS
2826 rxi_DestroyConnectionNoLock(conn);
2828 rxi_DestroyConnection(conn);
2829 #else /* RX_ENABLE_LOCKS */
2830 rxi_DestroyConnection(conn);
2831 #endif /* RX_ENABLE_LOCKS */
2833 MUTEX_EXIT(&conn->conn_data_lock);
2835 MUTEX_ENTER(&rx_refcnt_mutex);
2839 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2840 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2843 rxi_Alloc(size_t size)
2847 if (rx_stats_active) {
2848 rx_atomic_add(&rxi_Allocsize, (int) size);
2849 rx_atomic_inc(&rxi_Alloccnt);
2853 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD_ENV)
2854 afs_osi_Alloc_NoSleep(size);
2859 osi_Panic("rxi_Alloc error");
2865 rxi_Free(void *addr, size_t size)
2870 if (rx_stats_active) {
2871 rx_atomic_sub(&rxi_Allocsize, (int) size);
2872 rx_atomic_dec(&rxi_Alloccnt);
2874 osi_Free(addr, size);
2878 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2880 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2881 struct rx_peer *next = NULL;
2885 MUTEX_ENTER(&rx_peerHashTable_lock);
2887 peer_ptr = &rx_peerHashTable[0];
2888 peer_end = &rx_peerHashTable[rx_hashTableSize];
2891 for ( ; peer_ptr < peer_end; peer_ptr++) {
2894 for ( ; peer; peer = next) {
2896 if (host == peer->host)
2901 hashIndex = PEER_HASH(host, port);
2902 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2903 if ((peer->host == host) && (peer->port == port))
2908 MUTEX_ENTER(&rx_peerHashTable_lock);
2913 MUTEX_EXIT(&rx_peerHashTable_lock);
2915 MUTEX_ENTER(&peer->peer_lock);
2916 /* We don't handle dropping below min, so don't */
2917 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2918 peer->ifMTU=MIN(mtu, peer->ifMTU);
2919 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2920 /* if we tweaked this down, need to tune our peer MTU too */
2921 peer->MTU = MIN(peer->MTU, peer->natMTU);
2922 /* if we discovered a sub-1500 mtu, degrade */
2923 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2924 peer->maxDgramPackets = 1;
2925 /* We no longer have valid peer packet information */
2926 if (peer->maxPacketSize + RX_HEADER_SIZE > peer->ifMTU)
2927 peer->maxPacketSize = 0;
2928 MUTEX_EXIT(&peer->peer_lock);
2930 MUTEX_ENTER(&rx_peerHashTable_lock);
2932 if (host && !port) {
2934 /* pick up where we left off */
2938 MUTEX_EXIT(&rx_peerHashTable_lock);
2941 #ifdef AFS_RXERRQ_ENV
2943 rxi_SetPeerDead(struct sock_extended_err *err, afs_uint32 host, afs_uint16 port)
2945 int hashIndex = PEER_HASH(host, port);
2946 struct rx_peer *peer;
2948 MUTEX_ENTER(&rx_peerHashTable_lock);
2950 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2951 if (peer->host == host && peer->port == port) {
2957 MUTEX_EXIT(&rx_peerHashTable_lock);
2960 rx_atomic_inc(&peer->neterrs);
2961 MUTEX_ENTER(&peer->peer_lock);
2962 peer->last_err_origin = RX_NETWORK_ERROR_ORIGIN_ICMP;
2963 peer->last_err_type = err->ee_type;
2964 peer->last_err_code = err->ee_code;
2965 MUTEX_EXIT(&peer->peer_lock);
2967 MUTEX_ENTER(&rx_peerHashTable_lock);
2969 MUTEX_EXIT(&rx_peerHashTable_lock);
2974 rxi_ProcessNetError(struct sock_extended_err *err, afs_uint32 addr, afs_uint16 port)
2976 # ifdef AFS_ADAPT_PMTU
2977 if (err->ee_errno == EMSGSIZE && err->ee_info >= 68) {
2978 rxi_SetPeerMtu(NULL, addr, port, err->ee_info - RX_IPUDP_SIZE);
2982 if (err->ee_origin == SO_EE_ORIGIN_ICMP && err->ee_type == ICMP_DEST_UNREACH) {
2983 switch (err->ee_code) {
2984 case ICMP_NET_UNREACH:
2985 case ICMP_HOST_UNREACH:
2986 case ICMP_PORT_UNREACH:
2989 rxi_SetPeerDead(err, addr, port);
2996 rxi_TranslateICMP(int type, int code)
2999 case ICMP_DEST_UNREACH:
3001 case ICMP_NET_UNREACH:
3002 return "Destination Net Unreachable";
3003 case ICMP_HOST_UNREACH:
3004 return "Destination Host Unreachable";
3005 case ICMP_PROT_UNREACH:
3006 return "Destination Protocol Unreachable";
3007 case ICMP_PORT_UNREACH:
3008 return "Destination Port Unreachable";
3010 return "Destination Net Prohibited";
3012 return "Destination Host Prohibited";
3018 #endif /* AFS_RXERRQ_ENV */
3021 * Get the last network error for a connection
3023 * A "network error" here means an error retrieved from ICMP, or some other
3024 * mechanism outside of Rx that informs us of errors in network reachability.
3026 * If a peer associated with the given Rx connection has received a network
3027 * error recently, this function allows the caller to know what error
3028 * specifically occurred. This can be useful to know, since e.g. ICMP errors
3029 * can cause calls to that peer to be quickly aborted. So, this function can
3030 * help see why a call was aborted due to network errors.
3032 * If we have received traffic from a peer since the last network error, we
3033 * treat that peer as if we had not received an network error for it.
3035 * @param[in] conn The Rx connection to examine
3036 * @param[out] err_origin The origin of the last network error (e.g. ICMP);
3037 * one of the RX_NETWORK_ERROR_ORIGIN_* constants
3038 * @param[out] err_type The type of the last error
3039 * @param[out] err_code The code of the last error
3040 * @param[out] msg Human-readable error message, if applicable; NULL otherwise
3042 * @return If we have an error
3043 * @retval -1 No error to get; 'out' params are undefined
3044 * @retval 0 We have an error; 'out' params contain the last error
3047 rx_GetNetworkError(struct rx_connection *conn, int *err_origin, int *err_type,
3048 int *err_code, const char **msg)
3050 #ifdef AFS_RXERRQ_ENV
3051 struct rx_peer *peer = conn->peer;
3052 if (rx_atomic_read(&peer->neterrs)) {
3053 MUTEX_ENTER(&peer->peer_lock);
3054 *err_origin = peer->last_err_origin;
3055 *err_type = peer->last_err_type;
3056 *err_code = peer->last_err_code;
3057 MUTEX_EXIT(&peer->peer_lock);
3060 if (*err_origin == RX_NETWORK_ERROR_ORIGIN_ICMP) {
3061 *msg = rxi_TranslateICMP(*err_type, *err_code);
3070 /* Find the peer process represented by the supplied (host,port)
3071 * combination. If there is no appropriate active peer structure, a
3072 * new one will be allocated and initialized
3075 rxi_FindPeer(afs_uint32 host, u_short port, int create)
3079 hashIndex = PEER_HASH(host, port);
3080 MUTEX_ENTER(&rx_peerHashTable_lock);
3081 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
3082 if ((pp->host == host) && (pp->port == port))
3087 pp = rxi_AllocPeer(); /* This bzero's *pp */
3088 pp->host = host; /* set here or in InitPeerParams is zero */
3090 #ifdef AFS_RXERRQ_ENV
3091 rx_atomic_set(&pp->neterrs, 0);
3093 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
3094 opr_queue_Init(&pp->rpcStats);
3095 pp->next = rx_peerHashTable[hashIndex];
3096 rx_peerHashTable[hashIndex] = pp;
3097 rxi_InitPeerParams(pp);
3098 if (rx_stats_active)
3099 rx_atomic_inc(&rx_stats.nPeerStructs);
3105 MUTEX_EXIT(&rx_peerHashTable_lock);
3110 rxi_ConnectionMatch(struct rx_connection *conn,
3111 afs_uint32 host, u_short port, afs_uint32 cid,
3112 afs_uint32 epoch, int type, u_int securityIndex,
3113 int *a_badSecurityIndex)
3116 if (conn->type != type) {
3119 if (conn->cid != (cid & RX_CIDMASK)) {
3122 if (conn->epoch != epoch) {
3125 if (conn->securityIndex != securityIndex) {
3126 if (a_badSecurityIndex) {
3127 *a_badSecurityIndex = 1;
3132 if (pp->host == host && pp->port == port) {
3135 if (type == RX_CLIENT_CONNECTION && pp->port == port) {
3136 /* For client conns, we allow packets from any host to be associated
3140 if ((conn->epoch & 0x80000000)) {
3141 /* If the epoch high bit is set, we ignore the host/port of any packets
3142 * coming in for the conn. */
3148 /* Find the connection at (host, port) started at epoch, and with the
3149 * given connection id. Creates the server connection if necessary.
3150 * The type specifies whether a client connection or a server
3151 * connection is desired. In both cases, (host, port) specify the
3152 * peer's (host, pair) pair. Client connections are not made
3153 * automatically by this routine. The parameter socket gives the
3154 * socket descriptor on which the packet was received. This is used,
3155 * in the case of server connections, to check that *new* connections
3156 * come via a valid (port, serviceId). Finally, the securityIndex
3157 * parameter must match the existing index for the connection. If a
3158 * server connection is created, it will be created using the supplied
3159 * index, if the index is valid for this service */
3160 static struct rx_connection *
3161 rxi_FindConnection(osi_socket socket, afs_uint32 host,
3162 u_short port, u_short serviceId, afs_uint32 cid,
3163 afs_uint32 epoch, int type, u_int securityIndex,
3164 int *unknownService)
3166 int hashindex, flag, i;
3168 struct rx_connection *conn;
3169 *unknownService = 0;
3170 hashindex = CONN_HASH(host, port, cid, epoch, type);
3171 MUTEX_ENTER(&rx_connHashTable_lock);
3172 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
3173 rx_connHashTable[hashindex],
3177 if (rxi_ConnectionMatch(conn, host, port, cid, epoch, type,
3178 securityIndex, &bad_sec)) {
3183 * This isn't supposed to happen, but someone could forge a packet
3184 * like this, and bugs causing such packets are not unheard of.
3186 MUTEX_EXIT(&rx_connHashTable_lock);
3190 /* the connection rxLastConn that was used the last time is not the
3191 ** one we are looking for now. Hence, start searching in the hash */
3193 conn = rx_connHashTable[hashindex];
3198 struct rx_service *service;
3199 if (type == RX_CLIENT_CONNECTION) {
3200 MUTEX_EXIT(&rx_connHashTable_lock);
3201 return (struct rx_connection *)0;
3203 service = rxi_FindService(socket, serviceId);
3204 if (!service || (securityIndex >= service->nSecurityObjects)
3205 || (service->securityObjects[securityIndex] == 0)) {
3206 MUTEX_EXIT(&rx_connHashTable_lock);
3207 *unknownService = 1;
3208 return (struct rx_connection *)0;
3210 conn = rxi_AllocConnection(); /* This bzero's the connection */
3211 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
3212 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
3213 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
3214 conn->next = rx_connHashTable[hashindex];
3215 rx_connHashTable[hashindex] = conn;
3216 conn->peer = rxi_FindPeer(host, port, 1);
3217 conn->type = RX_SERVER_CONNECTION;
3218 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
3219 conn->epoch = epoch;
3220 conn->cid = cid & RX_CIDMASK;
3221 conn->ackRate = RX_FAST_ACK_RATE;
3222 conn->service = service;
3223 conn->serviceId = serviceId;
3224 conn->securityIndex = securityIndex;
3225 conn->securityObject = service->securityObjects[securityIndex];
3226 conn->nSpecific = 0;
3227 conn->specific = NULL;
3228 rx_SetConnDeadTime(conn, service->connDeadTime);
3229 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
3230 for (i = 0; i < RX_MAXCALLS; i++) {
3231 conn->twind[i] = rx_initSendWindow;
3232 conn->rwind[i] = rx_initReceiveWindow;
3234 /* Notify security object of the new connection */
3235 code = RXS_NewConnection(conn->securityObject, conn);
3236 /* XXXX Connection timeout? */
3237 if (service->newConnProc)
3238 (*service->newConnProc) (conn);
3239 if (rx_stats_active)
3240 rx_atomic_inc(&rx_stats.nServerConns);
3243 rx_GetConnection(conn);
3245 rxLastConn = conn; /* store this connection as the last conn used */
3246 MUTEX_EXIT(&rx_connHashTable_lock);
3248 rxi_ConnectionError(conn, code);
3254 * Abort the call if the server is over the busy threshold. This
3255 * can be used without requiring a call structure be initialised,
3256 * or connected to a particular channel
3259 rxi_AbortIfServerBusy(osi_socket socket, struct rx_connection *conn,
3260 struct rx_packet *np)
3264 if ((rx_BusyThreshold > 0) &&
3265 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3266 MUTEX_ENTER(&conn->conn_data_lock);
3267 serial = ++conn->serial;
3268 MUTEX_EXIT(&conn->conn_data_lock);
3269 rxi_SendRawAbort(socket, conn->peer->host, conn->peer->port,
3270 serial, rx_BusyError, np, 0);
3271 if (rx_stats_active)
3272 rx_atomic_inc(&rx_stats.nBusies);
3279 static_inline struct rx_call *
3280 rxi_ReceiveClientCall(struct rx_packet *np, struct rx_connection *conn)
3283 struct rx_call *call;
3285 channel = np->header.cid & RX_CHANNELMASK;
3286 MUTEX_ENTER(&conn->conn_call_lock);
3287 call = conn->call[channel];
3288 if (np->header.type == RX_PACKET_TYPE_BUSY) {
3289 conn->lastBusy[channel] = clock_Sec();
3291 if (!call || conn->callNumber[channel] != np->header.callNumber) {
3292 MUTEX_EXIT(&conn->conn_call_lock);
3293 if (rx_stats_active)
3294 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3298 MUTEX_ENTER(&call->lock);
3299 MUTEX_EXIT(&conn->conn_call_lock);
3301 if ((call->state == RX_STATE_DALLY)
3302 && np->header.type == RX_PACKET_TYPE_ACK) {
3303 if (rx_stats_active)
3304 rx_atomic_inc(&rx_stats.ignorePacketDally);
3305 MUTEX_EXIT(&call->lock);
3312 static_inline struct rx_call *
3313 rxi_ReceiveServerCall(osi_socket socket, struct rx_packet *np,
3314 struct rx_connection *conn)
3317 struct rx_call *call;
3319 channel = np->header.cid & RX_CHANNELMASK;
3320 MUTEX_ENTER(&conn->conn_call_lock);
3321 call = conn->call[channel];
3324 if (np->header.type != RX_PACKET_TYPE_DATA) {
3326 * Clients must send DATA packets at some point to create a new
3327 * call. If the first packet we saw for this call channel is
3328 * something else, then either the DATA packets got lost/delayed,
3329 * or we were restarted and this is an existing call from before we
3330 * were restarted. In the latter case, some clients get confused if
3331 * we respond to such requests, so just drop the packet to make
3332 * things easier for them.
3334 MUTEX_EXIT(&conn->conn_call_lock);
3335 if (rx_stats_active)
3336 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3340 if (np->header.seq > rx_maxReceiveWindow) {
3342 * This is a DATA packet for further along in the call than is
3343 * possible for a new call. This is probably from an existing call
3344 * that was in the middle of running when we were restarted; ignore
3345 * it to avoid confusing clients. (See above comment about non-DATA
3348 MUTEX_EXIT(&conn->conn_call_lock);
3349 if (rx_stats_active)
3350 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3354 if (rxi_AbortIfServerBusy(socket, conn, np)) {
3355 MUTEX_EXIT(&conn->conn_call_lock);
3359 call = rxi_NewCall(conn, channel); /* returns locked call */
3360 *call->callNumber = np->header.callNumber;
3361 MUTEX_EXIT(&conn->conn_call_lock);
3363 call->state = RX_STATE_PRECALL;
3364 clock_GetTime(&call->queueTime);
3365 call->app.bytesSent = 0;
3366 call->app.bytesRcvd = 0;
3367 rxi_KeepAliveOn(call);
3372 if (np->header.callNumber == conn->callNumber[channel]) {
3373 MUTEX_ENTER(&call->lock);
3374 MUTEX_EXIT(&conn->conn_call_lock);
3378 if (np->header.callNumber < conn->callNumber[channel]) {
3379 MUTEX_EXIT(&conn->conn_call_lock);
3380 if (rx_stats_active)
3381 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3385 MUTEX_ENTER(&call->lock);
3386 MUTEX_EXIT(&conn->conn_call_lock);
3388 /* Wait until the transmit queue is idle before deciding
3389 * whether to reset the current call. Chances are that the
3390 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3393 #ifdef RX_ENABLE_LOCKS
3394 if (call->state == RX_STATE_ACTIVE && !call->error) {
3395 rxi_WaitforTQBusy(call);
3396 /* If we entered error state while waiting,
3397 * must call rxi_CallError to permit rxi_ResetCall
3398 * to processed when the tqWaiter count hits zero.
3401 rxi_CallError(call, call->error);
3402 MUTEX_EXIT(&call->lock);
3406 #endif /* RX_ENABLE_LOCKS */
3407 /* If the new call cannot be taken right now send a busy and set
3408 * the error condition in this call, so that it terminates as
3409 * quickly as possible */
3410 if (call->state == RX_STATE_ACTIVE) {
3411 rxi_CallError(call, RX_CALL_DEAD);
3412 rxi_SendSpecial(call, conn, NULL, RX_PACKET_TYPE_BUSY,
3414 MUTEX_EXIT(&call->lock);
3418 if (rxi_AbortIfServerBusy(socket, conn, np)) {
3419 MUTEX_EXIT(&call->lock);
3423 rxi_ResetCall(call, 0);
3424 /* The conn_call_lock is not held but no one else should be
3425 * using this call channel while we are processing this incoming
3426 * packet. This assignment should be safe.
3428 *call->callNumber = np->header.callNumber;
3429 call->state = RX_STATE_PRECALL;
3430 clock_GetTime(&call->queueTime);
3431 call->app.bytesSent = 0;
3432 call->app.bytesRcvd = 0;
3433 rxi_KeepAliveOn(call);
3439 /* There are two packet tracing routines available for testing and monitoring
3440 * Rx. One is called just after every packet is received and the other is
3441 * called just before every packet is sent. Received packets, have had their
3442 * headers decoded, and packets to be sent have not yet had their headers
3443 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
3444 * containing the network address. Both can be modified. The return value, if
3445 * non-zero, indicates that the packet should be dropped. */
3447 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
3448 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
3450 /* A packet has been received off the interface. Np is the packet, socket is
3451 * the socket number it was received from (useful in determining which service
3452 * this packet corresponds to), and (host, port) reflect the host,port of the
3453 * sender. This call returns the packet to the caller if it is finished with
3454 * it, rather than de-allocating it, just as a small performance hack */
3457 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
3458 afs_uint32 host, u_short port, int *tnop,
3459 struct rx_call **newcallp)
3461 struct rx_call *call;
3462 struct rx_connection *conn;
3464 int unknownService = 0;
3469 struct rx_packet *tnp;
3472 /* We don't print out the packet until now because (1) the time may not be
3473 * accurate enough until now in the lwp implementation (rx_Listener only gets
3474 * the time after the packet is read) and (2) from a protocol point of view,
3475 * this is the first time the packet has been seen */
3476 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
3477 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
3478 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %p\n",
3479 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
3480 np->header.epoch, np->header.cid, np->header.callNumber,
3481 np->header.seq, np->header.flags, np));
3484 /* Account for connectionless packets */
3485 if (rx_stats_active &&
3486 ((np->header.type == RX_PACKET_TYPE_VERSION) ||
3487 (np->header.type == RX_PACKET_TYPE_DEBUG))) {
3488 struct rx_peer *peer;
3490 /* Try to look up the peer structure, but don't create one */
3491 peer = rxi_FindPeer(host, port, 0);
3493 /* Since this may not be associated with a connection, it may have
3494 * no refCount, meaning we could race with ReapConnections
3497 if (peer && (peer->refCount > 0)) {
3498 #ifdef AFS_RXERRQ_ENV
3499 if (rx_atomic_read(&peer->neterrs)) {
3500 rx_atomic_set(&peer->neterrs, 0);
3503 MUTEX_ENTER(&peer->peer_lock);
3504 peer->bytesReceived += np->length;
3505 MUTEX_EXIT(&peer->peer_lock);
3509 if (np->header.type == RX_PACKET_TYPE_VERSION) {
3510 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
3513 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
3514 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
3517 /* If an input tracer function is defined, call it with the packet and
3518 * network address. Note this function may modify its arguments. */
3519 if (rx_justReceived) {
3520 struct sockaddr_in addr;
3522 addr.sin_family = AF_INET;
3523 addr.sin_port = port;
3524 addr.sin_addr.s_addr = host;
3525 memset(&addr.sin_zero, 0, sizeof(addr.sin_zero));
3526 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
3527 addr.sin_len = sizeof(addr);
3529 drop = (*rx_justReceived) (np, &addr);
3530 /* drop packet if return value is non-zero */
3533 port = addr.sin_port; /* in case fcn changed addr */
3534 host = addr.sin_addr.s_addr;
3538 /* If packet was not sent by the client, then *we* must be the client */
3539 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
3540 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
3542 /* Find the connection (or fabricate one, if we're the server & if
3543 * necessary) associated with this packet */
3545 rxi_FindConnection(socket, host, port, np->header.serviceId,
3546 np->header.cid, np->header.epoch, type,
3547 np->header.securityIndex, &unknownService);
3549 /* To avoid having 2 connections just abort at each other,
3550 don't abort an abort. */
3552 if (unknownService && (np->header.type != RX_PACKET_TYPE_ABORT))
3553 rxi_SendRawAbort(socket, host, port, 0, RX_INVALID_OPERATION,
3558 #ifdef AFS_RXERRQ_ENV
3559 if (rx_atomic_read(&conn->peer->neterrs)) {
3560 rx_atomic_set(&conn->peer->neterrs, 0);
3564 /* If we're doing statistics, then account for the incoming packet */
3565 if (rx_stats_active) {
3566 MUTEX_ENTER(&conn->peer->peer_lock);
3567 conn->peer->bytesReceived += np->length;
3568 MUTEX_EXIT(&conn->peer->peer_lock);
3571 /* If the connection is in an error state, send an abort packet and ignore
3572 * the incoming packet */
3574 /* Don't respond to an abort packet--we don't want loops! */
3575 MUTEX_ENTER(&conn->conn_data_lock);
3576 if (np->header.type != RX_PACKET_TYPE_ABORT)
3577 np = rxi_SendConnectionAbort(conn, np, 1, 0);
3578 putConnection(conn);
3579 MUTEX_EXIT(&conn->conn_data_lock);
3583 /* Check for connection-only requests (i.e. not call specific). */
3584 if (np->header.callNumber == 0) {
3585 switch (np->header.type) {
3586 case RX_PACKET_TYPE_ABORT: {
3587 /* What if the supplied error is zero? */
3588 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
3589 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
3590 rxi_ConnectionError(conn, errcode);
3591 putConnection(conn);
3594 case RX_PACKET_TYPE_CHALLENGE:
3595 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
3596 putConnection(conn);
3598 case RX_PACKET_TYPE_RESPONSE:
3599 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
3600 putConnection(conn);
3602 case RX_PACKET_TYPE_PARAMS:
3603 case RX_PACKET_TYPE_PARAMS + 1:
3604 case RX_PACKET_TYPE_PARAMS + 2:
3605 /* ignore these packet types for now */
3606 putConnection(conn);
3610 /* Should not reach here, unless the peer is broken: send an
3612 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
3613 MUTEX_ENTER(&conn->conn_data_lock);
3614 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
3615 putConnection(conn);
3616 MUTEX_EXIT(&conn->conn_data_lock);
3621 if (type == RX_SERVER_CONNECTION)
3622 call = rxi_ReceiveServerCall(socket, np, conn);
3624 call = rxi_ReceiveClientCall(np, conn);
3627 putConnection(conn);
3631 MUTEX_ASSERT(&call->lock);
3632 /* Set remote user defined status from packet */
3633 call->remoteStatus = np->header.userStatus;
3635 /* Now do packet type-specific processing */
3636 switch (np->header.type) {
3637 case RX_PACKET_TYPE_DATA:
3638 /* If we're a client, and receiving a response, then all the packets
3639 * we transmitted packets are implicitly acknowledged. */
3640 if (type == RX_CLIENT_CONNECTION && !opr_queue_IsEmpty(&call->tq))
3641 rxi_AckAllInTransmitQueue(call);
3643 np = rxi_ReceiveDataPacket(call, np, 1, socket, tnop, newcallp);
3645 case RX_PACKET_TYPE_ACK:
3646 /* Respond immediately to ack packets requesting acknowledgement
3648 if (np->header.flags & RX_REQUEST_ACK) {
3650 (void)rxi_SendCallAbort(call, 0, 1, 0);
3652 (void)rxi_SendAck(call, 0, np->header.serial,
3653 RX_ACK_PING_RESPONSE, 1);
3655 np = rxi_ReceiveAckPacket(call, np, 1, &invalid);
3657 case RX_PACKET_TYPE_ABORT: {
3658 /* An abort packet: reset the call, passing the error up to the user. */
3659 /* What if error is zero? */
3660 /* What if the error is -1? the application will treat it as a timeout. */
3661 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3662 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3663 rxi_CallError(call, errdata);
3664 MUTEX_EXIT(&call->lock);
3665 putConnection(conn);
3666 return np; /* xmitting; drop packet */
3668 case RX_PACKET_TYPE_BUSY:
3669 /* Mostly ignore BUSY packets. We will update lastReceiveTime below,
3670 * so we don't think the endpoint is completely dead, but otherwise
3671 * just act as if we never saw anything. If all we get are BUSY packets
3672 * back, then we will eventually error out with RX_CALL_TIMEOUT if the
3673 * connection is configured with idle/hard timeouts. */
3676 case RX_PACKET_TYPE_ACKALL:
3677 /* All packets acknowledged, so we can drop all packets previously
3678 * readied for sending */
3679 rxi_AckAllInTransmitQueue(call);
3682 /* Should not reach here, unless the peer is broken: send an abort
3684 rxi_CallError(call, RX_PROTOCOL_ERROR);
3685 np = rxi_SendCallAbort(call, np, 1, 0);
3689 if (rx_stats_active)
3690 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3693 * Note when this last legitimate packet was received, for keep-alive
3696 call->lastReceiveTime = clock_Sec();
3698 MUTEX_EXIT(&call->lock);
3699 putConnection(conn);
3703 /* return true if this is an "interesting" connection from the point of view
3704 of someone trying to debug the system */
3706 rxi_IsConnInteresting(struct rx_connection *aconn)
3709 struct rx_call *tcall;
3711 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3714 for (i = 0; i < RX_MAXCALLS; i++) {
3715 tcall = aconn->call[i];
3717 if ((tcall->state == RX_STATE_PRECALL)
3718 || (tcall->state == RX_STATE_ACTIVE))
3720 if ((tcall->app.mode == RX_MODE_SENDING)
3721 || (tcall->app.mode == RX_MODE_RECEIVING))
3729 /* if this is one of the last few packets AND it wouldn't be used by the
3730 receiving call to immediately satisfy a read request, then drop it on
3731 the floor, since accepting it might prevent a lock-holding thread from
3732 making progress in its reading. If a call has been cleared while in
3733 the precall state then ignore all subsequent packets until the call
3734 is assigned to a thread. */
3737 TooLow(struct rx_packet *ap, struct rx_call *acall)
3741 MUTEX_ENTER(&rx_quota_mutex);
3742 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3743 && (acall->state == RX_STATE_PRECALL))
3744 || ((rx_nFreePackets < rxi_dataQuota + 2)
3745 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3746 && (acall->flags & RX_CALL_READER_WAIT)))) {
3749 MUTEX_EXIT(&rx_quota_mutex);
3755 * Clear the attach wait flag on a connection and proceed.
3757 * Any processing waiting for a connection to be attached should be
3758 * unblocked. We clear the flag and do any other needed tasks.
3761 * the conn to unmark waiting for attach
3763 * @pre conn's conn_data_lock must be locked before calling this function
3767 rxi_ConnClearAttachWait(struct rx_connection *conn)
3769 /* Indicate that rxi_CheckReachEvent is no longer running by
3770 * clearing the flag. Must be atomic under conn_data_lock to
3771 * avoid a new call slipping by: rxi_CheckConnReach holds
3772 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3774 conn->flags &= ~RX_CONN_ATTACHWAIT;
3775 if (conn->flags & RX_CONN_NAT_PING) {
3776 conn->flags &= ~RX_CONN_NAT_PING;
3777 rxi_ScheduleNatKeepAliveEvent(conn);
3782 * Event handler function for connection-specific events for checking
3783 * reachability. Also called directly from main code with |event| == NULL
3784 * in order to trigger the initial reachability check.
3786 * When |event| == NULL, must be called with the connection data lock held,
3787 * but returns with the lock unlocked.
3790 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2, int dummy)
3792 struct rx_connection *conn = arg1;
3793 struct rx_call *acall = arg2;
3794 struct rx_call *call = acall;
3795 struct clock when, now;
3799 MUTEX_ENTER(&conn->conn_data_lock);
3801 MUTEX_ASSERT(&conn->conn_data_lock);
3803 if (event != NULL && event == conn->checkReachEvent)
3804 rxevent_Put(&conn->checkReachEvent);
3805 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3806 MUTEX_EXIT(&conn->conn_data_lock);
3810 MUTEX_ENTER(&conn->conn_call_lock);
3811 MUTEX_ENTER(&conn->conn_data_lock);
3812 for (i = 0; i < RX_MAXCALLS; i++) {
3813 struct rx_call *tc = conn->call[i];
3814 if (tc && tc->state == RX_STATE_PRECALL) {
3820 rxi_ConnClearAttachWait(conn);
3821 MUTEX_EXIT(&conn->conn_data_lock);
3822 MUTEX_EXIT(&conn->conn_call_lock);
3827 MUTEX_ENTER(&call->lock);
3828 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3830 MUTEX_EXIT(&call->lock);
3832 clock_GetTime(&now);
3834 when.sec += RX_CHECKREACH_TIMEOUT;
3835 MUTEX_ENTER(&conn->conn_data_lock);
3836 if (!conn->checkReachEvent) {
3837 rx_GetConnection(conn);
3838 conn->checkReachEvent = rxevent_Post(&when, &now,
3839 rxi_CheckReachEvent, conn,
3842 MUTEX_EXIT(&conn->conn_data_lock);
3845 /* If fired as an event handler, drop our refcount on the connection. */
3847 putConnection(conn);
3851 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3853 struct rx_service *service = conn->service;
3854 struct rx_peer *peer = conn->peer;
3855 afs_uint32 now, lastReach;
3857 if (service->checkReach == 0)
3861 MUTEX_ENTER(&peer->peer_lock);
3862 lastReach = peer->lastReachTime;
3863 MUTEX_EXIT(&peer->peer_lock);
3864 if (now - lastReach < RX_CHECKREACH_TTL)
3867 MUTEX_ENTER(&conn->conn_data_lock);
3868 if (conn->flags & RX_CONN_ATTACHWAIT) {
3869 MUTEX_EXIT(&conn->conn_data_lock);
3872 conn->flags |= RX_CONN_ATTACHWAIT;
3873 if (conn->checkReachEvent == NULL) {
3874 /* rxi_CheckReachEvent(NULL, ...) will drop the lock. */
3875 rxi_CheckReachEvent(NULL, conn, call, 0);
3877 MUTEX_EXIT(&conn->conn_data_lock);
3883 /* try to attach call, if authentication is complete */
3885 TryAttach(struct rx_call *acall, osi_socket socket,
3886 int *tnop, struct rx_call **newcallp,
3887 int reachOverride, int istack)
3889 struct rx_connection *conn = acall->conn;
3891 if (conn->type == RX_SERVER_CONNECTION
3892 && acall->state == RX_STATE_PRECALL) {
3893 /* Don't attach until we have any req'd. authentication. */
3894 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3895 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3896 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3897 /* Note: this does not necessarily succeed; there
3898 * may not any proc available
3902 code = rxi_ChallengeOn(acall->conn);
3905 * Ideally we would rxi_ConnectionError here, but doing that is
3906 * difficult, because some callers may have locked 'call',
3907 * _and_ another call on the same conn. So we cannot
3908 * rxi_ConnectionError, since that needs to lock every call on
3909 * the conn. But we can at least abort the call we have.
3911 rxi_CallError(acall, code);
3912 rxi_SendCallAbort(acall, NULL, istack, 0);
3918 /* A data packet has been received off the interface. This packet is
3919 * appropriate to the call (the call is in the right state, etc.). This
3920 * routine can return a packet to the caller, for re-use */
3922 static struct rx_packet *
3923 rxi_ReceiveDataPacket(struct rx_call *call,
3924 struct rx_packet *np, int istack,
3925 osi_socket socket, int *tnop, struct rx_call **newcallp)
3927 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3932 afs_uint32 serial=0, flags=0;
3934 struct rx_packet *tnp;
3935 if (rx_stats_active)
3936 rx_atomic_inc(&rx_stats.dataPacketsRead);
3939 /* If there are no packet buffers, drop this new packet, unless we can find
3940 * packet buffers from inactive calls */
3942 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3943 MUTEX_ENTER(&rx_freePktQ_lock);
3944 rxi_NeedMorePackets = TRUE;
3945 MUTEX_EXIT(&rx_freePktQ_lock);
3946 if (rx_stats_active)
3947 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3948 rxi_calltrace(RX_TRACE_DROP, call);
3949 dpf(("packet %p dropped on receipt - quota problems\n", np));
3950 /* We used to clear the receive queue here, in an attempt to free
3951 * packets. However this is unsafe if the queue has received a
3952 * soft ACK for the final packet */
3953 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
3959 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3960 * packet is one of several packets transmitted as a single
3961 * datagram. Do not send any soft or hard acks until all packets
3962 * in a jumbogram have been processed. Send negative acks right away.
3964 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3965 /* tnp is non-null when there are more packets in the
3966 * current jumbo gram */
3973 seq = np->header.seq;
3974 serial = np->header.serial;
3975 flags = np->header.flags;
3977 /* If the call is in an error state, send an abort message */
3979 return rxi_SendCallAbort(call, np, istack, 0);
3981 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3982 * AFS 3.5 jumbogram. */
3983 if (flags & RX_JUMBO_PACKET) {
3984 tnp = rxi_SplitJumboPacket(np);
3989 if (np->header.spare != 0) {
3990 MUTEX_ENTER(&call->conn->conn_data_lock);
3991 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3992 MUTEX_EXIT(&call->conn->conn_data_lock);
3995 /* The usual case is that this is the expected next packet */
3996 if (seq == call->rnext) {
3998 /* Check to make sure it is not a duplicate of one already queued */
3999 if (!opr_queue_IsEmpty(&call->rq)
4000 && opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq == seq) {
4001 if (rx_stats_active)
4002 rx_atomic_inc(&rx_stats.dupPacketsRead);
4003 dpf(("packet %p dropped on receipt - duplicate\n", np));
4004 rxi_CancelDelayedAckEvent(call);
4005 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
4011 /* It's the next packet. Stick it on the receive queue
4012 * for this call. Set newPackets to make sure we wake
4013 * the reader once all packets have been processed */
4014 #ifdef RX_TRACK_PACKETS
4015 np->flags |= RX_PKTFLAG_RQ;
4017 opr_queue_Prepend(&call->rq, &np->entry);
4018 #ifdef RXDEBUG_PACKET
4020 #endif /* RXDEBUG_PACKET */
4022 np = NULL; /* We can't use this anymore */
4025 /* If an ack is requested then set a flag to make sure we
4026 * send an acknowledgement for this packet */
4027 if (flags & RX_REQUEST_ACK) {
4028 ackNeeded = RX_ACK_REQUESTED;
4031 /* Keep track of whether we have received the last packet */
4032 if (flags & RX_LAST_PACKET) {
4033 call->flags |= RX_CALL_HAVE_LAST;
4037 /* Check whether we have all of the packets for this call */
4038 if (call->flags & RX_CALL_HAVE_LAST) {
4039 afs_uint32 tseq; /* temporary sequence number */
4040 struct opr_queue *cursor;
4042 for (tseq = seq, opr_queue_Scan(&call->rq, cursor)) {
4043 struct rx_packet *tp;
4045 tp = opr_queue_Entry(cursor, struct rx_packet, entry);
4046 if (tseq != tp->header.seq)
4048 if (tp->header.flags & RX_LAST_PACKET) {
4049 call->flags |= RX_CALL_RECEIVE_DONE;
4056 /* Provide asynchronous notification for those who want it
4057 * (e.g. multi rx) */
4058 if (call->arrivalProc) {
4059 (*call->arrivalProc) (call, call->arrivalProcHandle,
4060 call->arrivalProcArg);
4061 call->arrivalProc = NULL;
4064 /* Update last packet received */
4067 /* If there is no server process serving this call, grab
4068 * one, if available. We only need to do this once. If a
4069 * server thread is available, this thread becomes a server
4070 * thread and the server thread becomes a listener thread. */
4072 TryAttach(call, socket, tnop, newcallp, 0, istack);
4075 /* This is not the expected next packet. */
4077 /* Determine whether this is a new or old packet, and if it's
4078 * a new one, whether it fits into the current receive window.
4079 * Also figure out whether the packet was delivered in sequence.
4080 * We use the prev variable to determine whether the new packet
4081 * is the successor of its immediate predecessor in the
4082 * receive queue, and the missing flag to determine whether
4083 * any of this packets predecessors are missing. */
4085 afs_uint32 prev; /* "Previous packet" sequence number */
4086 struct opr_queue *cursor;
4087 int missing; /* Are any predecessors missing? */
4089 /* If the new packet's sequence number has been sent to the
4090 * application already, then this is a duplicate */
4091 if (seq < call->rnext) {
4092 if (rx_stats_active)
4093 rx_atomic_inc(&rx_stats.dupPacketsRead);
4094 rxi_CancelDelayedAckEvent(call);
4095 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
4101 /* If the sequence number is greater than what can be
4102 * accomodated by the current window, then send a negative
4103 * acknowledge and drop the packet */
4104 if ((call->rnext + call->rwind) <= seq) {
4105 rxi_CancelDelayedAckEvent(call);
4106 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
4113 /* Look for the packet in the queue of old received packets */
4114 prev = call->rnext - 1;
4116 for (opr_queue_Scan(&call->rq, cursor)) {
4117 struct rx_packet *tp
4118 = opr_queue_Entry(cursor, struct rx_packet, entry);
4120 /*Check for duplicate packet */
4121 if (seq == tp->header.seq) {
4122 if (rx_stats_active)
4123 rx_atomic_inc(&rx_stats.dupPacketsRead);
4124 rxi_CancelDelayedAckEvent(call);
4125 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
4131 /* If we find a higher sequence packet, break out and
4132 * insert the new packet here. */
4133 if (seq < tp->header.seq)
4135 /* Check for missing packet */
4136 if (tp->header.seq != prev + 1) {
4140 prev = tp->header.seq;
4143 /* Keep track of whether we have received the last packet. */
4144 if (flags & RX_LAST_PACKET) {
4145 call->flags |= RX_CALL_HAVE_LAST;
4148 /* It's within the window: add it to the the receive queue.
4149 * tp is left by the previous loop either pointing at the
4150 * packet before which to insert the new packet, or at the
4151 * queue head if the queue is empty or the packet should be
4153 #ifdef RX_TRACK_PACKETS
4154 np->flags |= RX_PKTFLAG_RQ;
4156 #ifdef RXDEBUG_PACKET
4158 #endif /* RXDEBUG_PACKET */
4159 opr_queue_InsertBefore(cursor, &np->entry);
4163 /* Check whether we have all of the packets for this call */
4164 if ((call->flags & RX_CALL_HAVE_LAST)
4165 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
4166 afs_uint32 tseq; /* temporary sequence number */
4169 for (opr_queue_Scan(&call->rq, cursor)) {
4170 struct rx_packet *tp
4171 = opr_queue_Entry(cursor, struct rx_packet, entry);
4172 if (tseq != tp->header.seq)
4174 if (tp->header.flags & RX_LAST_PACKET) {
4175 call->flags |= RX_CALL_RECEIVE_DONE;
4182 /* We need to send an ack of the packet is out of sequence,
4183 * or if an ack was requested by the peer. */
4184 if (seq != prev + 1 || missing) {
4185 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
4186 } else if (flags & RX_REQUEST_ACK) {
4187 ackNeeded = RX_ACK_REQUESTED;
4190 /* Acknowledge the last packet for each call */
4191 if (flags & RX_LAST_PACKET) {
4202 * If the receiver is waiting for an iovec, fill the iovec
4203 * using the data from the receive queue */
4204 if (call->flags & RX_CALL_IOVEC_WAIT) {
4205 didHardAck = rxi_FillReadVec(call, serial);
4206 /* the call may have been aborted */
4215 /* Wakeup the reader if any */
4216 if ((call->flags & RX_CALL_READER_WAIT)
4217 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
4218 || (call->iovNext >= call->iovMax)
4219 || (call->flags & RX_CALL_RECEIVE_DONE))) {
4220 call->flags &= ~RX_CALL_READER_WAIT;
4221 #ifdef RX_ENABLE_LOCKS
4222 CV_BROADCAST(&call->cv_rq);
4224 osi_rxWakeup(&call->rq);
4230 * Send an ack when requested by the peer, or once every
4231 * rxi_SoftAckRate packets until the last packet has been
4232 * received. Always send a soft ack for the last packet in
4233 * the server's reply. */
4235 rxi_CancelDelayedAckEvent(call);
4236 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
4237 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
4238 rxi_CancelDelayedAckEvent(call);
4239 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
4240 } else if (call->nSoftAcks) {
4241 if (haveLast && !(flags & RX_CLIENT_INITIATED))
4242 rxi_PostDelayedAckEvent(call, &rx_lastAckDelay);
4244 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
4245 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
4246 rxi_CancelDelayedAckEvent(call);
4253 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall,
4256 struct rx_peer *peer = conn->peer;
4258 MUTEX_ENTER(&peer->peer_lock);
4259 peer->lastReachTime = clock_Sec();
4260 MUTEX_EXIT(&peer->peer_lock);
4262 MUTEX_ENTER(&conn->conn_data_lock);
4263 if (conn->flags & RX_CONN_ATTACHWAIT) {
4266 rxi_ConnClearAttachWait(conn);
4267 MUTEX_EXIT(&conn->conn_data_lock);
4269 for (i = 0; i < RX_MAXCALLS; i++) {
4270 struct rx_call *call = conn->call[i];
4273 MUTEX_ENTER(&call->lock);
4274 /* tnop can be null if newcallp is null */
4275 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1, istack);
4277 MUTEX_EXIT(&call->lock);
4281 MUTEX_EXIT(&conn->conn_data_lock);
4284 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
4286 rx_ack_reason(int reason)
4289 case RX_ACK_REQUESTED:
4291 case RX_ACK_DUPLICATE:
4293 case RX_ACK_OUT_OF_SEQUENCE:
4295 case RX_ACK_EXCEEDS_WINDOW:
4297 case RX_ACK_NOSPACE:
4301 case RX_ACK_PING_RESPONSE:
4314 ack_is_valid(struct rx_call *call, afs_uint32 first, afs_uint32 prev)
4316 if (first < call->tfirst) {
4318 * The peer indicated that the window went backwards. That's not
4319 * allowed; the window can only move forwards.
4324 if (first == call->tfirst && prev < call->tprev) {
4326 * The peer said the last DATA packet it received was seq X, but it
4327 * already told us before that it had received data after X. This is
4328 * probably just an out-of-order ACK, and so we can ignore it.
4330 if (prev >= call->tfirst + call->twind) {
4332 * Some peers (OpenAFS libafs before 1.6.23) mistakenly set the
4333 * previousPacket field to a serial number, not a sequence number.
4334 * The sequence number the peer told us about is further than our
4335 * transmit window, so it cannot possibly be correct; it's probably
4336 * actually a serial number. Don't ignore packets based on this;
4337 * the previousPacket information is not accurate.
4345 /* Otherwise, the ack looks valid. */
4349 /* The real smarts of the whole thing. */
4350 static struct rx_packet *
4351 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
4352 int istack, int *a_invalid)
4354 struct rx_ackPacket *ap;
4356 struct rx_packet *tp;
4357 struct rx_connection *conn = call->conn;
4358 struct rx_peer *peer = conn->peer;
4359 struct opr_queue *cursor;
4360 struct clock now; /* Current time, for RTT calculations */
4368 int newAckCount = 0;
4369 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
4370 int pktsize = 0; /* Set if we need to update the peer mtu */
4371 int conn_data_locked = 0;
4375 if (rx_stats_active)
4376 rx_atomic_inc(&rx_stats.ackPacketsRead);
4377 ap = (struct rx_ackPacket *)rx_DataOf(np);
4378 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
4380 return np; /* truncated ack packet */
4382 /* depends on ack packet struct */
4383 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
4384 first = ntohl(ap->firstPacket);
4385 prev = ntohl(ap->previousPacket);
4386 serial = ntohl(ap->serial);
4388 if (!ack_is_valid(call, first, prev)) {
4396 if (np->header.flags & RX_SLOW_START_OK) {
4397 call->flags |= RX_CALL_SLOW_START_OK;
4400 if (ap->reason == RX_ACK_PING_RESPONSE)
4401 rxi_UpdatePeerReach(conn, call, istack);
4403 if (conn->lastPacketSizeSeq) {
4404 MUTEX_ENTER(&conn->conn_data_lock);
4405 conn_data_locked = 1;
4406 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
4407 pktsize = conn->lastPacketSize;
4408 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
4411 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
4412 if (!conn_data_locked) {
4413 MUTEX_ENTER(&conn->conn_data_lock);
4414 conn_data_locked = 1;
4416 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
4417 /* process mtu ping ack */
4418 pktsize = conn->lastPingSize;
4419 conn->lastPingSizeSer = conn->lastPingSize = 0;
4423 if (conn_data_locked) {
4424 MUTEX_EXIT(&conn->conn_data_lock);
4425 conn_data_locked = 0;
4429 if (rxdebug_active) {
4433 len = _snprintf(msg, sizeof(msg),
4434 "tid[%d] RACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
4435 GetCurrentThreadId(), rx_ack_reason(ap->reason),
4436 ntohl(ap->serial), ntohl(ap->previousPacket),
4437 (unsigned int)np->header.seq, ntohl(ap->firstPacket),
4438 ap->nAcks, ntohs(ap->bufferSpace) );
4442 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
4443 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4447 OutputDebugString(msg);
4449 #else /* AFS_NT40_ENV */
4452 "RACK: reason %x previous %u seq %u serial %u first %u",
4453 ap->reason, ntohl(ap->previousPacket),
4454 (unsigned int)np->header.seq, (unsigned int)serial,
4455 ntohl(ap->firstPacket));
4458 for (offset = 0; offset < nAcks; offset++)
4459 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4464 #endif /* AFS_NT40_ENV */
4467 MUTEX_ENTER(&peer->peer_lock);
4470 * Start somewhere. Can't assume we can send what we can receive,
4471 * but we are clearly receiving.
4473 if (!peer->maxPacketSize)
4474 peer->maxPacketSize = RX_MIN_PACKET_SIZE - RX_HEADER_SIZE;
4476 if (pktsize > peer->maxPacketSize) {
4477 peer->maxPacketSize = pktsize;
4478 if ((pktsize + RX_HEADER_SIZE > peer->ifMTU)) {
4479 peer->ifMTU = pktsize + RX_HEADER_SIZE;
4480 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4481 rxi_ScheduleGrowMTUEvent(call, 1);
4486 clock_GetTime(&now);
4488 /* The transmit queue splits into 4 sections.
4490 * The first section is packets which have now been acknowledged
4491 * by a window size change in the ack. These have reached the
4492 * application layer, and may be discarded. These are packets
4493 * with sequence numbers < ap->firstPacket.
4495 * The second section is packets which have sequence numbers in
4496 * the range ap->firstPacket to ap->firstPacket + ap->nAcks. The
4497 * contents of the packet's ack array determines whether these
4498 * packets are acknowledged or not.
4500 * The third section is packets which fall above the range
4501 * addressed in the ack packet. These have not yet been received
4504 * The four section is packets which have not yet been transmitted.
4505 * These packets will have a header.serial of 0.
4508 /* First section - implicitly acknowledged packets that can be
4512 tp = opr_queue_First(&call->tq, struct rx_packet, entry);
4513 while(!opr_queue_IsEnd(&call->tq, &tp->entry) && tp->header.seq < first) {
4514 struct rx_packet *next;
4516 next = opr_queue_Next(&tp->entry, struct rx_packet, entry);
4517 call->tfirst = tp->header.seq + 1;
4519 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4521 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4524 #ifdef RX_ENABLE_LOCKS
4525 /* XXX Hack. Because we have to release the global call lock when sending
4526 * packets (rxi_NetSend) we drop all acks while we're traversing the tq
4527 * in rxi_Start sending packets out because packets may move to the
4528 * freePacketQueue as result of being here! So we drop these packets until
4529 * we're safely out of the traversing. Really ugly!
4530 * To make it even uglier, if we're using fine grain locking, we can
4531 * set the ack bits in the packets and have rxi_Start remove the packets
4532 * when it's done transmitting.
4534 if (call->flags & RX_CALL_TQ_BUSY) {
4535 tp->flags |= RX_PKTFLAG_ACKED;
4536 call->flags |= RX_CALL_TQ_SOME_ACKED;
4538 #endif /* RX_ENABLE_LOCKS */
4540 opr_queue_Remove(&tp->entry);
4541 #ifdef RX_TRACK_PACKETS
4542 tp->flags &= ~RX_PKTFLAG_TQ;
4544 #ifdef RXDEBUG_PACKET
4546 #endif /* RXDEBUG_PACKET */
4547 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4552 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
4554 /* Second section of the queue - packets for which we are receiving
4557 * Go through the explicit acks/nacks and record the results in
4558 * the waiting packets. These are packets that can't be released
4559 * yet, even with a positive acknowledge. This positive
4560 * acknowledge only means the packet has been received by the
4561 * peer, not that it will be retained long enough to be sent to
4562 * the peer's upper level. In addition, reset the transmit timers
4563 * of any missing packets (those packets that must be missing
4564 * because this packet was out of sequence) */
4566 call->nSoftAcked = 0;
4568 while (!opr_queue_IsEnd(&call->tq, &tp->entry)
4569 && tp->header.seq < first + nAcks) {
4570 /* Set the acknowledge flag per packet based on the
4571 * information in the ack packet. An acknowlegded packet can
4572 * be downgraded when the server has discarded a packet it
4573 * soacked previously, or when an ack packet is received
4574 * out of sequence. */
4575 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4576 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4578 tp->flags |= RX_PKTFLAG_ACKED;
4579 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4586 } else /* RX_ACK_TYPE_NACK */ {
4587 tp->flags &= ~RX_PKTFLAG_ACKED;
4591 tp = opr_queue_Next(&tp->entry, struct rx_packet, entry);
4594 /* We don't need to take any action with the 3rd or 4th section in the
4595 * queue - they're not addressed by the contents of this ACK packet.
4598 /* if the ack packet has a receivelen field hanging off it,
4599 * update our state */
4600 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4603 /* If the ack packet has a "recommended" size that is less than
4604 * what I am using now, reduce my size to match */
4605 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4606 (int)sizeof(afs_int32), &tSize);
4607 tSize = (afs_uint32) ntohl(tSize);
4608 if (tSize > RX_MAX_PACKET_SIZE)
4609 tSize = RX_MAX_PACKET_SIZE;
4610 if (tSize < RX_MIN_PACKET_SIZE)
4611 tSize = RX_MIN_PACKET_SIZE;
4612 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4614 /* Get the maximum packet size to send to this peer */
4615 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4617 tSize = (afs_uint32) ntohl(tSize);
4618 if (tSize > RX_MAX_PACKET_SIZE)
4619 tSize = RX_MAX_PACKET_SIZE;
4620 if (tSize < RX_MIN_PACKET_SIZE)
4621 tSize = RX_MIN_PACKET_SIZE;
4622 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4623 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4625 /* sanity check - peer might have restarted with different params.
4626 * If peer says "send less", dammit, send less... Peer should never
4627 * be unable to accept packets of the size that prior AFS versions would
4628 * send without asking. */
4629 if (peer->maxMTU != tSize) {
4630 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4632 peer->maxMTU = tSize;
4633 peer->MTU = MIN(tSize, peer->MTU);
4634 call->MTU = MIN(call->MTU, tSize);
4637 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4640 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4641 (int)sizeof(afs_int32), &tSize);
4642 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4645 if (tSize >= rx_maxSendWindow)
4646 tSize = rx_maxSendWindow;
4647 if (tSize < call->twind) { /* smaller than our send */
4648 call->twind = tSize; /* window, we must send less... */
4649 call->ssthresh = MIN(call->twind, call->ssthresh);
4650 call->conn->twind[call->channel] = call->twind;
4653 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4654 * network MTU confused with the loopback MTU. Calculate the
4655 * maximum MTU here for use in the slow start code below.
4657 /* Did peer restart with older RX version? */
4658 if (peer->maxDgramPackets > 1) {
4659 peer->maxDgramPackets = 1;
4661 } else if (np->length >=
4662 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4665 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4666 sizeof(afs_int32), &tSize);
4667 tSize = (afs_uint32) ntohl(tSize);
4670 if (tSize >= rx_maxSendWindow)
4671 tSize = rx_maxSendWindow;
4673 * As of AFS 3.5 we set the send window to match the receive window.
4675 if (tSize < call->twind) {
4676 call->twind = tSize;
4677 call->conn->twind[call->channel] = call->twind;
4678 call->ssthresh = MIN(call->twind, call->ssthresh);
4679 } else if (tSize > call->twind) {
4680 call->twind = tSize;
4681 call->conn->twind[call->channel] = call->twind;
4685 * As of AFS 3.5, a jumbogram is more than one fixed size
4686 * packet transmitted in a single UDP datagram. If the remote
4687 * MTU is smaller than our local MTU then never send a datagram
4688 * larger than the natural MTU.
4691 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4692 (int)sizeof(afs_int32), &tSize);
4693 maxDgramPackets = (afs_uint32) ntohl(tSize);
4694 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4696 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4697 if (maxDgramPackets > 1) {
4698 peer->maxDgramPackets = maxDgramPackets;
4699 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4701 peer->maxDgramPackets = 1;
4702 call->MTU = peer->natMTU;
4704 } else if (peer->maxDgramPackets > 1) {
4705 /* Restarted with lower version of RX */
4706 peer->maxDgramPackets = 1;
4708 } else if (peer->maxDgramPackets > 1
4709 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4710 /* Restarted with lower version of RX */
4711 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4712 peer->natMTU = OLD_MAX_PACKET_SIZE;
4713 peer->MTU = OLD_MAX_PACKET_SIZE;
4714 peer->maxDgramPackets = 1;
4715 peer->nDgramPackets = 1;
4717 call->MTU = OLD_MAX_PACKET_SIZE;
4720 /* If the window has been extended by this acknowledge packet,
4721 * then wakeup a sender waiting in alloc for window space, or try
4722 * sending packets now, if he's been sitting on packets due to
4723 * lack of window space */
4724 if (call->tnext < (call->tfirst + call->twind)) {
4725 #ifdef RX_ENABLE_LOCKS
4726 CV_SIGNAL(&call->cv_twind);
4728 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4729 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4730 osi_rxWakeup(&call->twind);
4733 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4734 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4740 * Calculate how many datagrams were successfully received after
4741 * the first missing packet and adjust the negative ack counter
4746 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4747 if (call->nNacks < nNacked) {
4748 call->nNacks = nNacked;
4751 call->nAcks += newAckCount;
4755 /* If the packet contained new acknowledgements, rather than just
4756 * being a duplicate of one we have previously seen, then we can restart
4759 if (newAckCount > 0)
4760 rxi_rto_packet_acked(call, istack);
4762 if (call->flags & RX_CALL_FAST_RECOVER) {
4763 if (newAckCount == 0) {
4764 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4766 call->flags &= ~RX_CALL_FAST_RECOVER;
4767 call->cwind = call->nextCwind;
4768 call->nextCwind = 0;
4771 call->nCwindAcks = 0;
4772 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4773 /* Three negative acks in a row trigger congestion recovery */
4774 call->flags |= RX_CALL_FAST_RECOVER;
4775 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4777 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4778 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4779 call->nextCwind = call->ssthresh;
4782 peer->MTU = call->MTU;
4783 peer->cwind = call->nextCwind;
4784 peer->nDgramPackets = call->nDgramPackets;
4786 call->congestSeq = peer->congestSeq;
4788 /* Reset the resend times on the packets that were nacked
4789 * so we will retransmit as soon as the window permits
4793 for (opr_queue_ScanBackwards(&call->tq, cursor)) {
4794 struct rx_packet *tp =
4795 opr_queue_Entry(cursor, struct rx_packet, entry);
4797 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4798 tp->flags &= ~RX_PKTFLAG_SENT;
4800 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4805 /* If cwind is smaller than ssthresh, then increase
4806 * the window one packet for each ack we receive (exponential
4808 * If cwind is greater than or equal to ssthresh then increase
4809 * the congestion window by one packet for each cwind acks we
4810 * receive (linear growth). */
4811 if (call->cwind < call->ssthresh) {
4813 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4814 call->nCwindAcks = 0;
4816 call->nCwindAcks += newAckCount;
4817 if (call->nCwindAcks >= call->cwind) {
4818 call->nCwindAcks = 0;
4819 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4823 * If we have received several acknowledgements in a row then
4824 * it is time to increase the size of our datagrams
4826 if ((int)call->nAcks > rx_nDgramThreshold) {
4827 if (peer->maxDgramPackets > 1) {
4828 if (call->nDgramPackets < peer->maxDgramPackets) {
4829 call->nDgramPackets++;
4831 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4832 } else if (call->MTU < peer->maxMTU) {
4833 /* don't upgrade if we can't handle it */
4834 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4835 call->MTU = peer->ifMTU;
4837 call->MTU += peer->natMTU;
4838 call->MTU = MIN(call->MTU, peer->maxMTU);
4845 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4847 /* Servers need to hold the call until all response packets have
4848 * been acknowledged. Soft acks are good enough since clients
4849 * are not allowed to clear their receive queues. */
4850 if (call->state == RX_STATE_HOLD
4851 && call->tfirst + call->nSoftAcked >= call->tnext) {
4852 call->state = RX_STATE_DALLY;
4853 rxi_ClearTransmitQueue(call, 0);
4854 rxi_CancelKeepAliveEvent(call);
4855 } else if (!opr_queue_IsEmpty(&call->tq)) {
4856 rxi_Start(call, istack);
4862 * Schedule a connection abort to be sent after some delay.
4864 * @param[in] conn The connection to send the abort on.
4865 * @param[in] msec The number of milliseconds to wait before sending.
4867 * @pre conn_data_lock must be held
4870 rxi_SendConnectionAbortLater(struct rx_connection *conn, int msec)
4872 struct clock when, now;
4874 MUTEX_ASSERT(&conn->conn_data_lock);
4878 if (!conn->delayedAbortEvent) {
4879 clock_GetTime(&now);
4881 clock_Addmsec(&when, msec);
4882 rx_GetConnection(conn);
4883 conn->delayedAbortEvent =
4884 rxevent_Post(&when, &now, rxi_SendDelayedConnAbort, conn, NULL, 0);
4888 /* Received a response to a challenge packet */
4889 static struct rx_packet *
4890 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4891 struct rx_packet *np, int istack)
4895 /* Ignore the packet if we're the client */
4896 if (conn->type == RX_CLIENT_CONNECTION)
4899 /* If already authenticated, ignore the packet (it's probably a retry) */
4900 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4903 if (!conn->securityChallengeSent) {
4904 /* We've never sent out a challenge for this connection, so this
4905 * response cannot possibly be correct; ignore it. This can happen
4906 * if we sent a challenge to the client, then we were restarted, and
4907 * then the client sent us a response. If we ignore the response, the
4908 * client will eventually resend a data packet, causing us to send a
4909 * new challenge and the client to send a new response. */
4913 /* Otherwise, have the security object evaluate the response packet */
4914 error = RXS_CheckResponse(conn->securityObject, conn, np);
4916 /* If the response is invalid, reset the connection, sending
4917 * an abort to the peer. Send the abort with a 1 second delay,
4918 * to avoid a peer hammering us by constantly recreating a
4919 * connection with bad credentials. */
4920 rxi_ConnectionError(conn, error);
4921 MUTEX_ENTER(&conn->conn_data_lock);
4922 rxi_SendConnectionAbortLater(conn, 1000);
4923 MUTEX_EXIT(&conn->conn_data_lock);
4926 /* If the response is valid, any calls waiting to attach
4927 * servers can now do so */
4930 for (i = 0; i < RX_MAXCALLS; i++) {
4931 struct rx_call *call = conn->call[i];
4933 MUTEX_ENTER(&call->lock);
4934 if (call->state == RX_STATE_PRECALL)
4935 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4936 /* tnop can be null if newcallp is null */
4937 MUTEX_EXIT(&call->lock);
4941 /* Update the peer reachability information, just in case
4942 * some calls went into attach-wait while we were waiting
4943 * for authentication..
4945 rxi_UpdatePeerReach(conn, NULL, istack);
4950 /* A client has received an authentication challenge: the security
4951 * object is asked to cough up a respectable response packet to send
4952 * back to the server. The server is responsible for retrying the
4953 * challenge if it fails to get a response. */
4955 static struct rx_packet *
4956 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4957 struct rx_packet *np, int istack)
4961 /* Ignore the challenge if we're the server */
4962 if (conn->type == RX_SERVER_CONNECTION)
4965 /* Ignore the challenge if the connection is otherwise idle; someone's
4966 * trying to use us as an oracle. */
4967 if (!rxi_HasActiveCalls(conn))
4970 /* Send the security object the challenge packet. It is expected to fill
4971 * in the response. */
4972 error = RXS_GetResponse(conn->securityObject, conn, np);
4974 /* If the security object is unable to return a valid response, reset the
4975 * connection and send an abort to the peer. Otherwise send the response
4976 * packet to the peer connection. */
4978 rxi_ConnectionError(conn, error);
4979 MUTEX_ENTER(&conn->conn_data_lock);
4980 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4981 MUTEX_EXIT(&conn->conn_data_lock);
4983 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4984 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4990 /* Find an available server process to service the current request in
4991 * the given call structure. If one isn't available, queue up this
4992 * call so it eventually gets one */
4994 rxi_AttachServerProc(struct rx_call *call,
4995 osi_socket socket, int *tnop,
4996 struct rx_call **newcallp)
4998 struct rx_serverQueueEntry *sq;
4999 struct rx_service *service = call->conn->service;
5002 /* May already be attached */
5003 if (call->state == RX_STATE_ACTIVE)
5006 MUTEX_ENTER(&rx_serverPool_lock);
5008 haveQuota = QuotaOK(service);
5009 if ((!haveQuota) || opr_queue_IsEmpty(&rx_idleServerQueue)) {
5010 /* If there are no processes available to service this call,
5011 * put the call on the incoming call queue (unless it's
5012 * already on the queue).
5014 #ifdef RX_ENABLE_LOCKS
5016 ReturnToServerPool(service);
5017 #endif /* RX_ENABLE_LOCKS */
5019 if (!(call->flags & RX_CALL_WAIT_PROC)) {
5020 call->flags |= RX_CALL_WAIT_PROC;
5021 rx_atomic_inc(&rx_nWaiting);
5022 rx_atomic_inc(&rx_nWaited);
5023 rxi_calltrace(RX_CALL_ARRIVAL, call);
5024 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
5025 opr_queue_Append(&rx_incomingCallQueue, &call->entry);
5028 sq = opr_queue_Last(&rx_idleServerQueue,
5029 struct rx_serverQueueEntry, entry);
5031 /* If hot threads are enabled, and both newcallp and sq->socketp
5032 * are non-null, then this thread will process the call, and the
5033 * idle server thread will start listening on this threads socket.
5035 opr_queue_Remove(&sq->entry);
5037 if (rx_enable_hot_thread && newcallp && sq->socketp) {
5040 *sq->socketp = socket;
5041 clock_GetTime(&call->startTime);
5042 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
5046 if (call->flags & RX_CALL_WAIT_PROC) {
5047 /* Conservative: I don't think this should happen */
5048 call->flags &= ~RX_CALL_WAIT_PROC;
5049 rx_atomic_dec(&rx_nWaiting);
5050 if (opr_queue_IsOnQueue(&call->entry)) {
5051 opr_queue_Remove(&call->entry);
5053 CLEAR_CALL_QUEUE_LOCK(call);
5055 call->state = RX_STATE_ACTIVE;
5056 call->app.mode = RX_MODE_RECEIVING;
5057 #ifdef RX_KERNEL_TRACE
5059 int glockOwner = ISAFS_GLOCK();
5062 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
5063 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
5069 if (call->flags & RX_CALL_CLEARED) {
5070 /* send an ack now to start the packet flow up again */
5071 call->flags &= ~RX_CALL_CLEARED;
5072 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
5074 #ifdef RX_ENABLE_LOCKS
5077 service->nRequestsRunning++;
5078 MUTEX_ENTER(&rx_quota_mutex);
5079 if (service->nRequestsRunning <= service->minProcs)
5082 MUTEX_EXIT(&rx_quota_mutex);
5086 MUTEX_EXIT(&rx_serverPool_lock);
5089 /* Delay the sending of an acknowledge event for a short while, while
5090 * a new call is being prepared (in the case of a client) or a reply
5091 * is being prepared (in the case of a server). Rather than sending
5092 * an ack packet, an ACKALL packet is sent. */
5094 rxi_AckAll(struct rx_call *call)
5096 rxi_SendSpecial(call, call->conn, NULL, RX_PACKET_TYPE_ACKALL,
5098 call->flags |= RX_CALL_ACKALL_SENT;
5102 * Event handler for per-call delayed acks.
5103 * Also called synchronously, with |event| == NULL, to send a "delayed" ack
5107 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused1,
5110 struct rx_call *call = arg1;
5111 #ifdef RX_ENABLE_LOCKS
5113 MUTEX_ENTER(&call->lock);
5114 if (event == call->delayedAckEvent)
5115 rxevent_Put(&call->delayedAckEvent);
5117 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
5119 MUTEX_EXIT(&call->lock);
5120 #else /* RX_ENABLE_LOCKS */
5122 rxevent_Put(&call->delayedAckEvent);
5123 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
5124 #endif /* RX_ENABLE_LOCKS */
5125 /* Release the call reference for the event that fired. */
5127 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
5130 #ifdef RX_ENABLE_LOCKS
5131 /* Set ack in all packets in transmit queue. rxi_Start will deal with
5132 * clearing them out.
5135 rxi_SetAcksInTransmitQueue(struct rx_call *call)
5137 struct opr_queue *cursor;
5140 for (opr_queue_Scan(&call->tq, cursor)) {
5142 = opr_queue_Entry(cursor, struct rx_packet, entry);
5144 p->flags |= RX_PKTFLAG_ACKED;
5149 call->flags |= RX_CALL_TQ_CLEARME;
5150 call->flags |= RX_CALL_TQ_SOME_ACKED;
5153 rxi_rto_cancel(call);
5155 call->tfirst = call->tnext;
5156 call->nSoftAcked = 0;
5158 if (call->flags & RX_CALL_FAST_RECOVER) {
5159 call->flags &= ~RX_CALL_FAST_RECOVER;
5160 call->cwind = call->nextCwind;
5161 call->nextCwind = 0;
5164 CV_SIGNAL(&call->cv_twind);
5166 #endif /* RX_ENABLE_LOCKS */
5169 * Acknowledge the whole transmit queue.
5171 * If we're running without locks, or the transmit queue isn't busy, then
5172 * we can just clear the queue now. Otherwise, we have to mark all of the
5173 * packets as acknowledged, and let rxi_Start clear it later on
5176 rxi_AckAllInTransmitQueue(struct rx_call *call)
5178 #ifdef RX_ENABLE_LOCKS
5179 if (call->flags & RX_CALL_TQ_BUSY) {
5180 rxi_SetAcksInTransmitQueue(call);
5184 rxi_ClearTransmitQueue(call, 0);
5186 /* Clear out the transmit queue for the current call (all packets have
5187 * been received by peer) */
5189 rxi_ClearTransmitQueue(struct rx_call *call, int force)
5191 #ifdef RX_ENABLE_LOCKS
5192 struct opr_queue *cursor;
5193 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
5195 for (opr_queue_Scan(&call->tq, cursor)) {
5197 = opr_queue_Entry(cursor, struct rx_packet, entry);
5199 p->flags |= RX_PKTFLAG_ACKED;
5203 call->flags |= RX_CALL_TQ_CLEARME;
5204 call->flags |= RX_CALL_TQ_SOME_ACKED;
5207 #endif /* RX_ENABLE_LOCKS */
5208 #ifdef RXDEBUG_PACKET
5210 #endif /* RXDEBUG_PACKET */
5211 rxi_FreePackets(0, &call->tq);
5212 rxi_WakeUpTransmitQueue(call);
5213 #ifdef RX_ENABLE_LOCKS
5214 call->flags &= ~RX_CALL_TQ_CLEARME;
5218 rxi_rto_cancel(call);
5219 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
5220 call->nSoftAcked = 0;
5222 if (call->flags & RX_CALL_FAST_RECOVER) {
5223 call->flags &= ~RX_CALL_FAST_RECOVER;
5224 call->cwind = call->nextCwind;
5226 #ifdef RX_ENABLE_LOCKS
5227 CV_SIGNAL(&call->cv_twind);
5229 osi_rxWakeup(&call->twind);
5234 rxi_ClearReceiveQueue(struct rx_call *call)
5236 if (!opr_queue_IsEmpty(&call->rq)) {
5239 count = rxi_FreePackets(0, &call->rq);
5240 rx_packetReclaims += count;
5241 #ifdef RXDEBUG_PACKET
5243 if ( call->rqc != 0 )
5244 dpf(("rxi_ClearReceiveQueue call %p rqc %u != 0\n", call, call->rqc));
5246 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
5248 if (call->state == RX_STATE_PRECALL) {
5249 call->flags |= RX_CALL_CLEARED;
5253 /* Send an abort packet for the specified call */
5254 static struct rx_packet *
5255 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
5256 int istack, int force)
5259 struct clock when, now;
5264 /* Clients should never delay abort messages */
5265 if (rx_IsClientConn(call->conn))
5269 * An opcode that has been deprecated or has yet to be implemented is not
5270 * a misbehavior of the client. Do not punish the client by introducing
5273 if (call->error == RXGEN_OPCODE) {
5275 } else if (call->abortCode != call->error) {
5276 call->abortCode = call->error;
5277 call->abortCount = 0;
5280 if (force || rxi_callAbortThreshhold == 0
5281 || call->abortCount < rxi_callAbortThreshhold) {
5282 rxi_CancelDelayedAbortEvent(call);
5283 error = htonl(call->error);
5287 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5288 (char *)&error, sizeof(error), istack);
5289 } else if (!call->delayedAbortEvent) {
5290 clock_GetTime(&now);
5292 clock_Addmsec(&when, rxi_callAbortDelay);
5293 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
5294 call->delayedAbortEvent =
5295 rxevent_Post(&when, &now, rxi_SendDelayedCallAbort, call, 0, 0);
5301 rxi_CancelDelayedAbortEvent(struct rx_call *call)
5303 MUTEX_ASSERT(&call->lock);
5304 if (rxevent_Cancel(&call->delayedAbortEvent))
5305 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
5308 /* Send an abort packet for the specified connection. Packet is an
5309 * optional pointer to a packet that can be used to send the abort.
5310 * Once the number of abort messages reaches the threshhold, an
5311 * event is scheduled to send the abort. Setting the force flag
5312 * overrides sending delayed abort messages.
5314 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
5315 * to send the abort packet.
5318 rxi_SendConnectionAbort(struct rx_connection *conn,
5319 struct rx_packet *packet, int istack, int force)
5326 /* Clients should never delay abort messages */
5327 if (rx_IsClientConn(conn))
5330 if (force || rxi_connAbortThreshhold == 0
5331 || conn->abortCount < rxi_connAbortThreshhold) {
5333 if (rxevent_Cancel(&conn->delayedAbortEvent))
5334 putConnection(conn);
5335 error = htonl(conn->error);
5337 MUTEX_EXIT(&conn->conn_data_lock);
5339 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5340 RX_PACKET_TYPE_ABORT, (char *)&error,
5341 sizeof(error), istack);
5342 MUTEX_ENTER(&conn->conn_data_lock);
5344 rxi_SendConnectionAbortLater(conn, rxi_connAbortDelay);
5349 /* Associate an error all of the calls owned by a connection. Called
5350 * with error non-zero. This is only for really fatal things, like
5351 * bad authentication responses. The connection itself is set in
5352 * error at this point, so that future packets received will be
5355 rxi_ConnectionError(struct rx_connection *conn,
5361 dpf(("rxi_ConnectionError conn %p error %d\n", conn, error));
5363 MUTEX_ENTER(&conn->conn_data_lock);
5364 if (rxevent_Cancel(&conn->challengeEvent))
5365 putConnection(conn);
5366 if (rxevent_Cancel(&conn->natKeepAliveEvent))
5367 putConnection(conn);
5368 if (rxevent_Cancel(&conn->checkReachEvent)) {
5369 conn->flags &= ~(RX_CONN_ATTACHWAIT|RX_CONN_NAT_PING);
5370 putConnection(conn);
5372 MUTEX_EXIT(&conn->conn_data_lock);
5373 for (i = 0; i < RX_MAXCALLS; i++) {
5374 struct rx_call *call = conn->call[i];
5376 MUTEX_ENTER(&call->lock);
5377 rxi_CallError(call, error);
5378 MUTEX_EXIT(&call->lock);
5381 conn->error = error;
5382 if (rx_stats_active)
5383 rx_atomic_inc(&rx_stats.fatalErrors);
5388 * Interrupt an in-progress call with the specified error and wakeup waiters.
5390 * @param[in] call The call to interrupt
5391 * @param[in] error The error code to send to the peer
5394 rx_InterruptCall(struct rx_call *call, afs_int32 error)
5396 MUTEX_ENTER(&call->lock);
5397 rxi_CallError(call, error);
5398 rxi_SendCallAbort(call, NULL, 0, 1);
5399 MUTEX_EXIT(&call->lock);
5403 rxi_CallError(struct rx_call *call, afs_int32 error)
5405 MUTEX_ASSERT(&call->lock);
5406 dpf(("rxi_CallError call %p error %d call->error %d\n", call, error, call->error));
5408 error = call->error;
5410 #ifdef RX_ENABLE_LOCKS
5411 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
5412 rxi_ResetCall(call, 0);
5415 rxi_ResetCall(call, 0);
5417 call->error = error;
5420 /* Reset various fields in a call structure, and wakeup waiting
5421 * processes. Some fields aren't changed: state & mode are not
5422 * touched (these must be set by the caller), and bufptr, nLeft, and
5423 * nFree are not reset, since these fields are manipulated by
5424 * unprotected macros, and may only be reset by non-interrupting code.
5428 rxi_ResetCall(struct rx_call *call, int newcall)
5431 struct rx_peer *peer;
5432 struct rx_packet *packet;
5434 MUTEX_ASSERT(&call->lock);
5435 dpf(("rxi_ResetCall(call %p, newcall %d)\n", call, newcall));
5437 /* Notify anyone who is waiting for asynchronous packet arrival */
5438 if (call->arrivalProc) {
5439 (*call->arrivalProc) (call, call->arrivalProcHandle,
5440 call->arrivalProcArg);
5441 call->arrivalProc = NULL;
5445 rxi_CancelGrowMTUEvent(call);
5447 if (call->delayedAbortEvent) {
5448 rxi_CancelDelayedAbortEvent(call);
5449 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5451 rxi_SendCallAbort(call, packet, 0, 1);
5452 rxi_FreePacket(packet);
5457 * Update the peer with the congestion information in this call
5458 * so other calls on this connection can pick up where this call
5459 * left off. If the congestion sequence numbers don't match then
5460 * another call experienced a retransmission.
5462 peer = call->conn->peer;
5463 MUTEX_ENTER(&peer->peer_lock);
5465 if (call->congestSeq == peer->congestSeq) {
5466 peer->cwind = MAX(peer->cwind, call->cwind);
5467 peer->MTU = MAX(peer->MTU, call->MTU);
5468 peer->nDgramPackets =
5469 MAX(peer->nDgramPackets, call->nDgramPackets);
5472 call->abortCode = 0;
5473 call->abortCount = 0;
5475 if (peer->maxDgramPackets > 1) {
5476 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
5478 call->MTU = peer->MTU;
5480 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
5481 call->ssthresh = rx_maxSendWindow;
5482 call->nDgramPackets = peer->nDgramPackets;
5483 call->congestSeq = peer->congestSeq;
5484 call->rtt = peer->rtt;
5485 call->rtt_dev = peer->rtt_dev;
5486 clock_Zero(&call->rto);
5487 clock_Addmsec(&call->rto,
5488 MAX(((call->rtt >> 3) + call->rtt_dev), rx_minPeerTimeout) + 200);
5489 MUTEX_EXIT(&peer->peer_lock);
5491 flags = call->flags;
5492 rxi_WaitforTQBusy(call);
5494 rxi_ClearTransmitQueue(call, 1);
5495 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
5496 dpf(("rcall %p has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5500 rxi_ClearReceiveQueue(call);
5501 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
5505 call->twind = call->conn->twind[call->channel];
5506 call->rwind = call->conn->rwind[call->channel];
5507 call->nSoftAcked = 0;
5508 call->nextCwind = 0;
5511 call->nCwindAcks = 0;
5512 call->nSoftAcks = 0;
5513 call->nHardAcks = 0;
5515 call->tfirst = call->rnext = call->tnext = 1;
5518 call->lastAcked = 0;
5519 call->localStatus = call->remoteStatus = 0;
5521 if (flags & RX_CALL_READER_WAIT) {
5522 #ifdef RX_ENABLE_LOCKS
5523 CV_BROADCAST(&call->cv_rq);
5525 osi_rxWakeup(&call->rq);
5528 if (flags & RX_CALL_WAIT_PACKETS) {
5529 MUTEX_ENTER(&rx_freePktQ_lock);
5530 rxi_PacketsUnWait(); /* XXX */
5531 MUTEX_EXIT(&rx_freePktQ_lock);
5533 #ifdef RX_ENABLE_LOCKS
5534 CV_SIGNAL(&call->cv_twind);
5536 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5537 osi_rxWakeup(&call->twind);
5540 if (flags & RX_CALL_WAIT_PROC) {
5541 rx_atomic_dec(&rx_nWaiting);
5543 #ifdef RX_ENABLE_LOCKS
5544 /* The following ensures that we don't mess with any queue while some
5545 * other thread might also be doing so. The call_queue_lock field is
5546 * is only modified under the call lock. If the call is in the process
5547 * of being removed from a queue, the call is not locked until the
5548 * the queue lock is dropped and only then is the call_queue_lock field
5549 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5550 * Note that any other routine which removes a call from a queue has to
5551 * obtain the queue lock before examing the queue and removing the call.
5553 if (call->call_queue_lock) {
5554 MUTEX_ENTER(call->call_queue_lock);
5555 if (opr_queue_IsOnQueue(&call->entry)) {
5556 opr_queue_Remove(&call->entry);
5558 MUTEX_EXIT(call->call_queue_lock);
5559 CLEAR_CALL_QUEUE_LOCK(call);
5561 #else /* RX_ENABLE_LOCKS */
5562 if (opr_queue_IsOnQueue(&call->entry)) {
5563 opr_queue_Remove(&call->entry);
5565 #endif /* RX_ENABLE_LOCKS */
5567 rxi_CancelKeepAliveEvent(call);
5568 rxi_CancelDelayedAckEvent(call);
5571 /* Send an acknowledge for the indicated packet (seq,serial) of the
5572 * indicated call, for the indicated reason (reason). This
5573 * acknowledge will specifically acknowledge receiving the packet, and
5574 * will also specify which other packets for this call have been
5575 * received. This routine returns the packet that was used to the
5576 * caller. The caller is responsible for freeing it or re-using it.
5577 * This acknowledgement also returns the highest sequence number
5578 * actually read out by the higher level to the sender; the sender
5579 * promises to keep around packets that have not been read by the
5580 * higher level yet (unless, of course, the sender decides to abort
5581 * the call altogether). Any of p, seq, serial, pflags, or reason may
5582 * be set to zero without ill effect. That is, if they are zero, they
5583 * will not convey any information.
5584 * NOW there is a trailer field, after the ack where it will safely be
5585 * ignored by mundanes, which indicates the maximum size packet this
5586 * host can swallow. */
5588 struct rx_packet *optionalPacket; use to send ack (or null)
5589 int seq; Sequence number of the packet we are acking
5590 int serial; Serial number of the packet
5591 int pflags; Flags field from packet header
5592 int reason; Reason an acknowledge was prompted
5595 #define RX_ZEROS 1024
5596 static char rx_zeros[RX_ZEROS];
5599 rxi_SendAck(struct rx_call *call,
5600 struct rx_packet *optionalPacket, int serial, int reason,
5603 struct rx_ackPacket *ap;
5604 struct rx_packet *p;
5605 struct opr_queue *cursor;
5608 afs_uint32 padbytes = 0;
5609 #ifdef RX_ENABLE_TSFPQ
5610 struct rx_ts_info_t * rx_ts_info;
5614 * Open the receive window once a thread starts reading packets
5616 if (call->rnext > 1) {
5617 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5620 /* Don't attempt to grow MTU if this is a critical ping */
5621 if (reason == RX_ACK_MTU) {
5622 /* keep track of per-call attempts, if we're over max, do in small
5623 * otherwise in larger? set a size to increment by, decrease
5626 if (call->conn->peer->maxPacketSize &&
5627 (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5629 padbytes = call->conn->peer->maxPacketSize+16;
5631 padbytes = call->conn->peer->maxMTU + 128;
5633 /* do always try a minimum size ping */
5634 padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5636 /* subtract the ack payload */
5637 padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5638 reason = RX_ACK_PING;
5641 call->nHardAcks = 0;
5642 call->nSoftAcks = 0;
5643 if (call->rnext > call->lastAcked)
5644 call->lastAcked = call->rnext;
5648 rx_computelen(p, p->length); /* reset length, you never know */
5649 } /* where that's been... */
5650 #ifdef RX_ENABLE_TSFPQ
5652 RX_TS_INFO_GET(rx_ts_info);
5653 if ((p = rx_ts_info->local_special_packet)) {
5654 rx_computelen(p, p->length);
5655 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5656 rx_ts_info->local_special_packet = p;
5657 } else { /* We won't send the ack, but don't panic. */
5658 return optionalPacket;
5662 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5663 /* We won't send the ack, but don't panic. */
5664 return optionalPacket;
5669 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5672 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5673 #ifndef RX_ENABLE_TSFPQ
5674 if (!optionalPacket)
5677 return optionalPacket;
5679 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5680 if (rx_Contiguous(p) < templ) {
5681 #ifndef RX_ENABLE_TSFPQ
5682 if (!optionalPacket)
5685 return optionalPacket;
5690 /* MTUXXX failing to send an ack is very serious. We should */
5691 /* try as hard as possible to send even a partial ack; it's */
5692 /* better than nothing. */
5693 ap = (struct rx_ackPacket *)rx_DataOf(p);
5694 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5695 ap->reason = reason;
5697 /* The skew computation used to be bogus, I think it's better now. */
5698 /* We should start paying attention to skew. XXX */
5699 ap->serial = htonl(serial);
5700 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
5703 * First packet not yet forwarded to reader. When ACKALL has been
5704 * sent the peer has been told that all received packets will be
5705 * delivered to the reader. The value 'rnext' is used internally
5706 * to refer to the next packet in the receive queue that must be
5707 * delivered to the reader. From the perspective of the peer it
5708 * already has so report the last sequence number plus one if there
5709 * are packets in the receive queue awaiting processing.
5711 if ((call->flags & RX_CALL_ACKALL_SENT) &&
5712 !opr_queue_IsEmpty(&call->rq)) {
5713 ap->firstPacket = htonl(opr_queue_Last(&call->rq, struct rx_packet, entry)->header.seq + 1);
5715 ap->firstPacket = htonl(call->rnext);
5717 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
5719 /* No fear of running out of ack packet here because there can only
5720 * be at most one window full of unacknowledged packets. The window
5721 * size must be constrained to be less than the maximum ack size,
5722 * of course. Also, an ack should always fit into a single packet
5723 * -- it should not ever be fragmented. */
5725 for (opr_queue_Scan(&call->rq, cursor)) {
5726 struct rx_packet *rqp
5727 = opr_queue_Entry(cursor, struct rx_packet, entry);
5729 if (!rqp || !call->rq.next
5730 || (rqp->header.seq > (call->rnext + call->rwind))) {
5731 #ifndef RX_ENABLE_TSFPQ
5732 if (!optionalPacket)
5735 rxi_CallError(call, RX_CALL_DEAD);
5736 return optionalPacket;
5739 while (rqp->header.seq > call->rnext + offset)
5740 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5741 ap->acks[offset++] = RX_ACK_TYPE_ACK;
5743 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5744 #ifndef RX_ENABLE_TSFPQ
5745 if (!optionalPacket)
5748 rxi_CallError(call, RX_CALL_DEAD);
5749 return optionalPacket;
5755 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5757 /* Must zero the 3 octets that rx_AckDataSize skips at the end of the
5760 rx_packetwrite(p, rx_AckDataSize(offset) - 3, 3, rx_zeros);
5762 /* these are new for AFS 3.3 */
5763 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5764 templ = htonl(templ);
5765 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5766 templ = htonl(call->conn->peer->ifMTU);
5767 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5768 sizeof(afs_int32), &templ);
5770 /* new for AFS 3.4 */
5771 templ = htonl(call->rwind);
5772 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5773 sizeof(afs_int32), &templ);
5775 /* new for AFS 3.5 */
5776 templ = htonl(call->conn->peer->ifDgramPackets);
5777 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5778 sizeof(afs_int32), &templ);
5780 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5782 p->header.serviceId = call->conn->serviceId;
5783 p->header.cid = (call->conn->cid | call->channel);
5784 p->header.callNumber = *call->callNumber;
5786 p->header.securityIndex = call->conn->securityIndex;
5787 p->header.epoch = call->conn->epoch;
5788 p->header.type = RX_PACKET_TYPE_ACK;
5789 p->header.flags = RX_SLOW_START_OK;
5790 if (reason == RX_ACK_PING)
5791 p->header.flags |= RX_REQUEST_ACK;
5793 while (padbytes > 0) {
5794 if (padbytes > RX_ZEROS) {
5795 rx_packetwrite(p, p->length, RX_ZEROS, rx_zeros);
5796 p->length += RX_ZEROS;
5797 padbytes -= RX_ZEROS;
5799 rx_packetwrite(p, p->length, padbytes, rx_zeros);
5800 p->length += padbytes;
5805 if (call->conn->type == RX_CLIENT_CONNECTION)
5806 p->header.flags |= RX_CLIENT_INITIATED;
5810 if (rxdebug_active) {
5814 len = _snprintf(msg, sizeof(msg),
5815 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5816 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5817 ntohl(ap->serial), ntohl(ap->previousPacket),
5818 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5819 ap->nAcks, ntohs(ap->bufferSpace) );
5823 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5824 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5828 OutputDebugString(msg);
5830 #else /* AFS_NT40_ENV */
5832 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5833 ap->reason, ntohl(ap->previousPacket),
5834 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5836 for (offset = 0; offset < ap->nAcks; offset++)
5837 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5842 #endif /* AFS_NT40_ENV */
5845 int i, nbytes = p->length;
5847 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5848 if (nbytes <= p->wirevec[i].iov_len) {
5851 savelen = p->wirevec[i].iov_len;
5853 p->wirevec[i].iov_len = nbytes;
5855 rxi_Send(call, p, istack);
5856 p->wirevec[i].iov_len = savelen;
5860 nbytes -= p->wirevec[i].iov_len;
5863 if (rx_stats_active)
5864 rx_atomic_inc(&rx_stats.ackPacketsSent);
5865 #ifndef RX_ENABLE_TSFPQ
5866 if (!optionalPacket)
5869 return optionalPacket; /* Return packet for re-use by caller */
5873 struct rx_packet **list;
5878 /* Send all of the packets in the list in single datagram */
5880 rxi_SendList(struct rx_call *call, struct xmitlist *xmit,
5881 int istack, int moreFlag)
5887 struct rx_connection *conn = call->conn;
5888 struct rx_peer *peer = conn->peer;
5890 MUTEX_ENTER(&peer->peer_lock);
5891 peer->nSent += xmit->len;
5892 if (xmit->resending)
5893 peer->reSends += xmit->len;
5894 MUTEX_EXIT(&peer->peer_lock);
5896 if (rx_stats_active) {
5897 if (xmit->resending)
5898 rx_atomic_add(&rx_stats.dataPacketsReSent, xmit->len);
5900 rx_atomic_add(&rx_stats.dataPacketsSent, xmit->len);
5903 clock_GetTime(&now);
5905 if (xmit->list[xmit->len - 1]->header.flags & RX_LAST_PACKET) {
5909 /* Set the packet flags and schedule the resend events */
5910 /* Only request an ack for the last packet in the list */
5911 for (i = 0; i < xmit->len; i++) {
5912 struct rx_packet *packet = xmit->list[i];
5914 /* Record the time sent */
5915 packet->timeSent = now;
5916 packet->flags |= RX_PKTFLAG_SENT;
5918 /* Ask for an ack on retransmitted packets, on every other packet
5919 * if the peer doesn't support slow start. Ask for an ack on every
5920 * packet until the congestion window reaches the ack rate. */
5921 if (packet->header.serial) {
5924 packet->firstSent = now;
5925 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5926 || (!(call->flags & RX_CALL_SLOW_START_OK)
5927 && (packet->header.seq & 1)))) {
5932 /* Tag this packet as not being the last in this group,
5933 * for the receiver's benefit */
5934 if (i < xmit->len - 1 || moreFlag) {
5935 packet->header.flags |= RX_MORE_PACKETS;
5940 xmit->list[xmit->len - 1]->header.flags |= RX_REQUEST_ACK;
5943 /* Since we're about to send a data packet to the peer, it's
5944 * safe to nuke any scheduled end-of-packets ack */
5945 rxi_CancelDelayedAckEvent(call);
5947 MUTEX_EXIT(&call->lock);
5948 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5949 if (xmit->len > 1) {
5950 rxi_SendPacketList(call, conn, xmit->list, xmit->len, istack);
5952 rxi_SendPacket(call, conn, xmit->list[0], istack);
5954 MUTEX_ENTER(&call->lock);
5955 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5957 /* Tell the RTO calculation engine that we have sent a packet, and
5958 * if it was the last one */
5959 rxi_rto_packet_sent(call, lastPacket, istack);
5961 /* Update last send time for this call (for keep-alive
5962 * processing), and for the connection (so that we can discover
5963 * idle connections) */
5964 conn->lastSendTime = call->lastSendTime = clock_Sec();
5967 /* When sending packets we need to follow these rules:
5968 * 1. Never send more than maxDgramPackets in a jumbogram.
5969 * 2. Never send a packet with more than two iovecs in a jumbogram.
5970 * 3. Never send a retransmitted packet in a jumbogram.
5971 * 4. Never send more than cwind/4 packets in a jumbogram
5972 * We always keep the last list we should have sent so we
5973 * can set the RX_MORE_PACKETS flags correctly.
5977 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5982 struct xmitlist working;
5983 struct xmitlist last;
5985 struct rx_peer *peer = call->conn->peer;
5986 int morePackets = 0;
5988 memset(&last, 0, sizeof(struct xmitlist));
5989 working.list = &list[0];
5991 working.resending = 0;
5993 recovery = call->flags & RX_CALL_FAST_RECOVER;
5995 for (i = 0; i < len; i++) {
5996 /* Does the current packet force us to flush the current list? */
5998 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5999 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
6001 /* This sends the 'last' list and then rolls the current working
6002 * set into the 'last' one, and resets the working set */
6005 rxi_SendList(call, &last, istack, 1);
6006 /* If the call enters an error state stop sending, or if
6007 * we entered congestion recovery mode, stop sending */
6009 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
6014 working.resending = 0;
6015 working.list = &list[i];
6017 /* Add the current packet to the list if it hasn't been acked.
6018 * Otherwise adjust the list pointer to skip the current packet. */
6019 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
6022 if (list[i]->header.serial)
6023 working.resending = 1;
6025 /* Do we need to flush the list? */
6026 if (working.len >= (int)peer->maxDgramPackets
6027 || working.len >= (int)call->nDgramPackets
6028 || working.len >= (int)call->cwind
6029 || list[i]->header.serial
6030 || list[i]->length != RX_JUMBOBUFFERSIZE) {
6032 rxi_SendList(call, &last, istack, 1);
6033 /* If the call enters an error state stop sending, or if
6034 * we entered congestion recovery mode, stop sending */
6036 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
6041 working.resending = 0;
6042 working.list = &list[i + 1];
6045 if (working.len != 0) {
6046 osi_Panic("rxi_SendList error");
6048 working.list = &list[i + 1];
6052 /* Send the whole list when the call is in receive mode, when
6053 * the call is in eof mode, when we are in fast recovery mode,
6054 * and when we have the last packet */
6055 /* XXX - The accesses to app.mode aren't safe, as this may be called by
6056 * the listener or event threads
6058 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
6059 || (call->flags & RX_CALL_FLUSH)
6060 || (call->flags & RX_CALL_FAST_RECOVER)) {
6061 /* Check for the case where the current list contains
6062 * an acked packet. Since we always send retransmissions
6063 * in a separate packet, we only need to check the first
6064 * packet in the list */
6065 if (working.len > 0 && !(working.list[0]->flags & RX_PKTFLAG_ACKED)) {
6069 rxi_SendList(call, &last, istack, morePackets);
6070 /* If the call enters an error state stop sending, or if
6071 * we entered congestion recovery mode, stop sending */
6073 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
6077 rxi_SendList(call, &working, istack, 0);
6079 } else if (last.len > 0) {
6080 rxi_SendList(call, &last, istack, 0);
6081 /* Packets which are in 'working' are not sent by this call */
6086 * Check if the peer for the given call is known to be dead
6088 * If the call's peer appears dead (it has encountered fatal network errors
6089 * since the call started) the call is killed with RX_CALL_DEAD if the call
6090 * is active. Otherwise, we do nothing.
6092 * @param[in] call The call to check
6095 * @retval 0 The call is fine, and we haven't done anything to the call
6096 * @retval nonzero The call's peer appears dead, and the call has been
6097 * terminated if it was active
6099 * @pre call->lock must be locked
6102 rxi_CheckPeerDead(struct rx_call *call)
6104 #ifdef AFS_RXERRQ_ENV
6107 if (call->state == RX_STATE_DALLY) {
6111 peererrs = rx_atomic_read(&call->conn->peer->neterrs);
6112 if (call->neterr_gen < peererrs) {
6113 /* we have received network errors since this call started; kill
6115 if (call->state == RX_STATE_ACTIVE) {
6116 rxi_CallError(call, RX_CALL_DEAD);
6120 if (call->neterr_gen > peererrs) {
6121 /* someone has reset the number of peer errors; set the call error gen
6122 * so we can detect if more errors are encountered */
6123 call->neterr_gen = peererrs;
6130 rxi_Resend(struct rxevent *event, void *arg0, void *arg1, int istack)
6132 struct rx_call *call = arg0;
6133 struct rx_peer *peer;
6134 struct opr_queue *cursor;
6135 struct clock maxTimeout = { 60, 0 };
6137 MUTEX_ENTER(&call->lock);
6139 peer = call->conn->peer;
6141 /* Make sure that the event pointer is removed from the call
6142 * structure, since there is no longer a per-call retransmission
6144 if (event == call->resendEvent)
6145 rxevent_Put(&call->resendEvent);
6147 rxi_CheckPeerDead(call);
6149 if (opr_queue_IsEmpty(&call->tq)) {
6150 /* Nothing to do. This means that we've been raced, and that an
6151 * ACK has come in between when we were triggered, and when we
6152 * actually got to run. */
6156 /* We're in loss recovery */
6157 call->flags |= RX_CALL_FAST_RECOVER;
6159 /* Mark all of the pending packets in the queue as being lost */
6160 for (opr_queue_Scan(&call->tq, cursor)) {
6161 struct rx_packet *p = opr_queue_Entry(cursor, struct rx_packet, entry);
6162 if (!(p->flags & RX_PKTFLAG_ACKED))
6163 p->flags &= ~RX_PKTFLAG_SENT;
6166 /* We're resending, so we double the timeout of the call. This will be
6167 * dropped back down by the first successful ACK that we receive.
6169 * We apply a maximum value here of 60 seconds
6171 clock_Add(&call->rto, &call->rto);
6172 if (clock_Gt(&call->rto, &maxTimeout))
6173 call->rto = maxTimeout;
6175 /* Packet loss is most likely due to congestion, so drop our window size
6176 * and start again from the beginning */
6177 if (peer->maxDgramPackets >1) {
6178 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
6179 call->MTU = MIN(peer->natMTU, peer->maxMTU);
6181 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
6182 call->nDgramPackets = 1;
6184 call->nextCwind = 1;
6187 MUTEX_ENTER(&peer->peer_lock);
6188 peer->MTU = call->MTU;
6189 peer->cwind = call->cwind;
6190 peer->nDgramPackets = 1;
6192 call->congestSeq = peer->congestSeq;
6193 MUTEX_EXIT(&peer->peer_lock);
6195 rxi_Start(call, istack);
6198 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
6199 MUTEX_EXIT(&call->lock);
6202 /* This routine is called when new packets are readied for
6203 * transmission and when retransmission may be necessary, or when the
6204 * transmission window or burst count are favourable. This should be
6205 * better optimized for new packets, the usual case, now that we've
6206 * got rid of queues of send packets. XXXXXXXXXXX */
6208 rxi_Start(struct rx_call *call, int istack)
6210 struct opr_queue *cursor;
6211 #ifdef RX_ENABLE_LOCKS
6212 struct opr_queue *store;
6218 #ifdef RX_ENABLE_LOCKS
6219 if (rx_stats_active)
6220 rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
6225 if (!opr_queue_IsEmpty(&call->tq)) { /* If we have anything to send */
6226 /* Send (or resend) any packets that need it, subject to
6227 * window restrictions and congestion burst control
6228 * restrictions. Ask for an ack on the last packet sent in
6229 * this burst. For now, we're relying upon the window being
6230 * considerably bigger than the largest number of packets that
6231 * are typically sent at once by one initial call to
6232 * rxi_Start. This is probably bogus (perhaps we should ask
6233 * for an ack when we're half way through the current
6234 * window?). Also, for non file transfer applications, this
6235 * may end up asking for an ack for every packet. Bogus. XXXX
6238 * But check whether we're here recursively, and let the other guy
6241 #ifdef RX_ENABLE_LOCKS
6242 if (!(call->flags & RX_CALL_TQ_BUSY)) {
6243 call->flags |= RX_CALL_TQ_BUSY;
6245 #endif /* RX_ENABLE_LOCKS */
6247 #ifdef RX_ENABLE_LOCKS
6248 call->flags &= ~RX_CALL_NEED_START;
6249 #endif /* RX_ENABLE_LOCKS */
6251 maxXmitPackets = MIN(call->twind, call->cwind);
6252 for (opr_queue_Scan(&call->tq, cursor)) {
6254 = opr_queue_Entry(cursor, struct rx_packet, entry);
6256 if (p->flags & RX_PKTFLAG_ACKED) {
6257 /* Since we may block, don't trust this */
6258 if (rx_stats_active)
6259 rx_atomic_inc(&rx_stats.ignoreAckedPacket);
6260 continue; /* Ignore this packet if it has been acknowledged */
6263 /* Turn off all flags except these ones, which are the same
6264 * on each transmission */
6265 p->header.flags &= RX_PRESET_FLAGS;
6267 if (p->header.seq >=
6268 call->tfirst + MIN((int)call->twind,
6269 (int)(call->nSoftAcked +
6271 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
6272 /* Note: if we're waiting for more window space, we can
6273 * still send retransmits; hence we don't return here, but
6274 * break out to schedule a retransmit event */
6275 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
6276 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
6281 /* Transmit the packet if it needs to be sent. */
6282 if (!(p->flags & RX_PKTFLAG_SENT)) {
6283 if (nXmitPackets == maxXmitPackets) {
6284 rxi_SendXmitList(call, call->xmitList,
6285 nXmitPackets, istack);
6288 dpf(("call %d xmit packet %p\n",
6289 *(call->callNumber), p));
6290 call->xmitList[nXmitPackets++] = p;
6292 } /* end of the queue_Scan */
6294 /* xmitList now hold pointers to all of the packets that are
6295 * ready to send. Now we loop to send the packets */
6296 if (nXmitPackets > 0) {
6297 rxi_SendXmitList(call, call->xmitList, nXmitPackets,
6301 #ifdef RX_ENABLE_LOCKS
6303 /* We went into the error state while sending packets. Now is
6304 * the time to reset the call. This will also inform the using
6305 * process that the call is in an error state.
6307 if (rx_stats_active)
6308 rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
6309 call->flags &= ~RX_CALL_TQ_BUSY;
6310 rxi_WakeUpTransmitQueue(call);
6311 rxi_CallError(call, call->error);
6315 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
6317 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
6318 /* Some packets have received acks. If they all have, we can clear
6319 * the transmit queue.
6322 for (opr_queue_ScanSafe(&call->tq, cursor, store)) {
6324 = opr_queue_Entry(cursor, struct rx_packet, entry);
6326 if (p->header.seq < call->tfirst
6327 && (p->flags & RX_PKTFLAG_ACKED)) {
6328 opr_queue_Remove(&p->entry);
6329 #ifdef RX_TRACK_PACKETS
6330 p->flags &= ~RX_PKTFLAG_TQ;
6332 #ifdef RXDEBUG_PACKET
6340 call->flags |= RX_CALL_TQ_CLEARME;
6342 if (call->flags & RX_CALL_TQ_CLEARME)
6343 rxi_ClearTransmitQueue(call, 1);
6344 } while (call->flags & RX_CALL_NEED_START);
6346 * TQ references no longer protected by this flag; they must remain
6347 * protected by the call lock.
6349 call->flags &= ~RX_CALL_TQ_BUSY;
6350 rxi_WakeUpTransmitQueue(call);
6352 call->flags |= RX_CALL_NEED_START;
6354 #endif /* RX_ENABLE_LOCKS */
6356 rxi_rto_cancel(call);
6360 /* Also adjusts the keep alive parameters for the call, to reflect
6361 * that we have just sent a packet (so keep alives aren't sent
6364 rxi_Send(struct rx_call *call, struct rx_packet *p,
6368 struct rx_connection *conn = call->conn;
6370 /* Stamp each packet with the user supplied status */
6371 p->header.userStatus = call->localStatus;
6373 /* Allow the security object controlling this call's security to
6374 * make any last-minute changes to the packet */
6375 code = RXS_SendPacket(conn->securityObject, call, p);
6377 MUTEX_EXIT(&call->lock);
6378 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6379 rxi_ConnectionError(conn, code);
6380 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6381 MUTEX_ENTER(&call->lock);
6385 /* Since we're about to send SOME sort of packet to the peer, it's
6386 * safe to nuke any scheduled end-of-packets ack */
6387 rxi_CancelDelayedAckEvent(call);
6389 /* Actually send the packet, filling in more connection-specific fields */
6390 MUTEX_EXIT(&call->lock);
6391 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6392 rxi_SendPacket(call, conn, p, istack);
6393 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6394 MUTEX_ENTER(&call->lock);
6396 /* Update last send time for this call (for keep-alive
6397 * processing), and for the connection (so that we can discover
6398 * idle connections) */
6399 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6400 (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
6401 (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
6403 conn->lastSendTime = call->lastSendTime = clock_Sec();
6407 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
6408 * that things are fine. Also called periodically to guarantee that nothing
6409 * falls through the cracks (e.g. (error + dally) connections have keepalive
6410 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
6412 * haveCTLock Set if calling from rxi_ReapConnections
6415 rxi_CheckCall(struct rx_call *call, int haveCTLock)
6417 struct rx_connection *conn = call->conn;
6419 afs_uint32 deadTime, idleDeadTime = 0, hardDeadTime = 0;
6420 afs_uint32 fudgeFactor;
6423 int idle_timeout = 0;
6424 afs_int32 clock_diff = 0;
6426 if (rxi_CheckPeerDead(call)) {
6432 /* Large swings in the clock can have a significant impact on
6433 * the performance of RX call processing. Forward clock shifts
6434 * will result in premature event triggering or timeouts.
6435 * Backward shifts can result in calls not completing until
6436 * the clock catches up with the original start clock value.
6438 * If a backward clock shift of more than five minutes is noticed,
6439 * just fail the call.
6441 if (now < call->lastSendTime)
6442 clock_diff = call->lastSendTime - now;
6443 if (now < call->startWait)
6444 clock_diff = MAX(clock_diff, call->startWait - now);
6445 if (now < call->lastReceiveTime)
6446 clock_diff = MAX(clock_diff, call->lastReceiveTime - now);
6447 if (clock_diff > 5 * 60)
6449 if (call->state == RX_STATE_ACTIVE)
6450 rxi_CallError(call, RX_CALL_TIMEOUT);
6454 #ifdef RX_ENABLE_LOCKS
6455 if (call->flags & RX_CALL_TQ_BUSY) {
6456 /* Call is active and will be reset by rxi_Start if it's
6457 * in an error state.
6462 /* RTT + 8*MDEV, rounded up to the next second. */
6463 fudgeFactor = (((afs_uint32) call->rtt >> 3) +
6464 ((afs_uint32) call->rtt_dev << 1) + 1023) >> 10;
6466 deadTime = conn->secondsUntilDead + fudgeFactor;
6467 /* These are computed to the second (+- 1 second). But that's
6468 * good enough for these values, which should be a significant
6469 * number of seconds. */
6470 if (now > (call->lastReceiveTime + deadTime)) {
6471 if (call->state == RX_STATE_ACTIVE) {
6472 cerror = RX_CALL_DEAD;
6475 #ifdef RX_ENABLE_LOCKS
6476 /* Cancel pending events */
6477 rxi_CancelDelayedAckEvent(call);
6478 rxi_rto_cancel(call);
6479 rxi_CancelKeepAliveEvent(call);
6480 rxi_CancelGrowMTUEvent(call);
6481 MUTEX_ENTER(&rx_refcnt_mutex);
6482 /* if rxi_FreeCall returns 1 it has freed the call */
6483 if (call->refCount == 0 &&
6484 rxi_FreeCall(call, haveCTLock))
6486 MUTEX_EXIT(&rx_refcnt_mutex);
6489 MUTEX_EXIT(&rx_refcnt_mutex);
6491 #else /* RX_ENABLE_LOCKS */
6492 rxi_FreeCall(call, 0);
6494 #endif /* RX_ENABLE_LOCKS */
6496 /* Non-active calls are destroyed if they are not responding
6497 * to pings; active calls are simply flagged in error, so the
6498 * attached process can die reasonably gracefully. */
6501 if (conn->idleDeadTime) {
6502 idleDeadTime = conn->idleDeadTime + fudgeFactor;
6506 /* see if we have a non-activity timeout */
6507 if (call->startWait && ((call->startWait + idleDeadTime) < now)) {
6508 if (call->state == RX_STATE_ACTIVE) {
6509 cerror = RX_CALL_TIMEOUT;
6515 if (conn->hardDeadTime) {
6516 hardDeadTime = conn->hardDeadTime + fudgeFactor;
6519 /* see if we have a hard timeout */
6521 && (now > (hardDeadTime + call->startTime.sec))) {
6522 if (call->state == RX_STATE_ACTIVE)
6523 rxi_CallError(call, RX_CALL_TIMEOUT);
6528 if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT && !idle_timeout &&
6529 call->lastReceiveTime) {
6530 int oldMTU = conn->peer->ifMTU;
6532 /* If we thought we could send more, perhaps things got worse.
6533 * Shrink by 128 bytes and try again. */
6534 if (conn->peer->maxPacketSize < conn->lastPacketSize)
6535 /* maxPacketSize will be cleared in rxi_SetPeerMtu */
6536 newmtu = MAX(conn->peer->maxPacketSize + RX_HEADER_SIZE,
6537 conn->lastPacketSize - 128 + RX_HEADER_SIZE);
6539 newmtu = conn->lastPacketSize - 128 + RX_HEADER_SIZE;
6541 /* minimum capped in SetPeerMtu */
6542 rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6545 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
6547 /* needed so ResetCall doesn't clobber us. */
6548 call->MTU = conn->peer->ifMTU;
6550 /* if we never succeeded, let the error pass out as-is */
6551 if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6552 cerror = conn->msgsizeRetryErr;
6555 rxi_CallError(call, cerror);
6560 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1,
6561 void *dummy, int dummy2)
6563 struct rx_connection *conn = arg1;
6564 struct rx_header theader;
6565 char tbuffer[1 + sizeof(struct rx_header)];
6566 struct sockaddr_in taddr;
6570 struct iovec tmpiov[2];
6573 RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6576 tp = &tbuffer[sizeof(struct rx_header)];
6577 taddr.sin_family = AF_INET;
6578 taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6579 taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6580 memset(&taddr.sin_zero, 0, sizeof(taddr.sin_zero));
6581 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6582 taddr.sin_len = sizeof(struct sockaddr_in);
6584 memset(&theader, 0, sizeof(theader));
6585 theader.epoch = htonl(999);
6587 theader.callNumber = 0;
6590 theader.type = RX_PACKET_TYPE_VERSION;
6591 theader.flags = RX_LAST_PACKET;
6592 theader.serviceId = 0;
6594 memcpy(tbuffer, &theader, sizeof(theader));
6595 memcpy(tp, &a, sizeof(a));
6596 tmpiov[0].iov_base = tbuffer;
6597 tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6599 rxi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6601 MUTEX_ENTER(&conn->conn_data_lock);
6602 /* We ran, so the handle is no longer needed to try to cancel ourselves. */
6603 if (event == conn->natKeepAliveEvent)
6604 rxevent_Put(&conn->natKeepAliveEvent);
6605 MUTEX_ENTER(&rx_refcnt_mutex);
6606 /* Only reschedule ourselves if the connection would not be destroyed */
6607 if (conn->refCount > 1)
6609 if (conn->refCount <= 0) {
6610 #ifdef RX_REFCOUNT_CHECK
6611 osi_Assert(conn->refCount == 0);
6613 if (rx_stats_active) {
6614 MUTEX_ENTER(&rx_stats_mutex);
6615 rxi_lowConnRefCount++;
6616 MUTEX_EXIT(&rx_stats_mutex);
6619 MUTEX_EXIT(&rx_refcnt_mutex);
6621 rxi_ScheduleNatKeepAliveEvent(conn);
6622 MUTEX_EXIT(&conn->conn_data_lock);
6623 putConnection(conn);
6627 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6629 MUTEX_ASSERT(&conn->conn_data_lock);
6630 if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6631 struct clock when, now;
6632 clock_GetTime(&now);
6634 when.sec += conn->secondsUntilNatPing;
6635 rx_GetConnection(conn);
6636 conn->natKeepAliveEvent =
6637 rxevent_Post(&when, &now, rxi_NatKeepAliveEvent, conn, NULL, 0);
6642 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6644 MUTEX_ENTER(&conn->conn_data_lock);
6645 conn->secondsUntilNatPing = seconds;
6647 if (!(conn->flags & RX_CONN_ATTACHWAIT))
6648 rxi_ScheduleNatKeepAliveEvent(conn);
6650 conn->flags |= RX_CONN_NAT_PING;
6652 MUTEX_EXIT(&conn->conn_data_lock);
6655 /* When a call is in progress, this routine is called occasionally to
6656 * make sure that some traffic has arrived (or been sent to) the peer.
6657 * If nothing has arrived in a reasonable amount of time, the call is
6658 * declared dead; if nothing has been sent for a while, we send a
6659 * keep-alive packet (if we're actually trying to keep the call alive)
6662 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy,
6665 struct rx_call *call = arg1;
6666 struct rx_connection *conn;
6669 MUTEX_ENTER(&call->lock);
6671 if (event == call->keepAliveEvent)
6672 rxevent_Put(&call->keepAliveEvent);
6676 if (rxi_CheckCall(call, 0)) {
6677 MUTEX_EXIT(&call->lock);
6678 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6682 /* Don't try to keep alive dallying calls */
6683 if (call->state == RX_STATE_DALLY) {
6684 MUTEX_EXIT(&call->lock);
6685 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6690 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6691 /* Don't try to send keepalives if there is unacknowledged data */
6692 /* the rexmit code should be good enough, this little hack
6693 * doesn't quite work XXX */
6694 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6696 rxi_ScheduleKeepAliveEvent(call);
6697 MUTEX_EXIT(&call->lock);
6698 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6701 /* Does what's on the nameplate. */
6703 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy, int dummy2)
6705 struct rx_call *call = arg1;
6706 struct rx_connection *conn;
6708 MUTEX_ENTER(&call->lock);
6710 if (event == call->growMTUEvent)
6711 rxevent_Put(&call->growMTUEvent);
6713 if (rxi_CheckCall(call, 0))
6716 /* Don't bother with dallying calls */
6717 if (call->state == RX_STATE_DALLY)
6723 * keep being scheduled, just don't do anything if we're at peak,
6724 * or we're not set up to be properly handled (idle timeout required)
6726 if ((conn->peer->maxPacketSize != 0) &&
6727 (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6729 (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6730 rxi_ScheduleGrowMTUEvent(call, 0);
6732 MUTEX_EXIT(&call->lock);
6733 CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6737 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6739 MUTEX_ASSERT(&call->lock);
6740 if (!call->keepAliveEvent) {
6741 struct clock when, now;
6742 clock_GetTime(&now);
6744 when.sec += call->conn->secondsUntilPing;
6745 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6746 call->keepAliveEvent =
6747 rxevent_Post(&when, &now, rxi_KeepAliveEvent, call, NULL, 0);
6752 rxi_CancelKeepAliveEvent(struct rx_call *call) {
6753 MUTEX_ASSERT(&call->lock);
6754 if (rxevent_Cancel(&call->keepAliveEvent))
6755 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6759 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6761 MUTEX_ASSERT(&call->lock);
6762 if (!call->growMTUEvent) {
6763 struct clock when, now;
6765 clock_GetTime(&now);
6768 if (call->conn->secondsUntilPing)
6769 secs = (6*call->conn->secondsUntilPing)-1;
6771 if (call->conn->secondsUntilDead)
6772 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6776 CALL_HOLD(call, RX_CALL_REFCOUNT_MTU);
6777 call->growMTUEvent =
6778 rxevent_Post(&when, &now, rxi_GrowMTUEvent, call, NULL, 0);
6783 rxi_CancelGrowMTUEvent(struct rx_call *call)
6785 MUTEX_ASSERT(&call->lock);
6786 if (rxevent_Cancel(&call->growMTUEvent))
6787 CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6791 * Increment the counter for the next connection ID, handling overflow.
6794 update_nextCid(void)
6796 /* Overflow is technically undefined behavior; avoid it. */
6797 if (rx_nextCid > MAX_AFS_INT32 - (1 << RX_CIDSHIFT))
6798 rx_nextCid = -1 * ((MAX_AFS_INT32 / RX_CIDSHIFT) * RX_CIDSHIFT);
6800 rx_nextCid += 1 << RX_CIDSHIFT;
6804 rxi_KeepAliveOn(struct rx_call *call)
6806 /* Pretend last packet received was received now--i.e. if another
6807 * packet isn't received within the keep alive time, then the call
6808 * will die; Initialize last send time to the current time--even
6809 * if a packet hasn't been sent yet. This will guarantee that a
6810 * keep-alive is sent within the ping time */
6811 call->lastReceiveTime = call->lastSendTime = clock_Sec();
6812 rxi_ScheduleKeepAliveEvent(call);
6816 rxi_GrowMTUOn(struct rx_call *call)
6818 struct rx_connection *conn = call->conn;
6819 MUTEX_ENTER(&conn->conn_data_lock);
6820 conn->lastPingSizeSer = conn->lastPingSize = 0;
6821 MUTEX_EXIT(&conn->conn_data_lock);
6822 rxi_ScheduleGrowMTUEvent(call, 1);
6825 /* This routine is called to send connection abort messages
6826 * that have been delayed to throttle looping clients. */
6828 rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1, void *unused,
6831 struct rx_connection *conn = arg1;
6834 struct rx_packet *packet;
6836 MUTEX_ENTER(&conn->conn_data_lock);
6837 if (event == conn->delayedAbortEvent)
6838 rxevent_Put(&conn->delayedAbortEvent);
6839 error = htonl(conn->error);
6841 MUTEX_EXIT(&conn->conn_data_lock);
6842 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6845 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6846 RX_PACKET_TYPE_ABORT, (char *)&error,
6848 rxi_FreePacket(packet);
6850 putConnection(conn);
6853 /* This routine is called to send call abort messages
6854 * that have been delayed to throttle looping clients. */
6856 rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1, void *dummy,
6859 struct rx_call *call = arg1;
6862 struct rx_packet *packet;
6864 MUTEX_ENTER(&call->lock);
6865 if (event == call->delayedAbortEvent)
6866 rxevent_Put(&call->delayedAbortEvent);
6867 error = htonl(call->error);
6869 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6872 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6873 (char *)&error, sizeof(error), 0);
6874 rxi_FreePacket(packet);
6876 MUTEX_EXIT(&call->lock);
6877 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6881 * This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6882 * seconds) to ask the client to authenticate itself. The routine
6883 * issues a challenge to the client, which is obtained from the
6884 * security object associated with the connection
6886 * This routine is both an event handler and a function called directly;
6887 * when called directly the passed |event| is NULL and the
6888 * conn->conn->data>lock must must not be held. Also, when called as an
6889 * an event handler, we must putConnection before we exit; but when called
6890 * directly (the first challenge), we must NOT putConnection.
6893 rxi_ChallengeEvent(struct rxevent *event,
6894 void *arg0, void *arg1, int tries)
6896 struct rx_connection *conn = arg0;
6897 int event_raised = 0; /* assume we were called directly */
6899 MUTEX_ENTER(&conn->conn_data_lock);
6900 if (event != NULL && event == conn->challengeEvent) {
6901 event_raised = 1; /* called as an event */
6902 rxevent_Put(&conn->challengeEvent);
6904 MUTEX_EXIT(&conn->conn_data_lock);
6906 /* If there are no active calls it is not worth re-issuing the
6907 * challenge. If the client issues another call on this connection
6908 * the challenge can be requested at that time.
6910 if (!rxi_HasActiveCalls(conn))
6913 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6914 struct rx_packet *packet;
6915 struct clock when, now;
6918 /* We've failed to authenticate for too long.
6919 * Reset any calls waiting for authentication;
6920 * they are all in RX_STATE_PRECALL.
6924 MUTEX_ENTER(&conn->conn_call_lock);
6925 for (i = 0; i < RX_MAXCALLS; i++) {
6926 struct rx_call *call = conn->call[i];
6928 MUTEX_ENTER(&call->lock);
6929 if (call->state == RX_STATE_PRECALL) {
6930 rxi_CallError(call, RX_CALL_DEAD);
6931 rxi_SendCallAbort(call, NULL, 0, 0);
6933 MUTEX_EXIT(&call->lock);
6936 MUTEX_EXIT(&conn->conn_call_lock);
6940 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6943 code = RXS_GetChallenge(conn->securityObject, conn, packet);
6944 if (code && event_raised) {
6946 * We can only rxi_ConnectionError the connection if we are
6947 * running as an event. Otherwise, the caller may have our call
6948 * locked, and so we cannot call rxi_ConnectionError (since it
6949 * tries to lock each call in the conn).
6951 rxi_FreePacket(packet);
6952 rxi_ConnectionError(conn, code);
6956 /* Only send a challenge packet if we were able to allocate a
6957 * packet, and the security layer successfully populated the
6959 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6960 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6961 conn->securityChallengeSent = 1;
6963 rxi_FreePacket(packet);
6965 clock_GetTime(&now);
6967 when.sec += RX_CHALLENGE_TIMEOUT;
6968 MUTEX_ENTER(&conn->conn_data_lock);
6969 /* Only reschedule ourselves if not already pending. */
6970 if (conn->challengeEvent == NULL) {
6971 rx_GetConnection(conn);
6972 conn->challengeEvent =
6973 rxevent_Post(&when, &now, rxi_ChallengeEvent, conn, 0,
6976 MUTEX_EXIT(&conn->conn_data_lock);
6980 putConnection(conn);
6983 /* Call this routine to start requesting the client to authenticate
6984 * itself. This will continue until authentication is established,
6985 * the call times out, or an invalid response is returned. The
6986 * security object associated with the connection is asked to create
6987 * the challenge at this time. */
6989 rxi_ChallengeOn(struct rx_connection *conn)
6992 MUTEX_ENTER(&conn->conn_data_lock);
6993 if (!conn->challengeEvent)
6995 MUTEX_EXIT(&conn->conn_data_lock);
6998 code = RXS_CreateChallenge(conn->securityObject, conn);
7002 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
7008 /* rxi_ComputeRoundTripTime is called with peer locked. */
7009 /* peer may be null */
7011 rxi_ComputeRoundTripTime(struct rx_packet *p,
7012 struct rx_ackPacket *ack,
7013 struct rx_call *call,
7014 struct rx_peer *peer,
7017 struct clock thisRtt, *sentp;
7021 /* If the ACK is delayed, then do nothing */
7022 if (ack->reason == RX_ACK_DELAY)
7025 /* On the wire, jumbograms are a single UDP packet. We shouldn't count
7026 * their RTT multiple times, so only include the RTT of the last packet
7028 if (p->flags & RX_JUMBO_PACKET)
7031 /* Use the serial number to determine which transmission the ACK is for,
7032 * and set the sent time to match this. If we have no serial number, then
7033 * only use the ACK for RTT calculations if the packet has not been
7037 serial = ntohl(ack->serial);
7039 if (serial == p->header.serial) {
7040 sentp = &p->timeSent;
7041 } else if (serial == p->firstSerial) {
7042 sentp = &p->firstSent;
7043 } else if (clock_Eq(&p->timeSent, &p->firstSent)) {
7044 sentp = &p->firstSent;
7048 if (clock_Eq(&p->timeSent, &p->firstSent)) {
7049 sentp = &p->firstSent;
7056 if (clock_Lt(&thisRtt, sentp))
7057 return; /* somebody set the clock back, don't count this time. */
7059 clock_Sub(&thisRtt, sentp);
7060 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%p rttp=%d.%06d sec)\n",
7061 p->header.callNumber, p, thisRtt.sec, thisRtt.usec));
7063 if (clock_IsZero(&thisRtt)) {
7065 * The actual round trip time is shorter than the
7066 * clock_GetTime resolution. It is most likely 1ms or 100ns.
7067 * Since we can't tell which at the moment we will assume 1ms.
7069 thisRtt.usec = 1000;
7072 if (rx_stats_active) {
7073 MUTEX_ENTER(&rx_stats_mutex);
7074 if (clock_Lt(&thisRtt, &rx_stats.minRtt))
7075 rx_stats.minRtt = thisRtt;
7076 if (clock_Gt(&thisRtt, &rx_stats.maxRtt)) {
7077 if (thisRtt.sec > 60) {
7078 MUTEX_EXIT(&rx_stats_mutex);
7079 return; /* somebody set the clock ahead */
7081 rx_stats.maxRtt = thisRtt;
7083 clock_Add(&rx_stats.totalRtt, &thisRtt);
7084 rx_atomic_inc(&rx_stats.nRttSamples);
7085 MUTEX_EXIT(&rx_stats_mutex);
7088 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
7090 /* Apply VanJacobson round-trip estimations */
7095 * srtt (call->rtt) is in units of one-eighth-milliseconds.
7096 * srtt is stored as fixed point with 3 bits after the binary
7097 * point (i.e., scaled by 8). The following magic is
7098 * equivalent to the smoothing algorithm in rfc793 with an
7099 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
7100 * srtt'*8 = rtt + srtt*7
7101 * srtt'*8 = srtt*8 + rtt - srtt
7102 * srtt' = srtt + rtt/8 - srtt/8
7103 * srtt' = srtt + (rtt - srtt)/8
7106 delta = _8THMSEC(&thisRtt) - call->rtt;
7107 call->rtt += (delta >> 3);
7110 * We accumulate a smoothed rtt variance (actually, a smoothed
7111 * mean difference), then set the retransmit timer to smoothed
7112 * rtt + 4 times the smoothed variance (was 2x in van's original
7113 * paper, but 4x works better for me, and apparently for him as
7115 * rttvar is stored as
7116 * fixed point with 2 bits after the binary point (scaled by
7117 * 4). The following is equivalent to rfc793 smoothing with
7118 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
7119 * rttvar'*4 = rttvar*3 + |delta|
7120 * rttvar'*4 = rttvar*4 + |delta| - rttvar
7121 * rttvar' = rttvar + |delta|/4 - rttvar/4
7122 * rttvar' = rttvar + (|delta| - rttvar)/4
7123 * This replaces rfc793's wired-in beta.
7124 * dev*4 = dev*4 + (|actual - expected| - dev)
7130 delta -= (call->rtt_dev << 1);
7131 call->rtt_dev += (delta >> 3);
7133 /* I don't have a stored RTT so I start with this value. Since I'm
7134 * probably just starting a call, and will be pushing more data down
7135 * this, I expect congestion to increase rapidly. So I fudge a
7136 * little, and I set deviance to half the rtt. In practice,
7137 * deviance tends to approach something a little less than
7138 * half the smoothed rtt. */
7139 call->rtt = _8THMSEC(&thisRtt) + 8;
7140 call->rtt_dev = call->rtt >> 2; /* rtt/2: they're scaled differently */
7142 /* the smoothed RTT time is RTT + 4*MDEV
7144 * We allow a user specified minimum to be set for this, to allow clamping
7145 * at a minimum value in the same way as TCP. In addition, we have to allow
7146 * for the possibility that this packet is answered by a delayed ACK, so we
7147 * add on a fixed 200ms to account for that timer expiring.
7150 rtt_timeout = MAX(((call->rtt >> 3) + call->rtt_dev),
7151 rx_minPeerTimeout) + 200;
7152 clock_Zero(&call->rto);
7153 clock_Addmsec(&call->rto, rtt_timeout);
7155 /* Update the peer, so any new calls start with our values */
7156 peer->rtt_dev = call->rtt_dev;
7157 peer->rtt = call->rtt;
7159 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%p rtt=%d ms, srtt=%d ms, "
7160 "rtt_dev=%d ms, timeout=%d.%06d sec)\n",
7161 p->header.callNumber, p, MSEC(&thisRtt), call->rtt >> 3,
7162 call->rtt_dev >> 2, (call->rto.sec), (call->rto.usec)));
7166 /* Find all server connections that have not been active for a long time, and
7169 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2,
7172 struct clock now, when;
7173 struct rxevent *event;
7174 clock_GetTime(&now);
7176 /* Find server connection structures that haven't been used for
7177 * greater than rx_idleConnectionTime */
7179 struct rx_connection **conn_ptr, **conn_end;
7180 int i, havecalls = 0;
7181 MUTEX_ENTER(&rx_connHashTable_lock);
7182 for (conn_ptr = &rx_connHashTable[0], conn_end =
7183 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
7185 struct rx_connection *conn, *next;
7186 struct rx_call *call;
7190 for (conn = *conn_ptr; conn; conn = next) {
7191 /* XXX -- Shouldn't the connection be locked? */
7194 for (i = 0; i < RX_MAXCALLS; i++) {
7195 call = conn->call[i];
7199 code = MUTEX_TRYENTER(&call->lock);
7202 result = rxi_CheckCall(call, 1);
7203 MUTEX_EXIT(&call->lock);
7205 /* If CheckCall freed the call, it might
7206 * have destroyed the connection as well,
7207 * which screws up the linked lists.
7213 if (conn->type == RX_SERVER_CONNECTION) {
7214 /* This only actually destroys the connection if
7215 * there are no outstanding calls */
7216 MUTEX_ENTER(&conn->conn_data_lock);
7217 MUTEX_ENTER(&rx_refcnt_mutex);
7218 if (!havecalls && !conn->refCount
7219 && ((conn->lastSendTime + rx_idleConnectionTime) <
7221 conn->refCount++; /* it will be decr in rx_DestroyConn */
7222 MUTEX_EXIT(&rx_refcnt_mutex);
7223 MUTEX_EXIT(&conn->conn_data_lock);
7224 #ifdef RX_ENABLE_LOCKS
7225 rxi_DestroyConnectionNoLock(conn);
7226 #else /* RX_ENABLE_LOCKS */
7227 rxi_DestroyConnection(conn);
7228 #endif /* RX_ENABLE_LOCKS */
7230 #ifdef RX_ENABLE_LOCKS
7232 MUTEX_EXIT(&rx_refcnt_mutex);
7233 MUTEX_EXIT(&conn->conn_data_lock);
7235 #endif /* RX_ENABLE_LOCKS */
7239 #ifdef RX_ENABLE_LOCKS
7240 while (rx_connCleanup_list) {
7241 struct rx_connection *conn;
7242 conn = rx_connCleanup_list;
7243 rx_connCleanup_list = rx_connCleanup_list->next;
7244 MUTEX_EXIT(&rx_connHashTable_lock);
7245 rxi_CleanupConnection(conn);
7246 MUTEX_ENTER(&rx_connHashTable_lock);
7248 MUTEX_EXIT(&rx_connHashTable_lock);
7249 #endif /* RX_ENABLE_LOCKS */
7252 /* Find any peer structures that haven't been used (haven't had an
7253 * associated connection) for greater than rx_idlePeerTime */
7255 struct rx_peer **peer_ptr, **peer_end;
7259 * Why do we need to hold the rx_peerHashTable_lock across
7260 * the incrementing of peer_ptr since the rx_peerHashTable
7261 * array is not changing? We don't.
7263 * By dropping the lock periodically we can permit other
7264 * activities to be performed while a rxi_ReapConnections
7265 * call is in progress. The goal of reap connections
7266 * is to clean up quickly without causing large amounts
7267 * of contention. Therefore, it is important that global
7268 * mutexes not be held for extended periods of time.
7270 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7271 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7273 struct rx_peer *peer, *next, *prev;
7275 MUTEX_ENTER(&rx_peerHashTable_lock);
7276 for (prev = peer = *peer_ptr; peer; peer = next) {
7278 code = MUTEX_TRYENTER(&peer->peer_lock);
7279 if ((code) && (peer->refCount == 0)
7280 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
7281 struct opr_queue *cursor, *store;
7285 * now know that this peer object is one to be
7286 * removed from the hash table. Once it is removed
7287 * it can't be referenced by other threads.
7288 * Lets remove it first and decrement the struct
7289 * nPeerStructs count.
7291 if (peer == *peer_ptr) {
7297 if (rx_stats_active)
7298 rx_atomic_dec(&rx_stats.nPeerStructs);
7301 * Now if we hold references on 'prev' and 'next'
7302 * we can safely drop the rx_peerHashTable_lock
7303 * while we destroy this 'peer' object.
7309 MUTEX_EXIT(&rx_peerHashTable_lock);
7311 MUTEX_EXIT(&peer->peer_lock);
7312 MUTEX_DESTROY(&peer->peer_lock);
7314 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
7315 unsigned int num_funcs;
7316 struct rx_interface_stat *rpc_stat
7317 = opr_queue_Entry(cursor, struct rx_interface_stat,
7322 opr_queue_Remove(&rpc_stat->entry);
7323 opr_queue_Remove(&rpc_stat->entryPeers);
7325 num_funcs = rpc_stat->stats[0].func_total;
7327 sizeof(rx_interface_stat_t) +
7328 rpc_stat->stats[0].func_total *
7329 sizeof(rx_function_entry_v1_t);
7331 rxi_Free(rpc_stat, space);
7333 MUTEX_ENTER(&rx_rpc_stats);
7334 rxi_rpc_peer_stat_cnt -= num_funcs;
7335 MUTEX_EXIT(&rx_rpc_stats);
7340 * Regain the rx_peerHashTable_lock and
7341 * decrement the reference count on 'prev'
7344 MUTEX_ENTER(&rx_peerHashTable_lock);
7351 MUTEX_EXIT(&peer->peer_lock);
7356 MUTEX_EXIT(&rx_peerHashTable_lock);
7360 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
7361 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
7362 * GC, just below. Really, we shouldn't have to keep moving packets from
7363 * one place to another, but instead ought to always know if we can
7364 * afford to hold onto a packet in its particular use. */
7365 MUTEX_ENTER(&rx_freePktQ_lock);
7366 if (rx_waitingForPackets) {
7367 rx_waitingForPackets = 0;
7368 #ifdef RX_ENABLE_LOCKS
7369 CV_BROADCAST(&rx_waitingForPackets_cv);
7371 osi_rxWakeup(&rx_waitingForPackets);
7374 MUTEX_EXIT(&rx_freePktQ_lock);
7377 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
7378 event = rxevent_Post(&when, &now, rxi_ReapConnections, 0, NULL, 0);
7379 rxevent_Put(&event);
7383 /* rxs_Release - This isn't strictly necessary but, since the macro name from
7384 * rx.h is sort of strange this is better. This is called with a security
7385 * object before it is discarded. Each connection using a security object has
7386 * its own refcount to the object so it won't actually be freed until the last
7387 * connection is destroyed.
7389 * This is the only rxs module call. A hold could also be written but no one
7393 rxs_Release(struct rx_securityClass *aobj)
7395 return RXS_Close(aobj);
7403 #define TRACE_OPTION_RX_DEBUG 16
7411 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
7412 0, KEY_QUERY_VALUE, &parmKey);
7413 if (code != ERROR_SUCCESS)
7416 dummyLen = sizeof(TraceOption);
7417 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
7418 (BYTE *) &TraceOption, &dummyLen);
7419 if (code == ERROR_SUCCESS) {
7420 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
7422 RegCloseKey (parmKey);
7423 #endif /* AFS_NT40_ENV */
7428 rx_DebugOnOff(int on)
7432 rxdebug_active = on;
7438 rx_StatsOnOff(int on)
7440 rx_stats_active = on;
7444 /* Don't call this debugging routine directly; use dpf */
7446 rxi_DebugPrint(char *format, ...)
7455 va_start(ap, format);
7457 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7460 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7462 OutputDebugString(msg);
7468 va_start(ap, format);
7470 clock_GetTime(&now);
7471 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7472 (unsigned int)now.usec);
7473 vfprintf(rx_Log, format, ap);
7481 * This function is used to process the rx_stats structure that is local
7482 * to a process as well as an rx_stats structure received from a remote
7483 * process (via rxdebug). Therefore, it needs to do minimal version
7487 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7488 afs_int32 freePackets, char version)
7492 if (size != sizeof(struct rx_statistics)) {
7494 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7495 size, sizeof(struct rx_statistics));
7498 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7501 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7502 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7503 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7504 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7505 s->specialPktAllocFailures);
7507 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7508 s->receivePktAllocFailures, s->sendPktAllocFailures,
7509 s->specialPktAllocFailures);
7513 " greedy %u, " "bogusReads %u (last from host %x), "
7514 "noPackets %u, " "noBuffers %u, " "selects %u, "
7515 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7516 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7517 s->selects, s->sendSelects);
7519 fprintf(file, " packets read: ");
7520 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7521 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7523 fprintf(file, "\n");
7526 " other read counters: data %u, " "ack %u, " "dup %u "
7527 "spurious %u " "dally %u\n", s->dataPacketsRead,
7528 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7529 s->ignorePacketDally);
7531 fprintf(file, " packets sent: ");
7532 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7533 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7535 fprintf(file, "\n");
7538 " other send counters: ack %u, " "data %u (not resends), "
7539 "resends %u, " "pushed %u, " "acked&ignored %u\n",
7540 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7541 s->dataPacketsPushed, s->ignoreAckedPacket);
7544 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7545 s->netSendFailures, (int)s->fatalErrors);
7547 if (s->nRttSamples) {
7548 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
7549 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7551 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
7552 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7556 " %d server connections, " "%d client connections, "
7557 "%d peer structs, " "%d call structs, " "%d free call structs\n",
7558 s->nServerConns, s->nClientConns, s->nPeerStructs,
7559 s->nCallStructs, s->nFreeCallStructs);
7561 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7562 fprintf(file, " %d clock updates\n", clock_nUpdates);
7566 /* for backward compatibility */
7568 rx_PrintStats(FILE * file)
7570 MUTEX_ENTER(&rx_stats_mutex);
7571 rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7572 sizeof(rx_stats), rx_nFreePackets,
7574 MUTEX_EXIT(&rx_stats_mutex);
7578 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7580 fprintf(file, "Peer %x.%d.\n",
7581 ntohl(peer->host), (int)ntohs(peer->port));
7584 " Rtt %d, " "total sent %d, " "resent %d\n",
7585 peer->rtt, peer->nSent, peer->reSends);
7587 fprintf(file, " Packet size %d\n", peer->ifMTU);
7591 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7593 * This mutex protects the following static variables:
7597 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7598 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7600 #define LOCK_RX_DEBUG
7601 #define UNLOCK_RX_DEBUG
7602 #endif /* AFS_PTHREAD_ENV */
7604 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7606 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7607 u_char type, void *inputData, size_t inputLength,
7608 void *outputData, size_t outputLength)
7610 static afs_int32 counter = 100;
7611 time_t waitTime, waitCount;
7612 struct rx_header theader;
7615 struct timeval tv_now, tv_wake, tv_delta;
7616 struct sockaddr_in taddr, faddr;
7630 tp = &tbuffer[sizeof(struct rx_header)];
7631 taddr.sin_family = AF_INET;
7632 taddr.sin_port = remotePort;
7633 taddr.sin_addr.s_addr = remoteAddr;
7634 memset(&taddr.sin_zero, 0, sizeof(taddr.sin_zero));
7635 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7636 taddr.sin_len = sizeof(struct sockaddr_in);
7639 memset(&theader, 0, sizeof(theader));
7640 theader.epoch = htonl(999);
7642 theader.callNumber = htonl(counter);
7645 theader.type = type;
7646 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7647 theader.serviceId = 0;
7649 memcpy(tbuffer, &theader, sizeof(theader));
7650 memcpy(tp, inputData, inputLength);
7652 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7653 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7655 /* see if there's a packet available */
7656 gettimeofday(&tv_wake, NULL);
7657 tv_wake.tv_sec += waitTime;
7660 FD_SET(socket, &imask);
7661 tv_delta.tv_sec = tv_wake.tv_sec;
7662 tv_delta.tv_usec = tv_wake.tv_usec;
7663 gettimeofday(&tv_now, NULL);
7665 if (tv_delta.tv_usec < tv_now.tv_usec) {
7667 tv_delta.tv_usec += 1000000;
7670 tv_delta.tv_usec -= tv_now.tv_usec;
7672 if (tv_delta.tv_sec < tv_now.tv_sec) {
7676 tv_delta.tv_sec -= tv_now.tv_sec;
7679 code = select(0, &imask, 0, 0, &tv_delta);
7680 #else /* AFS_NT40_ENV */
7681 code = select(socket + 1, &imask, 0, 0, &tv_delta);
7682 #endif /* AFS_NT40_ENV */
7683 if (code == 1 && FD_ISSET(socket, &imask)) {
7684 /* now receive a packet */
7685 faddrLen = sizeof(struct sockaddr_in);
7687 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7688 (struct sockaddr *)&faddr, &faddrLen);
7691 memcpy(&theader, tbuffer, sizeof(struct rx_header));
7692 if (counter == ntohl(theader.callNumber))
7700 /* see if we've timed out */
7708 code -= sizeof(struct rx_header);
7709 if (code > outputLength)
7710 code = outputLength;
7711 memcpy(outputData, tp, code);
7714 #endif /* RXDEBUG */
7717 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7718 afs_uint16 remotePort, struct rx_debugStats * stat,
7719 afs_uint32 * supportedValues)
7721 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7723 struct rx_debugIn in;
7725 *supportedValues = 0;
7726 in.type = htonl(RX_DEBUGI_GETSTATS);
7729 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7730 &in, sizeof(in), stat, sizeof(*stat));
7733 * If the call was successful, fixup the version and indicate
7734 * what contents of the stat structure are valid.
7735 * Also do net to host conversion of fields here.
7739 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7740 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7742 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7743 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7745 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7746 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7748 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7749 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7751 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7752 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7754 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7755 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7757 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7758 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7760 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7761 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7763 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7764 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7766 stat->nFreePackets = ntohl(stat->nFreePackets);
7767 stat->packetReclaims = ntohl(stat->packetReclaims);
7768 stat->callsExecuted = ntohl(stat->callsExecuted);
7769 stat->nWaiting = ntohl(stat->nWaiting);
7770 stat->idleThreads = ntohl(stat->idleThreads);
7771 stat->nWaited = ntohl(stat->nWaited);
7772 stat->nPackets = ntohl(stat->nPackets);
7781 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7782 afs_uint16 remotePort, struct rx_statistics * stat,
7783 afs_uint32 * supportedValues)
7785 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7787 struct rx_debugIn in;
7788 afs_int32 *lp = (afs_int32 *) stat;
7792 * supportedValues is currently unused, but added to allow future
7793 * versioning of this function.
7796 *supportedValues = 0;
7797 in.type = htonl(RX_DEBUGI_RXSTATS);
7799 memset(stat, 0, sizeof(*stat));
7801 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7802 &in, sizeof(in), stat, sizeof(*stat));
7807 * Do net to host conversion here
7810 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7821 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7822 afs_uint16 remotePort, size_t version_length,
7825 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7827 return MakeDebugCall(socket, remoteAddr, remotePort,
7828 RX_PACKET_TYPE_VERSION, a, 1, version,
7836 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7837 afs_uint16 remotePort, afs_int32 * nextConnection,
7838 int allConnections, afs_uint32 debugSupportedValues,
7839 struct rx_debugConn * conn,
7840 afs_uint32 * supportedValues)
7842 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7844 struct rx_debugIn in;
7848 * supportedValues is currently unused, but added to allow future
7849 * versioning of this function.
7852 *supportedValues = 0;
7853 if (allConnections) {
7854 in.type = htonl(RX_DEBUGI_GETALLCONN);
7856 in.type = htonl(RX_DEBUGI_GETCONN);
7858 in.index = htonl(*nextConnection);
7859 memset(conn, 0, sizeof(*conn));
7861 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7862 &in, sizeof(in), conn, sizeof(*conn));
7865 *nextConnection += 1;
7868 * Convert old connection format to new structure.
7871 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7872 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7873 #define MOVEvL(a) (conn->a = vL->a)
7875 /* any old or unrecognized version... */
7876 for (i = 0; i < RX_MAXCALLS; i++) {
7877 MOVEvL(callState[i]);
7878 MOVEvL(callMode[i]);
7879 MOVEvL(callFlags[i]);
7880 MOVEvL(callOther[i]);
7882 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7883 MOVEvL(secStats.type);
7884 MOVEvL(secStats.level);
7885 MOVEvL(secStats.flags);
7886 MOVEvL(secStats.expires);
7887 MOVEvL(secStats.packetsReceived);
7888 MOVEvL(secStats.packetsSent);
7889 MOVEvL(secStats.bytesReceived);
7890 MOVEvL(secStats.bytesSent);
7895 * Do net to host conversion here
7897 * I don't convert host or port since we are most likely
7898 * going to want these in NBO.
7900 conn->cid = ntohl(conn->cid);
7901 conn->serial = ntohl(conn->serial);
7902 for (i = 0; i < RX_MAXCALLS; i++) {
7903 conn->callNumber[i] = ntohl(conn->callNumber[i]);
7905 conn->error = ntohl(conn->error);
7906 conn->secStats.flags = ntohl(conn->secStats.flags);
7907 conn->secStats.expires = ntohl(conn->secStats.expires);
7908 conn->secStats.packetsReceived =
7909 ntohl(conn->secStats.packetsReceived);
7910 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7911 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7912 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7913 conn->epoch = ntohl(conn->epoch);
7914 conn->natMTU = ntohl(conn->natMTU);
7923 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7924 afs_uint16 remotePort, afs_int32 * nextPeer,
7925 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7926 afs_uint32 * supportedValues)
7928 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7930 struct rx_debugIn in;
7933 * supportedValues is currently unused, but added to allow future
7934 * versioning of this function.
7937 *supportedValues = 0;
7938 in.type = htonl(RX_DEBUGI_GETPEER);
7939 in.index = htonl(*nextPeer);
7940 memset(peer, 0, sizeof(*peer));
7942 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7943 &in, sizeof(in), peer, sizeof(*peer));
7949 * Do net to host conversion here
7951 * I don't convert host or port since we are most likely
7952 * going to want these in NBO.
7954 peer->ifMTU = ntohs(peer->ifMTU);
7955 peer->idleWhen = ntohl(peer->idleWhen);
7956 peer->refCount = ntohs(peer->refCount);
7957 peer->rtt = ntohl(peer->rtt);
7958 peer->rtt_dev = ntohl(peer->rtt_dev);
7959 peer->timeout.sec = 0;
7960 peer->timeout.usec = 0;
7961 peer->nSent = ntohl(peer->nSent);
7962 peer->reSends = ntohl(peer->reSends);
7963 peer->natMTU = ntohs(peer->natMTU);
7964 peer->maxMTU = ntohs(peer->maxMTU);
7965 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7966 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7967 peer->MTU = ntohs(peer->MTU);
7968 peer->cwind = ntohs(peer->cwind);
7969 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7970 peer->congestSeq = ntohs(peer->congestSeq);
7971 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7972 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7973 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7974 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7983 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7984 struct rx_debugPeer * peerStats)
7987 afs_int32 error = 1; /* default to "did not succeed" */
7988 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7990 MUTEX_ENTER(&rx_peerHashTable_lock);
7991 for(tp = rx_peerHashTable[hashValue];
7992 tp != NULL; tp = tp->next) {
7993 if (tp->host == peerHost)
7999 MUTEX_EXIT(&rx_peerHashTable_lock);
8003 MUTEX_ENTER(&tp->peer_lock);
8004 peerStats->host = tp->host;
8005 peerStats->port = tp->port;
8006 peerStats->ifMTU = tp->ifMTU;
8007 peerStats->idleWhen = tp->idleWhen;
8008 peerStats->refCount = tp->refCount;
8009 peerStats->burstSize = 0;
8010 peerStats->burst = 0;
8011 peerStats->burstWait.sec = 0;
8012 peerStats->burstWait.usec = 0;
8013 peerStats->rtt = tp->rtt;
8014 peerStats->rtt_dev = tp->rtt_dev;
8015 peerStats->timeout.sec = 0;
8016 peerStats->timeout.usec = 0;
8017 peerStats->nSent = tp->nSent;
8018 peerStats->reSends = tp->reSends;
8019 peerStats->natMTU = tp->natMTU;
8020 peerStats->maxMTU = tp->maxMTU;
8021 peerStats->maxDgramPackets = tp->maxDgramPackets;
8022 peerStats->ifDgramPackets = tp->ifDgramPackets;
8023 peerStats->MTU = tp->MTU;
8024 peerStats->cwind = tp->cwind;
8025 peerStats->nDgramPackets = tp->nDgramPackets;
8026 peerStats->congestSeq = tp->congestSeq;
8027 peerStats->bytesSent.high = tp->bytesSent >> 32;
8028 peerStats->bytesSent.low = tp->bytesSent & MAX_AFS_UINT32;
8029 peerStats->bytesReceived.high = tp->bytesReceived >> 32;
8030 peerStats->bytesReceived.low
8031 = tp->bytesReceived & MAX_AFS_UINT32;
8032 MUTEX_EXIT(&tp->peer_lock);
8034 MUTEX_ENTER(&rx_peerHashTable_lock);
8037 MUTEX_EXIT(&rx_peerHashTable_lock);
8045 struct rx_serverQueueEntry *np;
8048 struct rx_call *call;
8049 struct rx_serverQueueEntry *sq;
8053 if (!rxi_IsRunning()) {
8055 return; /* Already shutdown. */
8057 rx_atomic_set(&rxi_running, 0);
8060 #ifndef AFS_PTHREAD_ENV
8061 FD_ZERO(&rx_selectMask);
8062 #endif /* AFS_PTHREAD_ENV */
8063 rxi_dataQuota = RX_MAX_QUOTA;
8064 #ifndef AFS_PTHREAD_ENV
8066 #endif /* AFS_PTHREAD_ENV */
8069 #ifndef AFS_PTHREAD_ENV
8070 #ifndef AFS_USE_GETTIMEOFDAY
8072 #endif /* AFS_USE_GETTIMEOFDAY */
8073 #endif /* AFS_PTHREAD_ENV */
8075 while (!opr_queue_IsEmpty(&rx_freeCallQueue)) {
8076 call = opr_queue_First(&rx_freeCallQueue, struct rx_call, entry);
8077 opr_queue_Remove(&call->entry);
8078 rxi_Free(call, sizeof(struct rx_call));
8081 while (!opr_queue_IsEmpty(&rx_idleServerQueue)) {
8082 sq = opr_queue_First(&rx_idleServerQueue, struct rx_serverQueueEntry,
8084 opr_queue_Remove(&sq->entry);
8089 struct rx_peer **peer_ptr, **peer_end;
8090 for (peer_ptr = &rx_peerHashTable[0], peer_end =
8091 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
8093 struct rx_peer *peer, *next;
8095 MUTEX_ENTER(&rx_peerHashTable_lock);
8096 for (peer = *peer_ptr; peer; peer = next) {
8097 struct opr_queue *cursor, *store;
8100 MUTEX_ENTER(&rx_rpc_stats);
8101 MUTEX_ENTER(&peer->peer_lock);
8102 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
8103 unsigned int num_funcs;
8104 struct rx_interface_stat *rpc_stat
8105 = opr_queue_Entry(cursor, struct rx_interface_stat,
8109 opr_queue_Remove(&rpc_stat->entry);
8110 opr_queue_Remove(&rpc_stat->entryPeers);
8111 num_funcs = rpc_stat->stats[0].func_total;
8113 sizeof(rx_interface_stat_t) +
8114 rpc_stat->stats[0].func_total *
8115 sizeof(rx_function_entry_v1_t);
8117 rxi_Free(rpc_stat, space);
8119 /* rx_rpc_stats must be held */
8120 rxi_rpc_peer_stat_cnt -= num_funcs;
8122 MUTEX_EXIT(&peer->peer_lock);
8123 MUTEX_EXIT(&rx_rpc_stats);
8127 if (rx_stats_active)
8128 rx_atomic_dec(&rx_stats.nPeerStructs);
8130 MUTEX_EXIT(&rx_peerHashTable_lock);
8133 for (i = 0; i < RX_MAX_SERVICES; i++) {
8135 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
8137 for (i = 0; i < rx_hashTableSize; i++) {
8138 struct rx_connection *tc, *ntc;
8139 MUTEX_ENTER(&rx_connHashTable_lock);
8140 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
8142 for (j = 0; j < RX_MAXCALLS; j++) {
8144 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
8147 rxi_Free(tc, sizeof(*tc));
8149 MUTEX_EXIT(&rx_connHashTable_lock);
8152 MUTEX_ENTER(&freeSQEList_lock);
8154 while (!opr_queue_IsEmpty(&rx_freeServerQueue)) {
8155 np = opr_queue_First(&rx_freeServerQueue, struct rx_serverQueueEntry,
8157 opr_queue_Remove(&np->entry);
8158 MUTEX_DESTROY(&np->lock);
8159 rxi_Free(np, sizeof(*np));
8162 MUTEX_EXIT(&freeSQEList_lock);
8163 MUTEX_DESTROY(&freeSQEList_lock);
8164 MUTEX_DESTROY(&rx_freeCallQueue_lock);
8165 MUTEX_DESTROY(&rx_connHashTable_lock);
8166 MUTEX_DESTROY(&rx_peerHashTable_lock);
8167 MUTEX_DESTROY(&rx_serverPool_lock);
8169 osi_Free(rx_connHashTable,
8170 rx_hashTableSize * sizeof(struct rx_connection *));
8171 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
8173 UNPIN(rx_connHashTable,
8174 rx_hashTableSize * sizeof(struct rx_connection *));
8175 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
8177 MUTEX_ENTER(&rx_quota_mutex);
8178 rxi_dataQuota = RX_MAX_QUOTA;
8179 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
8180 MUTEX_EXIT(&rx_quota_mutex);
8187 * Routines to implement connection specific data.
8191 rx_KeyCreate(rx_destructor_t rtn)
8194 MUTEX_ENTER(&rxi_keyCreate_lock);
8195 key = rxi_keyCreate_counter++;
8196 rxi_keyCreate_destructor = (rx_destructor_t *)
8197 realloc((void *)rxi_keyCreate_destructor,
8198 (key + 1) * sizeof(rx_destructor_t));
8199 rxi_keyCreate_destructor[key] = rtn;
8200 MUTEX_EXIT(&rxi_keyCreate_lock);
8205 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
8208 MUTEX_ENTER(&conn->conn_data_lock);
8209 if (!conn->specific) {
8210 conn->specific = malloc((key + 1) * sizeof(void *));
8211 for (i = 0; i < key; i++)
8212 conn->specific[i] = NULL;
8213 conn->nSpecific = key + 1;
8214 conn->specific[key] = ptr;
8215 } else if (key >= conn->nSpecific) {
8216 conn->specific = (void **)
8217 realloc(conn->specific, (key + 1) * sizeof(void *));
8218 for (i = conn->nSpecific; i < key; i++)
8219 conn->specific[i] = NULL;
8220 conn->nSpecific = key + 1;
8221 conn->specific[key] = ptr;
8223 if (conn->specific[key] && rxi_keyCreate_destructor[key])
8224 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
8225 conn->specific[key] = ptr;
8227 MUTEX_EXIT(&conn->conn_data_lock);
8231 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
8234 MUTEX_ENTER(&svc->svc_data_lock);
8235 if (!svc->specific) {
8236 svc->specific = malloc((key + 1) * sizeof(void *));
8237 for (i = 0; i < key; i++)
8238 svc->specific[i] = NULL;
8239 svc->nSpecific = key + 1;
8240 svc->specific[key] = ptr;
8241 } else if (key >= svc->nSpecific) {
8242 svc->specific = (void **)
8243 realloc(svc->specific, (key + 1) * sizeof(void *));
8244 for (i = svc->nSpecific; i < key; i++)
8245 svc->specific[i] = NULL;
8246 svc->nSpecific = key + 1;
8247 svc->specific[key] = ptr;
8249 if (svc->specific[key] && rxi_keyCreate_destructor[key])
8250 (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
8251 svc->specific[key] = ptr;
8253 MUTEX_EXIT(&svc->svc_data_lock);
8257 rx_GetSpecific(struct rx_connection *conn, int key)
8260 MUTEX_ENTER(&conn->conn_data_lock);
8261 if (key >= conn->nSpecific)
8264 ptr = conn->specific[key];
8265 MUTEX_EXIT(&conn->conn_data_lock);
8270 rx_GetServiceSpecific(struct rx_service *svc, int key)
8273 MUTEX_ENTER(&svc->svc_data_lock);
8274 if (key >= svc->nSpecific)
8277 ptr = svc->specific[key];
8278 MUTEX_EXIT(&svc->svc_data_lock);
8283 #endif /* !KERNEL */
8286 * processStats is a queue used to store the statistics for the local
8287 * process. Its contents are similar to the contents of the rpcStats
8288 * queue on a rx_peer structure, but the actual data stored within
8289 * this queue contains totals across the lifetime of the process (assuming
8290 * the stats have not been reset) - unlike the per peer structures
8291 * which can come and go based upon the peer lifetime.
8294 static struct opr_queue processStats = { &processStats, &processStats };
8297 * peerStats is a queue used to store the statistics for all peer structs.
8298 * Its contents are the union of all the peer rpcStats queues.
8301 static struct opr_queue peerStats = { &peerStats, &peerStats };
8304 * rxi_monitor_processStats is used to turn process wide stat collection
8308 static int rxi_monitor_processStats = 0;
8311 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
8314 static int rxi_monitor_peerStats = 0;
8318 rxi_ClearRPCOpStat(rx_function_entry_v1_p rpc_stat)
8320 rpc_stat->invocations = 0;
8321 rpc_stat->bytes_sent = 0;
8322 rpc_stat->bytes_rcvd = 0;
8323 rpc_stat->queue_time_sum.sec = 0;
8324 rpc_stat->queue_time_sum.usec = 0;
8325 rpc_stat->queue_time_sum_sqr.sec = 0;
8326 rpc_stat->queue_time_sum_sqr.usec = 0;
8327 rpc_stat->queue_time_min.sec = 9999999;
8328 rpc_stat->queue_time_min.usec = 9999999;
8329 rpc_stat->queue_time_max.sec = 0;
8330 rpc_stat->queue_time_max.usec = 0;
8331 rpc_stat->execution_time_sum.sec = 0;
8332 rpc_stat->execution_time_sum.usec = 0;
8333 rpc_stat->execution_time_sum_sqr.sec = 0;
8334 rpc_stat->execution_time_sum_sqr.usec = 0;
8335 rpc_stat->execution_time_min.sec = 9999999;
8336 rpc_stat->execution_time_min.usec = 9999999;
8337 rpc_stat->execution_time_max.sec = 0;
8338 rpc_stat->execution_time_max.usec = 0;
8342 * Given all of the information for a particular rpc
8343 * call, find or create (if requested) the stat structure for the rpc.
8346 * the queue of stats that will be updated with the new value
8348 * @param rxInterface
8349 * a unique number that identifies the rpc interface
8352 * the total number of functions in this interface. this is only
8353 * required if create is true
8356 * if true, this invocation was made to a server
8359 * the ip address of the remote host. this is only required if create
8360 * and addToPeerList are true
8363 * the port of the remote host. this is only required if create
8364 * and addToPeerList are true
8366 * @param addToPeerList
8367 * if != 0, add newly created stat to the global peer list
8370 * if a new stats structure is allocated, the counter will
8371 * be updated with the new number of allocated stat structures.
8372 * only required if create is true
8375 * if no stats structure exists, allocate one
8379 static rx_interface_stat_p
8380 rxi_FindRpcStat(struct opr_queue *stats, afs_uint32 rxInterface,
8381 afs_uint32 totalFunc, int isServer, afs_uint32 remoteHost,
8382 afs_uint32 remotePort, int addToPeerList,
8383 unsigned int *counter, int create)
8385 rx_interface_stat_p rpc_stat = NULL;
8386 struct opr_queue *cursor;
8389 * See if there's already a structure for this interface
8392 for (opr_queue_Scan(stats, cursor)) {
8393 rpc_stat = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8395 if ((rpc_stat->stats[0].interfaceId == rxInterface)
8396 && (rpc_stat->stats[0].remote_is_server == isServer))
8400 /* if they didn't ask us to create, we're done */
8402 if (opr_queue_IsEnd(stats, cursor))
8408 /* can't proceed without these */
8409 if (!totalFunc || !counter)
8413 * Didn't find a match so allocate a new structure and add it to the
8417 if (opr_queue_IsEnd(stats, cursor) || (rpc_stat == NULL)
8418 || (rpc_stat->stats[0].interfaceId != rxInterface)
8419 || (rpc_stat->stats[0].remote_is_server != isServer)) {
8424 sizeof(rx_interface_stat_t) +
8425 totalFunc * sizeof(rx_function_entry_v1_t);
8427 rpc_stat = rxi_Alloc(space);
8428 if (rpc_stat == NULL)
8431 *counter += totalFunc;
8432 for (i = 0; i < totalFunc; i++) {
8433 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8434 rpc_stat->stats[i].remote_peer = remoteHost;
8435 rpc_stat->stats[i].remote_port = remotePort;
8436 rpc_stat->stats[i].remote_is_server = isServer;
8437 rpc_stat->stats[i].interfaceId = rxInterface;
8438 rpc_stat->stats[i].func_total = totalFunc;
8439 rpc_stat->stats[i].func_index = i;
8441 opr_queue_Prepend(stats, &rpc_stat->entry);
8442 if (addToPeerList) {
8443 opr_queue_Prepend(&peerStats, &rpc_stat->entryPeers);
8450 rx_ClearProcessRPCStats(afs_int32 rxInterface)
8452 rx_interface_stat_p rpc_stat;
8455 if (rxInterface == -1)
8458 MUTEX_ENTER(&rx_rpc_stats);
8459 rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8462 totalFunc = rpc_stat->stats[0].func_total;
8463 for (i = 0; i < totalFunc; i++)
8464 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8466 MUTEX_EXIT(&rx_rpc_stats);
8471 rx_ClearPeerRPCStats(afs_int32 rxInterface, afs_uint32 peerHost, afs_uint16 peerPort)
8473 rx_interface_stat_p rpc_stat;
8475 struct rx_peer * peer;
8477 if (rxInterface == -1)
8480 peer = rxi_FindPeer(peerHost, peerPort, 0);
8484 MUTEX_ENTER(&rx_rpc_stats);
8485 rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8488 totalFunc = rpc_stat->stats[0].func_total;
8489 for (i = 0; i < totalFunc; i++)
8490 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8492 MUTEX_EXIT(&rx_rpc_stats);
8497 rx_CopyProcessRPCStats(afs_uint64 op)
8499 rx_interface_stat_p rpc_stat;
8500 rx_function_entry_v1_p rpcop_stat =
8501 rxi_Alloc(sizeof(rx_function_entry_v1_t));
8502 int currentFunc = (op & MAX_AFS_UINT32);
8503 afs_int32 rxInterface = (op >> 32);
8505 if (!rxi_monitor_processStats)
8508 if (rxInterface == -1)
8511 if (rpcop_stat == NULL)
8514 MUTEX_ENTER(&rx_rpc_stats);
8515 rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8518 memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8519 sizeof(rx_function_entry_v1_t));
8520 MUTEX_EXIT(&rx_rpc_stats);
8522 rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8529 rx_CopyPeerRPCStats(afs_uint64 op, afs_uint32 peerHost, afs_uint16 peerPort)
8531 rx_interface_stat_p rpc_stat;
8532 rx_function_entry_v1_p rpcop_stat =
8533 rxi_Alloc(sizeof(rx_function_entry_v1_t));
8534 int currentFunc = (op & MAX_AFS_UINT32);
8535 afs_int32 rxInterface = (op >> 32);
8536 struct rx_peer *peer;
8538 if (!rxi_monitor_peerStats)
8541 if (rxInterface == -1)
8544 if (rpcop_stat == NULL)
8547 peer = rxi_FindPeer(peerHost, peerPort, 0);
8551 MUTEX_ENTER(&rx_rpc_stats);
8552 rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8555 memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8556 sizeof(rx_function_entry_v1_t));
8557 MUTEX_EXIT(&rx_rpc_stats);
8559 rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8566 rx_ReleaseRPCStats(void *stats)
8569 rxi_Free(stats, sizeof(rx_function_entry_v1_t));
8573 * Given all of the information for a particular rpc
8574 * call, create (if needed) and update the stat totals for the rpc.
8577 * the queue of stats that will be updated with the new value
8579 * @param rxInterface
8580 * a unique number that identifies the rpc interface
8582 * @param currentFunc
8583 * the index of the function being invoked
8586 * the total number of functions in this interface
8589 * the amount of time this function waited for a thread
8592 * the amount of time this function invocation took to execute
8595 * the number bytes sent by this invocation
8598 * the number bytes received by this invocation
8601 * if true, this invocation was made to a server
8604 * the ip address of the remote host
8607 * the port of the remote host
8609 * @param addToPeerList
8610 * if != 0, add newly created stat to the global peer list
8613 * if a new stats structure is allocated, the counter will
8614 * be updated with the new number of allocated stat structures
8619 rxi_AddRpcStat(struct opr_queue *stats, afs_uint32 rxInterface,
8620 afs_uint32 currentFunc, afs_uint32 totalFunc,
8621 struct clock *queueTime, struct clock *execTime,
8622 afs_uint64 bytesSent, afs_uint64 bytesRcvd, int isServer,
8623 afs_uint32 remoteHost, afs_uint32 remotePort,
8624 int addToPeerList, unsigned int *counter)
8627 rx_interface_stat_p rpc_stat;
8629 rpc_stat = rxi_FindRpcStat(stats, rxInterface, totalFunc, isServer,
8630 remoteHost, remotePort, addToPeerList, counter,
8638 * Increment the stats for this function
8641 rpc_stat->stats[currentFunc].invocations++;
8642 rpc_stat->stats[currentFunc].bytes_sent += bytesSent;
8643 rpc_stat->stats[currentFunc].bytes_rcvd += bytesRcvd;
8644 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8645 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8646 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8647 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8649 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8650 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8652 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8653 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8655 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8656 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8658 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8659 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8667 rxi_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8668 afs_uint32 currentFunc, afs_uint32 totalFunc,
8669 struct clock *queueTime, struct clock *execTime,
8670 afs_uint64 bytesSent, afs_uint64 bytesRcvd,
8674 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8677 MUTEX_ENTER(&rx_rpc_stats);
8679 if (rxi_monitor_peerStats) {
8680 MUTEX_ENTER(&peer->peer_lock);
8681 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8682 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8683 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8684 MUTEX_EXIT(&peer->peer_lock);
8687 if (rxi_monitor_processStats) {
8688 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8689 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8690 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8693 MUTEX_EXIT(&rx_rpc_stats);
8697 * Increment the times and count for a particular rpc function.
8699 * Traditionally this call was invoked from rxgen stubs. Modern stubs
8700 * call rx_RecordCallStatistics instead, so the public version of this
8701 * function is left purely for legacy callers.
8704 * The peer who invoked the rpc
8706 * @param rxInterface
8707 * A unique number that identifies the rpc interface
8709 * @param currentFunc
8710 * The index of the function being invoked
8713 * The total number of functions in this interface
8716 * The amount of time this function waited for a thread
8719 * The amount of time this function invocation took to execute
8722 * The number bytes sent by this invocation
8725 * The number bytes received by this invocation
8728 * If true, this invocation was made to a server
8732 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8733 afs_uint32 currentFunc, afs_uint32 totalFunc,
8734 struct clock *queueTime, struct clock *execTime,
8735 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8741 sent64 = ((afs_uint64)bytesSent->high << 32) + bytesSent->low;
8742 rcvd64 = ((afs_uint64)bytesRcvd->high << 32) + bytesRcvd->low;
8744 rxi_IncrementTimeAndCount(peer, rxInterface, currentFunc, totalFunc,
8745 queueTime, execTime, sent64, rcvd64,
8752 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8756 * IN callerVersion - the rpc stat version of the caller.
8758 * IN count - the number of entries to marshall.
8760 * IN stats - pointer to stats to be marshalled.
8762 * OUT ptr - Where to store the marshalled data.
8769 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8770 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8776 * We only support the first version
8778 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8779 *(ptr++) = stats->remote_peer;
8780 *(ptr++) = stats->remote_port;
8781 *(ptr++) = stats->remote_is_server;
8782 *(ptr++) = stats->interfaceId;
8783 *(ptr++) = stats->func_total;
8784 *(ptr++) = stats->func_index;
8785 *(ptr++) = stats->invocations >> 32;
8786 *(ptr++) = stats->invocations & MAX_AFS_UINT32;
8787 *(ptr++) = stats->bytes_sent >> 32;
8788 *(ptr++) = stats->bytes_sent & MAX_AFS_UINT32;
8789 *(ptr++) = stats->bytes_rcvd >> 32;
8790 *(ptr++) = stats->bytes_rcvd & MAX_AFS_UINT32;
8791 *(ptr++) = stats->queue_time_sum.sec;
8792 *(ptr++) = stats->queue_time_sum.usec;
8793 *(ptr++) = stats->queue_time_sum_sqr.sec;
8794 *(ptr++) = stats->queue_time_sum_sqr.usec;
8795 *(ptr++) = stats->queue_time_min.sec;
8796 *(ptr++) = stats->queue_time_min.usec;
8797 *(ptr++) = stats->queue_time_max.sec;
8798 *(ptr++) = stats->queue_time_max.usec;
8799 *(ptr++) = stats->execution_time_sum.sec;
8800 *(ptr++) = stats->execution_time_sum.usec;
8801 *(ptr++) = stats->execution_time_sum_sqr.sec;
8802 *(ptr++) = stats->execution_time_sum_sqr.usec;
8803 *(ptr++) = stats->execution_time_min.sec;
8804 *(ptr++) = stats->execution_time_min.usec;
8805 *(ptr++) = stats->execution_time_max.sec;
8806 *(ptr++) = stats->execution_time_max.usec;
8812 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8817 * IN callerVersion - the rpc stat version of the caller
8819 * OUT myVersion - the rpc stat version of this function
8821 * OUT clock_sec - local time seconds
8823 * OUT clock_usec - local time microseconds
8825 * OUT allocSize - the number of bytes allocated to contain stats
8827 * OUT statCount - the number stats retrieved from this process.
8829 * OUT stats - the actual stats retrieved from this process.
8833 * Returns void. If successful, stats will != NULL.
8837 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8838 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8839 size_t * allocSize, afs_uint32 * statCount,
8840 afs_uint32 ** stats)
8850 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8853 * Check to see if stats are enabled
8856 MUTEX_ENTER(&rx_rpc_stats);
8857 if (!rxi_monitor_processStats) {
8858 MUTEX_EXIT(&rx_rpc_stats);
8862 clock_GetTime(&now);
8863 *clock_sec = now.sec;
8864 *clock_usec = now.usec;
8867 * Allocate the space based upon the caller version
8869 * If the client is at an older version than we are,
8870 * we return the statistic data in the older data format, but
8871 * we still return our version number so the client knows we
8872 * are maintaining more data than it can retrieve.
8875 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8876 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8877 *statCount = rxi_rpc_process_stat_cnt;
8880 * This can't happen yet, but in the future version changes
8881 * can be handled by adding additional code here
8885 if (space > (size_t) 0) {
8887 ptr = *stats = rxi_Alloc(space);
8890 struct opr_queue *cursor;
8892 for (opr_queue_Scan(&processStats, cursor)) {
8893 struct rx_interface_stat *rpc_stat =
8894 opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8896 * Copy the data based upon the caller version
8898 rx_MarshallProcessRPCStats(callerVersion,
8899 rpc_stat->stats[0].func_total,
8900 rpc_stat->stats, &ptr);
8906 MUTEX_EXIT(&rx_rpc_stats);
8911 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8915 * IN callerVersion - the rpc stat version of the caller
8917 * OUT myVersion - the rpc stat version of this function
8919 * OUT clock_sec - local time seconds
8921 * OUT clock_usec - local time microseconds
8923 * OUT allocSize - the number of bytes allocated to contain stats
8925 * OUT statCount - the number of stats retrieved from the individual
8928 * OUT stats - the actual stats retrieved from the individual peer structures.
8932 * Returns void. If successful, stats will != NULL.
8936 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8937 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8938 size_t * allocSize, afs_uint32 * statCount,
8939 afs_uint32 ** stats)
8949 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8952 * Check to see if stats are enabled
8955 MUTEX_ENTER(&rx_rpc_stats);
8956 if (!rxi_monitor_peerStats) {
8957 MUTEX_EXIT(&rx_rpc_stats);
8961 clock_GetTime(&now);
8962 *clock_sec = now.sec;
8963 *clock_usec = now.usec;
8966 * Allocate the space based upon the caller version
8968 * If the client is at an older version than we are,
8969 * we return the statistic data in the older data format, but
8970 * we still return our version number so the client knows we
8971 * are maintaining more data than it can retrieve.
8974 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8975 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8976 *statCount = rxi_rpc_peer_stat_cnt;
8979 * This can't happen yet, but in the future version changes
8980 * can be handled by adding additional code here
8984 if (space > (size_t) 0) {
8986 ptr = *stats = rxi_Alloc(space);
8989 struct opr_queue *cursor;
8991 for (opr_queue_Scan(&peerStats, cursor)) {
8992 struct rx_interface_stat *rpc_stat
8993 = opr_queue_Entry(cursor, struct rx_interface_stat,
8997 * Copy the data based upon the caller version
8999 rx_MarshallProcessRPCStats(callerVersion,
9000 rpc_stat->stats[0].func_total,
9001 rpc_stat->stats, &ptr);
9007 MUTEX_EXIT(&rx_rpc_stats);
9012 * rx_FreeRPCStats - free memory allocated by
9013 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
9017 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
9018 * rx_RetrievePeerRPCStats
9020 * IN allocSize - the number of bytes in stats.
9028 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
9030 rxi_Free(stats, allocSize);
9034 * rx_queryProcessRPCStats - see if process rpc stat collection is
9035 * currently enabled.
9041 * Returns 0 if stats are not enabled != 0 otherwise
9045 rx_queryProcessRPCStats(void)
9048 MUTEX_ENTER(&rx_rpc_stats);
9049 rc = rxi_monitor_processStats;
9050 MUTEX_EXIT(&rx_rpc_stats);
9055 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
9061 * Returns 0 if stats are not enabled != 0 otherwise
9065 rx_queryPeerRPCStats(void)
9068 MUTEX_ENTER(&rx_rpc_stats);
9069 rc = rxi_monitor_peerStats;
9070 MUTEX_EXIT(&rx_rpc_stats);
9075 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
9085 rx_enableProcessRPCStats(void)
9087 MUTEX_ENTER(&rx_rpc_stats);
9088 rx_enable_stats = 1;
9089 rxi_monitor_processStats = 1;
9090 MUTEX_EXIT(&rx_rpc_stats);
9094 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
9104 rx_enablePeerRPCStats(void)
9106 MUTEX_ENTER(&rx_rpc_stats);
9107 rx_enable_stats = 1;
9108 rxi_monitor_peerStats = 1;
9109 MUTEX_EXIT(&rx_rpc_stats);
9113 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
9123 rx_disableProcessRPCStats(void)
9125 struct opr_queue *cursor, *store;
9128 MUTEX_ENTER(&rx_rpc_stats);
9131 * Turn off process statistics and if peer stats is also off, turn
9135 rxi_monitor_processStats = 0;
9136 if (rxi_monitor_peerStats == 0) {
9137 rx_enable_stats = 0;
9140 for (opr_queue_ScanSafe(&processStats, cursor, store)) {
9141 unsigned int num_funcs = 0;
9142 struct rx_interface_stat *rpc_stat
9143 = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
9145 opr_queue_Remove(&rpc_stat->entry);
9147 num_funcs = rpc_stat->stats[0].func_total;
9149 sizeof(rx_interface_stat_t) +
9150 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
9152 rxi_Free(rpc_stat, space);
9153 rxi_rpc_process_stat_cnt -= num_funcs;
9155 MUTEX_EXIT(&rx_rpc_stats);
9159 * rx_disablePeerRPCStats - stop rpc stat collection for peers
9169 rx_disablePeerRPCStats(void)
9171 struct rx_peer **peer_ptr, **peer_end;
9175 * Turn off peer statistics and if process stats is also off, turn
9179 rxi_monitor_peerStats = 0;
9180 if (rxi_monitor_processStats == 0) {
9181 rx_enable_stats = 0;
9184 for (peer_ptr = &rx_peerHashTable[0], peer_end =
9185 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
9187 struct rx_peer *peer, *next, *prev;
9189 MUTEX_ENTER(&rx_peerHashTable_lock);
9190 MUTEX_ENTER(&rx_rpc_stats);
9191 for (prev = peer = *peer_ptr; peer; peer = next) {
9193 code = MUTEX_TRYENTER(&peer->peer_lock);
9196 struct opr_queue *cursor, *store;
9198 if (prev == *peer_ptr) {
9209 MUTEX_EXIT(&rx_peerHashTable_lock);
9211 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
9212 unsigned int num_funcs = 0;
9213 struct rx_interface_stat *rpc_stat
9214 = opr_queue_Entry(cursor, struct rx_interface_stat,
9217 opr_queue_Remove(&rpc_stat->entry);
9218 opr_queue_Remove(&rpc_stat->entryPeers);
9219 num_funcs = rpc_stat->stats[0].func_total;
9221 sizeof(rx_interface_stat_t) +
9222 rpc_stat->stats[0].func_total *
9223 sizeof(rx_function_entry_v1_t);
9225 rxi_Free(rpc_stat, space);
9226 rxi_rpc_peer_stat_cnt -= num_funcs;
9228 MUTEX_EXIT(&peer->peer_lock);
9230 MUTEX_ENTER(&rx_peerHashTable_lock);
9240 MUTEX_EXIT(&rx_rpc_stats);
9241 MUTEX_EXIT(&rx_peerHashTable_lock);
9246 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
9251 * IN clearFlag - flag indicating which stats to clear
9259 rx_clearProcessRPCStats(afs_uint32 clearFlag)
9261 struct opr_queue *cursor;
9263 MUTEX_ENTER(&rx_rpc_stats);
9265 for (opr_queue_Scan(&processStats, cursor)) {
9266 unsigned int num_funcs = 0, i;
9267 struct rx_interface_stat *rpc_stat
9268 = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
9270 num_funcs = rpc_stat->stats[0].func_total;
9271 for (i = 0; i < num_funcs; i++) {
9272 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9273 rpc_stat->stats[i].invocations = 0;
9275 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9276 rpc_stat->stats[i].bytes_sent = 0;
9278 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9279 rpc_stat->stats[i].bytes_rcvd = 0;
9281 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9282 rpc_stat->stats[i].queue_time_sum.sec = 0;
9283 rpc_stat->stats[i].queue_time_sum.usec = 0;
9285 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9286 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9287 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9289 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9290 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9291 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9293 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9294 rpc_stat->stats[i].queue_time_max.sec = 0;
9295 rpc_stat->stats[i].queue_time_max.usec = 0;
9297 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9298 rpc_stat->stats[i].execution_time_sum.sec = 0;
9299 rpc_stat->stats[i].execution_time_sum.usec = 0;
9301 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9302 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9303 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9305 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9306 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9307 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9309 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9310 rpc_stat->stats[i].execution_time_max.sec = 0;
9311 rpc_stat->stats[i].execution_time_max.usec = 0;
9316 MUTEX_EXIT(&rx_rpc_stats);
9320 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
9325 * IN clearFlag - flag indicating which stats to clear
9333 rx_clearPeerRPCStats(afs_uint32 clearFlag)
9335 struct opr_queue *cursor;
9337 MUTEX_ENTER(&rx_rpc_stats);
9339 for (opr_queue_Scan(&peerStats, cursor)) {
9340 unsigned int num_funcs, i;
9341 struct rx_interface_stat *rpc_stat
9342 = opr_queue_Entry(cursor, struct rx_interface_stat, entryPeers);
9344 num_funcs = rpc_stat->stats[0].func_total;
9345 for (i = 0; i < num_funcs; i++) {
9346 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9347 rpc_stat->stats[i].invocations = 0;
9349 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9350 rpc_stat->stats[i].bytes_sent = 0;
9352 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9353 rpc_stat->stats[i].bytes_rcvd = 0;
9355 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9356 rpc_stat->stats[i].queue_time_sum.sec = 0;
9357 rpc_stat->stats[i].queue_time_sum.usec = 0;
9359 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9360 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9361 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9363 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9364 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9365 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9367 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9368 rpc_stat->stats[i].queue_time_max.sec = 0;
9369 rpc_stat->stats[i].queue_time_max.usec = 0;
9371 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9372 rpc_stat->stats[i].execution_time_sum.sec = 0;
9373 rpc_stat->stats[i].execution_time_sum.usec = 0;
9375 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9376 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9377 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9379 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9380 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9381 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9383 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9384 rpc_stat->stats[i].execution_time_max.sec = 0;
9385 rpc_stat->stats[i].execution_time_max.usec = 0;
9390 MUTEX_EXIT(&rx_rpc_stats);
9394 * rxi_rxstat_userok points to a routine that returns 1 if the caller
9395 * is authorized to enable/disable/clear RX statistics.
9397 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
9400 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
9402 rxi_rxstat_userok = proc;
9406 rx_RxStatUserOk(struct rx_call *call)
9408 if (!rxi_rxstat_userok)
9410 return rxi_rxstat_userok(call);
9415 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
9416 * function in the MSVC runtime DLL (msvcrt.dll).
9418 * Note: the system serializes calls to this function.
9421 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
9422 DWORD reason, /* reason function is being called */
9423 LPVOID reserved) /* reserved for future use */
9426 case DLL_PROCESS_ATTACH:
9427 /* library is being attached to a process */
9431 case DLL_PROCESS_DETACH:
9438 #endif /* AFS_NT40_ENV */
9441 int rx_DumpCalls(FILE *outputFile, char *cookie)
9443 #ifdef RXDEBUG_PACKET
9444 #ifdef KDUMP_RX_LOCK
9445 struct rx_call_rx_lock *c;
9452 #define RXDPRINTF sprintf
9453 #define RXDPRINTOUT output
9455 #define RXDPRINTF fprintf
9456 #define RXDPRINTOUT outputFile
9459 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
9461 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9464 for (c = rx_allCallsp; c; c = c->allNextp) {
9465 u_short rqc, tqc, iovqc;
9467 MUTEX_ENTER(&c->lock);
9468 rqc = opr_queue_Count(&c->rq);
9469 tqc = opr_queue_Count(&c->tq);
9470 iovqc = opr_queue_Count(&c->app.iovq);
9472 RXDPRINTF(RXDPRINTOUT, "%s - call=0x%p, id=%u, state=%u, mode=%u, conn=%p, epoch=%u, cid=%u, callNum=%u, connFlags=0x%x, flags=0x%x, "
9473 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
9474 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
9475 "resendEvent=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
9476 "lastSendTime=%u, lastRecvTime=%u"
9477 #ifdef RX_ENABLE_LOCKS
9480 #ifdef RX_REFCOUNT_CHECK
9481 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
9482 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
9485 cookie, c, c->call_id, (afs_uint32)c->state, (afs_uint32)c->app.mode, c->conn, c->conn?c->conn->epoch:0, c->conn?c->conn->cid:0,
9486 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
9487 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
9488 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
9489 c->resendEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
9490 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime
9491 #ifdef RX_ENABLE_LOCKS
9492 , (afs_uint32)c->refCount
9494 #ifdef RX_REFCOUNT_CHECK
9495 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
9498 MUTEX_EXIT(&c->lock);
9501 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9504 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
9506 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9508 #endif /* RXDEBUG_PACKET */
9513 #ifdef AFS_RXERRQ_ENV
9515 rxi_HandleSocketErrors(osi_socket sock)
9517 size_t cmsgbuf_len = 256;
9520 int errno_save = errno;
9523 cmsgbuf = rxi_Alloc(cmsgbuf_len);
9524 if (cmsgbuf == NULL) {
9528 while (osi_HandleSocketError(sock, cmsgbuf, cmsgbuf_len))
9531 rxi_Free(cmsgbuf, cmsgbuf_len);
9541 NetSend_retry(osi_socket sock, void *addr, struct iovec *dvec, int nvecs,
9542 int length, int istack)
9547 * If an ICMP error comes in for any peer, sendmsg() can return -1 with an
9548 * errno of EHOSTUNREACH, ENETUNREACH, etc. There may be no problem with
9549 * sending this packet (an error is returned just to indicate we need to
9550 * read in pending errors), but the packet wasn't actually sent.
9552 * It's difficult to determine in general whether sendmsg() is returning an
9553 * error due to a received ICMP error, or we're getting an actual error for
9554 * this specific sendmsg() call, since there may be other threads running
9555 * sendmsg/recvmsg/rxi_HandleSocketErrors at the same time. So, just retry
9556 * the sendmsg a few times; make sure not to retry forever, in case we are
9557 * getting an actual error from this sendmsg() call.
9559 * Also note that if we accidentally drop a packet here that we didn't need
9560 * to, it's not the end of the world. Packets get dropped, and we should be
9563 for (safety = 0; safety < RXI_SENDMSG_RETRY; safety++) {
9564 code = osi_NetSend(sock, addr, dvec, nvecs, length, istack);
9568 rxi_HandleSocketErrors(sock);
9576 rxi_NetSend(osi_socket socket, void *addr, struct iovec *dvec,
9577 int nvecs, int length, int istack)
9579 if (rxi_IsRunning()) {
9580 #ifdef AFS_RXERRQ_ENV
9581 return NetSend_retry(socket, addr, dvec, nvecs, length, istack);
9583 return osi_NetSend(socket, addr, dvec, nvecs, length, istack);
9587 return WSAESHUTDOWN;