2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
10 /* RX: Extended Remote Procedure Call */
12 #include <afsconfig.h>
13 #include <afs/param.h>
16 # include "afs/sysincludes.h"
17 # include "afsincludes.h"
22 # ifdef AFS_LINUX20_ENV
23 # include "h/socket.h"
25 # include "netinet/in.h"
27 # include "netinet/ip6.h"
28 # include "inet/common.h"
30 # include "inet/ip_ire.h"
32 # include "afs/afs_args.h"
33 # include "afs/afs_osi.h"
34 # ifdef RX_KERNEL_TRACE
35 # include "rx_kcommon.h"
37 # if defined(AFS_AIX_ENV)
41 # undef RXDEBUG /* turn off debugging */
43 # if defined(AFS_SGI_ENV)
44 # include "sys/debug.h"
47 # include "afs/sysincludes.h"
48 # include "afsincludes.h"
49 # endif /* !UKERNEL */
50 # include "afs/lock.h"
51 # include "rx_kmutex.h"
52 # include "rx_kernel.h"
53 # define AFSOP_STOP_RXCALLBACK 210 /* Stop CALLBACK process */
54 # define AFSOP_STOP_AFS 211 /* Stop AFS process */
55 # define AFSOP_STOP_BKG 212 /* Stop BKG process */
56 extern afs_int32 afs_termState;
58 # include "sys/lockl.h"
59 # include "sys/lock_def.h"
60 # endif /* AFS_AIX41_ENV */
61 # include "afs/rxgen_consts.h"
66 # include <afs/afsutil.h>
67 # include <WINNT\afsreg.h>
75 #include <opr/queue.h>
76 #include <hcrypto/rand.h>
80 #include "rx_atomic.h"
81 #include "rx_globals.h"
83 #include "rx_internal.h"
90 #include "rx_packet.h"
91 #include "rx_server.h"
93 #include <afs/rxgen_consts.h>
96 #ifdef AFS_PTHREAD_ENV
98 int (*registerProgram) (pid_t, char *) = 0;
99 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
102 int (*registerProgram) (PROCESS, char *) = 0;
103 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
107 /* Local static routines */
108 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
109 static void rxi_ComputeRoundTripTime(struct rx_packet *, struct rx_ackPacket *,
110 struct rx_call *, struct rx_peer *,
112 static void rxi_Resend(struct rxevent *event, void *arg0, void *arg1,
114 static void rxi_SendDelayedAck(struct rxevent *event, void *call,
115 void *dummy, int dummy2);
116 static void rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1,
117 void *dummy, int dummy2);
118 static void rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1,
119 void *unused, int unused2);
120 static void rxi_ReapConnections(struct rxevent *unused, void *unused1,
121 void *unused2, int unused3);
122 static struct rx_packet *rxi_SendCallAbort(struct rx_call *call,
123 struct rx_packet *packet,
124 int istack, int force);
125 static void rxi_AckAll(struct rx_call *call);
126 static struct rx_connection
127 *rxi_FindConnection(osi_socket socket, afs_uint32 host, u_short port,
128 u_short serviceId, afs_uint32 cid,
129 afs_uint32 epoch, int type, u_int securityIndex,
130 int *unknownService);
131 static struct rx_packet
132 *rxi_ReceiveDataPacket(struct rx_call *call, struct rx_packet *np,
133 int istack, osi_socket socket,
134 afs_uint32 host, u_short port, int *tnop,
135 struct rx_call **newcallp);
136 static struct rx_packet
137 *rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
139 static struct rx_packet
140 *rxi_ReceiveResponsePacket(struct rx_connection *conn,
141 struct rx_packet *np, int istack);
142 static struct rx_packet
143 *rxi_ReceiveChallengePacket(struct rx_connection *conn,
144 struct rx_packet *np, int istack);
145 static void rxi_AttachServerProc(struct rx_call *call, osi_socket socket,
146 int *tnop, struct rx_call **newcallp);
147 static void rxi_ClearTransmitQueue(struct rx_call *call, int force);
148 static void rxi_ClearReceiveQueue(struct rx_call *call);
149 static void rxi_ResetCall(struct rx_call *call, int newcall);
150 static void rxi_ScheduleKeepAliveEvent(struct rx_call *call);
151 static void rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn);
152 static void rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs);
153 static void rxi_KeepAliveOn(struct rx_call *call);
154 static void rxi_GrowMTUOn(struct rx_call *call);
155 static int rxi_ChallengeOn(struct rx_connection *conn);
156 static int rxi_CheckCall(struct rx_call *call, int haveCTLock);
157 static void rxi_AckAllInTransmitQueue(struct rx_call *call);
158 static void rxi_CancelKeepAliveEvent(struct rx_call *call);
159 static void rxi_CancelDelayedAbortEvent(struct rx_call *call);
160 static void rxi_CancelGrowMTUEvent(struct rx_call *call);
161 static void update_nextCid(void);
164 static void rxi_Finalize_locked(void);
165 #elif defined(UKERNEL)
166 # define rxi_Finalize_locked() do { } while (0)
169 #ifdef RX_ENABLE_LOCKS
171 rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
172 rx_atomic_t rxi_start_in_error;
174 #endif /* RX_ENABLE_LOCKS */
176 /* Constant delay time before sending an acknowledge of the last packet
177 * received. This is to avoid sending an extra acknowledge when the
178 * client is about to make another call, anyway, or the server is
181 * The lastAckDelay may not exceeed 400ms without causing peers to
182 * unecessarily timeout.
184 struct clock rx_lastAckDelay = {0, 400000};
186 /* Constant delay time before sending a soft ack when none was requested.
187 * This is to make sure we send soft acks before the sender times out,
188 * Normally we wait and send a hard ack when the receiver consumes the packet
190 * This value has been 100ms in all shipping versions of OpenAFS. Changing it
191 * will require changes to the peer's RTT calculations.
193 struct clock rx_softAckDelay = {0, 100000};
196 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
197 * currently allocated within rx. This number is used to allocate the
198 * memory required to return the statistics when queried.
199 * Protected by the rx_rpc_stats mutex.
202 static unsigned int rxi_rpc_peer_stat_cnt;
205 * rxi_rpc_process_stat_cnt counts the total number of local process stat
206 * structures currently allocated within rx. The number is used to allocate
207 * the memory required to return the statistics when queried.
208 * Protected by the rx_rpc_stats mutex.
211 static unsigned int rxi_rpc_process_stat_cnt;
213 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
214 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
216 /* Incoming calls wait on this queue when there are no available
217 * server processes */
218 struct opr_queue rx_incomingCallQueue;
220 /* Server processes wait on this queue when there are no appropriate
221 * calls to process */
222 struct opr_queue rx_idleServerQueue;
224 #if !defined(offsetof)
225 #include <stddef.h> /* for definition of offsetof() */
228 #ifdef RX_ENABLE_LOCKS
229 afs_kmutex_t rx_atomic_mutex;
232 /* Forward prototypes */
233 static struct rx_call * rxi_NewCall(struct rx_connection *, int);
236 putConnection (struct rx_connection *conn) {
237 MUTEX_ENTER(&rx_refcnt_mutex);
239 MUTEX_EXIT(&rx_refcnt_mutex);
242 #ifdef AFS_PTHREAD_ENV
245 * Use procedural initialization of mutexes/condition variables
249 extern afs_kmutex_t rx_quota_mutex;
250 extern afs_kmutex_t rx_pthread_mutex;
251 extern afs_kmutex_t rx_packets_mutex;
252 extern afs_kmutex_t rx_refcnt_mutex;
253 extern afs_kmutex_t des_init_mutex;
254 extern afs_kmutex_t des_random_mutex;
256 extern afs_kmutex_t rx_clock_mutex;
257 extern afs_kmutex_t rxi_connCacheMutex;
258 extern afs_kmutex_t event_handler_mutex;
259 extern afs_kmutex_t listener_mutex;
260 extern afs_kmutex_t rx_if_init_mutex;
261 extern afs_kmutex_t rx_if_mutex;
263 extern afs_kcondvar_t rx_event_handler_cond;
264 extern afs_kcondvar_t rx_listener_cond;
267 static afs_kmutex_t epoch_mutex;
268 static afs_kmutex_t rx_init_mutex;
269 static afs_kmutex_t rx_debug_mutex;
270 static afs_kmutex_t rx_rpc_stats;
273 rxi_InitPthread(void)
275 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
276 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
277 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
278 MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
280 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
281 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
282 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
283 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
284 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
285 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
287 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
288 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
289 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
290 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
291 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
294 CV_INIT(&rx_event_handler_cond, "evhand", CV_DEFAULT, 0);
295 CV_INIT(&rx_listener_cond, "rxlisten", CV_DEFAULT, 0);
298 osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
299 osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
301 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
302 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
303 MUTEX_INIT(&rx_mallocedPktQ_lock, "rx_mallocedPktQ_lock", MUTEX_DEFAULT,
306 #ifdef RX_ENABLE_LOCKS
309 #endif /* RX_LOCKS_DB */
310 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
311 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
313 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
315 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
317 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
319 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
321 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
323 #endif /* RX_ENABLE_LOCKS */
326 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
327 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
329 * The rx_stats_mutex mutex protects the following global variables:
330 * rxi_lowConnRefCount
331 * rxi_lowPeerRefCount
340 * The rx_quota_mutex mutex protects the following global variables:
348 * The rx_freePktQ_lock protects the following global variables:
353 * The rx_packets_mutex mutex protects the following global variables:
361 * The rx_pthread_mutex mutex protects the following global variables:
362 * rxi_fcfs_thread_num
365 #define INIT_PTHREAD_LOCKS
369 /* Variables for handling the minProcs implementation. availProcs gives the
370 * number of threads available in the pool at this moment (not counting dudes
371 * executing right now). totalMin gives the total number of procs required
372 * for handling all minProcs requests. minDeficit is a dynamic variable
373 * tracking the # of procs required to satisfy all of the remaining minProcs
375 * For fine grain locking to work, the quota check and the reservation of
376 * a server thread has to come while rxi_availProcs and rxi_minDeficit
377 * are locked. To this end, the code has been modified under #ifdef
378 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
379 * same time. A new function, ReturnToServerPool() returns the allocation.
381 * A call can be on several queue's (but only one at a time). When
382 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
383 * that no one else is touching the queue. To this end, we store the address
384 * of the queue lock in the call structure (under the call lock) when we
385 * put the call on a queue, and we clear the call_queue_lock when the
386 * call is removed from a queue (once the call lock has been obtained).
387 * This allows rxi_ResetCall to safely synchronize with others wishing
388 * to manipulate the queue.
391 #if defined(RX_ENABLE_LOCKS)
392 static afs_kmutex_t rx_rpc_stats;
395 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
396 ** pretty good that the next packet coming in is from the same connection
397 ** as the last packet, since we're send multiple packets in a transmit window.
399 struct rx_connection *rxLastConn = 0;
401 #ifdef RX_ENABLE_LOCKS
402 /* The locking hierarchy for rx fine grain locking is composed of these
405 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
406 * also protects updates to rx_nextCid
407 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
408 * call->lock - locks call data fields.
409 * These are independent of each other:
410 * rx_freeCallQueue_lock
415 * serverQueueEntry->lock
416 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
418 * peer->lock - locks peer data fields.
419 * conn_data_lock - that more than one thread is not updating a conn data
420 * field at the same time.
431 * Do we need a lock to protect the peer field in the conn structure?
432 * conn->peer was previously a constant for all intents and so has no
433 * lock protecting this field. The multihomed client delta introduced
434 * a RX code change : change the peer field in the connection structure
435 * to that remote interface from which the last packet for this
436 * connection was sent out. This may become an issue if further changes
439 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
440 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
442 /* rxdb_fileID is used to identify the lock location, along with line#. */
443 static int rxdb_fileID = RXDB_FILE_RX;
444 #endif /* RX_LOCKS_DB */
445 #else /* RX_ENABLE_LOCKS */
446 #define SET_CALL_QUEUE_LOCK(C, L)
447 #define CLEAR_CALL_QUEUE_LOCK(C)
448 #endif /* RX_ENABLE_LOCKS */
449 struct rx_serverQueueEntry *rx_waitForPacket = 0;
452 * This mutex serializes calls to our initialization and shutdown routines
453 * (rx_InitHost, rx_Finalize and shutdown_rx). Only one thread can be running
454 * these at any time; all other threads must wait for it to finish running, and
455 * then examine the value of rxi_running afterwards.
457 #ifdef AFS_PTHREAD_ENV
458 # define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
459 # define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
461 # define LOCK_RX_INIT
462 # define UNLOCK_RX_INIT
465 /* ------------Exported Interfaces------------- */
467 static rx_atomic_t rxi_running = RX_ATOMIC_INIT(0);
471 return rx_atomic_read(&rxi_running);
474 /* Initialize rx. A port number may be mentioned, in which case this
475 * becomes the default port number for any service installed later.
476 * If 0 is provided for the port number, a random port will be chosen
477 * by the kernel. Whether this will ever overlap anything in
478 * /etc/services is anybody's guess... Returns 0 on success, -1 on
481 rx_InitHost(u_int host, u_int port)
488 char *htable, *ptable;
494 if (rxi_IsRunning()) {
496 return 0; /* already started */
502 if (afs_winsockInit() < 0)
508 * Initialize anything necessary to provide a non-premptive threading
511 rxi_InitializeThreadSupport();
514 /* Allocate and initialize a socket for client and perhaps server
517 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
518 if (rx_socket == OSI_NULLSOCKET) {
521 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
524 #endif /* RX_LOCKS_DB */
525 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
526 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
527 MUTEX_INIT(&rx_atomic_mutex, "rx_atomic_mutex", MUTEX_DEFAULT, 0);
528 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
529 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
530 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
531 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
532 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
533 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
534 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
536 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
538 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
540 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
542 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
543 MUTEX_INIT(&rx_mallocedPktQ_lock, "rx_mallocedPktQ_lock", MUTEX_DEFAULT,
546 #if defined(AFS_HPUX110_ENV)
548 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
549 #endif /* AFS_HPUX110_ENV */
550 #endif /* RX_ENABLE_LOCKS && KERNEL */
553 rx_connDeadTime = 12;
554 rx_tranquil = 0; /* reset flag */
555 rxi_ResetStatistics();
556 htable = osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
557 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
558 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
559 ptable = osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
560 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
561 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
563 /* Malloc up a bunch of packets & buffers */
565 opr_queue_Init(&rx_freePacketQueue);
566 rxi_NeedMorePackets = FALSE;
567 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
568 opr_queue_Init(&rx_mallocedPacketQueue);
570 /* enforce a minimum number of allocated packets */
571 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
572 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
574 /* allocate the initial free packet pool */
575 #ifdef RX_ENABLE_TSFPQ
576 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
577 #else /* RX_ENABLE_TSFPQ */
578 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
579 #endif /* RX_ENABLE_TSFPQ */
586 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
587 tv.tv_sec = clock_now.sec;
588 tv.tv_usec = clock_now.usec;
589 srand((unsigned int)tv.tv_usec);
596 #if defined(KERNEL) && !defined(UKERNEL)
597 /* Really, this should never happen in a real kernel */
600 struct sockaddr_in addr;
602 int addrlen = sizeof(addr);
604 socklen_t addrlen = sizeof(addr);
606 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
607 rxi_Finalize_locked();
608 osi_Free(htable, rx_hashTableSize * sizeof(struct rx_connection *));
611 rx_port = addr.sin_port;
614 rx_stats.minRtt.sec = 9999999;
615 if (RAND_bytes(&rx_epoch, sizeof(rx_epoch)) != 1)
617 rx_epoch = (rx_epoch & ~0x40000000) | 0x80000000;
618 if (RAND_bytes(&rx_nextCid, sizeof(rx_nextCid)) != 1)
620 rx_nextCid &= RX_CIDMASK;
621 MUTEX_ENTER(&rx_quota_mutex);
622 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
623 MUTEX_EXIT(&rx_quota_mutex);
624 /* *Slightly* random start time for the cid. This is just to help
625 * out with the hashing function at the peer */
626 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
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_incomingCallQueue);
638 opr_queue_Init(&rx_freeCallQueue);
640 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
641 /* Initialize our list of usable IP addresses. */
645 /* Start listener process (exact function is dependent on the
646 * implementation environment--kernel or user space) */
651 rx_atomic_set(&rxi_running, 1);
668 return rx_InitHost(htonl(INADDR_ANY), port);
674 * The rxi_rto functions implement a TCP (RFC2988) style algorithm for
675 * maintaing the round trip timer.
680 * Start a new RTT timer for a given call and packet.
682 * There must be no resendEvent already listed for this call, otherwise this
683 * will leak events - intended for internal use within the RTO code only
686 * the RX call to start the timer for
687 * @param[in] lastPacket
688 * a flag indicating whether the last packet has been sent or not
690 * @pre call must be locked before calling this function
694 rxi_rto_startTimer(struct rx_call *call, int lastPacket, int istack)
696 struct clock now, retryTime;
698 MUTEX_ASSERT(&call->lock);
702 clock_Add(&retryTime, &call->rto);
704 /* If we're sending the last packet, and we're the client, then the server
705 * may wait for an additional 400ms before returning the ACK, wait for it
706 * rather than hitting a timeout */
707 if (lastPacket && call->conn->type == RX_CLIENT_CONNECTION)
708 clock_Addmsec(&retryTime, 400);
710 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
711 call->resendEvent = rxevent_Post(&retryTime, &now, rxi_Resend,
716 * Cancel an RTT timer for a given call.
720 * the RX call to cancel the timer for
722 * @pre call must be locked before calling this function
727 rxi_rto_cancel(struct rx_call *call)
729 MUTEX_ASSERT(&call->lock);
730 if (rxevent_Cancel(&call->resendEvent))
731 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
735 * Tell the RTO timer that we have sent a packet.
737 * If the timer isn't already running, then start it. If the timer is running,
741 * the RX call that the packet has been sent on
742 * @param[in] lastPacket
743 * A flag which is true if this is the last packet for the call
745 * @pre The call must be locked before calling this function
750 rxi_rto_packet_sent(struct rx_call *call, int lastPacket, int istack)
752 if (call->resendEvent)
755 rxi_rto_startTimer(call, lastPacket, istack);
759 * Tell the RTO timer that we have received an new ACK message
761 * This function should be called whenever a call receives an ACK that
762 * acknowledges new packets. Whatever happens, we stop the current timer.
763 * If there are unacked packets in the queue which have been sent, then
764 * we restart the timer from now. Otherwise, we leave it stopped.
767 * the RX call that the ACK has been received on
771 rxi_rto_packet_acked(struct rx_call *call, int istack)
773 struct opr_queue *cursor;
775 rxi_rto_cancel(call);
777 if (opr_queue_IsEmpty(&call->tq))
780 for (opr_queue_Scan(&call->tq, cursor)) {
781 struct rx_packet *p = opr_queue_Entry(cursor, struct rx_packet, entry);
782 if (p->header.seq > call->tfirst + call->twind)
785 if (!(p->flags & RX_PKTFLAG_ACKED) && p->flags & RX_PKTFLAG_SENT) {
786 rxi_rto_startTimer(call, p->header.flags & RX_LAST_PACKET, istack);
794 * Set an initial round trip timeout for a peer connection
796 * @param[in] secs The timeout to set in seconds
800 rx_rto_setPeerTimeoutSecs(struct rx_peer *peer, int secs) {
801 peer->rtt = secs * 8000;
805 * Set a delayed ack event on the specified call for the given time
807 * @param[in] call - the call on which to set the event
808 * @param[in] offset - the delay from now after which the event fires
811 rxi_PostDelayedAckEvent(struct rx_call *call, struct clock *offset)
813 struct clock now, when;
815 MUTEX_ASSERT(&call->lock);
818 clock_Add(&when, offset);
820 if (clock_Gt(&call->delayedAckTime, &when) &&
821 rxevent_Cancel(&call->delayedAckEvent)) {
822 /* We successfully cancelled an event too far in the future to install
823 * our new one; we can reuse the reference on the call. */
824 call->delayedAckEvent = rxevent_Post(&when, &now, rxi_SendDelayedAck,
827 call->delayedAckTime = when;
828 } else if (call->delayedAckEvent == NULL) {
829 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
830 call->delayedAckEvent = rxevent_Post(&when, &now,
833 call->delayedAckTime = when;
838 rxi_CancelDelayedAckEvent(struct rx_call *call)
840 MUTEX_ASSERT(&call->lock);
841 /* Only drop the ref if we cancelled it before it could run. */
842 if (rxevent_Cancel(&call->delayedAckEvent))
843 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
846 /* called with unincremented nRequestsRunning to see if it is OK to start
847 * a new thread in this service. Could be "no" for two reasons: over the
848 * max quota, or would prevent others from reaching their min quota.
850 #ifdef RX_ENABLE_LOCKS
851 /* This verion of QuotaOK reserves quota if it's ok while the
852 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
855 QuotaOK(struct rx_service *aservice)
857 /* check if over max quota */
858 if (aservice->nRequestsRunning >= aservice->maxProcs) {
862 /* under min quota, we're OK */
863 /* otherwise, can use only if there are enough to allow everyone
864 * to go to their min quota after this guy starts.
867 MUTEX_ENTER(&rx_quota_mutex);
868 if ((aservice->nRequestsRunning < aservice->minProcs)
869 || (rxi_availProcs > rxi_minDeficit)) {
870 aservice->nRequestsRunning++;
871 /* just started call in minProcs pool, need fewer to maintain
873 if (aservice->nRequestsRunning <= aservice->minProcs)
876 MUTEX_EXIT(&rx_quota_mutex);
879 MUTEX_EXIT(&rx_quota_mutex);
885 ReturnToServerPool(struct rx_service *aservice)
887 aservice->nRequestsRunning--;
888 MUTEX_ENTER(&rx_quota_mutex);
889 if (aservice->nRequestsRunning < aservice->minProcs)
892 MUTEX_EXIT(&rx_quota_mutex);
895 #else /* RX_ENABLE_LOCKS */
897 QuotaOK(struct rx_service *aservice)
900 /* under min quota, we're OK */
901 if (aservice->nRequestsRunning < aservice->minProcs)
904 /* check if over max quota */
905 if (aservice->nRequestsRunning >= aservice->maxProcs)
908 /* otherwise, can use only if there are enough to allow everyone
909 * to go to their min quota after this guy starts.
911 MUTEX_ENTER(&rx_quota_mutex);
912 if (rxi_availProcs > rxi_minDeficit)
914 MUTEX_EXIT(&rx_quota_mutex);
917 #endif /* RX_ENABLE_LOCKS */
920 /* Called by rx_StartServer to start up lwp's to service calls.
921 NExistingProcs gives the number of procs already existing, and which
922 therefore needn't be created. */
924 rxi_StartServerProcs(int nExistingProcs)
926 struct rx_service *service;
931 /* For each service, reserve N processes, where N is the "minimum"
932 * number of processes that MUST be able to execute a request in parallel,
933 * at any time, for that process. Also compute the maximum difference
934 * between any service's maximum number of processes that can run
935 * (i.e. the maximum number that ever will be run, and a guarantee
936 * that this number will run if other services aren't running), and its
937 * minimum number. The result is the extra number of processes that
938 * we need in order to provide the latter guarantee */
939 for (i = 0; i < RX_MAX_SERVICES; i++) {
941 service = rx_services[i];
942 if (service == (struct rx_service *)0)
944 nProcs += service->minProcs;
945 diff = service->maxProcs - service->minProcs;
949 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
950 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
951 for (i = 0; i < nProcs; i++) {
952 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
958 /* This routine is only required on Windows */
960 rx_StartClientThread(void)
962 #ifdef AFS_PTHREAD_ENV
964 pid = pthread_self();
965 #endif /* AFS_PTHREAD_ENV */
967 #endif /* AFS_NT40_ENV */
969 /* This routine must be called if any services are exported. If the
970 * donateMe flag is set, the calling process is donated to the server
973 rx_StartServer(int donateMe)
975 struct rx_service *service;
981 /* Start server processes, if necessary (exact function is dependent
982 * on the implementation environment--kernel or user space). DonateMe
983 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
984 * case, one less new proc will be created rx_StartServerProcs.
986 rxi_StartServerProcs(donateMe);
988 /* count up the # of threads in minProcs, and add set the min deficit to
989 * be that value, too.
991 for (i = 0; i < RX_MAX_SERVICES; i++) {
992 service = rx_services[i];
993 if (service == (struct rx_service *)0)
995 MUTEX_ENTER(&rx_quota_mutex);
996 rxi_totalMin += service->minProcs;
997 /* below works even if a thread is running, since minDeficit would
998 * still have been decremented and later re-incremented.
1000 rxi_minDeficit += service->minProcs;
1001 MUTEX_EXIT(&rx_quota_mutex);
1004 /* Turn on reaping of idle server connections */
1005 rxi_ReapConnections(NULL, NULL, NULL, 0);
1010 #ifndef AFS_NT40_ENV
1014 #ifdef AFS_PTHREAD_ENV
1016 pid = afs_pointer_to_int(pthread_self());
1017 #else /* AFS_PTHREAD_ENV */
1019 LWP_CurrentProcess(&pid);
1020 #endif /* AFS_PTHREAD_ENV */
1022 sprintf(name, "srv_%d", ++nProcs);
1023 if (registerProgram)
1024 (*registerProgram) (pid, name);
1026 #endif /* AFS_NT40_ENV */
1027 rx_ServerProc(NULL); /* Never returns */
1029 #ifdef RX_ENABLE_TSFPQ
1030 /* no use leaving packets around in this thread's local queue if
1031 * it isn't getting donated to the server thread pool.
1033 rxi_FlushLocalPacketsTSFPQ();
1034 #endif /* RX_ENABLE_TSFPQ */
1038 /* Create a new client connection to the specified service, using the
1039 * specified security object to implement the security model for this
1041 struct rx_connection *
1042 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
1043 struct rx_securityClass *securityObject,
1044 int serviceSecurityIndex)
1047 struct rx_connection *conn;
1053 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
1054 "serviceSecurityIndex %d)\n",
1055 ntohl(shost), ntohs(sport), sservice, securityObject,
1056 serviceSecurityIndex));
1058 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
1059 * the case of kmem_alloc? */
1060 conn = rxi_AllocConnection();
1061 #ifdef RX_ENABLE_LOCKS
1062 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
1063 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
1064 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
1067 MUTEX_ENTER(&rx_connHashTable_lock);
1068 conn->type = RX_CLIENT_CONNECTION;
1069 conn->epoch = rx_epoch;
1070 conn->cid = rx_nextCid;
1072 conn->peer = rxi_FindPeer(shost, sport, 1);
1073 conn->serviceId = sservice;
1074 conn->securityObject = securityObject;
1075 conn->securityData = (void *) 0;
1076 conn->securityIndex = serviceSecurityIndex;
1077 rx_SetConnDeadTime(conn, rx_connDeadTime);
1078 rx_SetConnSecondsUntilNatPing(conn, 0);
1079 conn->ackRate = RX_FAST_ACK_RATE;
1080 conn->nSpecific = 0;
1081 conn->specific = NULL;
1082 conn->challengeEvent = NULL;
1083 conn->delayedAbortEvent = NULL;
1084 conn->abortCount = 0;
1086 for (i = 0; i < RX_MAXCALLS; i++) {
1087 conn->twind[i] = rx_initSendWindow;
1088 conn->rwind[i] = rx_initReceiveWindow;
1089 conn->lastBusy[i] = 0;
1092 code = RXS_NewConnection(securityObject, conn);
1094 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
1096 conn->refCount++; /* no lock required since only this thread knows... */
1097 conn->next = rx_connHashTable[hashindex];
1098 rx_connHashTable[hashindex] = conn;
1099 if (rx_stats_active)
1100 rx_atomic_inc(&rx_stats.nClientConns);
1101 MUTEX_EXIT(&rx_connHashTable_lock);
1104 rxi_ConnectionError(conn, code);
1110 * Ensure a connection's timeout values are valid.
1112 * @param[in] conn The connection to check
1114 * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
1115 * unless idleDeadTime and/or hardDeadTime are not set
1119 rxi_CheckConnTimeouts(struct rx_connection *conn)
1121 /* a connection's timeouts must have the relationship
1122 * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
1123 * total loss of network to a peer may cause an idle timeout instead of a
1124 * dead timeout, simply because the idle timeout gets hit first. Also set
1125 * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
1126 /* this logic is slightly complicated by the fact that
1127 * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
1129 conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
1130 if (conn->idleDeadTime) {
1131 conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
1133 if (conn->hardDeadTime) {
1134 if (conn->idleDeadTime) {
1135 conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
1137 conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
1143 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
1145 /* The idea is to set the dead time to a value that allows several
1146 * keepalives to be dropped without timing out the connection. */
1147 conn->secondsUntilDead = seconds;
1148 rxi_CheckConnTimeouts(conn);
1149 conn->secondsUntilPing = conn->secondsUntilDead / 6;
1153 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
1155 conn->hardDeadTime = seconds;
1156 rxi_CheckConnTimeouts(conn);
1160 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
1162 conn->idleDeadTime = seconds;
1163 rxi_CheckConnTimeouts(conn);
1166 int rxi_lowPeerRefCount = 0;
1167 int rxi_lowConnRefCount = 0;
1170 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
1171 * NOTE: must not be called with rx_connHashTable_lock held.
1174 rxi_CleanupConnection(struct rx_connection *conn)
1176 /* Notify the service exporter, if requested, that this connection
1177 * is being destroyed */
1178 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
1179 (*conn->service->destroyConnProc) (conn);
1181 /* Notify the security module that this connection is being destroyed */
1182 RXS_DestroyConnection(conn->securityObject, conn);
1184 /* If this is the last connection using the rx_peer struct, set its
1185 * idle time to now. rxi_ReapConnections will reap it if it's still
1186 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
1188 MUTEX_ENTER(&rx_peerHashTable_lock);
1189 if (conn->peer->refCount < 2) {
1190 conn->peer->idleWhen = clock_Sec();
1191 if (conn->peer->refCount < 1) {
1192 conn->peer->refCount = 1;
1193 if (rx_stats_active) {
1194 MUTEX_ENTER(&rx_stats_mutex);
1195 rxi_lowPeerRefCount++;
1196 MUTEX_EXIT(&rx_stats_mutex);
1200 conn->peer->refCount--;
1201 MUTEX_EXIT(&rx_peerHashTable_lock);
1203 if (rx_stats_active)
1205 if (conn->type == RX_SERVER_CONNECTION)
1206 rx_atomic_dec(&rx_stats.nServerConns);
1208 rx_atomic_dec(&rx_stats.nClientConns);
1211 if (conn->specific) {
1213 for (i = 0; i < conn->nSpecific; i++) {
1214 if (conn->specific[i] && rxi_keyCreate_destructor[i])
1215 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
1216 conn->specific[i] = NULL;
1218 free(conn->specific);
1220 conn->specific = NULL;
1221 conn->nSpecific = 0;
1222 #endif /* !KERNEL */
1224 MUTEX_DESTROY(&conn->conn_call_lock);
1225 MUTEX_DESTROY(&conn->conn_data_lock);
1226 CV_DESTROY(&conn->conn_call_cv);
1228 rxi_FreeConnection(conn);
1231 /* Destroy the specified connection */
1233 rxi_DestroyConnection(struct rx_connection *conn)
1235 MUTEX_ENTER(&rx_connHashTable_lock);
1236 rxi_DestroyConnectionNoLock(conn);
1237 /* conn should be at the head of the cleanup list */
1238 if (conn == rx_connCleanup_list) {
1239 rx_connCleanup_list = rx_connCleanup_list->next;
1240 MUTEX_EXIT(&rx_connHashTable_lock);
1241 rxi_CleanupConnection(conn);
1243 #ifdef RX_ENABLE_LOCKS
1245 MUTEX_EXIT(&rx_connHashTable_lock);
1247 #endif /* RX_ENABLE_LOCKS */
1251 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1253 struct rx_connection **conn_ptr;
1261 MUTEX_ENTER(&conn->conn_data_lock);
1262 MUTEX_ENTER(&rx_refcnt_mutex);
1263 if (conn->refCount > 0)
1266 #ifdef RX_REFCOUNT_CHECK
1267 osi_Assert(conn->refCount == 0);
1269 if (rx_stats_active) {
1270 MUTEX_ENTER(&rx_stats_mutex);
1271 rxi_lowConnRefCount++;
1272 MUTEX_EXIT(&rx_stats_mutex);
1276 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1277 /* Busy; wait till the last guy before proceeding */
1278 MUTEX_EXIT(&rx_refcnt_mutex);
1279 MUTEX_EXIT(&conn->conn_data_lock);
1284 /* If the client previously called rx_NewCall, but it is still
1285 * waiting, treat this as a running call, and wait to destroy the
1286 * connection later when the call completes. */
1287 if ((conn->type == RX_CLIENT_CONNECTION)
1288 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1289 conn->flags |= RX_CONN_DESTROY_ME;
1290 MUTEX_EXIT(&rx_refcnt_mutex);
1291 MUTEX_EXIT(&conn->conn_data_lock);
1295 MUTEX_EXIT(&rx_refcnt_mutex);
1296 MUTEX_EXIT(&conn->conn_data_lock);
1298 /* Check for extant references to this connection */
1299 MUTEX_ENTER(&conn->conn_call_lock);
1300 for (i = 0; i < RX_MAXCALLS; i++) {
1301 struct rx_call *call = conn->call[i];
1304 if (conn->type == RX_CLIENT_CONNECTION) {
1305 MUTEX_ENTER(&call->lock);
1306 if (call->delayedAckEvent) {
1307 /* Push the final acknowledgment out now--there
1308 * won't be a subsequent call to acknowledge the
1309 * last reply packets */
1310 rxi_CancelDelayedAckEvent(call);
1311 if (call->state == RX_STATE_PRECALL
1312 || call->state == RX_STATE_ACTIVE) {
1313 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1318 MUTEX_EXIT(&call->lock);
1322 MUTEX_EXIT(&conn->conn_call_lock);
1324 #ifdef RX_ENABLE_LOCKS
1326 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1327 MUTEX_EXIT(&conn->conn_data_lock);
1329 /* Someone is accessing a packet right now. */
1333 #endif /* RX_ENABLE_LOCKS */
1336 /* Don't destroy the connection if there are any call
1337 * structures still in use */
1338 MUTEX_ENTER(&conn->conn_data_lock);
1339 conn->flags |= RX_CONN_DESTROY_ME;
1340 MUTEX_EXIT(&conn->conn_data_lock);
1345 /* Remove from connection hash table before proceeding */
1347 &rx_connHashTable[CONN_HASH
1348 (peer->host, peer->port, conn->cid, conn->epoch,
1350 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1351 if (*conn_ptr == conn) {
1352 *conn_ptr = conn->next;
1356 /* if the conn that we are destroying was the last connection, then we
1357 * clear rxLastConn as well */
1358 if (rxLastConn == conn)
1361 /* Make sure the connection is completely reset before deleting it. */
1363 * Pending events hold a refcount, so we can't get here if they are
1365 osi_Assert(conn->challengeEvent == NULL);
1366 osi_Assert(conn->delayedAbortEvent == NULL);
1367 osi_Assert(conn->natKeepAliveEvent == NULL);
1368 osi_Assert(conn->checkReachEvent == NULL);
1370 /* Add the connection to the list of destroyed connections that
1371 * need to be cleaned up. This is necessary to avoid deadlocks
1372 * in the routines we call to inform others that this connection is
1373 * being destroyed. */
1374 conn->next = rx_connCleanup_list;
1375 rx_connCleanup_list = conn;
1378 /* Externally available version */
1380 rx_DestroyConnection(struct rx_connection *conn)
1385 rxi_DestroyConnection(conn);
1390 rx_GetConnection(struct rx_connection *conn)
1395 MUTEX_ENTER(&rx_refcnt_mutex);
1397 MUTEX_EXIT(&rx_refcnt_mutex);
1401 #ifdef RX_ENABLE_LOCKS
1402 /* Wait for the transmit queue to no longer be busy.
1403 * requires the call->lock to be held */
1405 rxi_WaitforTQBusy(struct rx_call *call) {
1406 while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1407 call->flags |= RX_CALL_TQ_WAIT;
1409 MUTEX_ASSERT(&call->lock);
1410 CV_WAIT(&call->cv_tq, &call->lock);
1412 if (call->tqWaiters == 0) {
1413 call->flags &= ~RX_CALL_TQ_WAIT;
1420 rxi_WakeUpTransmitQueue(struct rx_call *call)
1422 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1423 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
1424 call, call->tqWaiters, call->flags));
1425 #ifdef RX_ENABLE_LOCKS
1426 MUTEX_ASSERT(&call->lock);
1427 CV_BROADCAST(&call->cv_tq);
1428 #else /* RX_ENABLE_LOCKS */
1429 osi_rxWakeup(&call->tq);
1430 #endif /* RX_ENABLE_LOCKS */
1434 /* Start a new rx remote procedure call, on the specified connection.
1435 * If wait is set to 1, wait for a free call channel; otherwise return
1436 * 0. Maxtime gives the maximum number of seconds this call may take,
1437 * after rx_NewCall returns. After this time interval, a call to any
1438 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1439 * For fine grain locking, we hold the conn_call_lock in order to
1440 * to ensure that we don't get signalle after we found a call in an active
1441 * state and before we go to sleep.
1444 rx_NewCall(struct rx_connection *conn)
1446 int i, wait, ignoreBusy = 1;
1447 struct rx_call *call;
1448 struct clock queueTime;
1449 afs_uint32 leastBusy = 0;
1453 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1456 clock_GetTime(&queueTime);
1458 * Check if there are others waiting for a new call.
1459 * If so, let them go first to avoid starving them.
1460 * This is a fairly simple scheme, and might not be
1461 * a complete solution for large numbers of waiters.
1463 * makeCallWaiters keeps track of the number of
1464 * threads waiting to make calls and the
1465 * RX_CONN_MAKECALL_WAITING flag bit is used to
1466 * indicate that there are indeed calls waiting.
1467 * The flag is set when the waiter is incremented.
1468 * It is only cleared when makeCallWaiters is 0.
1469 * This prevents us from accidently destroying the
1470 * connection while it is potentially about to be used.
1472 MUTEX_ENTER(&conn->conn_call_lock);
1473 MUTEX_ENTER(&conn->conn_data_lock);
1474 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1475 conn->flags |= RX_CONN_MAKECALL_WAITING;
1476 conn->makeCallWaiters++;
1477 MUTEX_EXIT(&conn->conn_data_lock);
1479 #ifdef RX_ENABLE_LOCKS
1480 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1484 MUTEX_ENTER(&conn->conn_data_lock);
1485 conn->makeCallWaiters--;
1486 if (conn->makeCallWaiters == 0)
1487 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1490 /* We are now the active thread in rx_NewCall */
1491 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1492 MUTEX_EXIT(&conn->conn_data_lock);
1497 for (i = 0; i < RX_MAXCALLS; i++) {
1498 call = conn->call[i];
1500 if (!ignoreBusy && conn->lastBusy[i] != leastBusy) {
1501 /* we're not ignoring busy call slots; only look at the
1502 * call slot that is the "least" busy */
1506 if (call->state == RX_STATE_DALLY) {
1507 MUTEX_ENTER(&call->lock);
1508 if (call->state == RX_STATE_DALLY) {
1509 if (ignoreBusy && conn->lastBusy[i]) {
1510 /* if we're ignoring busy call slots, skip any ones that
1511 * have lastBusy set */
1512 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1513 leastBusy = conn->lastBusy[i];
1515 MUTEX_EXIT(&call->lock);
1520 * We are setting the state to RX_STATE_RESET to
1521 * ensure that no one else will attempt to use this
1522 * call once we drop the conn->conn_call_lock and
1523 * call->lock. We must drop the conn->conn_call_lock
1524 * before calling rxi_ResetCall because the process
1525 * of clearing the transmit queue can block for an
1526 * extended period of time. If we block while holding
1527 * the conn->conn_call_lock, then all rx_EndCall
1528 * processing will block as well. This has a detrimental
1529 * effect on overall system performance.
1531 call->state = RX_STATE_RESET;
1532 (*call->callNumber)++;
1533 MUTEX_EXIT(&conn->conn_call_lock);
1534 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1535 rxi_ResetCall(call, 0);
1536 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1540 * If we failed to be able to safely obtain the
1541 * conn->conn_call_lock we will have to drop the
1542 * call->lock to avoid a deadlock. When the call->lock
1543 * is released the state of the call can change. If it
1544 * is no longer RX_STATE_RESET then some other thread is
1547 MUTEX_EXIT(&call->lock);
1548 MUTEX_ENTER(&conn->conn_call_lock);
1549 MUTEX_ENTER(&call->lock);
1551 if (call->state == RX_STATE_RESET)
1555 * If we get here it means that after dropping
1556 * the conn->conn_call_lock and call->lock that
1557 * the call is no longer ours. If we can't find
1558 * a free call in the remaining slots we should
1559 * not go immediately to RX_CONN_MAKECALL_WAITING
1560 * because by dropping the conn->conn_call_lock
1561 * we have given up synchronization with rx_EndCall.
1562 * Instead, cycle through one more time to see if
1563 * we can find a call that can call our own.
1565 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1568 MUTEX_EXIT(&call->lock);
1571 if (ignoreBusy && conn->lastBusy[i]) {
1572 /* if we're ignoring busy call slots, skip any ones that
1573 * have lastBusy set */
1574 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1575 leastBusy = conn->lastBusy[i];
1580 /* rxi_NewCall returns with mutex locked */
1581 call = rxi_NewCall(conn, i);
1582 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1586 if (i < RX_MAXCALLS) {
1587 conn->lastBusy[i] = 0;
1592 if (leastBusy && ignoreBusy) {
1593 /* we didn't find a useable call slot, but we did see at least one
1594 * 'busy' slot; look again and only use a slot with the 'least
1600 MUTEX_ENTER(&conn->conn_data_lock);
1601 conn->flags |= RX_CONN_MAKECALL_WAITING;
1602 conn->makeCallWaiters++;
1603 MUTEX_EXIT(&conn->conn_data_lock);
1605 #ifdef RX_ENABLE_LOCKS
1606 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1610 MUTEX_ENTER(&conn->conn_data_lock);
1611 conn->makeCallWaiters--;
1612 if (conn->makeCallWaiters == 0)
1613 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1614 MUTEX_EXIT(&conn->conn_data_lock);
1616 /* Client is initially in send mode */
1617 call->state = RX_STATE_ACTIVE;
1618 call->error = conn->error;
1620 call->app.mode = RX_MODE_ERROR;
1622 call->app.mode = RX_MODE_SENDING;
1624 #ifdef AFS_RXERRQ_ENV
1625 /* remember how many network errors the peer has when we started, so if
1626 * more errors are encountered after the call starts, we know the other endpoint won't be
1627 * responding to us */
1628 call->neterr_gen = rx_atomic_read(&conn->peer->neterrs);
1631 /* remember start time for call in case we have hard dead time limit */
1632 call->queueTime = queueTime;
1633 clock_GetTime(&call->startTime);
1634 call->app.bytesSent = 0;
1635 call->app.bytesRcvd = 0;
1637 /* Turn on busy protocol. */
1638 rxi_KeepAliveOn(call);
1640 /* Attempt MTU discovery */
1641 rxi_GrowMTUOn(call);
1644 * We are no longer the active thread in rx_NewCall
1646 MUTEX_ENTER(&conn->conn_data_lock);
1647 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1648 MUTEX_EXIT(&conn->conn_data_lock);
1651 * Wake up anyone else who might be giving us a chance to
1652 * run (see code above that avoids resource starvation).
1654 #ifdef RX_ENABLE_LOCKS
1655 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1656 osi_Panic("rx_NewCall call about to be used without an empty tq");
1659 CV_BROADCAST(&conn->conn_call_cv);
1663 MUTEX_EXIT(&conn->conn_call_lock);
1664 MUTEX_EXIT(&call->lock);
1667 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1672 rxi_HasActiveCalls(struct rx_connection *aconn)
1675 struct rx_call *tcall;
1679 for (i = 0; i < RX_MAXCALLS; i++) {
1680 if ((tcall = aconn->call[i])) {
1681 if ((tcall->state == RX_STATE_ACTIVE)
1682 || (tcall->state == RX_STATE_PRECALL)) {
1693 rxi_GetCallNumberVector(struct rx_connection *aconn,
1694 afs_int32 * aint32s)
1697 struct rx_call *tcall;
1701 MUTEX_ENTER(&aconn->conn_call_lock);
1702 for (i = 0; i < RX_MAXCALLS; i++) {
1703 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1704 aint32s[i] = aconn->callNumber[i] + 1;
1706 aint32s[i] = aconn->callNumber[i];
1708 MUTEX_EXIT(&aconn->conn_call_lock);
1714 rxi_SetCallNumberVector(struct rx_connection *aconn,
1715 afs_int32 * aint32s)
1718 struct rx_call *tcall;
1722 MUTEX_ENTER(&aconn->conn_call_lock);
1723 for (i = 0; i < RX_MAXCALLS; i++) {
1724 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1725 aconn->callNumber[i] = aint32s[i] - 1;
1727 aconn->callNumber[i] = aint32s[i];
1729 MUTEX_EXIT(&aconn->conn_call_lock);
1734 /* Advertise a new service. A service is named locally by a UDP port
1735 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1738 char *serviceName; Name for identification purposes (e.g. the
1739 service name might be used for probing for
1742 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1743 char *serviceName, struct rx_securityClass **securityObjects,
1744 int nSecurityObjects,
1745 afs_int32(*serviceProc) (struct rx_call * acall))
1747 osi_socket socket = OSI_NULLSOCKET;
1748 struct rx_service *tservice;
1754 if (serviceId == 0) {
1756 "rx_NewService: service id for service %s is not non-zero.\n",
1763 "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",
1771 tservice = rxi_AllocService();
1774 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1776 for (i = 0; i < RX_MAX_SERVICES; i++) {
1777 struct rx_service *service = rx_services[i];
1779 if (port == service->servicePort && host == service->serviceHost) {
1780 if (service->serviceId == serviceId) {
1781 /* The identical service has already been
1782 * installed; if the caller was intending to
1783 * change the security classes used by this
1784 * service, he/she loses. */
1786 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1787 serviceName, serviceId, service->serviceName);
1789 rxi_FreeService(tservice);
1792 /* Different service, same port: re-use the socket
1793 * which is bound to the same port */
1794 socket = service->socket;
1797 if (socket == OSI_NULLSOCKET) {
1798 /* If we don't already have a socket (from another
1799 * service on same port) get a new one */
1800 socket = rxi_GetHostUDPSocket(host, port);
1801 if (socket == OSI_NULLSOCKET) {
1803 rxi_FreeService(tservice);
1808 service->socket = socket;
1809 service->serviceHost = host;
1810 service->servicePort = port;
1811 service->serviceId = serviceId;
1812 service->serviceName = serviceName;
1813 service->nSecurityObjects = nSecurityObjects;
1814 service->securityObjects = securityObjects;
1815 service->minProcs = 0;
1816 service->maxProcs = 1;
1817 service->idleDeadTime = 60;
1818 service->connDeadTime = rx_connDeadTime;
1819 service->executeRequestProc = serviceProc;
1820 service->checkReach = 0;
1821 service->nSpecific = 0;
1822 service->specific = NULL;
1823 rx_services[i] = service; /* not visible until now */
1829 rxi_FreeService(tservice);
1830 (osi_Msg "rx_NewService: cannot support > %d services\n",
1835 /* Set configuration options for all of a service's security objects */
1838 rx_SetSecurityConfiguration(struct rx_service *service,
1839 rx_securityConfigVariables type,
1844 for (i = 0; i<service->nSecurityObjects; i++) {
1845 if (service->securityObjects[i]) {
1846 code = RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1857 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1858 struct rx_securityClass **securityObjects, int nSecurityObjects,
1859 afs_int32(*serviceProc) (struct rx_call * acall))
1861 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1864 /* Generic request processing loop. This routine should be called
1865 * by the implementation dependent rx_ServerProc. If socketp is
1866 * non-null, it will be set to the file descriptor that this thread
1867 * is now listening on. If socketp is null, this routine will never
1870 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1872 struct rx_call *call;
1874 struct rx_service *tservice = NULL;
1881 call = rx_GetCall(threadID, tservice, socketp);
1882 if (socketp && *socketp != OSI_NULLSOCKET) {
1883 /* We are now a listener thread */
1889 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1890 #ifdef RX_ENABLE_LOCKS
1892 #endif /* RX_ENABLE_LOCKS */
1893 afs_termState = AFSOP_STOP_AFS;
1894 afs_osi_Wakeup(&afs_termState);
1895 #ifdef RX_ENABLE_LOCKS
1897 #endif /* RX_ENABLE_LOCKS */
1902 /* if server is restarting( typically smooth shutdown) then do not
1903 * allow any new calls.
1906 if (rx_tranquil && (call != NULL)) {
1910 MUTEX_ENTER(&call->lock);
1912 rxi_CallError(call, RX_RESTARTING);
1913 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1915 MUTEX_EXIT(&call->lock);
1920 tservice = call->conn->service;
1922 if (tservice->beforeProc)
1923 (*tservice->beforeProc) (call);
1925 code = tservice->executeRequestProc(call);
1927 if (tservice->afterProc)
1928 (*tservice->afterProc) (call, code);
1930 rx_EndCall(call, code);
1932 if (tservice->postProc)
1933 (*tservice->postProc) (code);
1935 if (rx_stats_active) {
1936 MUTEX_ENTER(&rx_stats_mutex);
1938 MUTEX_EXIT(&rx_stats_mutex);
1945 rx_WakeupServerProcs(void)
1947 struct rx_serverQueueEntry *np, *tqp;
1948 struct opr_queue *cursor;
1952 MUTEX_ENTER(&rx_serverPool_lock);
1954 #ifdef RX_ENABLE_LOCKS
1955 if (rx_waitForPacket)
1956 CV_BROADCAST(&rx_waitForPacket->cv);
1957 #else /* RX_ENABLE_LOCKS */
1958 if (rx_waitForPacket)
1959 osi_rxWakeup(rx_waitForPacket);
1960 #endif /* RX_ENABLE_LOCKS */
1961 MUTEX_ENTER(&freeSQEList_lock);
1962 for (np = rx_FreeSQEList; np; np = tqp) {
1963 tqp = *(struct rx_serverQueueEntry **)np;
1964 #ifdef RX_ENABLE_LOCKS
1965 CV_BROADCAST(&np->cv);
1966 #else /* RX_ENABLE_LOCKS */
1968 #endif /* RX_ENABLE_LOCKS */
1970 MUTEX_EXIT(&freeSQEList_lock);
1971 for (opr_queue_Scan(&rx_idleServerQueue, cursor)) {
1972 np = opr_queue_Entry(cursor, struct rx_serverQueueEntry, entry);
1973 #ifdef RX_ENABLE_LOCKS
1974 CV_BROADCAST(&np->cv);
1975 #else /* RX_ENABLE_LOCKS */
1977 #endif /* RX_ENABLE_LOCKS */
1979 MUTEX_EXIT(&rx_serverPool_lock);
1984 * One thing that seems to happen is that all the server threads get
1985 * tied up on some empty or slow call, and then a whole bunch of calls
1986 * arrive at once, using up the packet pool, so now there are more
1987 * empty calls. The most critical resources here are server threads
1988 * and the free packet pool. The "doreclaim" code seems to help in
1989 * general. I think that eventually we arrive in this state: there
1990 * are lots of pending calls which do have all their packets present,
1991 * so they won't be reclaimed, are multi-packet calls, so they won't
1992 * be scheduled until later, and thus are tying up most of the free
1993 * packet pool for a very long time.
1995 * 1. schedule multi-packet calls if all the packets are present.
1996 * Probably CPU-bound operation, useful to return packets to pool.
1997 * Do what if there is a full window, but the last packet isn't here?
1998 * 3. preserve one thread which *only* runs "best" calls, otherwise
1999 * it sleeps and waits for that type of call.
2000 * 4. Don't necessarily reserve a whole window for each thread. In fact,
2001 * the current dataquota business is badly broken. The quota isn't adjusted
2002 * to reflect how many packets are presently queued for a running call.
2003 * So, when we schedule a queued call with a full window of packets queued
2004 * up for it, that *should* free up a window full of packets for other 2d-class
2005 * calls to be able to use from the packet pool. But it doesn't.
2007 * NB. Most of the time, this code doesn't run -- since idle server threads
2008 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
2009 * as a new call arrives.
2011 /* Sleep until a call arrives. Returns a pointer to the call, ready
2012 * for an rx_Read. */
2013 #ifdef RX_ENABLE_LOCKS
2015 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2017 struct rx_serverQueueEntry *sq;
2018 struct rx_call *call = (struct rx_call *)0;
2019 struct rx_service *service = NULL;
2021 MUTEX_ENTER(&freeSQEList_lock);
2023 if ((sq = rx_FreeSQEList)) {
2024 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
2025 MUTEX_EXIT(&freeSQEList_lock);
2026 } else { /* otherwise allocate a new one and return that */
2027 MUTEX_EXIT(&freeSQEList_lock);
2028 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2029 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2030 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2033 MUTEX_ENTER(&rx_serverPool_lock);
2034 if (cur_service != NULL) {
2035 ReturnToServerPool(cur_service);
2038 if (!opr_queue_IsEmpty(&rx_incomingCallQueue)) {
2039 struct rx_call *tcall, *choice2 = NULL;
2040 struct opr_queue *cursor;
2042 /* Scan for eligible incoming calls. A call is not eligible
2043 * if the maximum number of calls for its service type are
2044 * already executing */
2045 /* One thread will process calls FCFS (to prevent starvation),
2046 * while the other threads may run ahead looking for calls which
2047 * have all their input data available immediately. This helps
2048 * keep threads from blocking, waiting for data from the client. */
2049 for (opr_queue_Scan(&rx_incomingCallQueue, cursor)) {
2050 tcall = opr_queue_Entry(cursor, struct rx_call, entry);
2052 service = tcall->conn->service;
2053 if (!QuotaOK(service)) {
2056 MUTEX_ENTER(&rx_pthread_mutex);
2057 if (tno == rxi_fcfs_thread_num
2058 || opr_queue_IsEnd(&rx_incomingCallQueue, cursor)) {
2059 MUTEX_EXIT(&rx_pthread_mutex);
2060 /* If we're the fcfs thread , then we'll just use
2061 * this call. If we haven't been able to find an optimal
2062 * choice, and we're at the end of the list, then use a
2063 * 2d choice if one has been identified. Otherwise... */
2064 call = (choice2 ? choice2 : tcall);
2065 service = call->conn->service;
2067 MUTEX_EXIT(&rx_pthread_mutex);
2068 if (!opr_queue_IsEmpty(&tcall->rq)) {
2069 struct rx_packet *rp;
2070 rp = opr_queue_First(&tcall->rq, struct rx_packet,
2072 if (rp->header.seq == 1) {
2074 || (rp->header.flags & RX_LAST_PACKET)) {
2076 } else if (rxi_2dchoice && !choice2
2077 && !(tcall->flags & RX_CALL_CLEARED)
2078 && (tcall->rprev > rxi_HardAckRate)) {
2088 ReturnToServerPool(service);
2094 opr_queue_Remove(&call->entry);
2095 MUTEX_EXIT(&rx_serverPool_lock);
2096 MUTEX_ENTER(&call->lock);
2098 if (call->flags & RX_CALL_WAIT_PROC) {
2099 call->flags &= ~RX_CALL_WAIT_PROC;
2100 rx_atomic_dec(&rx_nWaiting);
2103 if (call->state != RX_STATE_PRECALL || call->error) {
2104 MUTEX_EXIT(&call->lock);
2105 MUTEX_ENTER(&rx_serverPool_lock);
2106 ReturnToServerPool(service);
2111 if (opr_queue_IsEmpty(&call->rq)
2112 || opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq != 1)
2113 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2115 CLEAR_CALL_QUEUE_LOCK(call);
2118 /* If there are no eligible incoming calls, add this process
2119 * to the idle server queue, to wait for one */
2123 *socketp = OSI_NULLSOCKET;
2125 sq->socketp = socketp;
2126 opr_queue_Append(&rx_idleServerQueue, &sq->entry);
2127 #ifndef AFS_AIX41_ENV
2128 rx_waitForPacket = sq;
2129 #endif /* AFS_AIX41_ENV */
2131 CV_WAIT(&sq->cv, &rx_serverPool_lock);
2133 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2137 } while (!(call = sq->newcall)
2138 && !(socketp && *socketp != OSI_NULLSOCKET));
2139 MUTEX_EXIT(&rx_serverPool_lock);
2141 MUTEX_ENTER(&call->lock);
2147 MUTEX_ENTER(&freeSQEList_lock);
2148 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2149 rx_FreeSQEList = sq;
2150 MUTEX_EXIT(&freeSQEList_lock);
2153 clock_GetTime(&call->startTime);
2154 call->state = RX_STATE_ACTIVE;
2155 call->app.mode = RX_MODE_RECEIVING;
2156 #ifdef RX_KERNEL_TRACE
2157 if (ICL_SETACTIVE(afs_iclSetp)) {
2158 int glockOwner = ISAFS_GLOCK();
2161 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2162 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2169 rxi_calltrace(RX_CALL_START, call);
2170 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
2171 call->conn->service->servicePort, call->conn->service->serviceId,
2174 MUTEX_EXIT(&call->lock);
2175 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
2177 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2182 #else /* RX_ENABLE_LOCKS */
2184 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2186 struct rx_serverQueueEntry *sq;
2187 struct rx_call *call = (struct rx_call *)0, *choice2;
2188 struct rx_service *service = NULL;
2192 MUTEX_ENTER(&freeSQEList_lock);
2194 if ((sq = rx_FreeSQEList)) {
2195 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
2196 MUTEX_EXIT(&freeSQEList_lock);
2197 } else { /* otherwise allocate a new one and return that */
2198 MUTEX_EXIT(&freeSQEList_lock);
2199 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2200 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2201 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2203 MUTEX_ENTER(&sq->lock);
2205 if (cur_service != NULL) {
2206 cur_service->nRequestsRunning--;
2207 MUTEX_ENTER(&rx_quota_mutex);
2208 if (cur_service->nRequestsRunning < cur_service->minProcs)
2211 MUTEX_EXIT(&rx_quota_mutex);
2213 if (!opr_queue_IsEmpty(&rx_incomingCallQueue)) {
2214 struct rx_call *tcall;
2215 struct opr_queue *cursor;
2216 /* Scan for eligible incoming calls. A call is not eligible
2217 * if the maximum number of calls for its service type are
2218 * already executing */
2219 /* One thread will process calls FCFS (to prevent starvation),
2220 * while the other threads may run ahead looking for calls which
2221 * have all their input data available immediately. This helps
2222 * keep threads from blocking, waiting for data from the client. */
2223 choice2 = (struct rx_call *)0;
2224 for (opr_queue_Scan(&rx_incomingCallQueue, cursor)) {
2225 tcall = opr_queue_Entry(cursor, struct rx_call, entry);
2226 service = tcall->conn->service;
2227 if (QuotaOK(service)) {
2228 MUTEX_ENTER(&rx_pthread_mutex);
2229 /* XXX - If tcall->entry.next is NULL, then we're no longer
2230 * on a queue at all. This shouldn't happen. */
2231 if (tno == rxi_fcfs_thread_num || !tcall->entry.next) {
2232 MUTEX_EXIT(&rx_pthread_mutex);
2233 /* If we're the fcfs thread, then we'll just use
2234 * this call. If we haven't been able to find an optimal
2235 * choice, and we're at the end of the list, then use a
2236 * 2d choice if one has been identified. Otherwise... */
2237 call = (choice2 ? choice2 : tcall);
2238 service = call->conn->service;
2240 MUTEX_EXIT(&rx_pthread_mutex);
2241 if (!opr_queue_IsEmpty(&tcall->rq)) {
2242 struct rx_packet *rp;
2243 rp = opr_queue_First(&tcall->rq, struct rx_packet,
2245 if (rp->header.seq == 1
2247 || (rp->header.flags & RX_LAST_PACKET))) {
2249 } else if (rxi_2dchoice && !choice2
2250 && !(tcall->flags & RX_CALL_CLEARED)
2251 && (tcall->rprev > rxi_HardAckRate)) {
2264 opr_queue_Remove(&call->entry);
2265 /* we can't schedule a call if there's no data!!! */
2266 /* send an ack if there's no data, if we're missing the
2267 * first packet, or we're missing something between first
2268 * and last -- there's a "hole" in the incoming data. */
2269 if (opr_queue_IsEmpty(&call->rq)
2270 || opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq != 1
2271 || call->rprev != opr_queue_Last(&call->rq, struct rx_packet, entry)->header.seq)
2272 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2274 call->flags &= (~RX_CALL_WAIT_PROC);
2275 service->nRequestsRunning++;
2276 /* just started call in minProcs pool, need fewer to maintain
2278 MUTEX_ENTER(&rx_quota_mutex);
2279 if (service->nRequestsRunning <= service->minProcs)
2282 MUTEX_EXIT(&rx_quota_mutex);
2283 rx_atomic_dec(&rx_nWaiting);
2284 /* MUTEX_EXIT(&call->lock); */
2286 /* If there are no eligible incoming calls, add this process
2287 * to the idle server queue, to wait for one */
2290 *socketp = OSI_NULLSOCKET;
2292 sq->socketp = socketp;
2293 opr_queue_Append(&rx_idleServerQueue, &sq->entry);
2297 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2299 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2300 return (struct rx_call *)0;
2303 } while (!(call = sq->newcall)
2304 && !(socketp && *socketp != OSI_NULLSOCKET));
2306 MUTEX_EXIT(&sq->lock);
2308 MUTEX_ENTER(&freeSQEList_lock);
2309 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2310 rx_FreeSQEList = sq;
2311 MUTEX_EXIT(&freeSQEList_lock);
2314 clock_GetTime(&call->startTime);
2315 call->state = RX_STATE_ACTIVE;
2316 call->app.mode = RX_MODE_RECEIVING;
2317 #ifdef RX_KERNEL_TRACE
2318 if (ICL_SETACTIVE(afs_iclSetp)) {
2319 int glockOwner = ISAFS_GLOCK();
2322 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2323 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2330 rxi_calltrace(RX_CALL_START, call);
2331 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2332 call->conn->service->servicePort, call->conn->service->serviceId,
2335 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2342 #endif /* RX_ENABLE_LOCKS */
2346 /* Establish a procedure to be called when a packet arrives for a
2347 * call. This routine will be called at most once after each call,
2348 * and will also be called if there is an error condition on the or
2349 * the call is complete. Used by multi rx to build a selection
2350 * function which determines which of several calls is likely to be a
2351 * good one to read from.
2352 * NOTE: the way this is currently implemented it is probably only a
2353 * good idea to (1) use it immediately after a newcall (clients only)
2354 * and (2) only use it once. Other uses currently void your warranty
2357 rx_SetArrivalProc(struct rx_call *call,
2358 void (*proc) (struct rx_call * call,
2361 void * handle, int arg)
2363 call->arrivalProc = proc;
2364 call->arrivalProcHandle = handle;
2365 call->arrivalProcArg = arg;
2368 /* Call is finished (possibly prematurely). Return rc to the peer, if
2369 * appropriate, and return the final error code from the conversation
2373 rx_EndCall(struct rx_call *call, afs_int32 rc)
2375 struct rx_connection *conn = call->conn;
2379 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2380 call, rc, call->error, call->abortCode));
2383 MUTEX_ENTER(&call->lock);
2385 if (rc == 0 && call->error == 0) {
2386 call->abortCode = 0;
2387 call->abortCount = 0;
2390 call->arrivalProc = NULL;
2391 if (rc && call->error == 0) {
2392 rxi_CallError(call, rc);
2393 call->app.mode = RX_MODE_ERROR;
2394 /* Send an abort message to the peer if this error code has
2395 * only just been set. If it was set previously, assume the
2396 * peer has already been sent the error code or will request it
2398 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2400 if (conn->type == RX_SERVER_CONNECTION) {
2401 /* Make sure reply or at least dummy reply is sent */
2402 if (call->app.mode == RX_MODE_RECEIVING) {
2403 MUTEX_EXIT(&call->lock);
2404 rxi_WriteProc(call, 0, 0);
2405 MUTEX_ENTER(&call->lock);
2407 if (call->app.mode == RX_MODE_SENDING) {
2408 rxi_FlushWriteLocked(call);
2410 rxi_calltrace(RX_CALL_END, call);
2411 /* Call goes to hold state until reply packets are acknowledged */
2412 if (call->tfirst + call->nSoftAcked < call->tnext) {
2413 call->state = RX_STATE_HOLD;
2415 call->state = RX_STATE_DALLY;
2416 rxi_ClearTransmitQueue(call, 0);
2417 rxi_rto_cancel(call);
2418 rxi_CancelKeepAliveEvent(call);
2420 } else { /* Client connection */
2422 /* Make sure server receives input packets, in the case where
2423 * no reply arguments are expected */
2425 if ((call->app.mode == RX_MODE_SENDING)
2426 || (call->app.mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2427 MUTEX_EXIT(&call->lock);
2428 (void)rxi_ReadProc(call, &dummy, 1);
2429 MUTEX_ENTER(&call->lock);
2432 /* If we had an outstanding delayed ack, be nice to the server
2433 * and force-send it now.
2435 if (call->delayedAckEvent) {
2436 rxi_CancelDelayedAckEvent(call);
2437 rxi_SendDelayedAck(NULL, call, NULL, 0);
2440 /* We need to release the call lock since it's lower than the
2441 * conn_call_lock and we don't want to hold the conn_call_lock
2442 * over the rx_ReadProc call. The conn_call_lock needs to be held
2443 * here for the case where rx_NewCall is perusing the calls on
2444 * the connection structure. We don't want to signal until
2445 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2446 * have checked this call, found it active and by the time it
2447 * goes to sleep, will have missed the signal.
2449 MUTEX_EXIT(&call->lock);
2450 MUTEX_ENTER(&conn->conn_call_lock);
2451 MUTEX_ENTER(&call->lock);
2454 /* While there are some circumstances where a call with an error is
2455 * obviously not on a "busy" channel, be conservative (clearing
2456 * lastBusy is just best-effort to possibly speed up rx_NewCall).
2457 * The call channel is definitely not busy if we just successfully
2458 * completed a call on it. */
2459 conn->lastBusy[call->channel] = 0;
2461 } else if (call->error == RX_CALL_TIMEOUT) {
2462 /* The call is still probably running on the server side, so try to
2463 * avoid this call channel in the future. */
2464 conn->lastBusy[call->channel] = clock_Sec();
2467 MUTEX_ENTER(&conn->conn_data_lock);
2468 conn->flags |= RX_CONN_BUSY;
2469 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2470 MUTEX_EXIT(&conn->conn_data_lock);
2471 #ifdef RX_ENABLE_LOCKS
2472 CV_BROADCAST(&conn->conn_call_cv);
2477 #ifdef RX_ENABLE_LOCKS
2479 MUTEX_EXIT(&conn->conn_data_lock);
2481 #endif /* RX_ENABLE_LOCKS */
2482 call->state = RX_STATE_DALLY;
2484 error = call->error;
2486 /* currentPacket, nLeft, and NFree must be zeroed here, because
2487 * ResetCall cannot: ResetCall may be called at splnet(), in the
2488 * kernel version, and may interrupt the macros rx_Read or
2489 * rx_Write, which run at normal priority for efficiency. */
2490 if (call->app.currentPacket) {
2491 #ifdef RX_TRACK_PACKETS
2492 call->app.currentPacket->flags &= ~RX_PKTFLAG_CP;
2494 rxi_FreePacket(call->app.currentPacket);
2495 call->app.currentPacket = (struct rx_packet *)0;
2498 call->app.nLeft = call->app.nFree = call->app.curlen = 0;
2500 /* Free any packets from the last call to ReadvProc/WritevProc */
2501 #ifdef RXDEBUG_PACKET
2503 #endif /* RXDEBUG_PACKET */
2504 rxi_FreePackets(0, &call->app.iovq);
2505 MUTEX_EXIT(&call->lock);
2507 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2508 if (conn->type == RX_CLIENT_CONNECTION) {
2509 MUTEX_ENTER(&conn->conn_data_lock);
2510 conn->flags &= ~RX_CONN_BUSY;
2511 MUTEX_EXIT(&conn->conn_data_lock);
2512 MUTEX_EXIT(&conn->conn_call_lock);
2516 * Map errors to the local host's errno.h format.
2518 error = ntoh_syserr_conv(error);
2520 /* If the caller said the call failed with some error, we had better
2521 * return an error code. */
2522 osi_Assert(!rc || error);
2526 #if !defined(KERNEL)
2528 /* Call this routine when shutting down a server or client (especially
2529 * clients). This will allow Rx to gracefully garbage collect server
2530 * connections, and reduce the number of retries that a server might
2531 * make to a dead client.
2532 * This is not quite right, since some calls may still be ongoing and
2533 * we can't lock them to destroy them. */
2539 if (!rxi_IsRunning()) {
2541 return; /* Already shutdown. */
2543 rxi_Finalize_locked();
2548 rxi_Finalize_locked(void)
2550 struct rx_connection **conn_ptr, **conn_end;
2551 rx_atomic_set(&rxi_running, 0);
2552 rxi_DeleteCachedConnections();
2553 if (rx_connHashTable) {
2554 MUTEX_ENTER(&rx_connHashTable_lock);
2555 for (conn_ptr = &rx_connHashTable[0], conn_end =
2556 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2558 struct rx_connection *conn, *next;
2559 for (conn = *conn_ptr; conn; conn = next) {
2561 if (conn->type == RX_CLIENT_CONNECTION) {
2562 rx_GetConnection(conn);
2563 #ifdef RX_ENABLE_LOCKS
2564 rxi_DestroyConnectionNoLock(conn);
2565 #else /* RX_ENABLE_LOCKS */
2566 rxi_DestroyConnection(conn);
2567 #endif /* RX_ENABLE_LOCKS */
2571 #ifdef RX_ENABLE_LOCKS
2572 while (rx_connCleanup_list) {
2573 struct rx_connection *conn;
2574 conn = rx_connCleanup_list;
2575 rx_connCleanup_list = rx_connCleanup_list->next;
2576 MUTEX_EXIT(&rx_connHashTable_lock);
2577 rxi_CleanupConnection(conn);
2578 MUTEX_ENTER(&rx_connHashTable_lock);
2580 MUTEX_EXIT(&rx_connHashTable_lock);
2581 #endif /* RX_ENABLE_LOCKS */
2586 afs_winsockCleanup();
2591 /* if we wakeup packet waiter too often, can get in loop with two
2592 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2594 rxi_PacketsUnWait(void)
2596 if (!rx_waitingForPackets) {
2600 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2601 return; /* still over quota */
2604 rx_waitingForPackets = 0;
2605 #ifdef RX_ENABLE_LOCKS
2606 CV_BROADCAST(&rx_waitingForPackets_cv);
2608 osi_rxWakeup(&rx_waitingForPackets);
2614 /* ------------------Internal interfaces------------------------- */
2616 /* Return this process's service structure for the
2617 * specified socket and service */
2618 static struct rx_service *
2619 rxi_FindService(osi_socket socket, u_short serviceId)
2621 struct rx_service **sp;
2622 for (sp = &rx_services[0]; *sp; sp++) {
2623 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2629 #ifdef RXDEBUG_PACKET
2630 #ifdef KDUMP_RX_LOCK
2631 static struct rx_call_rx_lock *rx_allCallsp = 0;
2633 static struct rx_call *rx_allCallsp = 0;
2635 #endif /* RXDEBUG_PACKET */
2637 /* Allocate a call structure, for the indicated channel of the
2638 * supplied connection. The mode and state of the call must be set by
2639 * the caller. Returns the call with mutex locked. */
2640 static struct rx_call *
2641 rxi_NewCall(struct rx_connection *conn, int channel)
2643 struct rx_call *call;
2644 #ifdef RX_ENABLE_LOCKS
2645 struct rx_call *cp; /* Call pointer temp */
2646 struct opr_queue *cursor;
2649 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2651 /* Grab an existing call structure, or allocate a new one.
2652 * Existing call structures are assumed to have been left reset by
2654 MUTEX_ENTER(&rx_freeCallQueue_lock);
2656 #ifdef RX_ENABLE_LOCKS
2658 * EXCEPT that the TQ might not yet be cleared out.
2659 * Skip over those with in-use TQs.
2662 for (opr_queue_Scan(&rx_freeCallQueue, cursor)) {
2663 cp = opr_queue_Entry(cursor, struct rx_call, entry);
2664 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2670 #else /* RX_ENABLE_LOCKS */
2671 if (!opr_queue_IsEmpty(&rx_freeCallQueue)) {
2672 call = opr_queue_First(&rx_freeCallQueue, struct rx_call, entry);
2673 #endif /* RX_ENABLE_LOCKS */
2674 opr_queue_Remove(&call->entry);
2675 if (rx_stats_active)
2676 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2677 MUTEX_EXIT(&rx_freeCallQueue_lock);
2678 MUTEX_ENTER(&call->lock);
2679 CLEAR_CALL_QUEUE_LOCK(call);
2680 #ifdef RX_ENABLE_LOCKS
2681 /* Now, if TQ wasn't cleared earlier, do it now. */
2682 rxi_WaitforTQBusy(call);
2683 if (call->flags & RX_CALL_TQ_CLEARME) {
2684 rxi_ClearTransmitQueue(call, 1);
2685 /*queue_Init(&call->tq);*/
2687 #endif /* RX_ENABLE_LOCKS */
2688 /* Bind the call to its connection structure */
2690 rxi_ResetCall(call, 1);
2693 call = rxi_Alloc(sizeof(struct rx_call));
2694 #ifdef RXDEBUG_PACKET
2695 call->allNextp = rx_allCallsp;
2696 rx_allCallsp = call;
2698 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2699 #else /* RXDEBUG_PACKET */
2700 rx_atomic_inc(&rx_stats.nCallStructs);
2701 #endif /* RXDEBUG_PACKET */
2703 MUTEX_EXIT(&rx_freeCallQueue_lock);
2704 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2705 MUTEX_ENTER(&call->lock);
2706 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2707 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2708 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2710 /* Initialize once-only items */
2711 opr_queue_Init(&call->tq);
2712 opr_queue_Init(&call->rq);
2713 opr_queue_Init(&call->app.iovq);
2714 #ifdef RXDEBUG_PACKET
2715 call->rqc = call->tqc = call->iovqc = 0;
2716 #endif /* RXDEBUG_PACKET */
2717 /* Bind the call to its connection structure (prereq for reset) */
2719 rxi_ResetCall(call, 1);
2721 call->channel = channel;
2722 call->callNumber = &conn->callNumber[channel];
2723 call->rwind = conn->rwind[channel];
2724 call->twind = conn->twind[channel];
2725 /* Note that the next expected call number is retained (in
2726 * conn->callNumber[i]), even if we reallocate the call structure
2728 conn->call[channel] = call;
2729 /* if the channel's never been used (== 0), we should start at 1, otherwise
2730 * the call number is valid from the last time this channel was used */
2731 if (*call->callNumber == 0)
2732 *call->callNumber = 1;
2737 /* A call has been inactive long enough that so we can throw away
2738 * state, including the call structure, which is placed on the call
2741 * call->lock amd rx_refcnt_mutex are held upon entry.
2742 * haveCTLock is set when called from rxi_ReapConnections.
2744 * return 1 if the call is freed, 0 if not.
2747 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2749 int channel = call->channel;
2750 struct rx_connection *conn = call->conn;
2751 u_char state = call->state;
2754 * We are setting the state to RX_STATE_RESET to
2755 * ensure that no one else will attempt to use this
2756 * call once we drop the refcnt lock. We must drop
2757 * the refcnt lock before calling rxi_ResetCall
2758 * because it cannot be held across acquiring the
2759 * freepktQ lock. NewCall does the same.
2761 call->state = RX_STATE_RESET;
2762 MUTEX_EXIT(&rx_refcnt_mutex);
2763 rxi_ResetCall(call, 0);
2765 if (MUTEX_TRYENTER(&conn->conn_call_lock))
2767 if (state == RX_STATE_DALLY || state == RX_STATE_HOLD)
2768 (*call->callNumber)++;
2770 if (call->conn->call[channel] == call)
2771 call->conn->call[channel] = 0;
2772 MUTEX_EXIT(&conn->conn_call_lock);
2775 * We couldn't obtain the conn_call_lock so we can't
2776 * disconnect the call from the connection. Set the
2777 * call state to dally so that the call can be reused.
2779 MUTEX_ENTER(&rx_refcnt_mutex);
2780 call->state = RX_STATE_DALLY;
2784 MUTEX_ENTER(&rx_freeCallQueue_lock);
2785 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2786 #ifdef RX_ENABLE_LOCKS
2787 /* A call may be free even though its transmit queue is still in use.
2788 * Since we search the call list from head to tail, put busy calls at
2789 * the head of the list, and idle calls at the tail.
2791 if (call->flags & RX_CALL_TQ_BUSY)
2792 opr_queue_Prepend(&rx_freeCallQueue, &call->entry);
2794 opr_queue_Append(&rx_freeCallQueue, &call->entry);
2795 #else /* RX_ENABLE_LOCKS */
2796 opr_queue_Append(&rx_freeCallQueue, &call->entry);
2797 #endif /* RX_ENABLE_LOCKS */
2798 if (rx_stats_active)
2799 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2800 MUTEX_EXIT(&rx_freeCallQueue_lock);
2802 /* Destroy the connection if it was previously slated for
2803 * destruction, i.e. the Rx client code previously called
2804 * rx_DestroyConnection (client connections), or
2805 * rxi_ReapConnections called the same routine (server
2806 * connections). Only do this, however, if there are no
2807 * outstanding calls. Note that for fine grain locking, there appears
2808 * to be a deadlock in that rxi_FreeCall has a call locked and
2809 * DestroyConnectionNoLock locks each call in the conn. But note a
2810 * few lines up where we have removed this call from the conn.
2811 * If someone else destroys a connection, they either have no
2812 * call lock held or are going through this section of code.
2814 MUTEX_ENTER(&conn->conn_data_lock);
2815 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2816 rx_GetConnection(conn);
2817 MUTEX_EXIT(&conn->conn_data_lock);
2818 #ifdef RX_ENABLE_LOCKS
2820 rxi_DestroyConnectionNoLock(conn);
2822 rxi_DestroyConnection(conn);
2823 #else /* RX_ENABLE_LOCKS */
2824 rxi_DestroyConnection(conn);
2825 #endif /* RX_ENABLE_LOCKS */
2827 MUTEX_EXIT(&conn->conn_data_lock);
2829 MUTEX_ENTER(&rx_refcnt_mutex);
2833 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2834 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2837 rxi_Alloc(size_t size)
2841 if (rx_stats_active) {
2842 rx_atomic_add(&rxi_Allocsize, (int) size);
2843 rx_atomic_inc(&rxi_Alloccnt);
2847 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2848 afs_osi_Alloc_NoSleep(size);
2853 osi_Panic("rxi_Alloc error");
2859 rxi_Free(void *addr, size_t size)
2864 if (rx_stats_active) {
2865 rx_atomic_sub(&rxi_Allocsize, (int) size);
2866 rx_atomic_dec(&rxi_Alloccnt);
2868 osi_Free(addr, size);
2872 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2874 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2875 struct rx_peer *next = NULL;
2879 MUTEX_ENTER(&rx_peerHashTable_lock);
2881 peer_ptr = &rx_peerHashTable[0];
2882 peer_end = &rx_peerHashTable[rx_hashTableSize];
2885 for ( ; peer_ptr < peer_end; peer_ptr++) {
2888 for ( ; peer; peer = next) {
2890 if (host == peer->host)
2895 hashIndex = PEER_HASH(host, port);
2896 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2897 if ((peer->host == host) && (peer->port == port))
2902 MUTEX_ENTER(&rx_peerHashTable_lock);
2907 MUTEX_EXIT(&rx_peerHashTable_lock);
2909 MUTEX_ENTER(&peer->peer_lock);
2910 /* We don't handle dropping below min, so don't */
2911 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2912 peer->ifMTU=MIN(mtu, peer->ifMTU);
2913 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2914 /* if we tweaked this down, need to tune our peer MTU too */
2915 peer->MTU = MIN(peer->MTU, peer->natMTU);
2916 /* if we discovered a sub-1500 mtu, degrade */
2917 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2918 peer->maxDgramPackets = 1;
2919 /* We no longer have valid peer packet information */
2920 if (peer->maxPacketSize + RX_HEADER_SIZE > peer->ifMTU)
2921 peer->maxPacketSize = 0;
2922 MUTEX_EXIT(&peer->peer_lock);
2924 MUTEX_ENTER(&rx_peerHashTable_lock);
2926 if (host && !port) {
2928 /* pick up where we left off */
2932 MUTEX_EXIT(&rx_peerHashTable_lock);
2935 #ifdef AFS_RXERRQ_ENV
2937 rxi_SetPeerDead(struct sock_extended_err *err, afs_uint32 host, afs_uint16 port)
2939 int hashIndex = PEER_HASH(host, port);
2940 struct rx_peer *peer;
2942 MUTEX_ENTER(&rx_peerHashTable_lock);
2944 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2945 if (peer->host == host && peer->port == port) {
2951 MUTEX_EXIT(&rx_peerHashTable_lock);
2954 rx_atomic_inc(&peer->neterrs);
2955 MUTEX_ENTER(&peer->peer_lock);
2956 peer->last_err_origin = RX_NETWORK_ERROR_ORIGIN_ICMP;
2957 peer->last_err_type = err->ee_type;
2958 peer->last_err_code = err->ee_code;
2959 MUTEX_EXIT(&peer->peer_lock);
2961 MUTEX_ENTER(&rx_peerHashTable_lock);
2963 MUTEX_EXIT(&rx_peerHashTable_lock);
2968 rxi_ProcessNetError(struct sock_extended_err *err, afs_uint32 addr, afs_uint16 port)
2970 # ifdef AFS_ADAPT_PMTU
2971 if (err->ee_errno == EMSGSIZE && err->ee_info >= 68) {
2972 rxi_SetPeerMtu(NULL, addr, port, err->ee_info - RX_IPUDP_SIZE);
2976 if (err->ee_origin == SO_EE_ORIGIN_ICMP && err->ee_type == ICMP_DEST_UNREACH) {
2977 switch (err->ee_code) {
2978 case ICMP_NET_UNREACH:
2979 case ICMP_HOST_UNREACH:
2980 case ICMP_PORT_UNREACH:
2983 rxi_SetPeerDead(err, addr, port);
2990 rxi_TranslateICMP(int type, int code)
2993 case ICMP_DEST_UNREACH:
2995 case ICMP_NET_UNREACH:
2996 return "Destination Net Unreachable";
2997 case ICMP_HOST_UNREACH:
2998 return "Destination Host Unreachable";
2999 case ICMP_PROT_UNREACH:
3000 return "Destination Protocol Unreachable";
3001 case ICMP_PORT_UNREACH:
3002 return "Destination Port Unreachable";
3004 return "Destination Net Prohibited";
3006 return "Destination Host Prohibited";
3012 #endif /* AFS_RXERRQ_ENV */
3015 * Get the last network error for a connection
3017 * A "network error" here means an error retrieved from ICMP, or some other
3018 * mechanism outside of Rx that informs us of errors in network reachability.
3020 * If a peer associated with the given Rx connection has received a network
3021 * error recently, this function allows the caller to know what error
3022 * specifically occurred. This can be useful to know, since e.g. ICMP errors
3023 * can cause calls to that peer to be quickly aborted. So, this function can
3024 * help see why a call was aborted due to network errors.
3026 * If we have received traffic from a peer since the last network error, we
3027 * treat that peer as if we had not received an network error for it.
3029 * @param[in] conn The Rx connection to examine
3030 * @param[out] err_origin The origin of the last network error (e.g. ICMP);
3031 * one of the RX_NETWORK_ERROR_ORIGIN_* constants
3032 * @param[out] err_type The type of the last error
3033 * @param[out] err_code The code of the last error
3034 * @param[out] msg Human-readable error message, if applicable; NULL otherwise
3036 * @return If we have an error
3037 * @retval -1 No error to get; 'out' params are undefined
3038 * @retval 0 We have an error; 'out' params contain the last error
3041 rx_GetNetworkError(struct rx_connection *conn, int *err_origin, int *err_type,
3042 int *err_code, const char **msg)
3044 #ifdef AFS_RXERRQ_ENV
3045 struct rx_peer *peer = conn->peer;
3046 if (rx_atomic_read(&peer->neterrs)) {
3047 MUTEX_ENTER(&peer->peer_lock);
3048 *err_origin = peer->last_err_origin;
3049 *err_type = peer->last_err_type;
3050 *err_code = peer->last_err_code;
3051 MUTEX_EXIT(&peer->peer_lock);
3054 if (*err_origin == RX_NETWORK_ERROR_ORIGIN_ICMP) {
3055 *msg = rxi_TranslateICMP(*err_type, *err_code);
3064 /* Find the peer process represented by the supplied (host,port)
3065 * combination. If there is no appropriate active peer structure, a
3066 * new one will be allocated and initialized
3069 rxi_FindPeer(afs_uint32 host, u_short port, int create)
3073 hashIndex = PEER_HASH(host, port);
3074 MUTEX_ENTER(&rx_peerHashTable_lock);
3075 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
3076 if ((pp->host == host) && (pp->port == port))
3081 pp = rxi_AllocPeer(); /* This bzero's *pp */
3082 pp->host = host; /* set here or in InitPeerParams is zero */
3084 #ifdef AFS_RXERRQ_ENV
3085 rx_atomic_set(&pp->neterrs, 0);
3087 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
3088 opr_queue_Init(&pp->rpcStats);
3089 pp->next = rx_peerHashTable[hashIndex];
3090 rx_peerHashTable[hashIndex] = pp;
3091 rxi_InitPeerParams(pp);
3092 if (rx_stats_active)
3093 rx_atomic_inc(&rx_stats.nPeerStructs);
3099 MUTEX_EXIT(&rx_peerHashTable_lock);
3104 /* Find the connection at (host, port) started at epoch, and with the
3105 * given connection id. Creates the server connection if necessary.
3106 * The type specifies whether a client connection or a server
3107 * connection is desired. In both cases, (host, port) specify the
3108 * peer's (host, pair) pair. Client connections are not made
3109 * automatically by this routine. The parameter socket gives the
3110 * socket descriptor on which the packet was received. This is used,
3111 * in the case of server connections, to check that *new* connections
3112 * come via a valid (port, serviceId). Finally, the securityIndex
3113 * parameter must match the existing index for the connection. If a
3114 * server connection is created, it will be created using the supplied
3115 * index, if the index is valid for this service */
3116 static struct rx_connection *
3117 rxi_FindConnection(osi_socket socket, afs_uint32 host,
3118 u_short port, u_short serviceId, afs_uint32 cid,
3119 afs_uint32 epoch, int type, u_int securityIndex,
3120 int *unknownService)
3122 int hashindex, flag, i;
3124 struct rx_connection *conn;
3125 *unknownService = 0;
3126 hashindex = CONN_HASH(host, port, cid, epoch, type);
3127 MUTEX_ENTER(&rx_connHashTable_lock);
3128 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
3129 rx_connHashTable[hashindex],
3132 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
3133 && (epoch == conn->epoch)) {
3134 struct rx_peer *pp = conn->peer;
3135 if (securityIndex != conn->securityIndex) {
3136 /* this isn't supposed to happen, but someone could forge a packet
3137 * like this, and there seems to be some CM bug that makes this
3138 * happen from time to time -- in which case, the fileserver
3140 MUTEX_EXIT(&rx_connHashTable_lock);
3141 return (struct rx_connection *)0;
3143 if (pp->host == host && pp->port == port)
3145 if (type == RX_CLIENT_CONNECTION && pp->port == port)
3147 /* So what happens when it's a callback connection? */
3148 if ( /*type == RX_CLIENT_CONNECTION && */
3149 (conn->epoch & 0x80000000))
3153 /* the connection rxLastConn that was used the last time is not the
3154 ** one we are looking for now. Hence, start searching in the hash */
3156 conn = rx_connHashTable[hashindex];
3161 struct rx_service *service;
3162 if (type == RX_CLIENT_CONNECTION) {
3163 MUTEX_EXIT(&rx_connHashTable_lock);
3164 return (struct rx_connection *)0;
3166 service = rxi_FindService(socket, serviceId);
3167 if (!service || (securityIndex >= service->nSecurityObjects)
3168 || (service->securityObjects[securityIndex] == 0)) {
3169 MUTEX_EXIT(&rx_connHashTable_lock);
3170 *unknownService = 1;
3171 return (struct rx_connection *)0;
3173 conn = rxi_AllocConnection(); /* This bzero's the connection */
3174 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
3175 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
3176 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
3177 conn->next = rx_connHashTable[hashindex];
3178 rx_connHashTable[hashindex] = conn;
3179 conn->peer = rxi_FindPeer(host, port, 1);
3180 conn->type = RX_SERVER_CONNECTION;
3181 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
3182 conn->epoch = epoch;
3183 conn->cid = cid & RX_CIDMASK;
3184 conn->ackRate = RX_FAST_ACK_RATE;
3185 conn->service = service;
3186 conn->serviceId = serviceId;
3187 conn->securityIndex = securityIndex;
3188 conn->securityObject = service->securityObjects[securityIndex];
3189 conn->nSpecific = 0;
3190 conn->specific = NULL;
3191 rx_SetConnDeadTime(conn, service->connDeadTime);
3192 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
3193 for (i = 0; i < RX_MAXCALLS; i++) {
3194 conn->twind[i] = rx_initSendWindow;
3195 conn->rwind[i] = rx_initReceiveWindow;
3197 /* Notify security object of the new connection */
3198 code = RXS_NewConnection(conn->securityObject, conn);
3199 /* XXXX Connection timeout? */
3200 if (service->newConnProc)
3201 (*service->newConnProc) (conn);
3202 if (rx_stats_active)
3203 rx_atomic_inc(&rx_stats.nServerConns);
3206 rx_GetConnection(conn);
3208 rxLastConn = conn; /* store this connection as the last conn used */
3209 MUTEX_EXIT(&rx_connHashTable_lock);
3211 rxi_ConnectionError(conn, code);
3217 * Abort the call if the server is over the busy threshold. This
3218 * can be used without requiring a call structure be initialised,
3219 * or connected to a particular channel
3222 rxi_AbortIfServerBusy(osi_socket socket, struct rx_connection *conn,
3223 struct rx_packet *np)
3227 if ((rx_BusyThreshold > 0) &&
3228 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3229 MUTEX_ENTER(&conn->conn_data_lock);
3230 serial = ++conn->serial;
3231 MUTEX_EXIT(&conn->conn_data_lock);
3232 rxi_SendRawAbort(socket, conn->peer->host, conn->peer->port,
3233 serial, rx_BusyError, np, 0);
3234 if (rx_stats_active)
3235 rx_atomic_inc(&rx_stats.nBusies);
3242 static_inline struct rx_call *
3243 rxi_ReceiveClientCall(struct rx_packet *np, struct rx_connection *conn)
3246 struct rx_call *call;
3248 channel = np->header.cid & RX_CHANNELMASK;
3249 MUTEX_ENTER(&conn->conn_call_lock);
3250 call = conn->call[channel];
3251 if (np->header.type == RX_PACKET_TYPE_BUSY) {
3252 conn->lastBusy[channel] = clock_Sec();
3254 if (!call || conn->callNumber[channel] != np->header.callNumber) {
3255 MUTEX_EXIT(&conn->conn_call_lock);
3256 if (rx_stats_active)
3257 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3261 MUTEX_ENTER(&call->lock);
3262 MUTEX_EXIT(&conn->conn_call_lock);
3264 if ((call->state == RX_STATE_DALLY)
3265 && np->header.type == RX_PACKET_TYPE_ACK) {
3266 if (rx_stats_active)
3267 rx_atomic_inc(&rx_stats.ignorePacketDally);
3268 MUTEX_EXIT(&call->lock);
3275 static_inline struct rx_call *
3276 rxi_ReceiveServerCall(osi_socket socket, struct rx_packet *np,
3277 struct rx_connection *conn)
3280 struct rx_call *call;
3282 channel = np->header.cid & RX_CHANNELMASK;
3283 MUTEX_ENTER(&conn->conn_call_lock);
3284 call = conn->call[channel];
3287 if (rxi_AbortIfServerBusy(socket, conn, np)) {
3288 MUTEX_EXIT(&conn->conn_call_lock);
3292 call = rxi_NewCall(conn, channel); /* returns locked call */
3293 *call->callNumber = np->header.callNumber;
3294 MUTEX_EXIT(&conn->conn_call_lock);
3296 call->state = RX_STATE_PRECALL;
3297 clock_GetTime(&call->queueTime);
3298 call->app.bytesSent = 0;
3299 call->app.bytesRcvd = 0;
3300 rxi_KeepAliveOn(call);
3305 if (np->header.callNumber == conn->callNumber[channel]) {
3306 MUTEX_ENTER(&call->lock);
3307 MUTEX_EXIT(&conn->conn_call_lock);
3311 if (np->header.callNumber < conn->callNumber[channel]) {
3312 MUTEX_EXIT(&conn->conn_call_lock);
3313 if (rx_stats_active)
3314 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3318 MUTEX_ENTER(&call->lock);
3319 MUTEX_EXIT(&conn->conn_call_lock);
3321 /* Wait until the transmit queue is idle before deciding
3322 * whether to reset the current call. Chances are that the
3323 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3326 #ifdef RX_ENABLE_LOCKS
3327 if (call->state == RX_STATE_ACTIVE && !call->error) {
3328 rxi_WaitforTQBusy(call);
3329 /* If we entered error state while waiting,
3330 * must call rxi_CallError to permit rxi_ResetCall
3331 * to processed when the tqWaiter count hits zero.
3334 rxi_CallError(call, call->error);
3335 MUTEX_EXIT(&call->lock);
3339 #endif /* RX_ENABLE_LOCKS */
3340 /* If the new call cannot be taken right now send a busy and set
3341 * the error condition in this call, so that it terminates as
3342 * quickly as possible */
3343 if (call->state == RX_STATE_ACTIVE) {
3344 rxi_CallError(call, RX_CALL_DEAD);
3345 rxi_SendSpecial(call, conn, NULL, RX_PACKET_TYPE_BUSY,
3347 MUTEX_EXIT(&call->lock);
3351 if (rxi_AbortIfServerBusy(socket, conn, np)) {
3352 MUTEX_EXIT(&call->lock);
3356 rxi_ResetCall(call, 0);
3357 /* The conn_call_lock is not held but no one else should be
3358 * using this call channel while we are processing this incoming
3359 * packet. This assignment should be safe.
3361 *call->callNumber = np->header.callNumber;
3362 call->state = RX_STATE_PRECALL;
3363 clock_GetTime(&call->queueTime);
3364 call->app.bytesSent = 0;
3365 call->app.bytesRcvd = 0;
3366 rxi_KeepAliveOn(call);
3372 /* There are two packet tracing routines available for testing and monitoring
3373 * Rx. One is called just after every packet is received and the other is
3374 * called just before every packet is sent. Received packets, have had their
3375 * headers decoded, and packets to be sent have not yet had their headers
3376 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
3377 * containing the network address. Both can be modified. The return value, if
3378 * non-zero, indicates that the packet should be dropped. */
3380 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
3381 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
3383 /* A packet has been received off the interface. Np is the packet, socket is
3384 * the socket number it was received from (useful in determining which service
3385 * this packet corresponds to), and (host, port) reflect the host,port of the
3386 * sender. This call returns the packet to the caller if it is finished with
3387 * it, rather than de-allocating it, just as a small performance hack */
3390 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
3391 afs_uint32 host, u_short port, int *tnop,
3392 struct rx_call **newcallp)
3394 struct rx_call *call;
3395 struct rx_connection *conn;
3397 int unknownService = 0;
3401 struct rx_packet *tnp;
3404 /* We don't print out the packet until now because (1) the time may not be
3405 * accurate enough until now in the lwp implementation (rx_Listener only gets
3406 * the time after the packet is read) and (2) from a protocol point of view,
3407 * this is the first time the packet has been seen */
3408 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
3409 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
3410 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT"\n",
3411 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
3412 np->header.epoch, np->header.cid, np->header.callNumber,
3413 np->header.seq, np->header.flags, np));
3416 /* Account for connectionless packets */
3417 if (rx_stats_active &&
3418 ((np->header.type == RX_PACKET_TYPE_VERSION) ||
3419 (np->header.type == RX_PACKET_TYPE_DEBUG))) {
3420 struct rx_peer *peer;
3422 /* Try to look up the peer structure, but don't create one */
3423 peer = rxi_FindPeer(host, port, 0);
3425 /* Since this may not be associated with a connection, it may have
3426 * no refCount, meaning we could race with ReapConnections
3429 if (peer && (peer->refCount > 0)) {
3430 #ifdef AFS_RXERRQ_ENV
3431 if (rx_atomic_read(&peer->neterrs)) {
3432 rx_atomic_set(&peer->neterrs, 0);
3435 MUTEX_ENTER(&peer->peer_lock);
3436 peer->bytesReceived += np->length;
3437 MUTEX_EXIT(&peer->peer_lock);
3441 if (np->header.type == RX_PACKET_TYPE_VERSION) {
3442 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
3445 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
3446 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
3449 /* If an input tracer function is defined, call it with the packet and
3450 * network address. Note this function may modify its arguments. */
3451 if (rx_justReceived) {
3452 struct sockaddr_in addr;
3454 addr.sin_family = AF_INET;
3455 addr.sin_port = port;
3456 addr.sin_addr.s_addr = host;
3457 memset(&addr.sin_zero, 0, sizeof(addr.sin_zero));
3458 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
3459 addr.sin_len = sizeof(addr);
3461 drop = (*rx_justReceived) (np, &addr);
3462 /* drop packet if return value is non-zero */
3465 port = addr.sin_port; /* in case fcn changed addr */
3466 host = addr.sin_addr.s_addr;
3470 /* If packet was not sent by the client, then *we* must be the client */
3471 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
3472 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
3474 /* Find the connection (or fabricate one, if we're the server & if
3475 * necessary) associated with this packet */
3477 rxi_FindConnection(socket, host, port, np->header.serviceId,
3478 np->header.cid, np->header.epoch, type,
3479 np->header.securityIndex, &unknownService);
3481 /* To avoid having 2 connections just abort at each other,
3482 don't abort an abort. */
3484 if (unknownService && (np->header.type != RX_PACKET_TYPE_ABORT))
3485 rxi_SendRawAbort(socket, host, port, 0, RX_INVALID_OPERATION,
3490 #ifdef AFS_RXERRQ_ENV
3491 if (rx_atomic_read(&conn->peer->neterrs)) {
3492 rx_atomic_set(&conn->peer->neterrs, 0);
3496 /* If we're doing statistics, then account for the incoming packet */
3497 if (rx_stats_active) {
3498 MUTEX_ENTER(&conn->peer->peer_lock);
3499 conn->peer->bytesReceived += np->length;
3500 MUTEX_EXIT(&conn->peer->peer_lock);
3503 /* If the connection is in an error state, send an abort packet and ignore
3504 * the incoming packet */
3506 /* Don't respond to an abort packet--we don't want loops! */
3507 MUTEX_ENTER(&conn->conn_data_lock);
3508 if (np->header.type != RX_PACKET_TYPE_ABORT)
3509 np = rxi_SendConnectionAbort(conn, np, 1, 0);
3510 putConnection(conn);
3511 MUTEX_EXIT(&conn->conn_data_lock);
3515 /* Check for connection-only requests (i.e. not call specific). */
3516 if (np->header.callNumber == 0) {
3517 switch (np->header.type) {
3518 case RX_PACKET_TYPE_ABORT: {
3519 /* What if the supplied error is zero? */
3520 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
3521 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
3522 rxi_ConnectionError(conn, errcode);
3523 putConnection(conn);
3526 case RX_PACKET_TYPE_CHALLENGE:
3527 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
3528 putConnection(conn);
3530 case RX_PACKET_TYPE_RESPONSE:
3531 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
3532 putConnection(conn);
3534 case RX_PACKET_TYPE_PARAMS:
3535 case RX_PACKET_TYPE_PARAMS + 1:
3536 case RX_PACKET_TYPE_PARAMS + 2:
3537 /* ignore these packet types for now */
3538 putConnection(conn);
3542 /* Should not reach here, unless the peer is broken: send an
3544 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
3545 MUTEX_ENTER(&conn->conn_data_lock);
3546 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
3547 putConnection(conn);
3548 MUTEX_EXIT(&conn->conn_data_lock);
3553 if (type == RX_SERVER_CONNECTION)
3554 call = rxi_ReceiveServerCall(socket, np, conn);
3556 call = rxi_ReceiveClientCall(np, conn);
3559 putConnection(conn);
3563 MUTEX_ASSERT(&call->lock);
3564 /* Set remote user defined status from packet */
3565 call->remoteStatus = np->header.userStatus;
3567 /* Now do packet type-specific processing */
3568 switch (np->header.type) {
3569 case RX_PACKET_TYPE_DATA:
3570 /* If we're a client, and receiving a response, then all the packets
3571 * we transmitted packets are implicitly acknowledged. */
3572 if (type == RX_CLIENT_CONNECTION && !opr_queue_IsEmpty(&call->tq))
3573 rxi_AckAllInTransmitQueue(call);
3575 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3578 case RX_PACKET_TYPE_ACK:
3579 /* Respond immediately to ack packets requesting acknowledgement
3581 if (np->header.flags & RX_REQUEST_ACK) {
3583 (void)rxi_SendCallAbort(call, 0, 1, 0);
3585 (void)rxi_SendAck(call, 0, np->header.serial,
3586 RX_ACK_PING_RESPONSE, 1);
3588 np = rxi_ReceiveAckPacket(call, np, 1);
3590 case RX_PACKET_TYPE_ABORT: {
3591 /* An abort packet: reset the call, passing the error up to the user. */
3592 /* What if error is zero? */
3593 /* What if the error is -1? the application will treat it as a timeout. */
3594 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3595 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3596 rxi_CallError(call, errdata);
3597 MUTEX_EXIT(&call->lock);
3598 putConnection(conn);
3599 return np; /* xmitting; drop packet */
3601 case RX_PACKET_TYPE_BUSY:
3602 /* Mostly ignore BUSY packets. We will update lastReceiveTime below,
3603 * so we don't think the endpoint is completely dead, but otherwise
3604 * just act as if we never saw anything. If all we get are BUSY packets
3605 * back, then we will eventually error out with RX_CALL_TIMEOUT if the
3606 * connection is configured with idle/hard timeouts. */
3609 case RX_PACKET_TYPE_ACKALL:
3610 /* All packets acknowledged, so we can drop all packets previously
3611 * readied for sending */
3612 rxi_AckAllInTransmitQueue(call);
3615 /* Should not reach here, unless the peer is broken: send an abort
3617 rxi_CallError(call, RX_PROTOCOL_ERROR);
3618 np = rxi_SendCallAbort(call, np, 1, 0);
3621 /* Note when this last legitimate packet was received, for keep-alive
3622 * processing. Note, we delay getting the time until now in the hope that
3623 * the packet will be delivered to the user before any get time is required
3624 * (if not, then the time won't actually be re-evaluated here). */
3625 call->lastReceiveTime = clock_Sec();
3626 MUTEX_EXIT(&call->lock);
3627 putConnection(conn);
3631 /* return true if this is an "interesting" connection from the point of view
3632 of someone trying to debug the system */
3634 rxi_IsConnInteresting(struct rx_connection *aconn)
3637 struct rx_call *tcall;
3639 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3642 for (i = 0; i < RX_MAXCALLS; i++) {
3643 tcall = aconn->call[i];
3645 if ((tcall->state == RX_STATE_PRECALL)
3646 || (tcall->state == RX_STATE_ACTIVE))
3648 if ((tcall->app.mode == RX_MODE_SENDING)
3649 || (tcall->app.mode == RX_MODE_RECEIVING))
3657 /* if this is one of the last few packets AND it wouldn't be used by the
3658 receiving call to immediately satisfy a read request, then drop it on
3659 the floor, since accepting it might prevent a lock-holding thread from
3660 making progress in its reading. If a call has been cleared while in
3661 the precall state then ignore all subsequent packets until the call
3662 is assigned to a thread. */
3665 TooLow(struct rx_packet *ap, struct rx_call *acall)
3669 MUTEX_ENTER(&rx_quota_mutex);
3670 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3671 && (acall->state == RX_STATE_PRECALL))
3672 || ((rx_nFreePackets < rxi_dataQuota + 2)
3673 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3674 && (acall->flags & RX_CALL_READER_WAIT)))) {
3677 MUTEX_EXIT(&rx_quota_mutex);
3683 * Clear the attach wait flag on a connection and proceed.
3685 * Any processing waiting for a connection to be attached should be
3686 * unblocked. We clear the flag and do any other needed tasks.
3689 * the conn to unmark waiting for attach
3691 * @pre conn's conn_data_lock must be locked before calling this function
3695 rxi_ConnClearAttachWait(struct rx_connection *conn)
3697 /* Indicate that rxi_CheckReachEvent is no longer running by
3698 * clearing the flag. Must be atomic under conn_data_lock to
3699 * avoid a new call slipping by: rxi_CheckConnReach holds
3700 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3702 conn->flags &= ~RX_CONN_ATTACHWAIT;
3703 if (conn->flags & RX_CONN_NAT_PING) {
3704 conn->flags &= ~RX_CONN_NAT_PING;
3705 rxi_ScheduleNatKeepAliveEvent(conn);
3710 * Event handler function for connection-specific events for checking
3711 * reachability. Also called directly from main code with |event| == NULL
3712 * in order to trigger the initial reachability check.
3714 * When |event| == NULL, must be called with the connection data lock held,
3715 * but returns with the lock unlocked.
3718 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2, int dummy)
3720 struct rx_connection *conn = arg1;
3721 struct rx_call *acall = arg2;
3722 struct rx_call *call = acall;
3723 struct clock when, now;
3727 MUTEX_ENTER(&conn->conn_data_lock);
3729 MUTEX_ASSERT(&conn->conn_data_lock);
3731 if (event != NULL && event == conn->checkReachEvent)
3732 rxevent_Put(&conn->checkReachEvent);
3733 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3734 MUTEX_EXIT(&conn->conn_data_lock);
3738 MUTEX_ENTER(&conn->conn_call_lock);
3739 MUTEX_ENTER(&conn->conn_data_lock);
3740 for (i = 0; i < RX_MAXCALLS; i++) {
3741 struct rx_call *tc = conn->call[i];
3742 if (tc && tc->state == RX_STATE_PRECALL) {
3748 rxi_ConnClearAttachWait(conn);
3749 MUTEX_EXIT(&conn->conn_data_lock);
3750 MUTEX_EXIT(&conn->conn_call_lock);
3755 MUTEX_ENTER(&call->lock);
3756 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3758 MUTEX_EXIT(&call->lock);
3760 clock_GetTime(&now);
3762 when.sec += RX_CHECKREACH_TIMEOUT;
3763 MUTEX_ENTER(&conn->conn_data_lock);
3764 if (!conn->checkReachEvent) {
3765 rx_GetConnection(conn);
3766 conn->checkReachEvent = rxevent_Post(&when, &now,
3767 rxi_CheckReachEvent, conn,
3770 MUTEX_EXIT(&conn->conn_data_lock);
3773 /* If fired as an event handler, drop our refcount on the connection. */
3775 putConnection(conn);
3779 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3781 struct rx_service *service = conn->service;
3782 struct rx_peer *peer = conn->peer;
3783 afs_uint32 now, lastReach;
3785 if (service->checkReach == 0)
3789 MUTEX_ENTER(&peer->peer_lock);
3790 lastReach = peer->lastReachTime;
3791 MUTEX_EXIT(&peer->peer_lock);
3792 if (now - lastReach < RX_CHECKREACH_TTL)
3795 MUTEX_ENTER(&conn->conn_data_lock);
3796 if (conn->flags & RX_CONN_ATTACHWAIT) {
3797 MUTEX_EXIT(&conn->conn_data_lock);
3800 conn->flags |= RX_CONN_ATTACHWAIT;
3801 if (conn->checkReachEvent == NULL) {
3802 /* rxi_CheckReachEvent(NULL, ...) will drop the lock. */
3803 rxi_CheckReachEvent(NULL, conn, call, 0);
3805 MUTEX_EXIT(&conn->conn_data_lock);
3811 /* try to attach call, if authentication is complete */
3813 TryAttach(struct rx_call *acall, osi_socket socket,
3814 int *tnop, struct rx_call **newcallp,
3815 int reachOverride, int istack)
3817 struct rx_connection *conn = acall->conn;
3819 if (conn->type == RX_SERVER_CONNECTION
3820 && acall->state == RX_STATE_PRECALL) {
3821 /* Don't attach until we have any req'd. authentication. */
3822 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3823 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3824 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3825 /* Note: this does not necessarily succeed; there
3826 * may not any proc available
3830 code = rxi_ChallengeOn(acall->conn);
3833 * Ideally we would rxi_ConnectionError here, but doing that is
3834 * difficult, because some callers may have locked 'call',
3835 * _and_ another call on the same conn. So we cannot
3836 * rxi_ConnectionError, since that needs to lock every call on
3837 * the conn. But we can at least abort the call we have.
3839 rxi_CallError(acall, code);
3840 rxi_SendCallAbort(acall, NULL, istack, 0);
3846 /* A data packet has been received off the interface. This packet is
3847 * appropriate to the call (the call is in the right state, etc.). This
3848 * routine can return a packet to the caller, for re-use */
3850 static struct rx_packet *
3851 rxi_ReceiveDataPacket(struct rx_call *call,
3852 struct rx_packet *np, int istack,
3853 osi_socket socket, afs_uint32 host, u_short port,
3854 int *tnop, struct rx_call **newcallp)
3856 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3861 afs_uint32 serial=0, flags=0;
3863 struct rx_packet *tnp;
3864 if (rx_stats_active)
3865 rx_atomic_inc(&rx_stats.dataPacketsRead);
3868 /* If there are no packet buffers, drop this new packet, unless we can find
3869 * packet buffers from inactive calls */
3871 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3872 MUTEX_ENTER(&rx_freePktQ_lock);
3873 rxi_NeedMorePackets = TRUE;
3874 MUTEX_EXIT(&rx_freePktQ_lock);
3875 if (rx_stats_active)
3876 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3877 rxi_calltrace(RX_TRACE_DROP, call);
3878 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems\n", np));
3879 /* We used to clear the receive queue here, in an attempt to free
3880 * packets. However this is unsafe if the queue has received a
3881 * soft ACK for the final packet */
3882 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
3888 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3889 * packet is one of several packets transmitted as a single
3890 * datagram. Do not send any soft or hard acks until all packets
3891 * in a jumbogram have been processed. Send negative acks right away.
3893 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3894 /* tnp is non-null when there are more packets in the
3895 * current jumbo gram */
3902 seq = np->header.seq;
3903 serial = np->header.serial;
3904 flags = np->header.flags;
3906 /* If the call is in an error state, send an abort message */
3908 return rxi_SendCallAbort(call, np, istack, 0);
3910 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3911 * AFS 3.5 jumbogram. */
3912 if (flags & RX_JUMBO_PACKET) {
3913 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3918 if (np->header.spare != 0) {
3919 MUTEX_ENTER(&call->conn->conn_data_lock);
3920 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3921 MUTEX_EXIT(&call->conn->conn_data_lock);
3924 /* The usual case is that this is the expected next packet */
3925 if (seq == call->rnext) {
3927 /* Check to make sure it is not a duplicate of one already queued */
3928 if (!opr_queue_IsEmpty(&call->rq)
3929 && opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq == seq) {
3930 if (rx_stats_active)
3931 rx_atomic_inc(&rx_stats.dupPacketsRead);
3932 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate\n", np));
3933 rxi_CancelDelayedAckEvent(call);
3934 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3940 /* It's the next packet. Stick it on the receive queue
3941 * for this call. Set newPackets to make sure we wake
3942 * the reader once all packets have been processed */
3943 #ifdef RX_TRACK_PACKETS
3944 np->flags |= RX_PKTFLAG_RQ;
3946 opr_queue_Prepend(&call->rq, &np->entry);
3947 #ifdef RXDEBUG_PACKET
3949 #endif /* RXDEBUG_PACKET */
3951 np = NULL; /* We can't use this anymore */
3954 /* If an ack is requested then set a flag to make sure we
3955 * send an acknowledgement for this packet */
3956 if (flags & RX_REQUEST_ACK) {
3957 ackNeeded = RX_ACK_REQUESTED;
3960 /* Keep track of whether we have received the last packet */
3961 if (flags & RX_LAST_PACKET) {
3962 call->flags |= RX_CALL_HAVE_LAST;
3966 /* Check whether we have all of the packets for this call */
3967 if (call->flags & RX_CALL_HAVE_LAST) {
3968 afs_uint32 tseq; /* temporary sequence number */
3969 struct opr_queue *cursor;
3971 for (tseq = seq, opr_queue_Scan(&call->rq, cursor)) {
3972 struct rx_packet *tp;
3974 tp = opr_queue_Entry(cursor, struct rx_packet, entry);
3975 if (tseq != tp->header.seq)
3977 if (tp->header.flags & RX_LAST_PACKET) {
3978 call->flags |= RX_CALL_RECEIVE_DONE;
3985 /* Provide asynchronous notification for those who want it
3986 * (e.g. multi rx) */
3987 if (call->arrivalProc) {
3988 (*call->arrivalProc) (call, call->arrivalProcHandle,
3989 call->arrivalProcArg);
3990 call->arrivalProc = NULL;
3993 /* Update last packet received */
3996 /* If there is no server process serving this call, grab
3997 * one, if available. We only need to do this once. If a
3998 * server thread is available, this thread becomes a server
3999 * thread and the server thread becomes a listener thread. */
4001 TryAttach(call, socket, tnop, newcallp, 0, istack);
4004 /* This is not the expected next packet. */
4006 /* Determine whether this is a new or old packet, and if it's
4007 * a new one, whether it fits into the current receive window.
4008 * Also figure out whether the packet was delivered in sequence.
4009 * We use the prev variable to determine whether the new packet
4010 * is the successor of its immediate predecessor in the
4011 * receive queue, and the missing flag to determine whether
4012 * any of this packets predecessors are missing. */
4014 afs_uint32 prev; /* "Previous packet" sequence number */
4015 struct opr_queue *cursor;
4016 int missing; /* Are any predecessors missing? */
4018 /* If the new packet's sequence number has been sent to the
4019 * application already, then this is a duplicate */
4020 if (seq < call->rnext) {
4021 if (rx_stats_active)
4022 rx_atomic_inc(&rx_stats.dupPacketsRead);
4023 rxi_CancelDelayedAckEvent(call);
4024 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
4030 /* If the sequence number is greater than what can be
4031 * accomodated by the current window, then send a negative
4032 * acknowledge and drop the packet */
4033 if ((call->rnext + call->rwind) <= seq) {
4034 rxi_CancelDelayedAckEvent(call);
4035 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
4042 /* Look for the packet in the queue of old received packets */
4043 prev = call->rnext - 1;
4045 for (opr_queue_Scan(&call->rq, cursor)) {
4046 struct rx_packet *tp
4047 = opr_queue_Entry(cursor, struct rx_packet, entry);
4049 /*Check for duplicate packet */
4050 if (seq == tp->header.seq) {
4051 if (rx_stats_active)
4052 rx_atomic_inc(&rx_stats.dupPacketsRead);
4053 rxi_CancelDelayedAckEvent(call);
4054 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
4060 /* If we find a higher sequence packet, break out and
4061 * insert the new packet here. */
4062 if (seq < tp->header.seq)
4064 /* Check for missing packet */
4065 if (tp->header.seq != prev + 1) {
4069 prev = tp->header.seq;
4072 /* Keep track of whether we have received the last packet. */
4073 if (flags & RX_LAST_PACKET) {
4074 call->flags |= RX_CALL_HAVE_LAST;
4077 /* It's within the window: add it to the the receive queue.
4078 * tp is left by the previous loop either pointing at the
4079 * packet before which to insert the new packet, or at the
4080 * queue head if the queue is empty or the packet should be
4082 #ifdef RX_TRACK_PACKETS
4083 np->flags |= RX_PKTFLAG_RQ;
4085 #ifdef RXDEBUG_PACKET
4087 #endif /* RXDEBUG_PACKET */
4088 opr_queue_InsertBefore(cursor, &np->entry);
4092 /* Check whether we have all of the packets for this call */
4093 if ((call->flags & RX_CALL_HAVE_LAST)
4094 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
4095 afs_uint32 tseq; /* temporary sequence number */
4098 for (opr_queue_Scan(&call->rq, cursor)) {
4099 struct rx_packet *tp
4100 = opr_queue_Entry(cursor, struct rx_packet, entry);
4101 if (tseq != tp->header.seq)
4103 if (tp->header.flags & RX_LAST_PACKET) {
4104 call->flags |= RX_CALL_RECEIVE_DONE;
4111 /* We need to send an ack of the packet is out of sequence,
4112 * or if an ack was requested by the peer. */
4113 if (seq != prev + 1 || missing) {
4114 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
4115 } else if (flags & RX_REQUEST_ACK) {
4116 ackNeeded = RX_ACK_REQUESTED;
4119 /* Acknowledge the last packet for each call */
4120 if (flags & RX_LAST_PACKET) {
4131 * If the receiver is waiting for an iovec, fill the iovec
4132 * using the data from the receive queue */
4133 if (call->flags & RX_CALL_IOVEC_WAIT) {
4134 didHardAck = rxi_FillReadVec(call, serial);
4135 /* the call may have been aborted */
4144 /* Wakeup the reader if any */
4145 if ((call->flags & RX_CALL_READER_WAIT)
4146 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
4147 || (call->iovNext >= call->iovMax)
4148 || (call->flags & RX_CALL_RECEIVE_DONE))) {
4149 call->flags &= ~RX_CALL_READER_WAIT;
4150 #ifdef RX_ENABLE_LOCKS
4151 CV_BROADCAST(&call->cv_rq);
4153 osi_rxWakeup(&call->rq);
4159 * Send an ack when requested by the peer, or once every
4160 * rxi_SoftAckRate packets until the last packet has been
4161 * received. Always send a soft ack for the last packet in
4162 * the server's reply. */
4164 rxi_CancelDelayedAckEvent(call);
4165 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
4166 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
4167 rxi_CancelDelayedAckEvent(call);
4168 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
4169 } else if (call->nSoftAcks) {
4170 if (haveLast && !(flags & RX_CLIENT_INITIATED))
4171 rxi_PostDelayedAckEvent(call, &rx_lastAckDelay);
4173 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
4174 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
4175 rxi_CancelDelayedAckEvent(call);
4182 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall,
4185 struct rx_peer *peer = conn->peer;
4187 MUTEX_ENTER(&peer->peer_lock);
4188 peer->lastReachTime = clock_Sec();
4189 MUTEX_EXIT(&peer->peer_lock);
4191 MUTEX_ENTER(&conn->conn_data_lock);
4192 if (conn->flags & RX_CONN_ATTACHWAIT) {
4195 rxi_ConnClearAttachWait(conn);
4196 MUTEX_EXIT(&conn->conn_data_lock);
4198 for (i = 0; i < RX_MAXCALLS; i++) {
4199 struct rx_call *call = conn->call[i];
4202 MUTEX_ENTER(&call->lock);
4203 /* tnop can be null if newcallp is null */
4204 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1, istack);
4206 MUTEX_EXIT(&call->lock);
4210 MUTEX_EXIT(&conn->conn_data_lock);
4213 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
4215 rx_ack_reason(int reason)
4218 case RX_ACK_REQUESTED:
4220 case RX_ACK_DUPLICATE:
4222 case RX_ACK_OUT_OF_SEQUENCE:
4224 case RX_ACK_EXCEEDS_WINDOW:
4226 case RX_ACK_NOSPACE:
4230 case RX_ACK_PING_RESPONSE:
4243 /* The real smarts of the whole thing. */
4244 static struct rx_packet *
4245 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
4248 struct rx_ackPacket *ap;
4250 struct rx_packet *tp;
4251 struct rx_connection *conn = call->conn;
4252 struct rx_peer *peer = conn->peer;
4253 struct opr_queue *cursor;
4254 struct clock now; /* Current time, for RTT calculations */
4262 int newAckCount = 0;
4263 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
4264 int pktsize = 0; /* Set if we need to update the peer mtu */
4265 int conn_data_locked = 0;
4267 if (rx_stats_active)
4268 rx_atomic_inc(&rx_stats.ackPacketsRead);
4269 ap = (struct rx_ackPacket *)rx_DataOf(np);
4270 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
4272 return np; /* truncated ack packet */
4274 /* depends on ack packet struct */
4275 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
4276 first = ntohl(ap->firstPacket);
4277 prev = ntohl(ap->previousPacket);
4278 serial = ntohl(ap->serial);
4281 * Ignore ack packets received out of order while protecting
4282 * against peers that set the previousPacket field to a packet
4283 * serial number instead of a sequence number.
4285 if (first < call->tfirst ||
4286 (first == call->tfirst && prev < call->tprev && prev < call->tfirst
4293 if (np->header.flags & RX_SLOW_START_OK) {
4294 call->flags |= RX_CALL_SLOW_START_OK;
4297 if (ap->reason == RX_ACK_PING_RESPONSE)
4298 rxi_UpdatePeerReach(conn, call, istack);
4300 if (conn->lastPacketSizeSeq) {
4301 MUTEX_ENTER(&conn->conn_data_lock);
4302 conn_data_locked = 1;
4303 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
4304 pktsize = conn->lastPacketSize;
4305 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
4308 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
4309 if (!conn_data_locked) {
4310 MUTEX_ENTER(&conn->conn_data_lock);
4311 conn_data_locked = 1;
4313 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
4314 /* process mtu ping ack */
4315 pktsize = conn->lastPingSize;
4316 conn->lastPingSizeSer = conn->lastPingSize = 0;
4320 if (conn_data_locked) {
4321 MUTEX_EXIT(&conn->conn_data_lock);
4322 conn_data_locked = 0;
4326 if (rxdebug_active) {
4330 len = _snprintf(msg, sizeof(msg),
4331 "tid[%d] RACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
4332 GetCurrentThreadId(), rx_ack_reason(ap->reason),
4333 ntohl(ap->serial), ntohl(ap->previousPacket),
4334 (unsigned int)np->header.seq, ntohl(ap->firstPacket),
4335 ap->nAcks, ntohs(ap->bufferSpace) );
4339 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
4340 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4344 OutputDebugString(msg);
4346 #else /* AFS_NT40_ENV */
4349 "RACK: reason %x previous %u seq %u serial %u first %u",
4350 ap->reason, ntohl(ap->previousPacket),
4351 (unsigned int)np->header.seq, (unsigned int)serial,
4352 ntohl(ap->firstPacket));
4355 for (offset = 0; offset < nAcks; offset++)
4356 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4361 #endif /* AFS_NT40_ENV */
4364 MUTEX_ENTER(&peer->peer_lock);
4367 * Start somewhere. Can't assume we can send what we can receive,
4368 * but we are clearly receiving.
4370 if (!peer->maxPacketSize)
4371 peer->maxPacketSize = RX_MIN_PACKET_SIZE - RX_HEADER_SIZE;
4373 if (pktsize > peer->maxPacketSize) {
4374 peer->maxPacketSize = pktsize;
4375 if ((pktsize + RX_HEADER_SIZE > peer->ifMTU)) {
4376 peer->ifMTU = pktsize + RX_HEADER_SIZE;
4377 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4378 rxi_ScheduleGrowMTUEvent(call, 1);
4383 clock_GetTime(&now);
4385 /* The transmit queue splits into 4 sections.
4387 * The first section is packets which have now been acknowledged
4388 * by a window size change in the ack. These have reached the
4389 * application layer, and may be discarded. These are packets
4390 * with sequence numbers < ap->firstPacket.
4392 * The second section is packets which have sequence numbers in
4393 * the range ap->firstPacket to ap->firstPacket + ap->nAcks. The
4394 * contents of the packet's ack array determines whether these
4395 * packets are acknowledged or not.
4397 * The third section is packets which fall above the range
4398 * addressed in the ack packet. These have not yet been received
4401 * The four section is packets which have not yet been transmitted.
4402 * These packets will have a header.serial of 0.
4405 /* First section - implicitly acknowledged packets that can be
4409 tp = opr_queue_First(&call->tq, struct rx_packet, entry);
4410 while(!opr_queue_IsEnd(&call->tq, &tp->entry) && tp->header.seq < first) {
4411 struct rx_packet *next;
4413 next = opr_queue_Next(&tp->entry, struct rx_packet, entry);
4414 call->tfirst = tp->header.seq + 1;
4416 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4418 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4421 #ifdef RX_ENABLE_LOCKS
4422 /* XXX Hack. Because we have to release the global call lock when sending
4423 * packets (osi_NetSend) we drop all acks while we're traversing the tq
4424 * in rxi_Start sending packets out because packets may move to the
4425 * freePacketQueue as result of being here! So we drop these packets until
4426 * we're safely out of the traversing. Really ugly!
4427 * To make it even uglier, if we're using fine grain locking, we can
4428 * set the ack bits in the packets and have rxi_Start remove the packets
4429 * when it's done transmitting.
4431 if (call->flags & RX_CALL_TQ_BUSY) {
4432 tp->flags |= RX_PKTFLAG_ACKED;
4433 call->flags |= RX_CALL_TQ_SOME_ACKED;
4435 #endif /* RX_ENABLE_LOCKS */
4437 opr_queue_Remove(&tp->entry);
4438 #ifdef RX_TRACK_PACKETS
4439 tp->flags &= ~RX_PKTFLAG_TQ;
4441 #ifdef RXDEBUG_PACKET
4443 #endif /* RXDEBUG_PACKET */
4444 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4449 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
4451 /* Second section of the queue - packets for which we are receiving
4454 * Go through the explicit acks/nacks and record the results in
4455 * the waiting packets. These are packets that can't be released
4456 * yet, even with a positive acknowledge. This positive
4457 * acknowledge only means the packet has been received by the
4458 * peer, not that it will be retained long enough to be sent to
4459 * the peer's upper level. In addition, reset the transmit timers
4460 * of any missing packets (those packets that must be missing
4461 * because this packet was out of sequence) */
4463 call->nSoftAcked = 0;
4465 while (!opr_queue_IsEnd(&call->tq, &tp->entry)
4466 && tp->header.seq < first + nAcks) {
4467 /* Set the acknowledge flag per packet based on the
4468 * information in the ack packet. An acknowlegded packet can
4469 * be downgraded when the server has discarded a packet it
4470 * soacked previously, or when an ack packet is received
4471 * out of sequence. */
4472 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4473 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4475 tp->flags |= RX_PKTFLAG_ACKED;
4476 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4483 } else /* RX_ACK_TYPE_NACK */ {
4484 tp->flags &= ~RX_PKTFLAG_ACKED;
4488 tp = opr_queue_Next(&tp->entry, struct rx_packet, entry);
4491 /* We don't need to take any action with the 3rd or 4th section in the
4492 * queue - they're not addressed by the contents of this ACK packet.
4495 /* if the ack packet has a receivelen field hanging off it,
4496 * update our state */
4497 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4500 /* If the ack packet has a "recommended" size that is less than
4501 * what I am using now, reduce my size to match */
4502 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4503 (int)sizeof(afs_int32), &tSize);
4504 tSize = (afs_uint32) ntohl(tSize);
4505 if (tSize > RX_MAX_PACKET_SIZE)
4506 tSize = RX_MAX_PACKET_SIZE;
4507 if (tSize < RX_MIN_PACKET_SIZE)
4508 tSize = RX_MIN_PACKET_SIZE;
4509 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4511 /* Get the maximum packet size to send to this peer */
4512 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4514 tSize = (afs_uint32) ntohl(tSize);
4515 if (tSize > RX_MAX_PACKET_SIZE)
4516 tSize = RX_MAX_PACKET_SIZE;
4517 if (tSize < RX_MIN_PACKET_SIZE)
4518 tSize = RX_MIN_PACKET_SIZE;
4519 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4520 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4522 /* sanity check - peer might have restarted with different params.
4523 * If peer says "send less", dammit, send less... Peer should never
4524 * be unable to accept packets of the size that prior AFS versions would
4525 * send without asking. */
4526 if (peer->maxMTU != tSize) {
4527 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4529 peer->maxMTU = tSize;
4530 peer->MTU = MIN(tSize, peer->MTU);
4531 call->MTU = MIN(call->MTU, tSize);
4534 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4537 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4538 (int)sizeof(afs_int32), &tSize);
4539 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4542 if (tSize >= rx_maxSendWindow)
4543 tSize = rx_maxSendWindow;
4544 if (tSize < call->twind) { /* smaller than our send */
4545 call->twind = tSize; /* window, we must send less... */
4546 call->ssthresh = MIN(call->twind, call->ssthresh);
4547 call->conn->twind[call->channel] = call->twind;
4550 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4551 * network MTU confused with the loopback MTU. Calculate the
4552 * maximum MTU here for use in the slow start code below.
4554 /* Did peer restart with older RX version? */
4555 if (peer->maxDgramPackets > 1) {
4556 peer->maxDgramPackets = 1;
4558 } else if (np->length >=
4559 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4562 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4563 sizeof(afs_int32), &tSize);
4564 tSize = (afs_uint32) ntohl(tSize);
4567 if (tSize >= rx_maxSendWindow)
4568 tSize = rx_maxSendWindow;
4570 * As of AFS 3.5 we set the send window to match the receive window.
4572 if (tSize < call->twind) {
4573 call->twind = tSize;
4574 call->conn->twind[call->channel] = call->twind;
4575 call->ssthresh = MIN(call->twind, call->ssthresh);
4576 } else if (tSize > call->twind) {
4577 call->twind = tSize;
4578 call->conn->twind[call->channel] = call->twind;
4582 * As of AFS 3.5, a jumbogram is more than one fixed size
4583 * packet transmitted in a single UDP datagram. If the remote
4584 * MTU is smaller than our local MTU then never send a datagram
4585 * larger than the natural MTU.
4588 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4589 (int)sizeof(afs_int32), &tSize);
4590 maxDgramPackets = (afs_uint32) ntohl(tSize);
4591 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4593 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4594 if (maxDgramPackets > 1) {
4595 peer->maxDgramPackets = maxDgramPackets;
4596 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4598 peer->maxDgramPackets = 1;
4599 call->MTU = peer->natMTU;
4601 } else if (peer->maxDgramPackets > 1) {
4602 /* Restarted with lower version of RX */
4603 peer->maxDgramPackets = 1;
4605 } else if (peer->maxDgramPackets > 1
4606 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4607 /* Restarted with lower version of RX */
4608 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4609 peer->natMTU = OLD_MAX_PACKET_SIZE;
4610 peer->MTU = OLD_MAX_PACKET_SIZE;
4611 peer->maxDgramPackets = 1;
4612 peer->nDgramPackets = 1;
4614 call->MTU = OLD_MAX_PACKET_SIZE;
4617 /* If the window has been extended by this acknowledge packet,
4618 * then wakeup a sender waiting in alloc for window space, or try
4619 * sending packets now, if he's been sitting on packets due to
4620 * lack of window space */
4621 if (call->tnext < (call->tfirst + call->twind)) {
4622 #ifdef RX_ENABLE_LOCKS
4623 CV_SIGNAL(&call->cv_twind);
4625 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4626 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4627 osi_rxWakeup(&call->twind);
4630 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4631 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4637 * Calculate how many datagrams were successfully received after
4638 * the first missing packet and adjust the negative ack counter
4643 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4644 if (call->nNacks < nNacked) {
4645 call->nNacks = nNacked;
4648 call->nAcks += newAckCount;
4652 /* If the packet contained new acknowledgements, rather than just
4653 * being a duplicate of one we have previously seen, then we can restart
4656 if (newAckCount > 0)
4657 rxi_rto_packet_acked(call, istack);
4659 if (call->flags & RX_CALL_FAST_RECOVER) {
4660 if (newAckCount == 0) {
4661 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4663 call->flags &= ~RX_CALL_FAST_RECOVER;
4664 call->cwind = call->nextCwind;
4665 call->nextCwind = 0;
4668 call->nCwindAcks = 0;
4669 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4670 /* Three negative acks in a row trigger congestion recovery */
4671 call->flags |= RX_CALL_FAST_RECOVER;
4672 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4674 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4675 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4676 call->nextCwind = call->ssthresh;
4679 peer->MTU = call->MTU;
4680 peer->cwind = call->nextCwind;
4681 peer->nDgramPackets = call->nDgramPackets;
4683 call->congestSeq = peer->congestSeq;
4685 /* Reset the resend times on the packets that were nacked
4686 * so we will retransmit as soon as the window permits
4690 for (opr_queue_ScanBackwards(&call->tq, cursor)) {
4691 struct rx_packet *tp =
4692 opr_queue_Entry(cursor, struct rx_packet, entry);
4694 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4695 tp->flags &= ~RX_PKTFLAG_SENT;
4697 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4702 /* If cwind is smaller than ssthresh, then increase
4703 * the window one packet for each ack we receive (exponential
4705 * If cwind is greater than or equal to ssthresh then increase
4706 * the congestion window by one packet for each cwind acks we
4707 * receive (linear growth). */
4708 if (call->cwind < call->ssthresh) {
4710 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4711 call->nCwindAcks = 0;
4713 call->nCwindAcks += newAckCount;
4714 if (call->nCwindAcks >= call->cwind) {
4715 call->nCwindAcks = 0;
4716 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4720 * If we have received several acknowledgements in a row then
4721 * it is time to increase the size of our datagrams
4723 if ((int)call->nAcks > rx_nDgramThreshold) {
4724 if (peer->maxDgramPackets > 1) {
4725 if (call->nDgramPackets < peer->maxDgramPackets) {
4726 call->nDgramPackets++;
4728 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4729 } else if (call->MTU < peer->maxMTU) {
4730 /* don't upgrade if we can't handle it */
4731 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4732 call->MTU = peer->ifMTU;
4734 call->MTU += peer->natMTU;
4735 call->MTU = MIN(call->MTU, peer->maxMTU);
4742 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4744 /* Servers need to hold the call until all response packets have
4745 * been acknowledged. Soft acks are good enough since clients
4746 * are not allowed to clear their receive queues. */
4747 if (call->state == RX_STATE_HOLD
4748 && call->tfirst + call->nSoftAcked >= call->tnext) {
4749 call->state = RX_STATE_DALLY;
4750 rxi_ClearTransmitQueue(call, 0);
4751 rxi_CancelKeepAliveEvent(call);
4752 } else if (!opr_queue_IsEmpty(&call->tq)) {
4753 rxi_Start(call, istack);
4759 * Schedule a connection abort to be sent after some delay.
4761 * @param[in] conn The connection to send the abort on.
4762 * @param[in] msec The number of milliseconds to wait before sending.
4764 * @pre conn_data_lock must be held
4767 rxi_SendConnectionAbortLater(struct rx_connection *conn, int msec)
4769 struct clock when, now;
4771 MUTEX_ASSERT(&conn->conn_data_lock);
4775 if (!conn->delayedAbortEvent) {
4776 clock_GetTime(&now);
4778 clock_Addmsec(&when, msec);
4779 rx_GetConnection(conn);
4780 conn->delayedAbortEvent =
4781 rxevent_Post(&when, &now, rxi_SendDelayedConnAbort, conn, NULL, 0);
4785 /* Received a response to a challenge packet */
4786 static struct rx_packet *
4787 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4788 struct rx_packet *np, int istack)
4792 /* Ignore the packet if we're the client */
4793 if (conn->type == RX_CLIENT_CONNECTION)
4796 /* If already authenticated, ignore the packet (it's probably a retry) */
4797 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4800 if (!conn->securityChallengeSent) {
4801 /* We've never sent out a challenge for this connection, so this
4802 * response cannot possibly be correct; ignore it. This can happen
4803 * if we sent a challenge to the client, then we were restarted, and
4804 * then the client sent us a response. If we ignore the response, the
4805 * client will eventually resend a data packet, causing us to send a
4806 * new challenge and the client to send a new response. */
4810 /* Otherwise, have the security object evaluate the response packet */
4811 error = RXS_CheckResponse(conn->securityObject, conn, np);
4813 /* If the response is invalid, reset the connection, sending
4814 * an abort to the peer. Send the abort with a 1 second delay,
4815 * to avoid a peer hammering us by constantly recreating a
4816 * connection with bad credentials. */
4817 rxi_ConnectionError(conn, error);
4818 MUTEX_ENTER(&conn->conn_data_lock);
4819 rxi_SendConnectionAbortLater(conn, 1000);
4820 MUTEX_EXIT(&conn->conn_data_lock);
4823 /* If the response is valid, any calls waiting to attach
4824 * servers can now do so */
4827 for (i = 0; i < RX_MAXCALLS; i++) {
4828 struct rx_call *call = conn->call[i];
4830 MUTEX_ENTER(&call->lock);
4831 if (call->state == RX_STATE_PRECALL)
4832 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4833 /* tnop can be null if newcallp is null */
4834 MUTEX_EXIT(&call->lock);
4838 /* Update the peer reachability information, just in case
4839 * some calls went into attach-wait while we were waiting
4840 * for authentication..
4842 rxi_UpdatePeerReach(conn, NULL, istack);
4847 /* A client has received an authentication challenge: the security
4848 * object is asked to cough up a respectable response packet to send
4849 * back to the server. The server is responsible for retrying the
4850 * challenge if it fails to get a response. */
4852 static struct rx_packet *
4853 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4854 struct rx_packet *np, int istack)
4858 /* Ignore the challenge if we're the server */
4859 if (conn->type == RX_SERVER_CONNECTION)
4862 /* Ignore the challenge if the connection is otherwise idle; someone's
4863 * trying to use us as an oracle. */
4864 if (!rxi_HasActiveCalls(conn))
4867 /* Send the security object the challenge packet. It is expected to fill
4868 * in the response. */
4869 error = RXS_GetResponse(conn->securityObject, conn, np);
4871 /* If the security object is unable to return a valid response, reset the
4872 * connection and send an abort to the peer. Otherwise send the response
4873 * packet to the peer connection. */
4875 rxi_ConnectionError(conn, error);
4876 MUTEX_ENTER(&conn->conn_data_lock);
4877 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4878 MUTEX_EXIT(&conn->conn_data_lock);
4880 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4881 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4887 /* Find an available server process to service the current request in
4888 * the given call structure. If one isn't available, queue up this
4889 * call so it eventually gets one */
4891 rxi_AttachServerProc(struct rx_call *call,
4892 osi_socket socket, int *tnop,
4893 struct rx_call **newcallp)
4895 struct rx_serverQueueEntry *sq;
4896 struct rx_service *service = call->conn->service;
4899 /* May already be attached */
4900 if (call->state == RX_STATE_ACTIVE)
4903 MUTEX_ENTER(&rx_serverPool_lock);
4905 haveQuota = QuotaOK(service);
4906 if ((!haveQuota) || opr_queue_IsEmpty(&rx_idleServerQueue)) {
4907 /* If there are no processes available to service this call,
4908 * put the call on the incoming call queue (unless it's
4909 * already on the queue).
4911 #ifdef RX_ENABLE_LOCKS
4913 ReturnToServerPool(service);
4914 #endif /* RX_ENABLE_LOCKS */
4916 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4917 call->flags |= RX_CALL_WAIT_PROC;
4918 rx_atomic_inc(&rx_nWaiting);
4919 rx_atomic_inc(&rx_nWaited);
4920 rxi_calltrace(RX_CALL_ARRIVAL, call);
4921 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4922 opr_queue_Append(&rx_incomingCallQueue, &call->entry);
4925 sq = opr_queue_Last(&rx_idleServerQueue,
4926 struct rx_serverQueueEntry, entry);
4928 /* If hot threads are enabled, and both newcallp and sq->socketp
4929 * are non-null, then this thread will process the call, and the
4930 * idle server thread will start listening on this threads socket.
4932 opr_queue_Remove(&sq->entry);
4934 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4937 *sq->socketp = socket;
4938 clock_GetTime(&call->startTime);
4939 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4943 if (call->flags & RX_CALL_WAIT_PROC) {
4944 /* Conservative: I don't think this should happen */
4945 call->flags &= ~RX_CALL_WAIT_PROC;
4946 rx_atomic_dec(&rx_nWaiting);
4947 if (opr_queue_IsOnQueue(&call->entry)) {
4948 opr_queue_Remove(&call->entry);
4951 call->state = RX_STATE_ACTIVE;
4952 call->app.mode = RX_MODE_RECEIVING;
4953 #ifdef RX_KERNEL_TRACE
4955 int glockOwner = ISAFS_GLOCK();
4958 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4959 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4965 if (call->flags & RX_CALL_CLEARED) {
4966 /* send an ack now to start the packet flow up again */
4967 call->flags &= ~RX_CALL_CLEARED;
4968 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4970 #ifdef RX_ENABLE_LOCKS
4973 service->nRequestsRunning++;
4974 MUTEX_ENTER(&rx_quota_mutex);
4975 if (service->nRequestsRunning <= service->minProcs)
4978 MUTEX_EXIT(&rx_quota_mutex);
4982 MUTEX_EXIT(&rx_serverPool_lock);
4985 /* Delay the sending of an acknowledge event for a short while, while
4986 * a new call is being prepared (in the case of a client) or a reply
4987 * is being prepared (in the case of a server). Rather than sending
4988 * an ack packet, an ACKALL packet is sent. */
4990 rxi_AckAll(struct rx_call *call)
4992 rxi_SendSpecial(call, call->conn, NULL, RX_PACKET_TYPE_ACKALL,
4994 call->flags |= RX_CALL_ACKALL_SENT;
4998 * Event handler for per-call delayed acks.
4999 * Also called synchronously, with |event| == NULL, to send a "delayed" ack
5003 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused1,
5006 struct rx_call *call = arg1;
5007 #ifdef RX_ENABLE_LOCKS
5009 MUTEX_ENTER(&call->lock);
5010 if (event == call->delayedAckEvent)
5011 rxevent_Put(&call->delayedAckEvent);
5013 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
5015 MUTEX_EXIT(&call->lock);
5016 #else /* RX_ENABLE_LOCKS */
5018 rxevent_Put(&call->delayedAckEvent);
5019 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
5020 #endif /* RX_ENABLE_LOCKS */
5021 /* Release the call reference for the event that fired. */
5023 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
5026 #ifdef RX_ENABLE_LOCKS
5027 /* Set ack in all packets in transmit queue. rxi_Start will deal with
5028 * clearing them out.
5031 rxi_SetAcksInTransmitQueue(struct rx_call *call)
5033 struct opr_queue *cursor;
5036 for (opr_queue_Scan(&call->tq, cursor)) {
5038 = opr_queue_Entry(cursor, struct rx_packet, entry);
5040 p->flags |= RX_PKTFLAG_ACKED;
5045 call->flags |= RX_CALL_TQ_CLEARME;
5046 call->flags |= RX_CALL_TQ_SOME_ACKED;
5049 rxi_rto_cancel(call);
5051 call->tfirst = call->tnext;
5052 call->nSoftAcked = 0;
5054 if (call->flags & RX_CALL_FAST_RECOVER) {
5055 call->flags &= ~RX_CALL_FAST_RECOVER;
5056 call->cwind = call->nextCwind;
5057 call->nextCwind = 0;
5060 CV_SIGNAL(&call->cv_twind);
5062 #endif /* RX_ENABLE_LOCKS */
5065 * Acknowledge the whole transmit queue.
5067 * If we're running without locks, or the transmit queue isn't busy, then
5068 * we can just clear the queue now. Otherwise, we have to mark all of the
5069 * packets as acknowledged, and let rxi_Start clear it later on
5072 rxi_AckAllInTransmitQueue(struct rx_call *call)
5074 #ifdef RX_ENABLE_LOCKS
5075 if (call->flags & RX_CALL_TQ_BUSY) {
5076 rxi_SetAcksInTransmitQueue(call);
5080 rxi_ClearTransmitQueue(call, 0);
5082 /* Clear out the transmit queue for the current call (all packets have
5083 * been received by peer) */
5085 rxi_ClearTransmitQueue(struct rx_call *call, int force)
5087 #ifdef RX_ENABLE_LOCKS
5088 struct opr_queue *cursor;
5089 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
5091 for (opr_queue_Scan(&call->tq, cursor)) {
5093 = opr_queue_Entry(cursor, struct rx_packet, entry);
5095 p->flags |= RX_PKTFLAG_ACKED;
5099 call->flags |= RX_CALL_TQ_CLEARME;
5100 call->flags |= RX_CALL_TQ_SOME_ACKED;
5103 #endif /* RX_ENABLE_LOCKS */
5104 #ifdef RXDEBUG_PACKET
5106 #endif /* RXDEBUG_PACKET */
5107 rxi_FreePackets(0, &call->tq);
5108 rxi_WakeUpTransmitQueue(call);
5109 #ifdef RX_ENABLE_LOCKS
5110 call->flags &= ~RX_CALL_TQ_CLEARME;
5114 rxi_rto_cancel(call);
5115 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
5116 call->nSoftAcked = 0;
5118 if (call->flags & RX_CALL_FAST_RECOVER) {
5119 call->flags &= ~RX_CALL_FAST_RECOVER;
5120 call->cwind = call->nextCwind;
5122 #ifdef RX_ENABLE_LOCKS
5123 CV_SIGNAL(&call->cv_twind);
5125 osi_rxWakeup(&call->twind);
5130 rxi_ClearReceiveQueue(struct rx_call *call)
5132 if (!opr_queue_IsEmpty(&call->rq)) {
5135 count = rxi_FreePackets(0, &call->rq);
5136 rx_packetReclaims += count;
5137 #ifdef RXDEBUG_PACKET
5139 if ( call->rqc != 0 )
5140 dpf(("rxi_ClearReceiveQueue call %"AFS_PTR_FMT" rqc %u != 0\n", call, call->rqc));
5142 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
5144 if (call->state == RX_STATE_PRECALL) {
5145 call->flags |= RX_CALL_CLEARED;
5149 /* Send an abort packet for the specified call */
5150 static struct rx_packet *
5151 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
5152 int istack, int force)
5155 struct clock when, now;
5160 /* Clients should never delay abort messages */
5161 if (rx_IsClientConn(call->conn))
5165 * An opcode that has been deprecated or has yet to be implemented is not
5166 * a misbehavior of the client. Do not punish the client by introducing
5169 if (call->error == RXGEN_OPCODE) {
5171 } else if (call->abortCode != call->error) {
5172 call->abortCode = call->error;
5173 call->abortCount = 0;
5176 if (force || rxi_callAbortThreshhold == 0
5177 || call->abortCount < rxi_callAbortThreshhold) {
5178 rxi_CancelDelayedAbortEvent(call);
5179 error = htonl(call->error);
5183 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5184 (char *)&error, sizeof(error), istack);
5185 } else if (!call->delayedAbortEvent) {
5186 clock_GetTime(&now);
5188 clock_Addmsec(&when, rxi_callAbortDelay);
5189 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
5190 call->delayedAbortEvent =
5191 rxevent_Post(&when, &now, rxi_SendDelayedCallAbort, call, 0, 0);
5197 rxi_CancelDelayedAbortEvent(struct rx_call *call)
5199 MUTEX_ASSERT(&call->lock);
5200 if (rxevent_Cancel(&call->delayedAbortEvent))
5201 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
5204 /* Send an abort packet for the specified connection. Packet is an
5205 * optional pointer to a packet that can be used to send the abort.
5206 * Once the number of abort messages reaches the threshhold, an
5207 * event is scheduled to send the abort. Setting the force flag
5208 * overrides sending delayed abort messages.
5210 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
5211 * to send the abort packet.
5214 rxi_SendConnectionAbort(struct rx_connection *conn,
5215 struct rx_packet *packet, int istack, int force)
5222 /* Clients should never delay abort messages */
5223 if (rx_IsClientConn(conn))
5226 if (force || rxi_connAbortThreshhold == 0
5227 || conn->abortCount < rxi_connAbortThreshhold) {
5229 if (rxevent_Cancel(&conn->delayedAbortEvent))
5230 putConnection(conn);
5231 error = htonl(conn->error);
5233 MUTEX_EXIT(&conn->conn_data_lock);
5235 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5236 RX_PACKET_TYPE_ABORT, (char *)&error,
5237 sizeof(error), istack);
5238 MUTEX_ENTER(&conn->conn_data_lock);
5240 rxi_SendConnectionAbortLater(conn, rxi_connAbortDelay);
5245 /* Associate an error all of the calls owned by a connection. Called
5246 * with error non-zero. This is only for really fatal things, like
5247 * bad authentication responses. The connection itself is set in
5248 * error at this point, so that future packets received will be
5251 rxi_ConnectionError(struct rx_connection *conn,
5257 dpf(("rxi_ConnectionError conn %"AFS_PTR_FMT" error %d\n", conn, error));
5259 MUTEX_ENTER(&conn->conn_data_lock);
5260 if (rxevent_Cancel(&conn->challengeEvent))
5261 putConnection(conn);
5262 if (rxevent_Cancel(&conn->natKeepAliveEvent))
5263 putConnection(conn);
5264 if (rxevent_Cancel(&conn->checkReachEvent)) {
5265 conn->flags &= ~(RX_CONN_ATTACHWAIT|RX_CONN_NAT_PING);
5266 putConnection(conn);
5268 MUTEX_EXIT(&conn->conn_data_lock);
5269 for (i = 0; i < RX_MAXCALLS; i++) {
5270 struct rx_call *call = conn->call[i];
5272 MUTEX_ENTER(&call->lock);
5273 rxi_CallError(call, error);
5274 MUTEX_EXIT(&call->lock);
5277 conn->error = error;
5278 if (rx_stats_active)
5279 rx_atomic_inc(&rx_stats.fatalErrors);
5284 * Interrupt an in-progress call with the specified error and wakeup waiters.
5286 * @param[in] call The call to interrupt
5287 * @param[in] error The error code to send to the peer
5290 rx_InterruptCall(struct rx_call *call, afs_int32 error)
5292 MUTEX_ENTER(&call->lock);
5293 rxi_CallError(call, error);
5294 rxi_SendCallAbort(call, NULL, 0, 1);
5295 MUTEX_EXIT(&call->lock);
5299 rxi_CallError(struct rx_call *call, afs_int32 error)
5301 MUTEX_ASSERT(&call->lock);
5302 dpf(("rxi_CallError call %"AFS_PTR_FMT" error %d call->error %d\n", call, error, call->error));
5304 error = call->error;
5306 #ifdef RX_ENABLE_LOCKS
5307 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
5308 rxi_ResetCall(call, 0);
5311 rxi_ResetCall(call, 0);
5313 call->error = error;
5316 /* Reset various fields in a call structure, and wakeup waiting
5317 * processes. Some fields aren't changed: state & mode are not
5318 * touched (these must be set by the caller), and bufptr, nLeft, and
5319 * nFree are not reset, since these fields are manipulated by
5320 * unprotected macros, and may only be reset by non-interrupting code.
5324 rxi_ResetCall(struct rx_call *call, int newcall)
5327 struct rx_peer *peer;
5328 struct rx_packet *packet;
5330 MUTEX_ASSERT(&call->lock);
5331 dpf(("rxi_ResetCall(call %"AFS_PTR_FMT", newcall %d)\n", call, newcall));
5333 /* Notify anyone who is waiting for asynchronous packet arrival */
5334 if (call->arrivalProc) {
5335 (*call->arrivalProc) (call, call->arrivalProcHandle,
5336 call->arrivalProcArg);
5337 call->arrivalProc = NULL;
5341 rxi_CancelGrowMTUEvent(call);
5343 if (call->delayedAbortEvent) {
5344 rxi_CancelDelayedAbortEvent(call);
5345 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5347 rxi_SendCallAbort(call, packet, 0, 1);
5348 rxi_FreePacket(packet);
5353 * Update the peer with the congestion information in this call
5354 * so other calls on this connection can pick up where this call
5355 * left off. If the congestion sequence numbers don't match then
5356 * another call experienced a retransmission.
5358 peer = call->conn->peer;
5359 MUTEX_ENTER(&peer->peer_lock);
5361 if (call->congestSeq == peer->congestSeq) {
5362 peer->cwind = MAX(peer->cwind, call->cwind);
5363 peer->MTU = MAX(peer->MTU, call->MTU);
5364 peer->nDgramPackets =
5365 MAX(peer->nDgramPackets, call->nDgramPackets);
5368 call->abortCode = 0;
5369 call->abortCount = 0;
5371 if (peer->maxDgramPackets > 1) {
5372 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
5374 call->MTU = peer->MTU;
5376 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
5377 call->ssthresh = rx_maxSendWindow;
5378 call->nDgramPackets = peer->nDgramPackets;
5379 call->congestSeq = peer->congestSeq;
5380 call->rtt = peer->rtt;
5381 call->rtt_dev = peer->rtt_dev;
5382 clock_Zero(&call->rto);
5383 clock_Addmsec(&call->rto,
5384 MAX(((call->rtt >> 3) + call->rtt_dev), rx_minPeerTimeout) + 200);
5385 MUTEX_EXIT(&peer->peer_lock);
5387 flags = call->flags;
5388 rxi_WaitforTQBusy(call);
5390 rxi_ClearTransmitQueue(call, 1);
5391 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
5392 dpf(("rcall %"AFS_PTR_FMT" has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5396 rxi_ClearReceiveQueue(call);
5397 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
5401 call->twind = call->conn->twind[call->channel];
5402 call->rwind = call->conn->rwind[call->channel];
5403 call->nSoftAcked = 0;
5404 call->nextCwind = 0;
5407 call->nCwindAcks = 0;
5408 call->nSoftAcks = 0;
5409 call->nHardAcks = 0;
5411 call->tfirst = call->rnext = call->tnext = 1;
5414 call->lastAcked = 0;
5415 call->localStatus = call->remoteStatus = 0;
5417 if (flags & RX_CALL_READER_WAIT) {
5418 #ifdef RX_ENABLE_LOCKS
5419 CV_BROADCAST(&call->cv_rq);
5421 osi_rxWakeup(&call->rq);
5424 if (flags & RX_CALL_WAIT_PACKETS) {
5425 MUTEX_ENTER(&rx_freePktQ_lock);
5426 rxi_PacketsUnWait(); /* XXX */
5427 MUTEX_EXIT(&rx_freePktQ_lock);
5429 #ifdef RX_ENABLE_LOCKS
5430 CV_SIGNAL(&call->cv_twind);
5432 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5433 osi_rxWakeup(&call->twind);
5436 if (flags & RX_CALL_WAIT_PROC) {
5437 rx_atomic_dec(&rx_nWaiting);
5439 #ifdef RX_ENABLE_LOCKS
5440 /* The following ensures that we don't mess with any queue while some
5441 * other thread might also be doing so. The call_queue_lock field is
5442 * is only modified under the call lock. If the call is in the process
5443 * of being removed from a queue, the call is not locked until the
5444 * the queue lock is dropped and only then is the call_queue_lock field
5445 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5446 * Note that any other routine which removes a call from a queue has to
5447 * obtain the queue lock before examing the queue and removing the call.
5449 if (call->call_queue_lock) {
5450 MUTEX_ENTER(call->call_queue_lock);
5451 if (opr_queue_IsOnQueue(&call->entry)) {
5452 opr_queue_Remove(&call->entry);
5454 MUTEX_EXIT(call->call_queue_lock);
5455 CLEAR_CALL_QUEUE_LOCK(call);
5457 #else /* RX_ENABLE_LOCKS */
5458 if (opr_queue_IsOnQueue(&call->entry)) {
5459 opr_queue_Remove(&call->entry);
5461 #endif /* RX_ENABLE_LOCKS */
5463 rxi_CancelKeepAliveEvent(call);
5464 rxi_CancelDelayedAckEvent(call);
5467 /* Send an acknowledge for the indicated packet (seq,serial) of the
5468 * indicated call, for the indicated reason (reason). This
5469 * acknowledge will specifically acknowledge receiving the packet, and
5470 * will also specify which other packets for this call have been
5471 * received. This routine returns the packet that was used to the
5472 * caller. The caller is responsible for freeing it or re-using it.
5473 * This acknowledgement also returns the highest sequence number
5474 * actually read out by the higher level to the sender; the sender
5475 * promises to keep around packets that have not been read by the
5476 * higher level yet (unless, of course, the sender decides to abort
5477 * the call altogether). Any of p, seq, serial, pflags, or reason may
5478 * be set to zero without ill effect. That is, if they are zero, they
5479 * will not convey any information.
5480 * NOW there is a trailer field, after the ack where it will safely be
5481 * ignored by mundanes, which indicates the maximum size packet this
5482 * host can swallow. */
5484 struct rx_packet *optionalPacket; use to send ack (or null)
5485 int seq; Sequence number of the packet we are acking
5486 int serial; Serial number of the packet
5487 int pflags; Flags field from packet header
5488 int reason; Reason an acknowledge was prompted
5491 #define RX_ZEROS 1024
5492 static char rx_zeros[RX_ZEROS];
5495 rxi_SendAck(struct rx_call *call,
5496 struct rx_packet *optionalPacket, int serial, int reason,
5499 struct rx_ackPacket *ap;
5500 struct rx_packet *p;
5501 struct opr_queue *cursor;
5504 afs_uint32 padbytes = 0;
5505 #ifdef RX_ENABLE_TSFPQ
5506 struct rx_ts_info_t * rx_ts_info;
5510 * Open the receive window once a thread starts reading packets
5512 if (call->rnext > 1) {
5513 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5516 /* Don't attempt to grow MTU if this is a critical ping */
5517 if (reason == RX_ACK_MTU) {
5518 /* keep track of per-call attempts, if we're over max, do in small
5519 * otherwise in larger? set a size to increment by, decrease
5522 if (call->conn->peer->maxPacketSize &&
5523 (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5525 padbytes = call->conn->peer->maxPacketSize+16;
5527 padbytes = call->conn->peer->maxMTU + 128;
5529 /* do always try a minimum size ping */
5530 padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5532 /* subtract the ack payload */
5533 padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5534 reason = RX_ACK_PING;
5537 call->nHardAcks = 0;
5538 call->nSoftAcks = 0;
5539 if (call->rnext > call->lastAcked)
5540 call->lastAcked = call->rnext;
5544 rx_computelen(p, p->length); /* reset length, you never know */
5545 } /* where that's been... */
5546 #ifdef RX_ENABLE_TSFPQ
5548 RX_TS_INFO_GET(rx_ts_info);
5549 if ((p = rx_ts_info->local_special_packet)) {
5550 rx_computelen(p, p->length);
5551 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5552 rx_ts_info->local_special_packet = p;
5553 } else { /* We won't send the ack, but don't panic. */
5554 return optionalPacket;
5558 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5559 /* We won't send the ack, but don't panic. */
5560 return optionalPacket;
5565 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5568 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5569 #ifndef RX_ENABLE_TSFPQ
5570 if (!optionalPacket)
5573 return optionalPacket;
5575 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5576 if (rx_Contiguous(p) < templ) {
5577 #ifndef RX_ENABLE_TSFPQ
5578 if (!optionalPacket)
5581 return optionalPacket;
5586 /* MTUXXX failing to send an ack is very serious. We should */
5587 /* try as hard as possible to send even a partial ack; it's */
5588 /* better than nothing. */
5589 ap = (struct rx_ackPacket *)rx_DataOf(p);
5590 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5591 ap->reason = reason;
5593 /* The skew computation used to be bogus, I think it's better now. */
5594 /* We should start paying attention to skew. XXX */
5595 ap->serial = htonl(serial);
5596 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
5599 * First packet not yet forwarded to reader. When ACKALL has been
5600 * sent the peer has been told that all received packets will be
5601 * delivered to the reader. The value 'rnext' is used internally
5602 * to refer to the next packet in the receive queue that must be
5603 * delivered to the reader. From the perspective of the peer it
5604 * already has so report the last sequence number plus one if there
5605 * are packets in the receive queue awaiting processing.
5607 if ((call->flags & RX_CALL_ACKALL_SENT) &&
5608 !opr_queue_IsEmpty(&call->rq)) {
5609 ap->firstPacket = htonl(opr_queue_Last(&call->rq, struct rx_packet, entry)->header.seq + 1);
5611 ap->firstPacket = htonl(call->rnext);
5613 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
5615 /* No fear of running out of ack packet here because there can only
5616 * be at most one window full of unacknowledged packets. The window
5617 * size must be constrained to be less than the maximum ack size,
5618 * of course. Also, an ack should always fit into a single packet
5619 * -- it should not ever be fragmented. */
5621 for (opr_queue_Scan(&call->rq, cursor)) {
5622 struct rx_packet *rqp
5623 = opr_queue_Entry(cursor, struct rx_packet, entry);
5625 if (!rqp || !call->rq.next
5626 || (rqp->header.seq > (call->rnext + call->rwind))) {
5627 #ifndef RX_ENABLE_TSFPQ
5628 if (!optionalPacket)
5631 rxi_CallError(call, RX_CALL_DEAD);
5632 return optionalPacket;
5635 while (rqp->header.seq > call->rnext + offset)
5636 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5637 ap->acks[offset++] = RX_ACK_TYPE_ACK;
5639 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5640 #ifndef RX_ENABLE_TSFPQ
5641 if (!optionalPacket)
5644 rxi_CallError(call, RX_CALL_DEAD);
5645 return optionalPacket;
5651 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5653 /* Must zero the 3 octets that rx_AckDataSize skips at the end of the
5656 rx_packetwrite(p, rx_AckDataSize(offset) - 3, 3, rx_zeros);
5658 /* these are new for AFS 3.3 */
5659 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5660 templ = htonl(templ);
5661 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5662 templ = htonl(call->conn->peer->ifMTU);
5663 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5664 sizeof(afs_int32), &templ);
5666 /* new for AFS 3.4 */
5667 templ = htonl(call->rwind);
5668 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5669 sizeof(afs_int32), &templ);
5671 /* new for AFS 3.5 */
5672 templ = htonl(call->conn->peer->ifDgramPackets);
5673 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5674 sizeof(afs_int32), &templ);
5676 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5678 p->header.serviceId = call->conn->serviceId;
5679 p->header.cid = (call->conn->cid | call->channel);
5680 p->header.callNumber = *call->callNumber;
5682 p->header.securityIndex = call->conn->securityIndex;
5683 p->header.epoch = call->conn->epoch;
5684 p->header.type = RX_PACKET_TYPE_ACK;
5685 p->header.flags = RX_SLOW_START_OK;
5686 if (reason == RX_ACK_PING)
5687 p->header.flags |= RX_REQUEST_ACK;
5689 while (padbytes > 0) {
5690 if (padbytes > RX_ZEROS) {
5691 rx_packetwrite(p, p->length, RX_ZEROS, rx_zeros);
5692 p->length += RX_ZEROS;
5693 padbytes -= RX_ZEROS;
5695 rx_packetwrite(p, p->length, padbytes, rx_zeros);
5696 p->length += padbytes;
5701 if (call->conn->type == RX_CLIENT_CONNECTION)
5702 p->header.flags |= RX_CLIENT_INITIATED;
5706 if (rxdebug_active) {
5710 len = _snprintf(msg, sizeof(msg),
5711 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5712 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5713 ntohl(ap->serial), ntohl(ap->previousPacket),
5714 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5715 ap->nAcks, ntohs(ap->bufferSpace) );
5719 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5720 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5724 OutputDebugString(msg);
5726 #else /* AFS_NT40_ENV */
5728 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5729 ap->reason, ntohl(ap->previousPacket),
5730 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5732 for (offset = 0; offset < ap->nAcks; offset++)
5733 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5738 #endif /* AFS_NT40_ENV */
5741 int i, nbytes = p->length;
5743 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5744 if (nbytes <= p->wirevec[i].iov_len) {
5747 savelen = p->wirevec[i].iov_len;
5749 p->wirevec[i].iov_len = nbytes;
5751 rxi_Send(call, p, istack);
5752 p->wirevec[i].iov_len = savelen;
5756 nbytes -= p->wirevec[i].iov_len;
5759 if (rx_stats_active)
5760 rx_atomic_inc(&rx_stats.ackPacketsSent);
5761 #ifndef RX_ENABLE_TSFPQ
5762 if (!optionalPacket)
5765 return optionalPacket; /* Return packet for re-use by caller */
5769 struct rx_packet **list;
5774 /* Send all of the packets in the list in single datagram */
5776 rxi_SendList(struct rx_call *call, struct xmitlist *xmit,
5777 int istack, int moreFlag)
5783 struct rx_connection *conn = call->conn;
5784 struct rx_peer *peer = conn->peer;
5786 MUTEX_ENTER(&peer->peer_lock);
5787 peer->nSent += xmit->len;
5788 if (xmit->resending)
5789 peer->reSends += xmit->len;
5790 MUTEX_EXIT(&peer->peer_lock);
5792 if (rx_stats_active) {
5793 if (xmit->resending)
5794 rx_atomic_add(&rx_stats.dataPacketsReSent, xmit->len);
5796 rx_atomic_add(&rx_stats.dataPacketsSent, xmit->len);
5799 clock_GetTime(&now);
5801 if (xmit->list[xmit->len - 1]->header.flags & RX_LAST_PACKET) {
5805 /* Set the packet flags and schedule the resend events */
5806 /* Only request an ack for the last packet in the list */
5807 for (i = 0; i < xmit->len; i++) {
5808 struct rx_packet *packet = xmit->list[i];
5810 /* Record the time sent */
5811 packet->timeSent = now;
5812 packet->flags |= RX_PKTFLAG_SENT;
5814 /* Ask for an ack on retransmitted packets, on every other packet
5815 * if the peer doesn't support slow start. Ask for an ack on every
5816 * packet until the congestion window reaches the ack rate. */
5817 if (packet->header.serial) {
5820 packet->firstSent = now;
5821 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5822 || (!(call->flags & RX_CALL_SLOW_START_OK)
5823 && (packet->header.seq & 1)))) {
5828 /* Tag this packet as not being the last in this group,
5829 * for the receiver's benefit */
5830 if (i < xmit->len - 1 || moreFlag) {
5831 packet->header.flags |= RX_MORE_PACKETS;
5836 xmit->list[xmit->len - 1]->header.flags |= RX_REQUEST_ACK;
5839 /* Since we're about to send a data packet to the peer, it's
5840 * safe to nuke any scheduled end-of-packets ack */
5841 rxi_CancelDelayedAckEvent(call);
5843 MUTEX_EXIT(&call->lock);
5844 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5845 if (xmit->len > 1) {
5846 rxi_SendPacketList(call, conn, xmit->list, xmit->len, istack);
5848 rxi_SendPacket(call, conn, xmit->list[0], istack);
5850 MUTEX_ENTER(&call->lock);
5851 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5853 /* Tell the RTO calculation engine that we have sent a packet, and
5854 * if it was the last one */
5855 rxi_rto_packet_sent(call, lastPacket, istack);
5857 /* Update last send time for this call (for keep-alive
5858 * processing), and for the connection (so that we can discover
5859 * idle connections) */
5860 conn->lastSendTime = call->lastSendTime = clock_Sec();
5863 /* When sending packets we need to follow these rules:
5864 * 1. Never send more than maxDgramPackets in a jumbogram.
5865 * 2. Never send a packet with more than two iovecs in a jumbogram.
5866 * 3. Never send a retransmitted packet in a jumbogram.
5867 * 4. Never send more than cwind/4 packets in a jumbogram
5868 * We always keep the last list we should have sent so we
5869 * can set the RX_MORE_PACKETS flags correctly.
5873 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5878 struct xmitlist working;
5879 struct xmitlist last;
5881 struct rx_peer *peer = call->conn->peer;
5882 int morePackets = 0;
5884 memset(&last, 0, sizeof(struct xmitlist));
5885 working.list = &list[0];
5887 working.resending = 0;
5889 recovery = call->flags & RX_CALL_FAST_RECOVER;
5891 for (i = 0; i < len; i++) {
5892 /* Does the current packet force us to flush the current list? */
5894 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5895 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5897 /* This sends the 'last' list and then rolls the current working
5898 * set into the 'last' one, and resets the working set */
5901 rxi_SendList(call, &last, istack, 1);
5902 /* If the call enters an error state stop sending, or if
5903 * we entered congestion recovery mode, stop sending */
5905 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5910 working.resending = 0;
5911 working.list = &list[i];
5913 /* Add the current packet to the list if it hasn't been acked.
5914 * Otherwise adjust the list pointer to skip the current packet. */
5915 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5918 if (list[i]->header.serial)
5919 working.resending = 1;
5921 /* Do we need to flush the list? */
5922 if (working.len >= (int)peer->maxDgramPackets
5923 || working.len >= (int)call->nDgramPackets
5924 || working.len >= (int)call->cwind
5925 || list[i]->header.serial
5926 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5928 rxi_SendList(call, &last, istack, 1);
5929 /* If the call enters an error state stop sending, or if
5930 * we entered congestion recovery mode, stop sending */
5932 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5937 working.resending = 0;
5938 working.list = &list[i + 1];
5941 if (working.len != 0) {
5942 osi_Panic("rxi_SendList error");
5944 working.list = &list[i + 1];
5948 /* Send the whole list when the call is in receive mode, when
5949 * the call is in eof mode, when we are in fast recovery mode,
5950 * and when we have the last packet */
5951 /* XXX - The accesses to app.mode aren't safe, as this may be called by
5952 * the listener or event threads
5954 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5955 || (call->flags & RX_CALL_FLUSH)
5956 || (call->flags & RX_CALL_FAST_RECOVER)) {
5957 /* Check for the case where the current list contains
5958 * an acked packet. Since we always send retransmissions
5959 * in a separate packet, we only need to check the first
5960 * packet in the list */
5961 if (working.len > 0 && !(working.list[0]->flags & RX_PKTFLAG_ACKED)) {
5965 rxi_SendList(call, &last, istack, morePackets);
5966 /* If the call enters an error state stop sending, or if
5967 * we entered congestion recovery mode, stop sending */
5969 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5973 rxi_SendList(call, &working, istack, 0);
5975 } else if (last.len > 0) {
5976 rxi_SendList(call, &last, istack, 0);
5977 /* Packets which are in 'working' are not sent by this call */
5982 * Check if the peer for the given call is known to be dead
5984 * If the call's peer appears dead (it has encountered fatal network errors
5985 * since the call started) the call is killed with RX_CALL_DEAD if the call
5986 * is active. Otherwise, we do nothing.
5988 * @param[in] call The call to check
5991 * @retval 0 The call is fine, and we haven't done anything to the call
5992 * @retval nonzero The call's peer appears dead, and the call has been
5993 * terminated if it was active
5995 * @pre call->lock must be locked
5998 rxi_CheckPeerDead(struct rx_call *call)
6000 #ifdef AFS_RXERRQ_ENV
6003 if (call->state == RX_STATE_DALLY) {
6007 peererrs = rx_atomic_read(&call->conn->peer->neterrs);
6008 if (call->neterr_gen < peererrs) {
6009 /* we have received network errors since this call started; kill
6011 if (call->state == RX_STATE_ACTIVE) {
6012 rxi_CallError(call, RX_CALL_DEAD);
6016 if (call->neterr_gen > peererrs) {
6017 /* someone has reset the number of peer errors; set the call error gen
6018 * so we can detect if more errors are encountered */
6019 call->neterr_gen = peererrs;
6026 rxi_Resend(struct rxevent *event, void *arg0, void *arg1, int istack)
6028 struct rx_call *call = arg0;
6029 struct rx_peer *peer;
6030 struct opr_queue *cursor;
6031 struct clock maxTimeout = { 60, 0 };
6033 MUTEX_ENTER(&call->lock);
6035 peer = call->conn->peer;
6037 /* Make sure that the event pointer is removed from the call
6038 * structure, since there is no longer a per-call retransmission
6040 if (event == call->resendEvent)
6041 rxevent_Put(&call->resendEvent);
6043 rxi_CheckPeerDead(call);
6045 if (opr_queue_IsEmpty(&call->tq)) {
6046 /* Nothing to do. This means that we've been raced, and that an
6047 * ACK has come in between when we were triggered, and when we
6048 * actually got to run. */
6052 /* We're in loss recovery */
6053 call->flags |= RX_CALL_FAST_RECOVER;
6055 /* Mark all of the pending packets in the queue as being lost */
6056 for (opr_queue_Scan(&call->tq, cursor)) {
6057 struct rx_packet *p = opr_queue_Entry(cursor, struct rx_packet, entry);
6058 if (!(p->flags & RX_PKTFLAG_ACKED))
6059 p->flags &= ~RX_PKTFLAG_SENT;
6062 /* We're resending, so we double the timeout of the call. This will be
6063 * dropped back down by the first successful ACK that we receive.
6065 * We apply a maximum value here of 60 seconds
6067 clock_Add(&call->rto, &call->rto);
6068 if (clock_Gt(&call->rto, &maxTimeout))
6069 call->rto = maxTimeout;
6071 /* Packet loss is most likely due to congestion, so drop our window size
6072 * and start again from the beginning */
6073 if (peer->maxDgramPackets >1) {
6074 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
6075 call->MTU = MIN(peer->natMTU, peer->maxMTU);
6077 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
6078 call->nDgramPackets = 1;
6080 call->nextCwind = 1;
6083 MUTEX_ENTER(&peer->peer_lock);
6084 peer->MTU = call->MTU;
6085 peer->cwind = call->cwind;
6086 peer->nDgramPackets = 1;
6088 call->congestSeq = peer->congestSeq;
6089 MUTEX_EXIT(&peer->peer_lock);
6091 rxi_Start(call, istack);
6094 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
6095 MUTEX_EXIT(&call->lock);
6098 /* This routine is called when new packets are readied for
6099 * transmission and when retransmission may be necessary, or when the
6100 * transmission window or burst count are favourable. This should be
6101 * better optimized for new packets, the usual case, now that we've
6102 * got rid of queues of send packets. XXXXXXXXXXX */
6104 rxi_Start(struct rx_call *call, int istack)
6106 struct opr_queue *cursor;
6107 #ifdef RX_ENABLE_LOCKS
6108 struct opr_queue *store;
6114 #ifdef RX_ENABLE_LOCKS
6115 if (rx_stats_active)
6116 rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
6121 if (!opr_queue_IsEmpty(&call->tq)) { /* If we have anything to send */
6122 /* Send (or resend) any packets that need it, subject to
6123 * window restrictions and congestion burst control
6124 * restrictions. Ask for an ack on the last packet sent in
6125 * this burst. For now, we're relying upon the window being
6126 * considerably bigger than the largest number of packets that
6127 * are typically sent at once by one initial call to
6128 * rxi_Start. This is probably bogus (perhaps we should ask
6129 * for an ack when we're half way through the current
6130 * window?). Also, for non file transfer applications, this
6131 * may end up asking for an ack for every packet. Bogus. XXXX
6134 * But check whether we're here recursively, and let the other guy
6137 #ifdef RX_ENABLE_LOCKS
6138 if (!(call->flags & RX_CALL_TQ_BUSY)) {
6139 call->flags |= RX_CALL_TQ_BUSY;
6141 #endif /* RX_ENABLE_LOCKS */
6143 #ifdef RX_ENABLE_LOCKS
6144 call->flags &= ~RX_CALL_NEED_START;
6145 #endif /* RX_ENABLE_LOCKS */
6147 maxXmitPackets = MIN(call->twind, call->cwind);
6148 for (opr_queue_Scan(&call->tq, cursor)) {
6150 = opr_queue_Entry(cursor, struct rx_packet, entry);
6152 if (p->flags & RX_PKTFLAG_ACKED) {
6153 /* Since we may block, don't trust this */
6154 if (rx_stats_active)
6155 rx_atomic_inc(&rx_stats.ignoreAckedPacket);
6156 continue; /* Ignore this packet if it has been acknowledged */
6159 /* Turn off all flags except these ones, which are the same
6160 * on each transmission */
6161 p->header.flags &= RX_PRESET_FLAGS;
6163 if (p->header.seq >=
6164 call->tfirst + MIN((int)call->twind,
6165 (int)(call->nSoftAcked +
6167 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
6168 /* Note: if we're waiting for more window space, we can
6169 * still send retransmits; hence we don't return here, but
6170 * break out to schedule a retransmit event */
6171 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
6172 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
6177 /* Transmit the packet if it needs to be sent. */
6178 if (!(p->flags & RX_PKTFLAG_SENT)) {
6179 if (nXmitPackets == maxXmitPackets) {
6180 rxi_SendXmitList(call, call->xmitList,
6181 nXmitPackets, istack);
6184 dpf(("call %d xmit packet %"AFS_PTR_FMT"\n",
6185 *(call->callNumber), p));
6186 call->xmitList[nXmitPackets++] = p;
6188 } /* end of the queue_Scan */
6190 /* xmitList now hold pointers to all of the packets that are
6191 * ready to send. Now we loop to send the packets */
6192 if (nXmitPackets > 0) {
6193 rxi_SendXmitList(call, call->xmitList, nXmitPackets,
6197 #ifdef RX_ENABLE_LOCKS
6199 /* We went into the error state while sending packets. Now is
6200 * the time to reset the call. This will also inform the using
6201 * process that the call is in an error state.
6203 if (rx_stats_active)
6204 rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
6205 call->flags &= ~RX_CALL_TQ_BUSY;
6206 rxi_WakeUpTransmitQueue(call);
6207 rxi_CallError(call, call->error);
6211 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
6213 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
6214 /* Some packets have received acks. If they all have, we can clear
6215 * the transmit queue.
6218 for (opr_queue_ScanSafe(&call->tq, cursor, store)) {
6220 = opr_queue_Entry(cursor, struct rx_packet, entry);
6222 if (p->header.seq < call->tfirst
6223 && (p->flags & RX_PKTFLAG_ACKED)) {
6224 opr_queue_Remove(&p->entry);
6225 #ifdef RX_TRACK_PACKETS
6226 p->flags &= ~RX_PKTFLAG_TQ;
6228 #ifdef RXDEBUG_PACKET
6236 call->flags |= RX_CALL_TQ_CLEARME;
6238 if (call->flags & RX_CALL_TQ_CLEARME)
6239 rxi_ClearTransmitQueue(call, 1);
6240 } while (call->flags & RX_CALL_NEED_START);
6242 * TQ references no longer protected by this flag; they must remain
6243 * protected by the call lock.
6245 call->flags &= ~RX_CALL_TQ_BUSY;
6246 rxi_WakeUpTransmitQueue(call);
6248 call->flags |= RX_CALL_NEED_START;
6250 #endif /* RX_ENABLE_LOCKS */
6252 rxi_rto_cancel(call);
6256 /* Also adjusts the keep alive parameters for the call, to reflect
6257 * that we have just sent a packet (so keep alives aren't sent
6260 rxi_Send(struct rx_call *call, struct rx_packet *p,
6264 struct rx_connection *conn = call->conn;
6266 /* Stamp each packet with the user supplied status */
6267 p->header.userStatus = call->localStatus;
6269 /* Allow the security object controlling this call's security to
6270 * make any last-minute changes to the packet */
6271 code = RXS_SendPacket(conn->securityObject, call, p);
6273 MUTEX_EXIT(&call->lock);
6274 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6275 rxi_ConnectionError(conn, code);
6276 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6277 MUTEX_ENTER(&call->lock);
6281 /* Since we're about to send SOME sort of packet to the peer, it's
6282 * safe to nuke any scheduled end-of-packets ack */
6283 rxi_CancelDelayedAckEvent(call);
6285 /* Actually send the packet, filling in more connection-specific fields */
6286 MUTEX_EXIT(&call->lock);
6287 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6288 rxi_SendPacket(call, conn, p, istack);
6289 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6290 MUTEX_ENTER(&call->lock);
6292 /* Update last send time for this call (for keep-alive
6293 * processing), and for the connection (so that we can discover
6294 * idle connections) */
6295 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6296 (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
6297 (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
6299 conn->lastSendTime = call->lastSendTime = clock_Sec();
6303 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
6304 * that things are fine. Also called periodically to guarantee that nothing
6305 * falls through the cracks (e.g. (error + dally) connections have keepalive
6306 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
6308 * haveCTLock Set if calling from rxi_ReapConnections
6311 rxi_CheckCall(struct rx_call *call, int haveCTLock)
6313 struct rx_connection *conn = call->conn;
6315 afs_uint32 deadTime, idleDeadTime = 0, hardDeadTime = 0;
6316 afs_uint32 fudgeFactor;
6319 int idle_timeout = 0;
6320 afs_int32 clock_diff = 0;
6322 if (rxi_CheckPeerDead(call)) {
6328 /* Large swings in the clock can have a significant impact on
6329 * the performance of RX call processing. Forward clock shifts
6330 * will result in premature event triggering or timeouts.
6331 * Backward shifts can result in calls not completing until
6332 * the clock catches up with the original start clock value.
6334 * If a backward clock shift of more than five minutes is noticed,
6335 * just fail the call.
6337 if (now < call->lastSendTime)
6338 clock_diff = call->lastSendTime - now;
6339 if (now < call->startWait)
6340 clock_diff = MAX(clock_diff, call->startWait - now);
6341 if (now < call->lastReceiveTime)
6342 clock_diff = MAX(clock_diff, call->lastReceiveTime - now);
6343 if (clock_diff > 5 * 60)
6345 if (call->state == RX_STATE_ACTIVE)
6346 rxi_CallError(call, RX_CALL_TIMEOUT);
6350 #ifdef RX_ENABLE_LOCKS
6351 if (call->flags & RX_CALL_TQ_BUSY) {
6352 /* Call is active and will be reset by rxi_Start if it's
6353 * in an error state.
6358 /* RTT + 8*MDEV, rounded up to the next second. */
6359 fudgeFactor = (((afs_uint32) call->rtt >> 3) +
6360 ((afs_uint32) call->rtt_dev << 1) + 1023) >> 10;
6362 deadTime = conn->secondsUntilDead + fudgeFactor;
6363 /* These are computed to the second (+- 1 second). But that's
6364 * good enough for these values, which should be a significant
6365 * number of seconds. */
6366 if (now > (call->lastReceiveTime + deadTime)) {
6367 if (call->state == RX_STATE_ACTIVE) {
6368 cerror = RX_CALL_DEAD;
6371 #ifdef RX_ENABLE_LOCKS
6372 /* Cancel pending events */
6373 rxi_CancelDelayedAckEvent(call);
6374 rxi_rto_cancel(call);
6375 rxi_CancelKeepAliveEvent(call);
6376 rxi_CancelGrowMTUEvent(call);
6377 MUTEX_ENTER(&rx_refcnt_mutex);
6378 /* if rxi_FreeCall returns 1 it has freed the call */
6379 if (call->refCount == 0 &&
6380 rxi_FreeCall(call, haveCTLock))
6382 MUTEX_EXIT(&rx_refcnt_mutex);
6385 MUTEX_EXIT(&rx_refcnt_mutex);
6387 #else /* RX_ENABLE_LOCKS */
6388 rxi_FreeCall(call, 0);
6390 #endif /* RX_ENABLE_LOCKS */
6392 /* Non-active calls are destroyed if they are not responding
6393 * to pings; active calls are simply flagged in error, so the
6394 * attached process can die reasonably gracefully. */
6397 if (conn->idleDeadTime) {
6398 idleDeadTime = conn->idleDeadTime + fudgeFactor;
6402 /* see if we have a non-activity timeout */
6403 if (call->startWait && ((call->startWait + idleDeadTime) < now)) {
6404 if (call->state == RX_STATE_ACTIVE) {
6405 cerror = RX_CALL_TIMEOUT;
6411 if (conn->hardDeadTime) {
6412 hardDeadTime = conn->hardDeadTime + fudgeFactor;
6415 /* see if we have a hard timeout */
6417 && (now > (hardDeadTime + call->startTime.sec))) {
6418 if (call->state == RX_STATE_ACTIVE)
6419 rxi_CallError(call, RX_CALL_TIMEOUT);
6424 if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT && !idle_timeout &&
6425 call->lastReceiveTime) {
6426 int oldMTU = conn->peer->ifMTU;
6428 /* If we thought we could send more, perhaps things got worse.
6429 * Shrink by 128 bytes and try again. */
6430 if (conn->peer->maxPacketSize < conn->lastPacketSize)
6431 /* maxPacketSize will be cleared in rxi_SetPeerMtu */
6432 newmtu = MAX(conn->peer->maxPacketSize + RX_HEADER_SIZE,
6433 conn->lastPacketSize - 128 + RX_HEADER_SIZE);
6435 newmtu = conn->lastPacketSize - 128 + RX_HEADER_SIZE;
6437 /* minimum capped in SetPeerMtu */
6438 rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6441 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
6443 /* needed so ResetCall doesn't clobber us. */
6444 call->MTU = conn->peer->ifMTU;
6446 /* if we never succeeded, let the error pass out as-is */
6447 if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6448 cerror = conn->msgsizeRetryErr;
6451 rxi_CallError(call, cerror);
6456 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1,
6457 void *dummy, int dummy2)
6459 struct rx_connection *conn = arg1;
6460 struct rx_header theader;
6461 char tbuffer[1 + sizeof(struct rx_header)];
6462 struct sockaddr_in taddr;
6466 struct iovec tmpiov[2];
6469 RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6472 tp = &tbuffer[sizeof(struct rx_header)];
6473 taddr.sin_family = AF_INET;
6474 taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6475 taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6476 memset(&taddr.sin_zero, 0, sizeof(taddr.sin_zero));
6477 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6478 taddr.sin_len = sizeof(struct sockaddr_in);
6480 memset(&theader, 0, sizeof(theader));
6481 theader.epoch = htonl(999);
6483 theader.callNumber = 0;
6486 theader.type = RX_PACKET_TYPE_VERSION;
6487 theader.flags = RX_LAST_PACKET;
6488 theader.serviceId = 0;
6490 memcpy(tbuffer, &theader, sizeof(theader));
6491 memcpy(tp, &a, sizeof(a));
6492 tmpiov[0].iov_base = tbuffer;
6493 tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6495 osi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6497 MUTEX_ENTER(&conn->conn_data_lock);
6498 /* We ran, so the handle is no longer needed to try to cancel ourselves. */
6499 if (event == conn->natKeepAliveEvent)
6500 rxevent_Put(&conn->natKeepAliveEvent);
6501 MUTEX_ENTER(&rx_refcnt_mutex);
6502 /* Only reschedule ourselves if the connection would not be destroyed */
6503 if (conn->refCount > 1)
6505 if (conn->refCount <= 0) {
6506 #ifdef RX_REFCOUNT_CHECK
6507 osi_Assert(conn->refCount == 0);
6509 if (rx_stats_active) {
6510 MUTEX_ENTER(&rx_stats_mutex);
6511 rxi_lowConnRefCount++;
6512 MUTEX_EXIT(&rx_stats_mutex);
6515 MUTEX_EXIT(&rx_refcnt_mutex);
6517 rxi_ScheduleNatKeepAliveEvent(conn);
6518 MUTEX_EXIT(&conn->conn_data_lock);
6519 putConnection(conn);
6523 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6525 MUTEX_ASSERT(&conn->conn_data_lock);
6526 if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6527 struct clock when, now;
6528 clock_GetTime(&now);
6530 when.sec += conn->secondsUntilNatPing;
6531 rx_GetConnection(conn);
6532 conn->natKeepAliveEvent =
6533 rxevent_Post(&when, &now, rxi_NatKeepAliveEvent, conn, NULL, 0);
6538 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6540 MUTEX_ENTER(&conn->conn_data_lock);
6541 conn->secondsUntilNatPing = seconds;
6543 if (!(conn->flags & RX_CONN_ATTACHWAIT))
6544 rxi_ScheduleNatKeepAliveEvent(conn);
6546 conn->flags |= RX_CONN_NAT_PING;
6548 MUTEX_EXIT(&conn->conn_data_lock);
6551 /* When a call is in progress, this routine is called occasionally to
6552 * make sure that some traffic has arrived (or been sent to) the peer.
6553 * If nothing has arrived in a reasonable amount of time, the call is
6554 * declared dead; if nothing has been sent for a while, we send a
6555 * keep-alive packet (if we're actually trying to keep the call alive)
6558 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy,
6561 struct rx_call *call = arg1;
6562 struct rx_connection *conn;
6565 MUTEX_ENTER(&call->lock);
6567 if (event == call->keepAliveEvent)
6568 rxevent_Put(&call->keepAliveEvent);
6572 if (rxi_CheckCall(call, 0)) {
6573 MUTEX_EXIT(&call->lock);
6574 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6578 /* Don't try to keep alive dallying calls */
6579 if (call->state == RX_STATE_DALLY) {
6580 MUTEX_EXIT(&call->lock);
6581 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6586 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6587 /* Don't try to send keepalives if there is unacknowledged data */
6588 /* the rexmit code should be good enough, this little hack
6589 * doesn't quite work XXX */
6590 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6592 rxi_ScheduleKeepAliveEvent(call);
6593 MUTEX_EXIT(&call->lock);
6594 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6597 /* Does what's on the nameplate. */
6599 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy, int dummy2)
6601 struct rx_call *call = arg1;
6602 struct rx_connection *conn;
6604 MUTEX_ENTER(&call->lock);
6606 if (event == call->growMTUEvent)
6607 rxevent_Put(&call->growMTUEvent);
6609 if (rxi_CheckCall(call, 0))
6612 /* Don't bother with dallying calls */
6613 if (call->state == RX_STATE_DALLY)
6619 * keep being scheduled, just don't do anything if we're at peak,
6620 * or we're not set up to be properly handled (idle timeout required)
6622 if ((conn->peer->maxPacketSize != 0) &&
6623 (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6625 (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6626 rxi_ScheduleGrowMTUEvent(call, 0);
6628 MUTEX_EXIT(&call->lock);
6629 CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6633 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6635 MUTEX_ASSERT(&call->lock);
6636 if (!call->keepAliveEvent) {
6637 struct clock when, now;
6638 clock_GetTime(&now);
6640 when.sec += call->conn->secondsUntilPing;
6641 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6642 call->keepAliveEvent =
6643 rxevent_Post(&when, &now, rxi_KeepAliveEvent, call, NULL, 0);
6648 rxi_CancelKeepAliveEvent(struct rx_call *call) {
6649 MUTEX_ASSERT(&call->lock);
6650 if (rxevent_Cancel(&call->keepAliveEvent))
6651 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6655 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6657 MUTEX_ASSERT(&call->lock);
6658 if (!call->growMTUEvent) {
6659 struct clock when, now;
6661 clock_GetTime(&now);
6664 if (call->conn->secondsUntilPing)
6665 secs = (6*call->conn->secondsUntilPing)-1;
6667 if (call->conn->secondsUntilDead)
6668 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6672 CALL_HOLD(call, RX_CALL_REFCOUNT_MTU);
6673 call->growMTUEvent =
6674 rxevent_Post(&when, &now, rxi_GrowMTUEvent, call, NULL, 0);
6679 rxi_CancelGrowMTUEvent(struct rx_call *call)
6681 MUTEX_ASSERT(&call->lock);
6682 if (rxevent_Cancel(&call->growMTUEvent))
6683 CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6687 * Increment the counter for the next connection ID, handling overflow.
6690 update_nextCid(void)
6692 /* Overflow is technically undefined behavior; avoid it. */
6693 if (rx_nextCid > MAX_AFS_INT32 - (1 << RX_CIDSHIFT))
6694 rx_nextCid = -1 * ((MAX_AFS_INT32 / RX_CIDSHIFT) * RX_CIDSHIFT);
6696 rx_nextCid += 1 << RX_CIDSHIFT;
6700 rxi_KeepAliveOn(struct rx_call *call)
6702 /* Pretend last packet received was received now--i.e. if another
6703 * packet isn't received within the keep alive time, then the call
6704 * will die; Initialize last send time to the current time--even
6705 * if a packet hasn't been sent yet. This will guarantee that a
6706 * keep-alive is sent within the ping time */
6707 call->lastReceiveTime = call->lastSendTime = clock_Sec();
6708 rxi_ScheduleKeepAliveEvent(call);
6712 rxi_GrowMTUOn(struct rx_call *call)
6714 struct rx_connection *conn = call->conn;
6715 MUTEX_ENTER(&conn->conn_data_lock);
6716 conn->lastPingSizeSer = conn->lastPingSize = 0;
6717 MUTEX_EXIT(&conn->conn_data_lock);
6718 rxi_ScheduleGrowMTUEvent(call, 1);
6721 /* This routine is called to send connection abort messages
6722 * that have been delayed to throttle looping clients. */
6724 rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1, void *unused,
6727 struct rx_connection *conn = arg1;
6730 struct rx_packet *packet;
6732 MUTEX_ENTER(&conn->conn_data_lock);
6733 if (event == conn->delayedAbortEvent)
6734 rxevent_Put(&conn->delayedAbortEvent);
6735 error = htonl(conn->error);
6737 MUTEX_EXIT(&conn->conn_data_lock);
6738 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6741 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6742 RX_PACKET_TYPE_ABORT, (char *)&error,
6744 rxi_FreePacket(packet);
6746 putConnection(conn);
6749 /* This routine is called to send call abort messages
6750 * that have been delayed to throttle looping clients. */
6752 rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1, void *dummy,
6755 struct rx_call *call = arg1;
6758 struct rx_packet *packet;
6760 MUTEX_ENTER(&call->lock);
6761 if (event == call->delayedAbortEvent)
6762 rxevent_Put(&call->delayedAbortEvent);
6763 error = htonl(call->error);
6765 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6768 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6769 (char *)&error, sizeof(error), 0);
6770 rxi_FreePacket(packet);
6772 MUTEX_EXIT(&call->lock);
6773 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6777 * This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6778 * seconds) to ask the client to authenticate itself. The routine
6779 * issues a challenge to the client, which is obtained from the
6780 * security object associated with the connection
6782 * This routine is both an event handler and a function called directly;
6783 * when called directly the passed |event| is NULL and the
6784 * conn->conn->data>lock must must not be held. Also, when called as an
6785 * an event handler, we must putConnection before we exit; but when called
6786 * directly (the first challenge), we must NOT putConnection.
6789 rxi_ChallengeEvent(struct rxevent *event,
6790 void *arg0, void *arg1, int tries)
6792 struct rx_connection *conn = arg0;
6793 int event_raised = 0; /* assume we were called directly */
6795 MUTEX_ENTER(&conn->conn_data_lock);
6796 if (event != NULL && event == conn->challengeEvent) {
6797 event_raised = 1; /* called as an event */
6798 rxevent_Put(&conn->challengeEvent);
6800 MUTEX_EXIT(&conn->conn_data_lock);
6802 /* If there are no active calls it is not worth re-issuing the
6803 * challenge. If the client issues another call on this connection
6804 * the challenge can be requested at that time.
6806 if (!rxi_HasActiveCalls(conn))
6809 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6810 struct rx_packet *packet;
6811 struct clock when, now;
6814 /* We've failed to authenticate for too long.
6815 * Reset any calls waiting for authentication;
6816 * they are all in RX_STATE_PRECALL.
6820 MUTEX_ENTER(&conn->conn_call_lock);
6821 for (i = 0; i < RX_MAXCALLS; i++) {
6822 struct rx_call *call = conn->call[i];
6824 MUTEX_ENTER(&call->lock);
6825 if (call->state == RX_STATE_PRECALL) {
6826 rxi_CallError(call, RX_CALL_DEAD);
6827 rxi_SendCallAbort(call, NULL, 0, 0);
6829 MUTEX_EXIT(&call->lock);
6832 MUTEX_EXIT(&conn->conn_call_lock);
6836 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6839 code = RXS_GetChallenge(conn->securityObject, conn, packet);
6840 if (code && event_raised) {
6842 * We can only rxi_ConnectionError the connection if we are
6843 * running as an event. Otherwise, the caller may have our call
6844 * locked, and so we cannot call rxi_ConnectionError (since it
6845 * tries to lock each call in the conn).
6847 rxi_FreePacket(packet);
6848 rxi_ConnectionError(conn, code);
6852 /* Only send a challenge packet if we were able to allocate a
6853 * packet, and the security layer successfully populated the
6855 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6856 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6857 conn->securityChallengeSent = 1;
6859 rxi_FreePacket(packet);
6861 clock_GetTime(&now);
6863 when.sec += RX_CHALLENGE_TIMEOUT;
6864 MUTEX_ENTER(&conn->conn_data_lock);
6865 /* Only reschedule ourselves if not already pending. */
6866 if (conn->challengeEvent == NULL) {
6867 rx_GetConnection(conn);
6868 conn->challengeEvent =
6869 rxevent_Post(&when, &now, rxi_ChallengeEvent, conn, 0,
6872 MUTEX_EXIT(&conn->conn_data_lock);
6876 putConnection(conn);
6879 /* Call this routine to start requesting the client to authenticate
6880 * itself. This will continue until authentication is established,
6881 * the call times out, or an invalid response is returned. The
6882 * security object associated with the connection is asked to create
6883 * the challenge at this time. */
6885 rxi_ChallengeOn(struct rx_connection *conn)
6888 MUTEX_ENTER(&conn->conn_data_lock);
6889 if (!conn->challengeEvent)
6891 MUTEX_EXIT(&conn->conn_data_lock);
6894 code = RXS_CreateChallenge(conn->securityObject, conn);
6898 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
6904 /* rxi_ComputeRoundTripTime is called with peer locked. */
6905 /* peer may be null */
6907 rxi_ComputeRoundTripTime(struct rx_packet *p,
6908 struct rx_ackPacket *ack,
6909 struct rx_call *call,
6910 struct rx_peer *peer,
6913 struct clock thisRtt, *sentp;
6917 /* If the ACK is delayed, then do nothing */
6918 if (ack->reason == RX_ACK_DELAY)
6921 /* On the wire, jumbograms are a single UDP packet. We shouldn't count
6922 * their RTT multiple times, so only include the RTT of the last packet
6924 if (p->flags & RX_JUMBO_PACKET)
6927 /* Use the serial number to determine which transmission the ACK is for,
6928 * and set the sent time to match this. If we have no serial number, then
6929 * only use the ACK for RTT calculations if the packet has not been
6933 serial = ntohl(ack->serial);
6935 if (serial == p->header.serial) {
6936 sentp = &p->timeSent;
6937 } else if (serial == p->firstSerial) {
6938 sentp = &p->firstSent;
6939 } else if (clock_Eq(&p->timeSent, &p->firstSent)) {
6940 sentp = &p->firstSent;
6944 if (clock_Eq(&p->timeSent, &p->firstSent)) {
6945 sentp = &p->firstSent;
6952 if (clock_Lt(&thisRtt, sentp))
6953 return; /* somebody set the clock back, don't count this time. */
6955 clock_Sub(&thisRtt, sentp);
6956 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rttp=%d.%06d sec)\n",
6957 p->header.callNumber, p, thisRtt.sec, thisRtt.usec));
6959 if (clock_IsZero(&thisRtt)) {
6961 * The actual round trip time is shorter than the
6962 * clock_GetTime resolution. It is most likely 1ms or 100ns.
6963 * Since we can't tell which at the moment we will assume 1ms.
6965 thisRtt.usec = 1000;
6968 if (rx_stats_active) {
6969 MUTEX_ENTER(&rx_stats_mutex);
6970 if (clock_Lt(&thisRtt, &rx_stats.minRtt))
6971 rx_stats.minRtt = thisRtt;
6972 if (clock_Gt(&thisRtt, &rx_stats.maxRtt)) {
6973 if (thisRtt.sec > 60) {
6974 MUTEX_EXIT(&rx_stats_mutex);
6975 return; /* somebody set the clock ahead */
6977 rx_stats.maxRtt = thisRtt;
6979 clock_Add(&rx_stats.totalRtt, &thisRtt);
6980 rx_atomic_inc(&rx_stats.nRttSamples);
6981 MUTEX_EXIT(&rx_stats_mutex);
6984 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6986 /* Apply VanJacobson round-trip estimations */
6991 * srtt (call->rtt) is in units of one-eighth-milliseconds.
6992 * srtt is stored as fixed point with 3 bits after the binary
6993 * point (i.e., scaled by 8). The following magic is
6994 * equivalent to the smoothing algorithm in rfc793 with an
6995 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
6996 * srtt'*8 = rtt + srtt*7
6997 * srtt'*8 = srtt*8 + rtt - srtt
6998 * srtt' = srtt + rtt/8 - srtt/8
6999 * srtt' = srtt + (rtt - srtt)/8
7002 delta = _8THMSEC(&thisRtt) - call->rtt;
7003 call->rtt += (delta >> 3);
7006 * We accumulate a smoothed rtt variance (actually, a smoothed
7007 * mean difference), then set the retransmit timer to smoothed
7008 * rtt + 4 times the smoothed variance (was 2x in van's original
7009 * paper, but 4x works better for me, and apparently for him as
7011 * rttvar is stored as
7012 * fixed point with 2 bits after the binary point (scaled by
7013 * 4). The following is equivalent to rfc793 smoothing with
7014 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
7015 * rttvar'*4 = rttvar*3 + |delta|
7016 * rttvar'*4 = rttvar*4 + |delta| - rttvar
7017 * rttvar' = rttvar + |delta|/4 - rttvar/4
7018 * rttvar' = rttvar + (|delta| - rttvar)/4
7019 * This replaces rfc793's wired-in beta.
7020 * dev*4 = dev*4 + (|actual - expected| - dev)
7026 delta -= (call->rtt_dev << 1);
7027 call->rtt_dev += (delta >> 3);
7029 /* I don't have a stored RTT so I start with this value. Since I'm
7030 * probably just starting a call, and will be pushing more data down
7031 * this, I expect congestion to increase rapidly. So I fudge a
7032 * little, and I set deviance to half the rtt. In practice,
7033 * deviance tends to approach something a little less than
7034 * half the smoothed rtt. */
7035 call->rtt = _8THMSEC(&thisRtt) + 8;
7036 call->rtt_dev = call->rtt >> 2; /* rtt/2: they're scaled differently */
7038 /* the smoothed RTT time is RTT + 4*MDEV
7040 * We allow a user specified minimum to be set for this, to allow clamping
7041 * at a minimum value in the same way as TCP. In addition, we have to allow
7042 * for the possibility that this packet is answered by a delayed ACK, so we
7043 * add on a fixed 200ms to account for that timer expiring.
7046 rtt_timeout = MAX(((call->rtt >> 3) + call->rtt_dev),
7047 rx_minPeerTimeout) + 200;
7048 clock_Zero(&call->rto);
7049 clock_Addmsec(&call->rto, rtt_timeout);
7051 /* Update the peer, so any new calls start with our values */
7052 peer->rtt_dev = call->rtt_dev;
7053 peer->rtt = call->rtt;
7055 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rtt=%d ms, srtt=%d ms, rtt_dev=%d ms, timeout=%d.%06d sec)\n",
7056 p->header.callNumber, p, MSEC(&thisRtt), call->rtt >> 3, call->rtt_dev >> 2, (call->rto.sec), (call->rto.usec)));
7060 /* Find all server connections that have not been active for a long time, and
7063 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2,
7066 struct clock now, when;
7067 struct rxevent *event;
7068 clock_GetTime(&now);
7070 /* Find server connection structures that haven't been used for
7071 * greater than rx_idleConnectionTime */
7073 struct rx_connection **conn_ptr, **conn_end;
7074 int i, havecalls = 0;
7075 MUTEX_ENTER(&rx_connHashTable_lock);
7076 for (conn_ptr = &rx_connHashTable[0], conn_end =
7077 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
7079 struct rx_connection *conn, *next;
7080 struct rx_call *call;
7084 for (conn = *conn_ptr; conn; conn = next) {
7085 /* XXX -- Shouldn't the connection be locked? */
7088 for (i = 0; i < RX_MAXCALLS; i++) {
7089 call = conn->call[i];
7093 code = MUTEX_TRYENTER(&call->lock);
7096 result = rxi_CheckCall(call, 1);
7097 MUTEX_EXIT(&call->lock);
7099 /* If CheckCall freed the call, it might
7100 * have destroyed the connection as well,
7101 * which screws up the linked lists.
7107 if (conn->type == RX_SERVER_CONNECTION) {
7108 /* This only actually destroys the connection if
7109 * there are no outstanding calls */
7110 MUTEX_ENTER(&conn->conn_data_lock);
7111 MUTEX_ENTER(&rx_refcnt_mutex);
7112 if (!havecalls && !conn->refCount
7113 && ((conn->lastSendTime + rx_idleConnectionTime) <
7115 conn->refCount++; /* it will be decr in rx_DestroyConn */
7116 MUTEX_EXIT(&rx_refcnt_mutex);
7117 MUTEX_EXIT(&conn->conn_data_lock);
7118 #ifdef RX_ENABLE_LOCKS
7119 rxi_DestroyConnectionNoLock(conn);
7120 #else /* RX_ENABLE_LOCKS */
7121 rxi_DestroyConnection(conn);
7122 #endif /* RX_ENABLE_LOCKS */
7124 #ifdef RX_ENABLE_LOCKS
7126 MUTEX_EXIT(&rx_refcnt_mutex);
7127 MUTEX_EXIT(&conn->conn_data_lock);
7129 #endif /* RX_ENABLE_LOCKS */
7133 #ifdef RX_ENABLE_LOCKS
7134 while (rx_connCleanup_list) {
7135 struct rx_connection *conn;
7136 conn = rx_connCleanup_list;
7137 rx_connCleanup_list = rx_connCleanup_list->next;
7138 MUTEX_EXIT(&rx_connHashTable_lock);
7139 rxi_CleanupConnection(conn);
7140 MUTEX_ENTER(&rx_connHashTable_lock);
7142 MUTEX_EXIT(&rx_connHashTable_lock);
7143 #endif /* RX_ENABLE_LOCKS */
7146 /* Find any peer structures that haven't been used (haven't had an
7147 * associated connection) for greater than rx_idlePeerTime */
7149 struct rx_peer **peer_ptr, **peer_end;
7153 * Why do we need to hold the rx_peerHashTable_lock across
7154 * the incrementing of peer_ptr since the rx_peerHashTable
7155 * array is not changing? We don't.
7157 * By dropping the lock periodically we can permit other
7158 * activities to be performed while a rxi_ReapConnections
7159 * call is in progress. The goal of reap connections
7160 * is to clean up quickly without causing large amounts
7161 * of contention. Therefore, it is important that global
7162 * mutexes not be held for extended periods of time.
7164 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7165 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7167 struct rx_peer *peer, *next, *prev;
7169 MUTEX_ENTER(&rx_peerHashTable_lock);
7170 for (prev = peer = *peer_ptr; peer; peer = next) {
7172 code = MUTEX_TRYENTER(&peer->peer_lock);
7173 if ((code) && (peer->refCount == 0)
7174 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
7175 struct opr_queue *cursor, *store;
7179 * now know that this peer object is one to be
7180 * removed from the hash table. Once it is removed
7181 * it can't be referenced by other threads.
7182 * Lets remove it first and decrement the struct
7183 * nPeerStructs count.
7185 if (peer == *peer_ptr) {
7191 if (rx_stats_active)
7192 rx_atomic_dec(&rx_stats.nPeerStructs);
7195 * Now if we hold references on 'prev' and 'next'
7196 * we can safely drop the rx_peerHashTable_lock
7197 * while we destroy this 'peer' object.
7203 MUTEX_EXIT(&rx_peerHashTable_lock);
7205 MUTEX_EXIT(&peer->peer_lock);
7206 MUTEX_DESTROY(&peer->peer_lock);
7208 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
7209 unsigned int num_funcs;
7210 struct rx_interface_stat *rpc_stat
7211 = opr_queue_Entry(cursor, struct rx_interface_stat,
7216 opr_queue_Remove(&rpc_stat->entry);
7217 opr_queue_Remove(&rpc_stat->entryPeers);
7219 num_funcs = rpc_stat->stats[0].func_total;
7221 sizeof(rx_interface_stat_t) +
7222 rpc_stat->stats[0].func_total *
7223 sizeof(rx_function_entry_v1_t);
7225 rxi_Free(rpc_stat, space);
7227 MUTEX_ENTER(&rx_rpc_stats);
7228 rxi_rpc_peer_stat_cnt -= num_funcs;
7229 MUTEX_EXIT(&rx_rpc_stats);
7234 * Regain the rx_peerHashTable_lock and
7235 * decrement the reference count on 'prev'
7238 MUTEX_ENTER(&rx_peerHashTable_lock);
7245 MUTEX_EXIT(&peer->peer_lock);
7250 MUTEX_EXIT(&rx_peerHashTable_lock);
7254 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
7255 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
7256 * GC, just below. Really, we shouldn't have to keep moving packets from
7257 * one place to another, but instead ought to always know if we can
7258 * afford to hold onto a packet in its particular use. */
7259 MUTEX_ENTER(&rx_freePktQ_lock);
7260 if (rx_waitingForPackets) {
7261 rx_waitingForPackets = 0;
7262 #ifdef RX_ENABLE_LOCKS
7263 CV_BROADCAST(&rx_waitingForPackets_cv);
7265 osi_rxWakeup(&rx_waitingForPackets);
7268 MUTEX_EXIT(&rx_freePktQ_lock);
7271 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
7272 event = rxevent_Post(&when, &now, rxi_ReapConnections, 0, NULL, 0);
7273 rxevent_Put(&event);
7277 /* rxs_Release - This isn't strictly necessary but, since the macro name from
7278 * rx.h is sort of strange this is better. This is called with a security
7279 * object before it is discarded. Each connection using a security object has
7280 * its own refcount to the object so it won't actually be freed until the last
7281 * connection is destroyed.
7283 * This is the only rxs module call. A hold could also be written but no one
7287 rxs_Release(struct rx_securityClass *aobj)
7289 return RXS_Close(aobj);
7297 #define TRACE_OPTION_RX_DEBUG 16
7305 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
7306 0, KEY_QUERY_VALUE, &parmKey);
7307 if (code != ERROR_SUCCESS)
7310 dummyLen = sizeof(TraceOption);
7311 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
7312 (BYTE *) &TraceOption, &dummyLen);
7313 if (code == ERROR_SUCCESS) {
7314 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
7316 RegCloseKey (parmKey);
7317 #endif /* AFS_NT40_ENV */
7322 rx_DebugOnOff(int on)
7326 rxdebug_active = on;
7332 rx_StatsOnOff(int on)
7334 rx_stats_active = on;
7338 /* Don't call this debugging routine directly; use dpf */
7340 rxi_DebugPrint(char *format, ...)
7349 va_start(ap, format);
7351 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7354 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7356 OutputDebugString(msg);
7362 va_start(ap, format);
7364 clock_GetTime(&now);
7365 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7366 (unsigned int)now.usec);
7367 vfprintf(rx_Log, format, ap);
7375 * This function is used to process the rx_stats structure that is local
7376 * to a process as well as an rx_stats structure received from a remote
7377 * process (via rxdebug). Therefore, it needs to do minimal version
7381 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7382 afs_int32 freePackets, char version)
7386 if (size != sizeof(struct rx_statistics)) {
7388 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7389 size, sizeof(struct rx_statistics));
7392 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7395 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7396 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7397 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7398 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7399 s->specialPktAllocFailures);
7401 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7402 s->receivePktAllocFailures, s->sendPktAllocFailures,
7403 s->specialPktAllocFailures);
7407 " greedy %u, " "bogusReads %u (last from host %x), "
7408 "noPackets %u, " "noBuffers %u, " "selects %u, "
7409 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7410 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7411 s->selects, s->sendSelects);
7413 fprintf(file, " packets read: ");
7414 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7415 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7417 fprintf(file, "\n");
7420 " other read counters: data %u, " "ack %u, " "dup %u "
7421 "spurious %u " "dally %u\n", s->dataPacketsRead,
7422 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7423 s->ignorePacketDally);
7425 fprintf(file, " packets sent: ");
7426 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7427 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7429 fprintf(file, "\n");
7432 " other send counters: ack %u, " "data %u (not resends), "
7433 "resends %u, " "pushed %u, " "acked&ignored %u\n",
7434 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7435 s->dataPacketsPushed, s->ignoreAckedPacket);
7438 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7439 s->netSendFailures, (int)s->fatalErrors);
7441 if (s->nRttSamples) {
7442 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
7443 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7445 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
7446 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7450 " %d server connections, " "%d client connections, "
7451 "%d peer structs, " "%d call structs, " "%d free call structs\n",
7452 s->nServerConns, s->nClientConns, s->nPeerStructs,
7453 s->nCallStructs, s->nFreeCallStructs);
7455 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7456 fprintf(file, " %d clock updates\n", clock_nUpdates);
7460 /* for backward compatibility */
7462 rx_PrintStats(FILE * file)
7464 MUTEX_ENTER(&rx_stats_mutex);
7465 rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7466 sizeof(rx_stats), rx_nFreePackets,
7468 MUTEX_EXIT(&rx_stats_mutex);
7472 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7474 fprintf(file, "Peer %x.%d.\n",
7475 ntohl(peer->host), (int)ntohs(peer->port));
7478 " Rtt %d, " "total sent %d, " "resent %d\n",
7479 peer->rtt, peer->nSent, peer->reSends);
7481 fprintf(file, " Packet size %d\n", peer->ifMTU);
7485 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7487 * This mutex protects the following static variables:
7491 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7492 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7494 #define LOCK_RX_DEBUG
7495 #define UNLOCK_RX_DEBUG
7496 #endif /* AFS_PTHREAD_ENV */
7498 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7500 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7501 u_char type, void *inputData, size_t inputLength,
7502 void *outputData, size_t outputLength)
7504 static afs_int32 counter = 100;
7505 time_t waitTime, waitCount;
7506 struct rx_header theader;
7509 struct timeval tv_now, tv_wake, tv_delta;
7510 struct sockaddr_in taddr, faddr;
7524 tp = &tbuffer[sizeof(struct rx_header)];
7525 taddr.sin_family = AF_INET;
7526 taddr.sin_port = remotePort;
7527 taddr.sin_addr.s_addr = remoteAddr;
7528 memset(&taddr.sin_zero, 0, sizeof(taddr.sin_zero));
7529 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7530 taddr.sin_len = sizeof(struct sockaddr_in);
7533 memset(&theader, 0, sizeof(theader));
7534 theader.epoch = htonl(999);
7536 theader.callNumber = htonl(counter);
7539 theader.type = type;
7540 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7541 theader.serviceId = 0;
7543 memcpy(tbuffer, &theader, sizeof(theader));
7544 memcpy(tp, inputData, inputLength);
7546 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7547 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7549 /* see if there's a packet available */
7550 gettimeofday(&tv_wake, NULL);
7551 tv_wake.tv_sec += waitTime;
7554 FD_SET(socket, &imask);
7555 tv_delta.tv_sec = tv_wake.tv_sec;
7556 tv_delta.tv_usec = tv_wake.tv_usec;
7557 gettimeofday(&tv_now, NULL);
7559 if (tv_delta.tv_usec < tv_now.tv_usec) {
7561 tv_delta.tv_usec += 1000000;
7564 tv_delta.tv_usec -= tv_now.tv_usec;
7566 if (tv_delta.tv_sec < tv_now.tv_sec) {
7570 tv_delta.tv_sec -= tv_now.tv_sec;
7573 code = select(0, &imask, 0, 0, &tv_delta);
7574 #else /* AFS_NT40_ENV */
7575 code = select(socket + 1, &imask, 0, 0, &tv_delta);
7576 #endif /* AFS_NT40_ENV */
7577 if (code == 1 && FD_ISSET(socket, &imask)) {
7578 /* now receive a packet */
7579 faddrLen = sizeof(struct sockaddr_in);
7581 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7582 (struct sockaddr *)&faddr, &faddrLen);
7585 memcpy(&theader, tbuffer, sizeof(struct rx_header));
7586 if (counter == ntohl(theader.callNumber))
7594 /* see if we've timed out */
7602 code -= sizeof(struct rx_header);
7603 if (code > outputLength)
7604 code = outputLength;
7605 memcpy(outputData, tp, code);
7608 #endif /* RXDEBUG */
7611 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7612 afs_uint16 remotePort, struct rx_debugStats * stat,
7613 afs_uint32 * supportedValues)
7615 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7617 struct rx_debugIn in;
7619 *supportedValues = 0;
7620 in.type = htonl(RX_DEBUGI_GETSTATS);
7623 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7624 &in, sizeof(in), stat, sizeof(*stat));
7627 * If the call was successful, fixup the version and indicate
7628 * what contents of the stat structure are valid.
7629 * Also do net to host conversion of fields here.
7633 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7634 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7636 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7637 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7639 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7640 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7642 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7643 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7645 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7646 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7648 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7649 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7651 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7652 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7654 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7655 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7657 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7658 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7660 stat->nFreePackets = ntohl(stat->nFreePackets);
7661 stat->packetReclaims = ntohl(stat->packetReclaims);
7662 stat->callsExecuted = ntohl(stat->callsExecuted);
7663 stat->nWaiting = ntohl(stat->nWaiting);
7664 stat->idleThreads = ntohl(stat->idleThreads);
7665 stat->nWaited = ntohl(stat->nWaited);
7666 stat->nPackets = ntohl(stat->nPackets);
7675 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7676 afs_uint16 remotePort, struct rx_statistics * stat,
7677 afs_uint32 * supportedValues)
7679 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7681 struct rx_debugIn in;
7682 afs_int32 *lp = (afs_int32 *) stat;
7686 * supportedValues is currently unused, but added to allow future
7687 * versioning of this function.
7690 *supportedValues = 0;
7691 in.type = htonl(RX_DEBUGI_RXSTATS);
7693 memset(stat, 0, sizeof(*stat));
7695 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7696 &in, sizeof(in), stat, sizeof(*stat));
7701 * Do net to host conversion here
7704 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7715 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7716 afs_uint16 remotePort, size_t version_length,
7719 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7721 return MakeDebugCall(socket, remoteAddr, remotePort,
7722 RX_PACKET_TYPE_VERSION, a, 1, version,
7730 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7731 afs_uint16 remotePort, afs_int32 * nextConnection,
7732 int allConnections, afs_uint32 debugSupportedValues,
7733 struct rx_debugConn * conn,
7734 afs_uint32 * supportedValues)
7736 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7738 struct rx_debugIn in;
7742 * supportedValues is currently unused, but added to allow future
7743 * versioning of this function.
7746 *supportedValues = 0;
7747 if (allConnections) {
7748 in.type = htonl(RX_DEBUGI_GETALLCONN);
7750 in.type = htonl(RX_DEBUGI_GETCONN);
7752 in.index = htonl(*nextConnection);
7753 memset(conn, 0, sizeof(*conn));
7755 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7756 &in, sizeof(in), conn, sizeof(*conn));
7759 *nextConnection += 1;
7762 * Convert old connection format to new structure.
7765 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7766 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7767 #define MOVEvL(a) (conn->a = vL->a)
7769 /* any old or unrecognized version... */
7770 for (i = 0; i < RX_MAXCALLS; i++) {
7771 MOVEvL(callState[i]);
7772 MOVEvL(callMode[i]);
7773 MOVEvL(callFlags[i]);
7774 MOVEvL(callOther[i]);
7776 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7777 MOVEvL(secStats.type);
7778 MOVEvL(secStats.level);
7779 MOVEvL(secStats.flags);
7780 MOVEvL(secStats.expires);
7781 MOVEvL(secStats.packetsReceived);
7782 MOVEvL(secStats.packetsSent);
7783 MOVEvL(secStats.bytesReceived);
7784 MOVEvL(secStats.bytesSent);
7789 * Do net to host conversion here
7791 * I don't convert host or port since we are most likely
7792 * going to want these in NBO.
7794 conn->cid = ntohl(conn->cid);
7795 conn->serial = ntohl(conn->serial);
7796 for (i = 0; i < RX_MAXCALLS; i++) {
7797 conn->callNumber[i] = ntohl(conn->callNumber[i]);
7799 conn->error = ntohl(conn->error);
7800 conn->secStats.flags = ntohl(conn->secStats.flags);
7801 conn->secStats.expires = ntohl(conn->secStats.expires);
7802 conn->secStats.packetsReceived =
7803 ntohl(conn->secStats.packetsReceived);
7804 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7805 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7806 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7807 conn->epoch = ntohl(conn->epoch);
7808 conn->natMTU = ntohl(conn->natMTU);
7817 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7818 afs_uint16 remotePort, afs_int32 * nextPeer,
7819 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7820 afs_uint32 * supportedValues)
7822 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7824 struct rx_debugIn in;
7827 * supportedValues is currently unused, but added to allow future
7828 * versioning of this function.
7831 *supportedValues = 0;
7832 in.type = htonl(RX_DEBUGI_GETPEER);
7833 in.index = htonl(*nextPeer);
7834 memset(peer, 0, sizeof(*peer));
7836 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7837 &in, sizeof(in), peer, sizeof(*peer));
7843 * Do net to host conversion here
7845 * I don't convert host or port since we are most likely
7846 * going to want these in NBO.
7848 peer->ifMTU = ntohs(peer->ifMTU);
7849 peer->idleWhen = ntohl(peer->idleWhen);
7850 peer->refCount = ntohs(peer->refCount);
7851 peer->rtt = ntohl(peer->rtt);
7852 peer->rtt_dev = ntohl(peer->rtt_dev);
7853 peer->timeout.sec = 0;
7854 peer->timeout.usec = 0;
7855 peer->nSent = ntohl(peer->nSent);
7856 peer->reSends = ntohl(peer->reSends);
7857 peer->natMTU = ntohs(peer->natMTU);
7858 peer->maxMTU = ntohs(peer->maxMTU);
7859 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7860 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7861 peer->MTU = ntohs(peer->MTU);
7862 peer->cwind = ntohs(peer->cwind);
7863 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7864 peer->congestSeq = ntohs(peer->congestSeq);
7865 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7866 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7867 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7868 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7877 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7878 struct rx_debugPeer * peerStats)
7881 afs_int32 error = 1; /* default to "did not succeed" */
7882 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7884 MUTEX_ENTER(&rx_peerHashTable_lock);
7885 for(tp = rx_peerHashTable[hashValue];
7886 tp != NULL; tp = tp->next) {
7887 if (tp->host == peerHost)
7893 MUTEX_EXIT(&rx_peerHashTable_lock);
7897 MUTEX_ENTER(&tp->peer_lock);
7898 peerStats->host = tp->host;
7899 peerStats->port = tp->port;
7900 peerStats->ifMTU = tp->ifMTU;
7901 peerStats->idleWhen = tp->idleWhen;
7902 peerStats->refCount = tp->refCount;
7903 peerStats->burstSize = 0;
7904 peerStats->burst = 0;
7905 peerStats->burstWait.sec = 0;
7906 peerStats->burstWait.usec = 0;
7907 peerStats->rtt = tp->rtt;
7908 peerStats->rtt_dev = tp->rtt_dev;
7909 peerStats->timeout.sec = 0;
7910 peerStats->timeout.usec = 0;
7911 peerStats->nSent = tp->nSent;
7912 peerStats->reSends = tp->reSends;
7913 peerStats->natMTU = tp->natMTU;
7914 peerStats->maxMTU = tp->maxMTU;
7915 peerStats->maxDgramPackets = tp->maxDgramPackets;
7916 peerStats->ifDgramPackets = tp->ifDgramPackets;
7917 peerStats->MTU = tp->MTU;
7918 peerStats->cwind = tp->cwind;
7919 peerStats->nDgramPackets = tp->nDgramPackets;
7920 peerStats->congestSeq = tp->congestSeq;
7921 peerStats->bytesSent.high = tp->bytesSent >> 32;
7922 peerStats->bytesSent.low = tp->bytesSent & MAX_AFS_UINT32;
7923 peerStats->bytesReceived.high = tp->bytesReceived >> 32;
7924 peerStats->bytesReceived.low
7925 = tp->bytesReceived & MAX_AFS_UINT32;
7926 MUTEX_EXIT(&tp->peer_lock);
7928 MUTEX_ENTER(&rx_peerHashTable_lock);
7931 MUTEX_EXIT(&rx_peerHashTable_lock);
7939 struct rx_serverQueueEntry *np;
7942 struct rx_call *call;
7943 struct rx_serverQueueEntry *sq;
7947 if (!rxi_IsRunning()) {
7949 return; /* Already shutdown. */
7951 rx_atomic_set(&rxi_running, 0);
7954 #ifndef AFS_PTHREAD_ENV
7955 FD_ZERO(&rx_selectMask);
7956 #endif /* AFS_PTHREAD_ENV */
7957 rxi_dataQuota = RX_MAX_QUOTA;
7958 #ifndef AFS_PTHREAD_ENV
7960 #endif /* AFS_PTHREAD_ENV */
7963 #ifndef AFS_PTHREAD_ENV
7964 #ifndef AFS_USE_GETTIMEOFDAY
7966 #endif /* AFS_USE_GETTIMEOFDAY */
7967 #endif /* AFS_PTHREAD_ENV */
7969 while (!opr_queue_IsEmpty(&rx_freeCallQueue)) {
7970 call = opr_queue_First(&rx_freeCallQueue, struct rx_call, entry);
7971 opr_queue_Remove(&call->entry);
7972 rxi_Free(call, sizeof(struct rx_call));
7975 while (!opr_queue_IsEmpty(&rx_idleServerQueue)) {
7976 sq = opr_queue_First(&rx_idleServerQueue, struct rx_serverQueueEntry,
7978 opr_queue_Remove(&sq->entry);
7983 struct rx_peer **peer_ptr, **peer_end;
7984 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7985 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7987 struct rx_peer *peer, *next;
7989 MUTEX_ENTER(&rx_peerHashTable_lock);
7990 for (peer = *peer_ptr; peer; peer = next) {
7991 struct opr_queue *cursor, *store;
7994 MUTEX_ENTER(&rx_rpc_stats);
7995 MUTEX_ENTER(&peer->peer_lock);
7996 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
7997 unsigned int num_funcs;
7998 struct rx_interface_stat *rpc_stat
7999 = opr_queue_Entry(cursor, struct rx_interface_stat,
8003 opr_queue_Remove(&rpc_stat->entry);
8004 opr_queue_Remove(&rpc_stat->entryPeers);
8005 num_funcs = rpc_stat->stats[0].func_total;
8007 sizeof(rx_interface_stat_t) +
8008 rpc_stat->stats[0].func_total *
8009 sizeof(rx_function_entry_v1_t);
8011 rxi_Free(rpc_stat, space);
8013 /* rx_rpc_stats must be held */
8014 rxi_rpc_peer_stat_cnt -= num_funcs;
8016 MUTEX_EXIT(&peer->peer_lock);
8017 MUTEX_EXIT(&rx_rpc_stats);
8021 if (rx_stats_active)
8022 rx_atomic_dec(&rx_stats.nPeerStructs);
8024 MUTEX_EXIT(&rx_peerHashTable_lock);
8027 for (i = 0; i < RX_MAX_SERVICES; i++) {
8029 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
8031 for (i = 0; i < rx_hashTableSize; i++) {
8032 struct rx_connection *tc, *ntc;
8033 MUTEX_ENTER(&rx_connHashTable_lock);
8034 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
8036 for (j = 0; j < RX_MAXCALLS; j++) {
8038 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
8041 rxi_Free(tc, sizeof(*tc));
8043 MUTEX_EXIT(&rx_connHashTable_lock);
8046 MUTEX_ENTER(&freeSQEList_lock);
8048 while ((np = rx_FreeSQEList)) {
8049 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
8050 MUTEX_DESTROY(&np->lock);
8051 rxi_Free(np, sizeof(*np));
8054 MUTEX_EXIT(&freeSQEList_lock);
8055 MUTEX_DESTROY(&freeSQEList_lock);
8056 MUTEX_DESTROY(&rx_freeCallQueue_lock);
8057 MUTEX_DESTROY(&rx_connHashTable_lock);
8058 MUTEX_DESTROY(&rx_peerHashTable_lock);
8059 MUTEX_DESTROY(&rx_serverPool_lock);
8061 osi_Free(rx_connHashTable,
8062 rx_hashTableSize * sizeof(struct rx_connection *));
8063 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
8065 UNPIN(rx_connHashTable,
8066 rx_hashTableSize * sizeof(struct rx_connection *));
8067 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
8069 MUTEX_ENTER(&rx_quota_mutex);
8070 rxi_dataQuota = RX_MAX_QUOTA;
8071 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
8072 MUTEX_EXIT(&rx_quota_mutex);
8079 * Routines to implement connection specific data.
8083 rx_KeyCreate(rx_destructor_t rtn)
8086 MUTEX_ENTER(&rxi_keyCreate_lock);
8087 key = rxi_keyCreate_counter++;
8088 rxi_keyCreate_destructor = (rx_destructor_t *)
8089 realloc((void *)rxi_keyCreate_destructor,
8090 (key + 1) * sizeof(rx_destructor_t));
8091 rxi_keyCreate_destructor[key] = rtn;
8092 MUTEX_EXIT(&rxi_keyCreate_lock);
8097 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
8100 MUTEX_ENTER(&conn->conn_data_lock);
8101 if (!conn->specific) {
8102 conn->specific = malloc((key + 1) * sizeof(void *));
8103 for (i = 0; i < key; i++)
8104 conn->specific[i] = NULL;
8105 conn->nSpecific = key + 1;
8106 conn->specific[key] = ptr;
8107 } else if (key >= conn->nSpecific) {
8108 conn->specific = (void **)
8109 realloc(conn->specific, (key + 1) * sizeof(void *));
8110 for (i = conn->nSpecific; i < key; i++)
8111 conn->specific[i] = NULL;
8112 conn->nSpecific = key + 1;
8113 conn->specific[key] = ptr;
8115 if (conn->specific[key] && rxi_keyCreate_destructor[key])
8116 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
8117 conn->specific[key] = ptr;
8119 MUTEX_EXIT(&conn->conn_data_lock);
8123 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
8126 MUTEX_ENTER(&svc->svc_data_lock);
8127 if (!svc->specific) {
8128 svc->specific = malloc((key + 1) * sizeof(void *));
8129 for (i = 0; i < key; i++)
8130 svc->specific[i] = NULL;
8131 svc->nSpecific = key + 1;
8132 svc->specific[key] = ptr;
8133 } else if (key >= svc->nSpecific) {
8134 svc->specific = (void **)
8135 realloc(svc->specific, (key + 1) * sizeof(void *));
8136 for (i = svc->nSpecific; i < key; i++)
8137 svc->specific[i] = NULL;
8138 svc->nSpecific = key + 1;
8139 svc->specific[key] = ptr;
8141 if (svc->specific[key] && rxi_keyCreate_destructor[key])
8142 (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
8143 svc->specific[key] = ptr;
8145 MUTEX_EXIT(&svc->svc_data_lock);
8149 rx_GetSpecific(struct rx_connection *conn, int key)
8152 MUTEX_ENTER(&conn->conn_data_lock);
8153 if (key >= conn->nSpecific)
8156 ptr = conn->specific[key];
8157 MUTEX_EXIT(&conn->conn_data_lock);
8162 rx_GetServiceSpecific(struct rx_service *svc, int key)
8165 MUTEX_ENTER(&svc->svc_data_lock);
8166 if (key >= svc->nSpecific)
8169 ptr = svc->specific[key];
8170 MUTEX_EXIT(&svc->svc_data_lock);
8175 #endif /* !KERNEL */
8178 * processStats is a queue used to store the statistics for the local
8179 * process. Its contents are similar to the contents of the rpcStats
8180 * queue on a rx_peer structure, but the actual data stored within
8181 * this queue contains totals across the lifetime of the process (assuming
8182 * the stats have not been reset) - unlike the per peer structures
8183 * which can come and go based upon the peer lifetime.
8186 static struct opr_queue processStats = { &processStats, &processStats };
8189 * peerStats is a queue used to store the statistics for all peer structs.
8190 * Its contents are the union of all the peer rpcStats queues.
8193 static struct opr_queue peerStats = { &peerStats, &peerStats };
8196 * rxi_monitor_processStats is used to turn process wide stat collection
8200 static int rxi_monitor_processStats = 0;
8203 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
8206 static int rxi_monitor_peerStats = 0;
8210 rxi_ClearRPCOpStat(rx_function_entry_v1_p rpc_stat)
8212 rpc_stat->invocations = 0;
8213 rpc_stat->bytes_sent = 0;
8214 rpc_stat->bytes_rcvd = 0;
8215 rpc_stat->queue_time_sum.sec = 0;
8216 rpc_stat->queue_time_sum.usec = 0;
8217 rpc_stat->queue_time_sum_sqr.sec = 0;
8218 rpc_stat->queue_time_sum_sqr.usec = 0;
8219 rpc_stat->queue_time_min.sec = 9999999;
8220 rpc_stat->queue_time_min.usec = 9999999;
8221 rpc_stat->queue_time_max.sec = 0;
8222 rpc_stat->queue_time_max.usec = 0;
8223 rpc_stat->execution_time_sum.sec = 0;
8224 rpc_stat->execution_time_sum.usec = 0;
8225 rpc_stat->execution_time_sum_sqr.sec = 0;
8226 rpc_stat->execution_time_sum_sqr.usec = 0;
8227 rpc_stat->execution_time_min.sec = 9999999;
8228 rpc_stat->execution_time_min.usec = 9999999;
8229 rpc_stat->execution_time_max.sec = 0;
8230 rpc_stat->execution_time_max.usec = 0;
8234 * Given all of the information for a particular rpc
8235 * call, find or create (if requested) the stat structure for the rpc.
8238 * the queue of stats that will be updated with the new value
8240 * @param rxInterface
8241 * a unique number that identifies the rpc interface
8244 * the total number of functions in this interface. this is only
8245 * required if create is true
8248 * if true, this invocation was made to a server
8251 * the ip address of the remote host. this is only required if create
8252 * and addToPeerList are true
8255 * the port of the remote host. this is only required if create
8256 * and addToPeerList are true
8258 * @param addToPeerList
8259 * if != 0, add newly created stat to the global peer list
8262 * if a new stats structure is allocated, the counter will
8263 * be updated with the new number of allocated stat structures.
8264 * only required if create is true
8267 * if no stats structure exists, allocate one
8271 static rx_interface_stat_p
8272 rxi_FindRpcStat(struct opr_queue *stats, afs_uint32 rxInterface,
8273 afs_uint32 totalFunc, int isServer, afs_uint32 remoteHost,
8274 afs_uint32 remotePort, int addToPeerList,
8275 unsigned int *counter, int create)
8277 rx_interface_stat_p rpc_stat = NULL;
8278 struct opr_queue *cursor;
8281 * See if there's already a structure for this interface
8284 for (opr_queue_Scan(stats, cursor)) {
8285 rpc_stat = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8287 if ((rpc_stat->stats[0].interfaceId == rxInterface)
8288 && (rpc_stat->stats[0].remote_is_server == isServer))
8292 /* if they didn't ask us to create, we're done */
8294 if (opr_queue_IsEnd(stats, cursor))
8300 /* can't proceed without these */
8301 if (!totalFunc || !counter)
8305 * Didn't find a match so allocate a new structure and add it to the
8309 if (opr_queue_IsEnd(stats, cursor) || (rpc_stat == NULL)
8310 || (rpc_stat->stats[0].interfaceId != rxInterface)
8311 || (rpc_stat->stats[0].remote_is_server != isServer)) {
8316 sizeof(rx_interface_stat_t) +
8317 totalFunc * sizeof(rx_function_entry_v1_t);
8319 rpc_stat = rxi_Alloc(space);
8320 if (rpc_stat == NULL)
8323 *counter += totalFunc;
8324 for (i = 0; i < totalFunc; i++) {
8325 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8326 rpc_stat->stats[i].remote_peer = remoteHost;
8327 rpc_stat->stats[i].remote_port = remotePort;
8328 rpc_stat->stats[i].remote_is_server = isServer;
8329 rpc_stat->stats[i].interfaceId = rxInterface;
8330 rpc_stat->stats[i].func_total = totalFunc;
8331 rpc_stat->stats[i].func_index = i;
8333 opr_queue_Prepend(stats, &rpc_stat->entry);
8334 if (addToPeerList) {
8335 opr_queue_Prepend(&peerStats, &rpc_stat->entryPeers);
8342 rx_ClearProcessRPCStats(afs_int32 rxInterface)
8344 rx_interface_stat_p rpc_stat;
8347 if (rxInterface == -1)
8350 MUTEX_ENTER(&rx_rpc_stats);
8351 rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8354 totalFunc = rpc_stat->stats[0].func_total;
8355 for (i = 0; i < totalFunc; i++)
8356 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8358 MUTEX_EXIT(&rx_rpc_stats);
8363 rx_ClearPeerRPCStats(afs_int32 rxInterface, afs_uint32 peerHost, afs_uint16 peerPort)
8365 rx_interface_stat_p rpc_stat;
8367 struct rx_peer * peer;
8369 if (rxInterface == -1)
8372 peer = rxi_FindPeer(peerHost, peerPort, 0);
8376 MUTEX_ENTER(&rx_rpc_stats);
8377 rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8380 totalFunc = rpc_stat->stats[0].func_total;
8381 for (i = 0; i < totalFunc; i++)
8382 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8384 MUTEX_EXIT(&rx_rpc_stats);
8389 rx_CopyProcessRPCStats(afs_uint64 op)
8391 rx_interface_stat_p rpc_stat;
8392 rx_function_entry_v1_p rpcop_stat =
8393 rxi_Alloc(sizeof(rx_function_entry_v1_t));
8394 int currentFunc = (op & MAX_AFS_UINT32);
8395 afs_int32 rxInterface = (op >> 32);
8397 if (!rxi_monitor_processStats)
8400 if (rxInterface == -1)
8403 if (rpcop_stat == NULL)
8406 MUTEX_ENTER(&rx_rpc_stats);
8407 rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8410 memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8411 sizeof(rx_function_entry_v1_t));
8412 MUTEX_EXIT(&rx_rpc_stats);
8414 rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8421 rx_CopyPeerRPCStats(afs_uint64 op, afs_uint32 peerHost, afs_uint16 peerPort)
8423 rx_interface_stat_p rpc_stat;
8424 rx_function_entry_v1_p rpcop_stat =
8425 rxi_Alloc(sizeof(rx_function_entry_v1_t));
8426 int currentFunc = (op & MAX_AFS_UINT32);
8427 afs_int32 rxInterface = (op >> 32);
8428 struct rx_peer *peer;
8430 if (!rxi_monitor_peerStats)
8433 if (rxInterface == -1)
8436 if (rpcop_stat == NULL)
8439 peer = rxi_FindPeer(peerHost, peerPort, 0);
8443 MUTEX_ENTER(&rx_rpc_stats);
8444 rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8447 memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8448 sizeof(rx_function_entry_v1_t));
8449 MUTEX_EXIT(&rx_rpc_stats);
8451 rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8458 rx_ReleaseRPCStats(void *stats)
8461 rxi_Free(stats, sizeof(rx_function_entry_v1_t));
8465 * Given all of the information for a particular rpc
8466 * call, create (if needed) and update the stat totals for the rpc.
8469 * the queue of stats that will be updated with the new value
8471 * @param rxInterface
8472 * a unique number that identifies the rpc interface
8474 * @param currentFunc
8475 * the index of the function being invoked
8478 * the total number of functions in this interface
8481 * the amount of time this function waited for a thread
8484 * the amount of time this function invocation took to execute
8487 * the number bytes sent by this invocation
8490 * the number bytes received by this invocation
8493 * if true, this invocation was made to a server
8496 * the ip address of the remote host
8499 * the port of the remote host
8501 * @param addToPeerList
8502 * if != 0, add newly created stat to the global peer list
8505 * if a new stats structure is allocated, the counter will
8506 * be updated with the new number of allocated stat structures
8511 rxi_AddRpcStat(struct opr_queue *stats, afs_uint32 rxInterface,
8512 afs_uint32 currentFunc, afs_uint32 totalFunc,
8513 struct clock *queueTime, struct clock *execTime,
8514 afs_uint64 bytesSent, afs_uint64 bytesRcvd, int isServer,
8515 afs_uint32 remoteHost, afs_uint32 remotePort,
8516 int addToPeerList, unsigned int *counter)
8519 rx_interface_stat_p rpc_stat;
8521 rpc_stat = rxi_FindRpcStat(stats, rxInterface, totalFunc, isServer,
8522 remoteHost, remotePort, addToPeerList, counter,
8530 * Increment the stats for this function
8533 rpc_stat->stats[currentFunc].invocations++;
8534 rpc_stat->stats[currentFunc].bytes_sent += bytesSent;
8535 rpc_stat->stats[currentFunc].bytes_rcvd += bytesRcvd;
8536 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8537 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8538 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8539 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8541 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8542 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8544 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8545 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8547 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8548 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8550 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8551 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8559 rxi_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8560 afs_uint32 currentFunc, afs_uint32 totalFunc,
8561 struct clock *queueTime, struct clock *execTime,
8562 afs_uint64 bytesSent, afs_uint64 bytesRcvd,
8566 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8569 MUTEX_ENTER(&rx_rpc_stats);
8571 if (rxi_monitor_peerStats) {
8572 MUTEX_ENTER(&peer->peer_lock);
8573 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8574 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8575 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8576 MUTEX_EXIT(&peer->peer_lock);
8579 if (rxi_monitor_processStats) {
8580 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8581 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8582 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8585 MUTEX_EXIT(&rx_rpc_stats);
8589 * Increment the times and count for a particular rpc function.
8591 * Traditionally this call was invoked from rxgen stubs. Modern stubs
8592 * call rx_RecordCallStatistics instead, so the public version of this
8593 * function is left purely for legacy callers.
8596 * The peer who invoked the rpc
8598 * @param rxInterface
8599 * A unique number that identifies the rpc interface
8601 * @param currentFunc
8602 * The index of the function being invoked
8605 * The total number of functions in this interface
8608 * The amount of time this function waited for a thread
8611 * The amount of time this function invocation took to execute
8614 * The number bytes sent by this invocation
8617 * The number bytes received by this invocation
8620 * If true, this invocation was made to a server
8624 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8625 afs_uint32 currentFunc, afs_uint32 totalFunc,
8626 struct clock *queueTime, struct clock *execTime,
8627 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8633 sent64 = ((afs_uint64)bytesSent->high << 32) + bytesSent->low;
8634 rcvd64 = ((afs_uint64)bytesRcvd->high << 32) + bytesRcvd->low;
8636 rxi_IncrementTimeAndCount(peer, rxInterface, currentFunc, totalFunc,
8637 queueTime, execTime, sent64, rcvd64,
8644 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8648 * IN callerVersion - the rpc stat version of the caller.
8650 * IN count - the number of entries to marshall.
8652 * IN stats - pointer to stats to be marshalled.
8654 * OUT ptr - Where to store the marshalled data.
8661 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8662 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8668 * We only support the first version
8670 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8671 *(ptr++) = stats->remote_peer;
8672 *(ptr++) = stats->remote_port;
8673 *(ptr++) = stats->remote_is_server;
8674 *(ptr++) = stats->interfaceId;
8675 *(ptr++) = stats->func_total;
8676 *(ptr++) = stats->func_index;
8677 *(ptr++) = stats->invocations >> 32;
8678 *(ptr++) = stats->invocations & MAX_AFS_UINT32;
8679 *(ptr++) = stats->bytes_sent >> 32;
8680 *(ptr++) = stats->bytes_sent & MAX_AFS_UINT32;
8681 *(ptr++) = stats->bytes_rcvd >> 32;
8682 *(ptr++) = stats->bytes_rcvd & MAX_AFS_UINT32;
8683 *(ptr++) = stats->queue_time_sum.sec;
8684 *(ptr++) = stats->queue_time_sum.usec;
8685 *(ptr++) = stats->queue_time_sum_sqr.sec;
8686 *(ptr++) = stats->queue_time_sum_sqr.usec;
8687 *(ptr++) = stats->queue_time_min.sec;
8688 *(ptr++) = stats->queue_time_min.usec;
8689 *(ptr++) = stats->queue_time_max.sec;
8690 *(ptr++) = stats->queue_time_max.usec;
8691 *(ptr++) = stats->execution_time_sum.sec;
8692 *(ptr++) = stats->execution_time_sum.usec;
8693 *(ptr++) = stats->execution_time_sum_sqr.sec;
8694 *(ptr++) = stats->execution_time_sum_sqr.usec;
8695 *(ptr++) = stats->execution_time_min.sec;
8696 *(ptr++) = stats->execution_time_min.usec;
8697 *(ptr++) = stats->execution_time_max.sec;
8698 *(ptr++) = stats->execution_time_max.usec;
8704 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8709 * IN callerVersion - the rpc stat version of the caller
8711 * OUT myVersion - the rpc stat version of this function
8713 * OUT clock_sec - local time seconds
8715 * OUT clock_usec - local time microseconds
8717 * OUT allocSize - the number of bytes allocated to contain stats
8719 * OUT statCount - the number stats retrieved from this process.
8721 * OUT stats - the actual stats retrieved from this process.
8725 * Returns void. If successful, stats will != NULL.
8729 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8730 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8731 size_t * allocSize, afs_uint32 * statCount,
8732 afs_uint32 ** stats)
8742 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8745 * Check to see if stats are enabled
8748 MUTEX_ENTER(&rx_rpc_stats);
8749 if (!rxi_monitor_processStats) {
8750 MUTEX_EXIT(&rx_rpc_stats);
8754 clock_GetTime(&now);
8755 *clock_sec = now.sec;
8756 *clock_usec = now.usec;
8759 * Allocate the space based upon the caller version
8761 * If the client is at an older version than we are,
8762 * we return the statistic data in the older data format, but
8763 * we still return our version number so the client knows we
8764 * are maintaining more data than it can retrieve.
8767 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8768 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8769 *statCount = rxi_rpc_process_stat_cnt;
8772 * This can't happen yet, but in the future version changes
8773 * can be handled by adding additional code here
8777 if (space > (size_t) 0) {
8779 ptr = *stats = rxi_Alloc(space);
8782 struct opr_queue *cursor;
8784 for (opr_queue_Scan(&processStats, cursor)) {
8785 struct rx_interface_stat *rpc_stat =
8786 opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8788 * Copy the data based upon the caller version
8790 rx_MarshallProcessRPCStats(callerVersion,
8791 rpc_stat->stats[0].func_total,
8792 rpc_stat->stats, &ptr);
8798 MUTEX_EXIT(&rx_rpc_stats);
8803 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8807 * IN callerVersion - the rpc stat version of the caller
8809 * OUT myVersion - the rpc stat version of this function
8811 * OUT clock_sec - local time seconds
8813 * OUT clock_usec - local time microseconds
8815 * OUT allocSize - the number of bytes allocated to contain stats
8817 * OUT statCount - the number of stats retrieved from the individual
8820 * OUT stats - the actual stats retrieved from the individual peer structures.
8824 * Returns void. If successful, stats will != NULL.
8828 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8829 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8830 size_t * allocSize, afs_uint32 * statCount,
8831 afs_uint32 ** stats)
8841 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8844 * Check to see if stats are enabled
8847 MUTEX_ENTER(&rx_rpc_stats);
8848 if (!rxi_monitor_peerStats) {
8849 MUTEX_EXIT(&rx_rpc_stats);
8853 clock_GetTime(&now);
8854 *clock_sec = now.sec;
8855 *clock_usec = now.usec;
8858 * Allocate the space based upon the caller version
8860 * If the client is at an older version than we are,
8861 * we return the statistic data in the older data format, but
8862 * we still return our version number so the client knows we
8863 * are maintaining more data than it can retrieve.
8866 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8867 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8868 *statCount = rxi_rpc_peer_stat_cnt;
8871 * This can't happen yet, but in the future version changes
8872 * can be handled by adding additional code here
8876 if (space > (size_t) 0) {
8878 ptr = *stats = rxi_Alloc(space);
8881 struct opr_queue *cursor;
8883 for (opr_queue_Scan(&peerStats, cursor)) {
8884 struct rx_interface_stat *rpc_stat
8885 = opr_queue_Entry(cursor, struct rx_interface_stat,
8889 * Copy the data based upon the caller version
8891 rx_MarshallProcessRPCStats(callerVersion,
8892 rpc_stat->stats[0].func_total,
8893 rpc_stat->stats, &ptr);
8899 MUTEX_EXIT(&rx_rpc_stats);
8904 * rx_FreeRPCStats - free memory allocated by
8905 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
8909 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
8910 * rx_RetrievePeerRPCStats
8912 * IN allocSize - the number of bytes in stats.
8920 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
8922 rxi_Free(stats, allocSize);
8926 * rx_queryProcessRPCStats - see if process rpc stat collection is
8927 * currently enabled.
8933 * Returns 0 if stats are not enabled != 0 otherwise
8937 rx_queryProcessRPCStats(void)
8940 MUTEX_ENTER(&rx_rpc_stats);
8941 rc = rxi_monitor_processStats;
8942 MUTEX_EXIT(&rx_rpc_stats);
8947 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
8953 * Returns 0 if stats are not enabled != 0 otherwise
8957 rx_queryPeerRPCStats(void)
8960 MUTEX_ENTER(&rx_rpc_stats);
8961 rc = rxi_monitor_peerStats;
8962 MUTEX_EXIT(&rx_rpc_stats);
8967 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
8977 rx_enableProcessRPCStats(void)
8979 MUTEX_ENTER(&rx_rpc_stats);
8980 rx_enable_stats = 1;
8981 rxi_monitor_processStats = 1;
8982 MUTEX_EXIT(&rx_rpc_stats);
8986 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
8996 rx_enablePeerRPCStats(void)
8998 MUTEX_ENTER(&rx_rpc_stats);
8999 rx_enable_stats = 1;
9000 rxi_monitor_peerStats = 1;
9001 MUTEX_EXIT(&rx_rpc_stats);
9005 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
9015 rx_disableProcessRPCStats(void)
9017 struct opr_queue *cursor, *store;
9020 MUTEX_ENTER(&rx_rpc_stats);
9023 * Turn off process statistics and if peer stats is also off, turn
9027 rxi_monitor_processStats = 0;
9028 if (rxi_monitor_peerStats == 0) {
9029 rx_enable_stats = 0;
9032 for (opr_queue_ScanSafe(&processStats, cursor, store)) {
9033 unsigned int num_funcs = 0;
9034 struct rx_interface_stat *rpc_stat
9035 = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
9037 opr_queue_Remove(&rpc_stat->entry);
9039 num_funcs = rpc_stat->stats[0].func_total;
9041 sizeof(rx_interface_stat_t) +
9042 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
9044 rxi_Free(rpc_stat, space);
9045 rxi_rpc_process_stat_cnt -= num_funcs;
9047 MUTEX_EXIT(&rx_rpc_stats);
9051 * rx_disablePeerRPCStats - stop rpc stat collection for peers
9061 rx_disablePeerRPCStats(void)
9063 struct rx_peer **peer_ptr, **peer_end;
9067 * Turn off peer statistics and if process stats is also off, turn
9071 rxi_monitor_peerStats = 0;
9072 if (rxi_monitor_processStats == 0) {
9073 rx_enable_stats = 0;
9076 for (peer_ptr = &rx_peerHashTable[0], peer_end =
9077 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
9079 struct rx_peer *peer, *next, *prev;
9081 MUTEX_ENTER(&rx_peerHashTable_lock);
9082 MUTEX_ENTER(&rx_rpc_stats);
9083 for (prev = peer = *peer_ptr; peer; peer = next) {
9085 code = MUTEX_TRYENTER(&peer->peer_lock);
9088 struct opr_queue *cursor, *store;
9090 if (prev == *peer_ptr) {
9101 MUTEX_EXIT(&rx_peerHashTable_lock);
9103 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
9104 unsigned int num_funcs = 0;
9105 struct rx_interface_stat *rpc_stat
9106 = opr_queue_Entry(cursor, struct rx_interface_stat,
9109 opr_queue_Remove(&rpc_stat->entry);
9110 opr_queue_Remove(&rpc_stat->entryPeers);
9111 num_funcs = rpc_stat->stats[0].func_total;
9113 sizeof(rx_interface_stat_t) +
9114 rpc_stat->stats[0].func_total *
9115 sizeof(rx_function_entry_v1_t);
9117 rxi_Free(rpc_stat, space);
9118 rxi_rpc_peer_stat_cnt -= num_funcs;
9120 MUTEX_EXIT(&peer->peer_lock);
9122 MUTEX_ENTER(&rx_peerHashTable_lock);
9132 MUTEX_EXIT(&rx_rpc_stats);
9133 MUTEX_EXIT(&rx_peerHashTable_lock);
9138 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
9143 * IN clearFlag - flag indicating which stats to clear
9151 rx_clearProcessRPCStats(afs_uint32 clearFlag)
9153 struct opr_queue *cursor;
9155 MUTEX_ENTER(&rx_rpc_stats);
9157 for (opr_queue_Scan(&processStats, cursor)) {
9158 unsigned int num_funcs = 0, i;
9159 struct rx_interface_stat *rpc_stat
9160 = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
9162 num_funcs = rpc_stat->stats[0].func_total;
9163 for (i = 0; i < num_funcs; i++) {
9164 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9165 rpc_stat->stats[i].invocations = 0;
9167 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9168 rpc_stat->stats[i].bytes_sent = 0;
9170 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9171 rpc_stat->stats[i].bytes_rcvd = 0;
9173 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9174 rpc_stat->stats[i].queue_time_sum.sec = 0;
9175 rpc_stat->stats[i].queue_time_sum.usec = 0;
9177 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9178 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9179 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9181 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9182 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9183 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9185 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9186 rpc_stat->stats[i].queue_time_max.sec = 0;
9187 rpc_stat->stats[i].queue_time_max.usec = 0;
9189 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9190 rpc_stat->stats[i].execution_time_sum.sec = 0;
9191 rpc_stat->stats[i].execution_time_sum.usec = 0;
9193 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9194 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9195 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9197 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9198 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9199 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9201 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9202 rpc_stat->stats[i].execution_time_max.sec = 0;
9203 rpc_stat->stats[i].execution_time_max.usec = 0;
9208 MUTEX_EXIT(&rx_rpc_stats);
9212 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
9217 * IN clearFlag - flag indicating which stats to clear
9225 rx_clearPeerRPCStats(afs_uint32 clearFlag)
9227 struct opr_queue *cursor;
9229 MUTEX_ENTER(&rx_rpc_stats);
9231 for (opr_queue_Scan(&peerStats, cursor)) {
9232 unsigned int num_funcs, i;
9233 struct rx_interface_stat *rpc_stat
9234 = opr_queue_Entry(cursor, struct rx_interface_stat, entryPeers);
9236 num_funcs = rpc_stat->stats[0].func_total;
9237 for (i = 0; i < num_funcs; i++) {
9238 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9239 rpc_stat->stats[i].invocations = 0;
9241 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9242 rpc_stat->stats[i].bytes_sent = 0;
9244 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9245 rpc_stat->stats[i].bytes_rcvd = 0;
9247 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9248 rpc_stat->stats[i].queue_time_sum.sec = 0;
9249 rpc_stat->stats[i].queue_time_sum.usec = 0;
9251 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9252 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9253 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9255 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9256 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9257 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9259 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9260 rpc_stat->stats[i].queue_time_max.sec = 0;
9261 rpc_stat->stats[i].queue_time_max.usec = 0;
9263 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9264 rpc_stat->stats[i].execution_time_sum.sec = 0;
9265 rpc_stat->stats[i].execution_time_sum.usec = 0;
9267 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9268 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9269 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9271 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9272 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9273 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9275 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9276 rpc_stat->stats[i].execution_time_max.sec = 0;
9277 rpc_stat->stats[i].execution_time_max.usec = 0;
9282 MUTEX_EXIT(&rx_rpc_stats);
9286 * rxi_rxstat_userok points to a routine that returns 1 if the caller
9287 * is authorized to enable/disable/clear RX statistics.
9289 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
9292 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
9294 rxi_rxstat_userok = proc;
9298 rx_RxStatUserOk(struct rx_call *call)
9300 if (!rxi_rxstat_userok)
9302 return rxi_rxstat_userok(call);
9307 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
9308 * function in the MSVC runtime DLL (msvcrt.dll).
9310 * Note: the system serializes calls to this function.
9313 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
9314 DWORD reason, /* reason function is being called */
9315 LPVOID reserved) /* reserved for future use */
9318 case DLL_PROCESS_ATTACH:
9319 /* library is being attached to a process */
9323 case DLL_PROCESS_DETACH:
9330 #endif /* AFS_NT40_ENV */
9333 int rx_DumpCalls(FILE *outputFile, char *cookie)
9335 #ifdef RXDEBUG_PACKET
9336 #ifdef KDUMP_RX_LOCK
9337 struct rx_call_rx_lock *c;
9344 #define RXDPRINTF sprintf
9345 #define RXDPRINTOUT output
9347 #define RXDPRINTF fprintf
9348 #define RXDPRINTOUT outputFile
9351 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
9353 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9356 for (c = rx_allCallsp; c; c = c->allNextp) {
9357 u_short rqc, tqc, iovqc;
9359 MUTEX_ENTER(&c->lock);
9360 rqc = opr_queue_Count(&c->rq);
9361 tqc = opr_queue_Count(&c->tq);
9362 iovqc = opr_queue_Count(&c->app.iovq);
9364 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, "
9365 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
9366 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
9367 "resendEvent=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
9368 "lastSendTime=%u, lastRecvTime=%u"
9369 #ifdef RX_ENABLE_LOCKS
9372 #ifdef RX_REFCOUNT_CHECK
9373 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
9374 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
9377 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,
9378 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
9379 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
9380 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
9381 c->resendEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
9382 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime
9383 #ifdef RX_ENABLE_LOCKS
9384 , (afs_uint32)c->refCount
9386 #ifdef RX_REFCOUNT_CHECK
9387 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
9390 MUTEX_EXIT(&c->lock);
9393 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9396 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
9398 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9400 #endif /* RXDEBUG_PACKET */