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 void rxi_ChallengeOn(struct rx_connection *conn);
156 static int rxi_CheckCall(struct rx_call *call, int haveCTLock);
157 static void rxi_AckAllInTransmitQueue(struct rx_call *call);
158 static void rxi_CancelKeepAliveEvent(struct rx_call *call);
159 static void rxi_CancelDelayedAbortEvent(struct rx_call *call);
160 static void rxi_CancelGrowMTUEvent(struct rx_call *call);
161 static void update_nextCid(void);
163 #ifdef RX_ENABLE_LOCKS
165 rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
166 rx_atomic_t rxi_start_in_error;
168 #endif /* RX_ENABLE_LOCKS */
170 /* Constant delay time before sending an acknowledge of the last packet
171 * received. This is to avoid sending an extra acknowledge when the
172 * client is about to make another call, anyway, or the server is
175 * The lastAckDelay may not exceeed 400ms without causing peers to
176 * unecessarily timeout.
178 struct clock rx_lastAckDelay = {0, 400000};
180 /* Constant delay time before sending a soft ack when none was requested.
181 * This is to make sure we send soft acks before the sender times out,
182 * Normally we wait and send a hard ack when the receiver consumes the packet
184 * This value has been 100ms in all shipping versions of OpenAFS. Changing it
185 * will require changes to the peer's RTT calculations.
187 struct clock rx_softAckDelay = {0, 100000};
190 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
191 * currently allocated within rx. This number is used to allocate the
192 * memory required to return the statistics when queried.
193 * Protected by the rx_rpc_stats mutex.
196 static unsigned int rxi_rpc_peer_stat_cnt;
199 * rxi_rpc_process_stat_cnt counts the total number of local process stat
200 * structures currently allocated within rx. The number is used to allocate
201 * the memory required to return the statistics when queried.
202 * Protected by the rx_rpc_stats mutex.
205 static unsigned int rxi_rpc_process_stat_cnt;
207 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
208 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
210 /* Incoming calls wait on this queue when there are no available
211 * server processes */
212 struct opr_queue rx_incomingCallQueue;
214 /* Server processes wait on this queue when there are no appropriate
215 * calls to process */
216 struct opr_queue rx_idleServerQueue;
218 #if !defined(offsetof)
219 #include <stddef.h> /* for definition of offsetof() */
222 #ifdef RX_ENABLE_LOCKS
223 afs_kmutex_t rx_atomic_mutex;
226 /* Forward prototypes */
227 static struct rx_call * rxi_NewCall(struct rx_connection *, int);
230 putConnection (struct rx_connection *conn) {
231 MUTEX_ENTER(&rx_refcnt_mutex);
233 MUTEX_EXIT(&rx_refcnt_mutex);
236 #ifdef AFS_PTHREAD_ENV
239 * Use procedural initialization of mutexes/condition variables
243 extern afs_kmutex_t rx_quota_mutex;
244 extern afs_kmutex_t rx_pthread_mutex;
245 extern afs_kmutex_t rx_packets_mutex;
246 extern afs_kmutex_t rx_refcnt_mutex;
247 extern afs_kmutex_t des_init_mutex;
248 extern afs_kmutex_t des_random_mutex;
250 extern afs_kmutex_t rx_clock_mutex;
251 extern afs_kmutex_t rxi_connCacheMutex;
252 extern afs_kmutex_t event_handler_mutex;
253 extern afs_kmutex_t listener_mutex;
254 extern afs_kmutex_t rx_if_init_mutex;
255 extern afs_kmutex_t rx_if_mutex;
257 extern afs_kcondvar_t rx_event_handler_cond;
258 extern afs_kcondvar_t rx_listener_cond;
261 static afs_kmutex_t epoch_mutex;
262 static afs_kmutex_t rx_init_mutex;
263 static afs_kmutex_t rx_debug_mutex;
264 static afs_kmutex_t rx_rpc_stats;
267 rxi_InitPthread(void)
269 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
270 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
271 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
272 MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
274 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
275 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
276 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
277 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
278 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
279 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
281 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
282 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
283 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
284 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
285 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
288 CV_INIT(&rx_event_handler_cond, "evhand", CV_DEFAULT, 0);
289 CV_INIT(&rx_listener_cond, "rxlisten", CV_DEFAULT, 0);
292 osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
293 osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
295 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
296 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
297 #ifdef RX_ENABLE_LOCKS
300 #endif /* RX_LOCKS_DB */
301 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
302 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
304 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
306 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
308 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
310 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
312 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
314 #endif /* RX_ENABLE_LOCKS */
317 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
318 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
320 * The rx_stats_mutex mutex protects the following global variables:
321 * rxi_lowConnRefCount
322 * rxi_lowPeerRefCount
331 * The rx_quota_mutex mutex protects the following global variables:
339 * The rx_freePktQ_lock protects the following global variables:
344 * The rx_packets_mutex mutex protects the following global variables:
352 * The rx_pthread_mutex mutex protects the following global variables:
353 * rxi_fcfs_thread_num
356 #define INIT_PTHREAD_LOCKS
360 /* Variables for handling the minProcs implementation. availProcs gives the
361 * number of threads available in the pool at this moment (not counting dudes
362 * executing right now). totalMin gives the total number of procs required
363 * for handling all minProcs requests. minDeficit is a dynamic variable
364 * tracking the # of procs required to satisfy all of the remaining minProcs
366 * For fine grain locking to work, the quota check and the reservation of
367 * a server thread has to come while rxi_availProcs and rxi_minDeficit
368 * are locked. To this end, the code has been modified under #ifdef
369 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
370 * same time. A new function, ReturnToServerPool() returns the allocation.
372 * A call can be on several queue's (but only one at a time). When
373 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
374 * that no one else is touching the queue. To this end, we store the address
375 * of the queue lock in the call structure (under the call lock) when we
376 * put the call on a queue, and we clear the call_queue_lock when the
377 * call is removed from a queue (once the call lock has been obtained).
378 * This allows rxi_ResetCall to safely synchronize with others wishing
379 * to manipulate the queue.
382 #if defined(RX_ENABLE_LOCKS)
383 static afs_kmutex_t rx_rpc_stats;
386 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
387 ** pretty good that the next packet coming in is from the same connection
388 ** as the last packet, since we're send multiple packets in a transmit window.
390 struct rx_connection *rxLastConn = 0;
392 #ifdef RX_ENABLE_LOCKS
393 /* The locking hierarchy for rx fine grain locking is composed of these
396 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
397 * also protects updates to rx_nextCid
398 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
399 * call->lock - locks call data fields.
400 * These are independent of each other:
401 * rx_freeCallQueue_lock
406 * serverQueueEntry->lock
407 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
409 * peer->lock - locks peer data fields.
410 * conn_data_lock - that more than one thread is not updating a conn data
411 * field at the same time.
422 * Do we need a lock to protect the peer field in the conn structure?
423 * conn->peer was previously a constant for all intents and so has no
424 * lock protecting this field. The multihomed client delta introduced
425 * a RX code change : change the peer field in the connection structure
426 * to that remote interface from which the last packet for this
427 * connection was sent out. This may become an issue if further changes
430 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
431 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
433 /* rxdb_fileID is used to identify the lock location, along with line#. */
434 static int rxdb_fileID = RXDB_FILE_RX;
435 #endif /* RX_LOCKS_DB */
436 #else /* RX_ENABLE_LOCKS */
437 #define SET_CALL_QUEUE_LOCK(C, L)
438 #define CLEAR_CALL_QUEUE_LOCK(C)
439 #endif /* RX_ENABLE_LOCKS */
440 struct rx_serverQueueEntry *rx_waitForPacket = 0;
442 /* ------------Exported Interfaces------------- */
444 /* Initialize rx. A port number may be mentioned, in which case this
445 * becomes the default port number for any service installed later.
446 * If 0 is provided for the port number, a random port will be chosen
447 * by the kernel. Whether this will ever overlap anything in
448 * /etc/services is anybody's guess... Returns 0 on success, -1 on
453 rx_atomic_t rxinit_status = RX_ATOMIC_INIT(1);
456 rx_InitHost(u_int host, u_int port)
463 char *htable, *ptable;
468 if (!rx_atomic_test_and_clear_bit(&rxinit_status, 0))
469 return 0; /* already started */
475 if (afs_winsockInit() < 0)
481 * Initialize anything necessary to provide a non-premptive threading
484 rxi_InitializeThreadSupport();
487 /* Allocate and initialize a socket for client and perhaps server
490 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
491 if (rx_socket == OSI_NULLSOCKET) {
494 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
497 #endif /* RX_LOCKS_DB */
498 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
499 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
500 MUTEX_INIT(&rx_atomic_mutex, "rx_atomic_mutex", MUTEX_DEFAULT, 0);
501 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
502 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
503 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
504 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
505 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
506 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
507 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
509 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
511 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
513 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
515 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
516 #if defined(AFS_HPUX110_ENV)
518 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
519 #endif /* AFS_HPUX110_ENV */
520 #endif /* RX_ENABLE_LOCKS && KERNEL */
523 rx_connDeadTime = 12;
524 rx_tranquil = 0; /* reset flag */
525 rxi_ResetStatistics();
526 htable = osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
527 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
528 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
529 ptable = osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
530 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
531 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
533 /* Malloc up a bunch of packets & buffers */
535 opr_queue_Init(&rx_freePacketQueue);
536 rxi_NeedMorePackets = FALSE;
537 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
539 /* enforce a minimum number of allocated packets */
540 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
541 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
543 /* allocate the initial free packet pool */
544 #ifdef RX_ENABLE_TSFPQ
545 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
546 #else /* RX_ENABLE_TSFPQ */
547 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
548 #endif /* RX_ENABLE_TSFPQ */
555 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
556 tv.tv_sec = clock_now.sec;
557 tv.tv_usec = clock_now.usec;
558 srand((unsigned int)tv.tv_usec);
565 #if defined(KERNEL) && !defined(UKERNEL)
566 /* Really, this should never happen in a real kernel */
569 struct sockaddr_in addr;
571 int addrlen = sizeof(addr);
573 socklen_t addrlen = sizeof(addr);
575 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
577 osi_Free(htable, rx_hashTableSize * sizeof(struct rx_connection *));
580 rx_port = addr.sin_port;
583 rx_stats.minRtt.sec = 9999999;
584 if (RAND_bytes(&rx_epoch, sizeof(rx_epoch)) != 1)
586 rx_epoch = (rx_epoch & ~0x40000000) | 0x80000000;
587 if (RAND_bytes(&rx_nextCid, sizeof(rx_nextCid)) != 1)
589 rx_nextCid &= RX_CIDMASK;
590 MUTEX_ENTER(&rx_quota_mutex);
591 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
592 MUTEX_EXIT(&rx_quota_mutex);
593 /* *Slightly* random start time for the cid. This is just to help
594 * out with the hashing function at the peer */
595 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
596 rx_connHashTable = (struct rx_connection **)htable;
597 rx_peerHashTable = (struct rx_peer **)ptable;
599 rx_hardAckDelay.sec = 0;
600 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
602 rxevent_Init(20, rxi_ReScheduleEvents);
604 /* Initialize various global queues */
605 opr_queue_Init(&rx_idleServerQueue);
606 opr_queue_Init(&rx_incomingCallQueue);
607 opr_queue_Init(&rx_freeCallQueue);
609 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
610 /* Initialize our list of usable IP addresses. */
614 /* Start listener process (exact function is dependent on the
615 * implementation environment--kernel or user space) */
619 rx_atomic_clear_bit(&rxinit_status, 0);
626 return rx_InitHost(htonl(INADDR_ANY), port);
632 * The rxi_rto functions implement a TCP (RFC2988) style algorithm for
633 * maintaing the round trip timer.
638 * Start a new RTT timer for a given call and packet.
640 * There must be no resendEvent already listed for this call, otherwise this
641 * will leak events - intended for internal use within the RTO code only
644 * the RX call to start the timer for
645 * @param[in] lastPacket
646 * a flag indicating whether the last packet has been sent or not
648 * @pre call must be locked before calling this function
652 rxi_rto_startTimer(struct rx_call *call, int lastPacket, int istack)
654 struct clock now, retryTime;
659 clock_Add(&retryTime, &call->rto);
661 /* If we're sending the last packet, and we're the client, then the server
662 * may wait for an additional 400ms before returning the ACK, wait for it
663 * rather than hitting a timeout */
664 if (lastPacket && call->conn->type == RX_CLIENT_CONNECTION)
665 clock_Addmsec(&retryTime, 400);
667 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
668 call->resendEvent = rxevent_Post(&retryTime, &now, rxi_Resend,
673 * Cancel an RTT timer for a given call.
677 * the RX call to cancel the timer for
679 * @pre call must be locked before calling this function
684 rxi_rto_cancel(struct rx_call *call)
686 if (call->resendEvent != NULL) {
687 rxevent_Cancel(&call->resendEvent);
688 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
693 * Tell the RTO timer that we have sent a packet.
695 * If the timer isn't already running, then start it. If the timer is running,
699 * the RX call that the packet has been sent on
700 * @param[in] lastPacket
701 * A flag which is true if this is the last packet for the call
703 * @pre The call must be locked before calling this function
708 rxi_rto_packet_sent(struct rx_call *call, int lastPacket, int istack)
710 if (call->resendEvent)
713 rxi_rto_startTimer(call, lastPacket, istack);
717 * Tell the RTO timer that we have received an new ACK message
719 * This function should be called whenever a call receives an ACK that
720 * acknowledges new packets. Whatever happens, we stop the current timer.
721 * If there are unacked packets in the queue which have been sent, then
722 * we restart the timer from now. Otherwise, we leave it stopped.
725 * the RX call that the ACK has been received on
729 rxi_rto_packet_acked(struct rx_call *call, int istack)
731 struct opr_queue *cursor;
733 rxi_rto_cancel(call);
735 if (opr_queue_IsEmpty(&call->tq))
738 for (opr_queue_Scan(&call->tq, cursor)) {
739 struct rx_packet *p = opr_queue_Entry(cursor, struct rx_packet, entry);
740 if (p->header.seq > call->tfirst + call->twind)
743 if (!(p->flags & RX_PKTFLAG_ACKED) && p->flags & RX_PKTFLAG_SENT) {
744 rxi_rto_startTimer(call, p->header.flags & RX_LAST_PACKET, istack);
752 * Set an initial round trip timeout for a peer connection
754 * @param[in] secs The timeout to set in seconds
758 rx_rto_setPeerTimeoutSecs(struct rx_peer *peer, int secs) {
759 peer->rtt = secs * 8000;
763 * Set a delayed ack event on the specified call for the given time
765 * @param[in] call - the call on which to set the event
766 * @param[in] offset - the delay from now after which the event fires
769 rxi_PostDelayedAckEvent(struct rx_call *call, struct clock *offset)
771 struct clock now, when;
775 clock_Add(&when, offset);
777 if (call->delayedAckEvent && clock_Gt(&call->delayedAckTime, &when)) {
778 /* The event we're cancelling already has a reference, so we don't
780 rxevent_Cancel(&call->delayedAckEvent);
781 call->delayedAckEvent = rxevent_Post(&when, &now, rxi_SendDelayedAck,
784 call->delayedAckTime = when;
785 } else if (!call->delayedAckEvent) {
786 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
787 call->delayedAckEvent = rxevent_Post(&when, &now,
790 call->delayedAckTime = when;
795 rxi_CancelDelayedAckEvent(struct rx_call *call)
797 if (call->delayedAckEvent) {
798 rxevent_Cancel(&call->delayedAckEvent);
799 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
803 /* called with unincremented nRequestsRunning to see if it is OK to start
804 * a new thread in this service. Could be "no" for two reasons: over the
805 * max quota, or would prevent others from reaching their min quota.
807 #ifdef RX_ENABLE_LOCKS
808 /* This verion of QuotaOK reserves quota if it's ok while the
809 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
812 QuotaOK(struct rx_service *aservice)
814 /* check if over max quota */
815 if (aservice->nRequestsRunning >= aservice->maxProcs) {
819 /* under min quota, we're OK */
820 /* otherwise, can use only if there are enough to allow everyone
821 * to go to their min quota after this guy starts.
824 MUTEX_ENTER(&rx_quota_mutex);
825 if ((aservice->nRequestsRunning < aservice->minProcs)
826 || (rxi_availProcs > rxi_minDeficit)) {
827 aservice->nRequestsRunning++;
828 /* just started call in minProcs pool, need fewer to maintain
830 if (aservice->nRequestsRunning <= aservice->minProcs)
833 MUTEX_EXIT(&rx_quota_mutex);
836 MUTEX_EXIT(&rx_quota_mutex);
842 ReturnToServerPool(struct rx_service *aservice)
844 aservice->nRequestsRunning--;
845 MUTEX_ENTER(&rx_quota_mutex);
846 if (aservice->nRequestsRunning < aservice->minProcs)
849 MUTEX_EXIT(&rx_quota_mutex);
852 #else /* RX_ENABLE_LOCKS */
854 QuotaOK(struct rx_service *aservice)
857 /* under min quota, we're OK */
858 if (aservice->nRequestsRunning < aservice->minProcs)
861 /* check if over max quota */
862 if (aservice->nRequestsRunning >= aservice->maxProcs)
865 /* otherwise, can use only if there are enough to allow everyone
866 * to go to their min quota after this guy starts.
868 MUTEX_ENTER(&rx_quota_mutex);
869 if (rxi_availProcs > rxi_minDeficit)
871 MUTEX_EXIT(&rx_quota_mutex);
874 #endif /* RX_ENABLE_LOCKS */
877 /* Called by rx_StartServer to start up lwp's to service calls.
878 NExistingProcs gives the number of procs already existing, and which
879 therefore needn't be created. */
881 rxi_StartServerProcs(int nExistingProcs)
883 struct rx_service *service;
888 /* For each service, reserve N processes, where N is the "minimum"
889 * number of processes that MUST be able to execute a request in parallel,
890 * at any time, for that process. Also compute the maximum difference
891 * between any service's maximum number of processes that can run
892 * (i.e. the maximum number that ever will be run, and a guarantee
893 * that this number will run if other services aren't running), and its
894 * minimum number. The result is the extra number of processes that
895 * we need in order to provide the latter guarantee */
896 for (i = 0; i < RX_MAX_SERVICES; i++) {
898 service = rx_services[i];
899 if (service == (struct rx_service *)0)
901 nProcs += service->minProcs;
902 diff = service->maxProcs - service->minProcs;
906 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
907 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
908 for (i = 0; i < nProcs; i++) {
909 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
915 /* This routine is only required on Windows */
917 rx_StartClientThread(void)
919 #ifdef AFS_PTHREAD_ENV
921 pid = pthread_self();
922 #endif /* AFS_PTHREAD_ENV */
924 #endif /* AFS_NT40_ENV */
926 /* This routine must be called if any services are exported. If the
927 * donateMe flag is set, the calling process is donated to the server
930 rx_StartServer(int donateMe)
932 struct rx_service *service;
938 /* Start server processes, if necessary (exact function is dependent
939 * on the implementation environment--kernel or user space). DonateMe
940 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
941 * case, one less new proc will be created rx_StartServerProcs.
943 rxi_StartServerProcs(donateMe);
945 /* count up the # of threads in minProcs, and add set the min deficit to
946 * be that value, too.
948 for (i = 0; i < RX_MAX_SERVICES; i++) {
949 service = rx_services[i];
950 if (service == (struct rx_service *)0)
952 MUTEX_ENTER(&rx_quota_mutex);
953 rxi_totalMin += service->minProcs;
954 /* below works even if a thread is running, since minDeficit would
955 * still have been decremented and later re-incremented.
957 rxi_minDeficit += service->minProcs;
958 MUTEX_EXIT(&rx_quota_mutex);
961 /* Turn on reaping of idle server connections */
962 rxi_ReapConnections(NULL, NULL, NULL, 0);
971 #ifdef AFS_PTHREAD_ENV
973 pid = afs_pointer_to_int(pthread_self());
974 #else /* AFS_PTHREAD_ENV */
976 LWP_CurrentProcess(&pid);
977 #endif /* AFS_PTHREAD_ENV */
979 sprintf(name, "srv_%d", ++nProcs);
981 (*registerProgram) (pid, name);
983 #endif /* AFS_NT40_ENV */
984 rx_ServerProc(NULL); /* Never returns */
986 #ifdef RX_ENABLE_TSFPQ
987 /* no use leaving packets around in this thread's local queue if
988 * it isn't getting donated to the server thread pool.
990 rxi_FlushLocalPacketsTSFPQ();
991 #endif /* RX_ENABLE_TSFPQ */
995 /* Create a new client connection to the specified service, using the
996 * specified security object to implement the security model for this
998 struct rx_connection *
999 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
1000 struct rx_securityClass *securityObject,
1001 int serviceSecurityIndex)
1004 struct rx_connection *conn;
1009 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
1010 "serviceSecurityIndex %d)\n",
1011 ntohl(shost), ntohs(sport), sservice, securityObject,
1012 serviceSecurityIndex));
1014 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
1015 * the case of kmem_alloc? */
1016 conn = rxi_AllocConnection();
1017 #ifdef RX_ENABLE_LOCKS
1018 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
1019 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
1020 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
1023 MUTEX_ENTER(&rx_connHashTable_lock);
1024 conn->type = RX_CLIENT_CONNECTION;
1025 conn->epoch = rx_epoch;
1026 conn->cid = rx_nextCid;
1028 conn->peer = rxi_FindPeer(shost, sport, 1);
1029 conn->serviceId = sservice;
1030 conn->securityObject = securityObject;
1031 conn->securityData = (void *) 0;
1032 conn->securityIndex = serviceSecurityIndex;
1033 rx_SetConnDeadTime(conn, rx_connDeadTime);
1034 rx_SetConnSecondsUntilNatPing(conn, 0);
1035 conn->ackRate = RX_FAST_ACK_RATE;
1036 conn->nSpecific = 0;
1037 conn->specific = NULL;
1038 conn->challengeEvent = NULL;
1039 conn->delayedAbortEvent = NULL;
1040 conn->abortCount = 0;
1042 for (i = 0; i < RX_MAXCALLS; i++) {
1043 conn->twind[i] = rx_initSendWindow;
1044 conn->rwind[i] = rx_initReceiveWindow;
1045 conn->lastBusy[i] = 0;
1048 RXS_NewConnection(securityObject, conn);
1050 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
1052 conn->refCount++; /* no lock required since only this thread knows... */
1053 conn->next = rx_connHashTable[hashindex];
1054 rx_connHashTable[hashindex] = conn;
1055 if (rx_stats_active)
1056 rx_atomic_inc(&rx_stats.nClientConns);
1057 MUTEX_EXIT(&rx_connHashTable_lock);
1063 * Ensure a connection's timeout values are valid.
1065 * @param[in] conn The connection to check
1067 * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
1068 * unless idleDeadTime and/or hardDeadTime are not set
1072 rxi_CheckConnTimeouts(struct rx_connection *conn)
1074 /* a connection's timeouts must have the relationship
1075 * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
1076 * total loss of network to a peer may cause an idle timeout instead of a
1077 * dead timeout, simply because the idle timeout gets hit first. Also set
1078 * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
1079 /* this logic is slightly complicated by the fact that
1080 * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
1082 conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
1083 if (conn->idleDeadTime) {
1084 conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
1086 if (conn->hardDeadTime) {
1087 if (conn->idleDeadTime) {
1088 conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
1090 conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
1096 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
1098 /* The idea is to set the dead time to a value that allows several
1099 * keepalives to be dropped without timing out the connection. */
1100 conn->secondsUntilDead = seconds;
1101 rxi_CheckConnTimeouts(conn);
1102 conn->secondsUntilPing = conn->secondsUntilDead / 6;
1106 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
1108 conn->hardDeadTime = seconds;
1109 rxi_CheckConnTimeouts(conn);
1113 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
1115 conn->idleDeadTime = seconds;
1116 rxi_CheckConnTimeouts(conn);
1119 int rxi_lowPeerRefCount = 0;
1120 int rxi_lowConnRefCount = 0;
1123 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
1124 * NOTE: must not be called with rx_connHashTable_lock held.
1127 rxi_CleanupConnection(struct rx_connection *conn)
1129 /* Notify the service exporter, if requested, that this connection
1130 * is being destroyed */
1131 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
1132 (*conn->service->destroyConnProc) (conn);
1134 /* Notify the security module that this connection is being destroyed */
1135 RXS_DestroyConnection(conn->securityObject, conn);
1137 /* If this is the last connection using the rx_peer struct, set its
1138 * idle time to now. rxi_ReapConnections will reap it if it's still
1139 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
1141 MUTEX_ENTER(&rx_peerHashTable_lock);
1142 if (conn->peer->refCount < 2) {
1143 conn->peer->idleWhen = clock_Sec();
1144 if (conn->peer->refCount < 1) {
1145 conn->peer->refCount = 1;
1146 if (rx_stats_active) {
1147 MUTEX_ENTER(&rx_stats_mutex);
1148 rxi_lowPeerRefCount++;
1149 MUTEX_EXIT(&rx_stats_mutex);
1153 conn->peer->refCount--;
1154 MUTEX_EXIT(&rx_peerHashTable_lock);
1156 if (rx_stats_active)
1158 if (conn->type == RX_SERVER_CONNECTION)
1159 rx_atomic_dec(&rx_stats.nServerConns);
1161 rx_atomic_dec(&rx_stats.nClientConns);
1164 if (conn->specific) {
1166 for (i = 0; i < conn->nSpecific; i++) {
1167 if (conn->specific[i] && rxi_keyCreate_destructor[i])
1168 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
1169 conn->specific[i] = NULL;
1171 free(conn->specific);
1173 conn->specific = NULL;
1174 conn->nSpecific = 0;
1175 #endif /* !KERNEL */
1177 MUTEX_DESTROY(&conn->conn_call_lock);
1178 MUTEX_DESTROY(&conn->conn_data_lock);
1179 CV_DESTROY(&conn->conn_call_cv);
1181 rxi_FreeConnection(conn);
1184 /* Destroy the specified connection */
1186 rxi_DestroyConnection(struct rx_connection *conn)
1188 MUTEX_ENTER(&rx_connHashTable_lock);
1189 rxi_DestroyConnectionNoLock(conn);
1190 /* conn should be at the head of the cleanup list */
1191 if (conn == rx_connCleanup_list) {
1192 rx_connCleanup_list = rx_connCleanup_list->next;
1193 MUTEX_EXIT(&rx_connHashTable_lock);
1194 rxi_CleanupConnection(conn);
1196 #ifdef RX_ENABLE_LOCKS
1198 MUTEX_EXIT(&rx_connHashTable_lock);
1200 #endif /* RX_ENABLE_LOCKS */
1204 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1206 struct rx_connection **conn_ptr;
1208 struct rx_packet *packet;
1215 MUTEX_ENTER(&conn->conn_data_lock);
1216 MUTEX_ENTER(&rx_refcnt_mutex);
1217 if (conn->refCount > 0)
1220 if (rx_stats_active) {
1221 MUTEX_ENTER(&rx_stats_mutex);
1222 rxi_lowConnRefCount++;
1223 MUTEX_EXIT(&rx_stats_mutex);
1227 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1228 /* Busy; wait till the last guy before proceeding */
1229 MUTEX_EXIT(&rx_refcnt_mutex);
1230 MUTEX_EXIT(&conn->conn_data_lock);
1235 /* If the client previously called rx_NewCall, but it is still
1236 * waiting, treat this as a running call, and wait to destroy the
1237 * connection later when the call completes. */
1238 if ((conn->type == RX_CLIENT_CONNECTION)
1239 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1240 conn->flags |= RX_CONN_DESTROY_ME;
1241 MUTEX_EXIT(&conn->conn_data_lock);
1245 MUTEX_EXIT(&rx_refcnt_mutex);
1246 MUTEX_EXIT(&conn->conn_data_lock);
1248 /* Check for extant references to this connection */
1249 MUTEX_ENTER(&conn->conn_call_lock);
1250 for (i = 0; i < RX_MAXCALLS; i++) {
1251 struct rx_call *call = conn->call[i];
1254 if (conn->type == RX_CLIENT_CONNECTION) {
1255 MUTEX_ENTER(&call->lock);
1256 if (call->delayedAckEvent) {
1257 /* Push the final acknowledgment out now--there
1258 * won't be a subsequent call to acknowledge the
1259 * last reply packets */
1260 rxi_CancelDelayedAckEvent(call);
1261 if (call->state == RX_STATE_PRECALL
1262 || call->state == RX_STATE_ACTIVE) {
1263 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1268 MUTEX_EXIT(&call->lock);
1272 MUTEX_EXIT(&conn->conn_call_lock);
1274 #ifdef RX_ENABLE_LOCKS
1276 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1277 MUTEX_EXIT(&conn->conn_data_lock);
1279 /* Someone is accessing a packet right now. */
1283 #endif /* RX_ENABLE_LOCKS */
1286 /* Don't destroy the connection if there are any call
1287 * structures still in use */
1288 MUTEX_ENTER(&conn->conn_data_lock);
1289 conn->flags |= RX_CONN_DESTROY_ME;
1290 MUTEX_EXIT(&conn->conn_data_lock);
1295 if (conn->natKeepAliveEvent) {
1296 rxi_NatKeepAliveOff(conn);
1299 if (conn->delayedAbortEvent) {
1300 rxevent_Cancel(&conn->delayedAbortEvent);
1301 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
1303 MUTEX_ENTER(&conn->conn_data_lock);
1304 rxi_SendConnectionAbort(conn, packet, 0, 1);
1305 MUTEX_EXIT(&conn->conn_data_lock);
1306 rxi_FreePacket(packet);
1310 /* Remove from connection hash table before proceeding */
1312 &rx_connHashTable[CONN_HASH
1313 (peer->host, peer->port, conn->cid, conn->epoch,
1315 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1316 if (*conn_ptr == conn) {
1317 *conn_ptr = conn->next;
1321 /* if the conn that we are destroying was the last connection, then we
1322 * clear rxLastConn as well */
1323 if (rxLastConn == conn)
1326 /* Make sure the connection is completely reset before deleting it. */
1327 /* get rid of pending events that could zap us later */
1328 rxevent_Cancel(&conn->challengeEvent);
1329 rxevent_Cancel(&conn->checkReachEvent);
1330 rxevent_Cancel(&conn->natKeepAliveEvent);
1332 /* Add the connection to the list of destroyed connections that
1333 * need to be cleaned up. This is necessary to avoid deadlocks
1334 * in the routines we call to inform others that this connection is
1335 * being destroyed. */
1336 conn->next = rx_connCleanup_list;
1337 rx_connCleanup_list = conn;
1340 /* Externally available version */
1342 rx_DestroyConnection(struct rx_connection *conn)
1347 rxi_DestroyConnection(conn);
1352 rx_GetConnection(struct rx_connection *conn)
1357 MUTEX_ENTER(&rx_refcnt_mutex);
1359 MUTEX_EXIT(&rx_refcnt_mutex);
1363 #ifdef RX_ENABLE_LOCKS
1364 /* Wait for the transmit queue to no longer be busy.
1365 * requires the call->lock to be held */
1367 rxi_WaitforTQBusy(struct rx_call *call) {
1368 while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1369 call->flags |= RX_CALL_TQ_WAIT;
1371 MUTEX_ASSERT(&call->lock);
1372 CV_WAIT(&call->cv_tq, &call->lock);
1374 if (call->tqWaiters == 0) {
1375 call->flags &= ~RX_CALL_TQ_WAIT;
1382 rxi_WakeUpTransmitQueue(struct rx_call *call)
1384 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1385 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
1386 call, call->tqWaiters, call->flags));
1387 #ifdef RX_ENABLE_LOCKS
1388 MUTEX_ASSERT(&call->lock);
1389 CV_BROADCAST(&call->cv_tq);
1390 #else /* RX_ENABLE_LOCKS */
1391 osi_rxWakeup(&call->tq);
1392 #endif /* RX_ENABLE_LOCKS */
1396 /* Start a new rx remote procedure call, on the specified connection.
1397 * If wait is set to 1, wait for a free call channel; otherwise return
1398 * 0. Maxtime gives the maximum number of seconds this call may take,
1399 * after rx_NewCall returns. After this time interval, a call to any
1400 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1401 * For fine grain locking, we hold the conn_call_lock in order to
1402 * to ensure that we don't get signalle after we found a call in an active
1403 * state and before we go to sleep.
1406 rx_NewCall(struct rx_connection *conn)
1408 int i, wait, ignoreBusy = 1;
1409 struct rx_call *call;
1410 struct clock queueTime;
1411 afs_uint32 leastBusy = 0;
1415 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1418 clock_GetTime(&queueTime);
1420 * Check if there are others waiting for a new call.
1421 * If so, let them go first to avoid starving them.
1422 * This is a fairly simple scheme, and might not be
1423 * a complete solution for large numbers of waiters.
1425 * makeCallWaiters keeps track of the number of
1426 * threads waiting to make calls and the
1427 * RX_CONN_MAKECALL_WAITING flag bit is used to
1428 * indicate that there are indeed calls waiting.
1429 * The flag is set when the waiter is incremented.
1430 * It is only cleared when makeCallWaiters is 0.
1431 * This prevents us from accidently destroying the
1432 * connection while it is potentially about to be used.
1434 MUTEX_ENTER(&conn->conn_call_lock);
1435 MUTEX_ENTER(&conn->conn_data_lock);
1436 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1437 conn->flags |= RX_CONN_MAKECALL_WAITING;
1438 conn->makeCallWaiters++;
1439 MUTEX_EXIT(&conn->conn_data_lock);
1441 #ifdef RX_ENABLE_LOCKS
1442 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1446 MUTEX_ENTER(&conn->conn_data_lock);
1447 conn->makeCallWaiters--;
1448 if (conn->makeCallWaiters == 0)
1449 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1452 /* We are now the active thread in rx_NewCall */
1453 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1454 MUTEX_EXIT(&conn->conn_data_lock);
1459 for (i = 0; i < RX_MAXCALLS; i++) {
1460 call = conn->call[i];
1462 if (!ignoreBusy && conn->lastBusy[i] != leastBusy) {
1463 /* we're not ignoring busy call slots; only look at the
1464 * call slot that is the "least" busy */
1468 if (call->state == RX_STATE_DALLY) {
1469 MUTEX_ENTER(&call->lock);
1470 if (call->state == RX_STATE_DALLY) {
1471 if (ignoreBusy && conn->lastBusy[i]) {
1472 /* if we're ignoring busy call slots, skip any ones that
1473 * have lastBusy set */
1474 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1475 leastBusy = conn->lastBusy[i];
1477 MUTEX_EXIT(&call->lock);
1482 * We are setting the state to RX_STATE_RESET to
1483 * ensure that no one else will attempt to use this
1484 * call once we drop the conn->conn_call_lock and
1485 * call->lock. We must drop the conn->conn_call_lock
1486 * before calling rxi_ResetCall because the process
1487 * of clearing the transmit queue can block for an
1488 * extended period of time. If we block while holding
1489 * the conn->conn_call_lock, then all rx_EndCall
1490 * processing will block as well. This has a detrimental
1491 * effect on overall system performance.
1493 call->state = RX_STATE_RESET;
1494 (*call->callNumber)++;
1495 MUTEX_EXIT(&conn->conn_call_lock);
1496 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1497 rxi_ResetCall(call, 0);
1498 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1502 * If we failed to be able to safely obtain the
1503 * conn->conn_call_lock we will have to drop the
1504 * call->lock to avoid a deadlock. When the call->lock
1505 * is released the state of the call can change. If it
1506 * is no longer RX_STATE_RESET then some other thread is
1509 MUTEX_EXIT(&call->lock);
1510 MUTEX_ENTER(&conn->conn_call_lock);
1511 MUTEX_ENTER(&call->lock);
1513 if (call->state == RX_STATE_RESET)
1517 * If we get here it means that after dropping
1518 * the conn->conn_call_lock and call->lock that
1519 * the call is no longer ours. If we can't find
1520 * a free call in the remaining slots we should
1521 * not go immediately to RX_CONN_MAKECALL_WAITING
1522 * because by dropping the conn->conn_call_lock
1523 * we have given up synchronization with rx_EndCall.
1524 * Instead, cycle through one more time to see if
1525 * we can find a call that can call our own.
1527 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1530 MUTEX_EXIT(&call->lock);
1533 if (ignoreBusy && conn->lastBusy[i]) {
1534 /* if we're ignoring busy call slots, skip any ones that
1535 * have lastBusy set */
1536 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1537 leastBusy = conn->lastBusy[i];
1542 /* rxi_NewCall returns with mutex locked */
1543 call = rxi_NewCall(conn, i);
1544 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1548 if (i < RX_MAXCALLS) {
1549 conn->lastBusy[i] = 0;
1554 if (leastBusy && ignoreBusy) {
1555 /* we didn't find a useable call slot, but we did see at least one
1556 * 'busy' slot; look again and only use a slot with the 'least
1562 MUTEX_ENTER(&conn->conn_data_lock);
1563 conn->flags |= RX_CONN_MAKECALL_WAITING;
1564 conn->makeCallWaiters++;
1565 MUTEX_EXIT(&conn->conn_data_lock);
1567 #ifdef RX_ENABLE_LOCKS
1568 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1572 MUTEX_ENTER(&conn->conn_data_lock);
1573 conn->makeCallWaiters--;
1574 if (conn->makeCallWaiters == 0)
1575 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1576 MUTEX_EXIT(&conn->conn_data_lock);
1578 /* Client is initially in send mode */
1579 call->state = RX_STATE_ACTIVE;
1580 call->error = conn->error;
1582 call->app.mode = RX_MODE_ERROR;
1584 call->app.mode = RX_MODE_SENDING;
1586 #ifdef AFS_RXERRQ_ENV
1587 /* remember how many network errors the peer has when we started, so if
1588 * more errors are encountered after the call starts, we know the other endpoint won't be
1589 * responding to us */
1590 call->neterr_gen = rx_atomic_read(&conn->peer->neterrs);
1593 /* remember start time for call in case we have hard dead time limit */
1594 call->queueTime = queueTime;
1595 clock_GetTime(&call->startTime);
1596 call->app.bytesSent = 0;
1597 call->app.bytesRcvd = 0;
1599 /* Turn on busy protocol. */
1600 rxi_KeepAliveOn(call);
1602 /* Attempt MTU discovery */
1603 rxi_GrowMTUOn(call);
1606 * We are no longer the active thread in rx_NewCall
1608 MUTEX_ENTER(&conn->conn_data_lock);
1609 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1610 MUTEX_EXIT(&conn->conn_data_lock);
1613 * Wake up anyone else who might be giving us a chance to
1614 * run (see code above that avoids resource starvation).
1616 #ifdef RX_ENABLE_LOCKS
1617 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1618 osi_Panic("rx_NewCall call about to be used without an empty tq");
1621 CV_BROADCAST(&conn->conn_call_cv);
1625 MUTEX_EXIT(&conn->conn_call_lock);
1626 MUTEX_EXIT(&call->lock);
1629 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1634 rxi_HasActiveCalls(struct rx_connection *aconn)
1637 struct rx_call *tcall;
1641 for (i = 0; i < RX_MAXCALLS; i++) {
1642 if ((tcall = aconn->call[i])) {
1643 if ((tcall->state == RX_STATE_ACTIVE)
1644 || (tcall->state == RX_STATE_PRECALL)) {
1655 rxi_GetCallNumberVector(struct rx_connection *aconn,
1656 afs_int32 * aint32s)
1659 struct rx_call *tcall;
1663 MUTEX_ENTER(&aconn->conn_call_lock);
1664 for (i = 0; i < RX_MAXCALLS; i++) {
1665 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1666 aint32s[i] = aconn->callNumber[i] + 1;
1668 aint32s[i] = aconn->callNumber[i];
1670 MUTEX_EXIT(&aconn->conn_call_lock);
1676 rxi_SetCallNumberVector(struct rx_connection *aconn,
1677 afs_int32 * aint32s)
1680 struct rx_call *tcall;
1684 MUTEX_ENTER(&aconn->conn_call_lock);
1685 for (i = 0; i < RX_MAXCALLS; i++) {
1686 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1687 aconn->callNumber[i] = aint32s[i] - 1;
1689 aconn->callNumber[i] = aint32s[i];
1691 MUTEX_EXIT(&aconn->conn_call_lock);
1696 /* Advertise a new service. A service is named locally by a UDP port
1697 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1700 char *serviceName; Name for identification purposes (e.g. the
1701 service name might be used for probing for
1704 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1705 char *serviceName, struct rx_securityClass **securityObjects,
1706 int nSecurityObjects,
1707 afs_int32(*serviceProc) (struct rx_call * acall))
1709 osi_socket socket = OSI_NULLSOCKET;
1710 struct rx_service *tservice;
1716 if (serviceId == 0) {
1718 "rx_NewService: service id for service %s is not non-zero.\n",
1725 "rx_NewService: A non-zero port must be specified on this call if a non-zero port was not provided at Rx initialization (service %s).\n",
1733 tservice = rxi_AllocService();
1736 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1738 for (i = 0; i < RX_MAX_SERVICES; i++) {
1739 struct rx_service *service = rx_services[i];
1741 if (port == service->servicePort && host == service->serviceHost) {
1742 if (service->serviceId == serviceId) {
1743 /* The identical service has already been
1744 * installed; if the caller was intending to
1745 * change the security classes used by this
1746 * service, he/she loses. */
1748 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1749 serviceName, serviceId, service->serviceName);
1751 rxi_FreeService(tservice);
1754 /* Different service, same port: re-use the socket
1755 * which is bound to the same port */
1756 socket = service->socket;
1759 if (socket == OSI_NULLSOCKET) {
1760 /* If we don't already have a socket (from another
1761 * service on same port) get a new one */
1762 socket = rxi_GetHostUDPSocket(host, port);
1763 if (socket == OSI_NULLSOCKET) {
1765 rxi_FreeService(tservice);
1770 service->socket = socket;
1771 service->serviceHost = host;
1772 service->servicePort = port;
1773 service->serviceId = serviceId;
1774 service->serviceName = serviceName;
1775 service->nSecurityObjects = nSecurityObjects;
1776 service->securityObjects = securityObjects;
1777 service->minProcs = 0;
1778 service->maxProcs = 1;
1779 service->idleDeadTime = 60;
1780 service->connDeadTime = rx_connDeadTime;
1781 service->executeRequestProc = serviceProc;
1782 service->checkReach = 0;
1783 service->nSpecific = 0;
1784 service->specific = NULL;
1785 rx_services[i] = service; /* not visible until now */
1791 rxi_FreeService(tservice);
1792 (osi_Msg "rx_NewService: cannot support > %d services\n",
1797 /* Set configuration options for all of a service's security objects */
1800 rx_SetSecurityConfiguration(struct rx_service *service,
1801 rx_securityConfigVariables type,
1805 for (i = 0; i<service->nSecurityObjects; i++) {
1806 if (service->securityObjects[i]) {
1807 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1815 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1816 struct rx_securityClass **securityObjects, int nSecurityObjects,
1817 afs_int32(*serviceProc) (struct rx_call * acall))
1819 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1822 /* Generic request processing loop. This routine should be called
1823 * by the implementation dependent rx_ServerProc. If socketp is
1824 * non-null, it will be set to the file descriptor that this thread
1825 * is now listening on. If socketp is null, this routine will never
1828 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1830 struct rx_call *call;
1832 struct rx_service *tservice = NULL;
1839 call = rx_GetCall(threadID, tservice, socketp);
1840 if (socketp && *socketp != OSI_NULLSOCKET) {
1841 /* We are now a listener thread */
1847 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1848 #ifdef RX_ENABLE_LOCKS
1850 #endif /* RX_ENABLE_LOCKS */
1851 afs_termState = AFSOP_STOP_AFS;
1852 afs_osi_Wakeup(&afs_termState);
1853 #ifdef RX_ENABLE_LOCKS
1855 #endif /* RX_ENABLE_LOCKS */
1860 /* if server is restarting( typically smooth shutdown) then do not
1861 * allow any new calls.
1864 if (rx_tranquil && (call != NULL)) {
1868 MUTEX_ENTER(&call->lock);
1870 rxi_CallError(call, RX_RESTARTING);
1871 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1873 MUTEX_EXIT(&call->lock);
1878 tservice = call->conn->service;
1880 if (tservice->beforeProc)
1881 (*tservice->beforeProc) (call);
1883 code = tservice->executeRequestProc(call);
1885 if (tservice->afterProc)
1886 (*tservice->afterProc) (call, code);
1888 rx_EndCall(call, code);
1890 if (tservice->postProc)
1891 (*tservice->postProc) (code);
1893 if (rx_stats_active) {
1894 MUTEX_ENTER(&rx_stats_mutex);
1896 MUTEX_EXIT(&rx_stats_mutex);
1903 rx_WakeupServerProcs(void)
1905 struct rx_serverQueueEntry *np, *tqp;
1906 struct opr_queue *cursor;
1910 MUTEX_ENTER(&rx_serverPool_lock);
1912 #ifdef RX_ENABLE_LOCKS
1913 if (rx_waitForPacket)
1914 CV_BROADCAST(&rx_waitForPacket->cv);
1915 #else /* RX_ENABLE_LOCKS */
1916 if (rx_waitForPacket)
1917 osi_rxWakeup(rx_waitForPacket);
1918 #endif /* RX_ENABLE_LOCKS */
1919 MUTEX_ENTER(&freeSQEList_lock);
1920 for (np = rx_FreeSQEList; np; np = tqp) {
1921 tqp = *(struct rx_serverQueueEntry **)np;
1922 #ifdef RX_ENABLE_LOCKS
1923 CV_BROADCAST(&np->cv);
1924 #else /* RX_ENABLE_LOCKS */
1926 #endif /* RX_ENABLE_LOCKS */
1928 MUTEX_EXIT(&freeSQEList_lock);
1929 for (opr_queue_Scan(&rx_idleServerQueue, cursor)) {
1930 np = opr_queue_Entry(cursor, struct rx_serverQueueEntry, entry);
1931 #ifdef RX_ENABLE_LOCKS
1932 CV_BROADCAST(&np->cv);
1933 #else /* RX_ENABLE_LOCKS */
1935 #endif /* RX_ENABLE_LOCKS */
1937 MUTEX_EXIT(&rx_serverPool_lock);
1942 * One thing that seems to happen is that all the server threads get
1943 * tied up on some empty or slow call, and then a whole bunch of calls
1944 * arrive at once, using up the packet pool, so now there are more
1945 * empty calls. The most critical resources here are server threads
1946 * and the free packet pool. The "doreclaim" code seems to help in
1947 * general. I think that eventually we arrive in this state: there
1948 * are lots of pending calls which do have all their packets present,
1949 * so they won't be reclaimed, are multi-packet calls, so they won't
1950 * be scheduled until later, and thus are tying up most of the free
1951 * packet pool for a very long time.
1953 * 1. schedule multi-packet calls if all the packets are present.
1954 * Probably CPU-bound operation, useful to return packets to pool.
1955 * Do what if there is a full window, but the last packet isn't here?
1956 * 3. preserve one thread which *only* runs "best" calls, otherwise
1957 * it sleeps and waits for that type of call.
1958 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1959 * the current dataquota business is badly broken. The quota isn't adjusted
1960 * to reflect how many packets are presently queued for a running call.
1961 * So, when we schedule a queued call with a full window of packets queued
1962 * up for it, that *should* free up a window full of packets for other 2d-class
1963 * calls to be able to use from the packet pool. But it doesn't.
1965 * NB. Most of the time, this code doesn't run -- since idle server threads
1966 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1967 * as a new call arrives.
1969 /* Sleep until a call arrives. Returns a pointer to the call, ready
1970 * for an rx_Read. */
1971 #ifdef RX_ENABLE_LOCKS
1973 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1975 struct rx_serverQueueEntry *sq;
1976 struct rx_call *call = (struct rx_call *)0;
1977 struct rx_service *service = NULL;
1979 MUTEX_ENTER(&freeSQEList_lock);
1981 if ((sq = rx_FreeSQEList)) {
1982 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1983 MUTEX_EXIT(&freeSQEList_lock);
1984 } else { /* otherwise allocate a new one and return that */
1985 MUTEX_EXIT(&freeSQEList_lock);
1986 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1987 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1988 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1991 MUTEX_ENTER(&rx_serverPool_lock);
1992 if (cur_service != NULL) {
1993 ReturnToServerPool(cur_service);
1996 if (!opr_queue_IsEmpty(&rx_incomingCallQueue)) {
1997 struct rx_call *tcall, *choice2 = NULL;
1998 struct opr_queue *cursor;
2000 /* Scan for eligible incoming calls. A call is not eligible
2001 * if the maximum number of calls for its service type are
2002 * already executing */
2003 /* One thread will process calls FCFS (to prevent starvation),
2004 * while the other threads may run ahead looking for calls which
2005 * have all their input data available immediately. This helps
2006 * keep threads from blocking, waiting for data from the client. */
2007 for (opr_queue_Scan(&rx_incomingCallQueue, cursor)) {
2008 tcall = opr_queue_Entry(cursor, struct rx_call, entry);
2010 service = tcall->conn->service;
2011 if (!QuotaOK(service)) {
2014 MUTEX_ENTER(&rx_pthread_mutex);
2015 if (tno == rxi_fcfs_thread_num
2016 || opr_queue_IsEnd(&rx_incomingCallQueue, cursor)) {
2017 MUTEX_EXIT(&rx_pthread_mutex);
2018 /* If we're the fcfs thread , then we'll just use
2019 * this call. If we haven't been able to find an optimal
2020 * choice, and we're at the end of the list, then use a
2021 * 2d choice if one has been identified. Otherwise... */
2022 call = (choice2 ? choice2 : tcall);
2023 service = call->conn->service;
2025 MUTEX_EXIT(&rx_pthread_mutex);
2026 if (!opr_queue_IsEmpty(&tcall->rq)) {
2027 struct rx_packet *rp;
2028 rp = opr_queue_First(&tcall->rq, struct rx_packet,
2030 if (rp->header.seq == 1) {
2032 || (rp->header.flags & RX_LAST_PACKET)) {
2034 } else if (rxi_2dchoice && !choice2
2035 && !(tcall->flags & RX_CALL_CLEARED)
2036 && (tcall->rprev > rxi_HardAckRate)) {
2046 ReturnToServerPool(service);
2052 opr_queue_Remove(&call->entry);
2053 MUTEX_EXIT(&rx_serverPool_lock);
2054 MUTEX_ENTER(&call->lock);
2056 if (call->flags & RX_CALL_WAIT_PROC) {
2057 call->flags &= ~RX_CALL_WAIT_PROC;
2058 rx_atomic_dec(&rx_nWaiting);
2061 if (call->state != RX_STATE_PRECALL || call->error) {
2062 MUTEX_EXIT(&call->lock);
2063 MUTEX_ENTER(&rx_serverPool_lock);
2064 ReturnToServerPool(service);
2069 if (opr_queue_IsEmpty(&call->rq)
2070 || opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq != 1)
2071 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2073 CLEAR_CALL_QUEUE_LOCK(call);
2076 /* If there are no eligible incoming calls, add this process
2077 * to the idle server queue, to wait for one */
2081 *socketp = OSI_NULLSOCKET;
2083 sq->socketp = socketp;
2084 opr_queue_Append(&rx_idleServerQueue, &sq->entry);
2085 #ifndef AFS_AIX41_ENV
2086 rx_waitForPacket = sq;
2087 #endif /* AFS_AIX41_ENV */
2089 CV_WAIT(&sq->cv, &rx_serverPool_lock);
2091 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2092 MUTEX_EXIT(&rx_serverPool_lock);
2093 return (struct rx_call *)0;
2096 } while (!(call = sq->newcall)
2097 && !(socketp && *socketp != OSI_NULLSOCKET));
2098 MUTEX_EXIT(&rx_serverPool_lock);
2100 MUTEX_ENTER(&call->lock);
2106 MUTEX_ENTER(&freeSQEList_lock);
2107 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2108 rx_FreeSQEList = sq;
2109 MUTEX_EXIT(&freeSQEList_lock);
2112 clock_GetTime(&call->startTime);
2113 call->state = RX_STATE_ACTIVE;
2114 call->app.mode = RX_MODE_RECEIVING;
2115 #ifdef RX_KERNEL_TRACE
2116 if (ICL_SETACTIVE(afs_iclSetp)) {
2117 int glockOwner = ISAFS_GLOCK();
2120 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2121 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2128 rxi_calltrace(RX_CALL_START, call);
2129 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
2130 call->conn->service->servicePort, call->conn->service->serviceId,
2133 MUTEX_EXIT(&call->lock);
2134 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
2136 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2141 #else /* RX_ENABLE_LOCKS */
2143 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2145 struct rx_serverQueueEntry *sq;
2146 struct rx_call *call = (struct rx_call *)0, *choice2;
2147 struct rx_service *service = NULL;
2151 MUTEX_ENTER(&freeSQEList_lock);
2153 if ((sq = rx_FreeSQEList)) {
2154 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
2155 MUTEX_EXIT(&freeSQEList_lock);
2156 } else { /* otherwise allocate a new one and return that */
2157 MUTEX_EXIT(&freeSQEList_lock);
2158 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2159 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2160 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2162 MUTEX_ENTER(&sq->lock);
2164 if (cur_service != NULL) {
2165 cur_service->nRequestsRunning--;
2166 MUTEX_ENTER(&rx_quota_mutex);
2167 if (cur_service->nRequestsRunning < cur_service->minProcs)
2170 MUTEX_EXIT(&rx_quota_mutex);
2172 if (!opr_queue_IsEmpty(&rx_incomingCallQueue)) {
2173 struct rx_call *tcall;
2174 struct opr_queue *cursor;
2175 /* Scan for eligible incoming calls. A call is not eligible
2176 * if the maximum number of calls for its service type are
2177 * already executing */
2178 /* One thread will process calls FCFS (to prevent starvation),
2179 * while the other threads may run ahead looking for calls which
2180 * have all their input data available immediately. This helps
2181 * keep threads from blocking, waiting for data from the client. */
2182 choice2 = (struct rx_call *)0;
2183 for (opr_queue_Scan(&rx_incomingCallQueue, cursor)) {
2184 tcall = opr_queue_Entry(cursor, struct rx_call, entry);
2185 service = tcall->conn->service;
2186 if (QuotaOK(service)) {
2187 MUTEX_ENTER(&rx_pthread_mutex);
2188 /* XXX - If tcall->entry.next is NULL, then we're no longer
2189 * on a queue at all. This shouldn't happen. */
2190 if (tno == rxi_fcfs_thread_num || !tcall->entry.next) {
2191 MUTEX_EXIT(&rx_pthread_mutex);
2192 /* If we're the fcfs thread, then we'll just use
2193 * this call. If we haven't been able to find an optimal
2194 * choice, and we're at the end of the list, then use a
2195 * 2d choice if one has been identified. Otherwise... */
2196 call = (choice2 ? choice2 : tcall);
2197 service = call->conn->service;
2199 MUTEX_EXIT(&rx_pthread_mutex);
2200 if (!opr_queue_IsEmpty(&tcall->rq)) {
2201 struct rx_packet *rp;
2202 rp = opr_queue_First(&tcall->rq, struct rx_packet,
2204 if (rp->header.seq == 1
2206 || (rp->header.flags & RX_LAST_PACKET))) {
2208 } else if (rxi_2dchoice && !choice2
2209 && !(tcall->flags & RX_CALL_CLEARED)
2210 && (tcall->rprev > rxi_HardAckRate)) {
2223 opr_queue_Remove(&call->entry);
2224 /* we can't schedule a call if there's no data!!! */
2225 /* send an ack if there's no data, if we're missing the
2226 * first packet, or we're missing something between first
2227 * and last -- there's a "hole" in the incoming data. */
2228 if (opr_queue_IsEmpty(&call->rq)
2229 || opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq != 1
2230 || call->rprev != opr_queue_Last(&call->rq, struct rx_packet, entry)->header.seq)
2231 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2233 call->flags &= (~RX_CALL_WAIT_PROC);
2234 service->nRequestsRunning++;
2235 /* just started call in minProcs pool, need fewer to maintain
2237 MUTEX_ENTER(&rx_quota_mutex);
2238 if (service->nRequestsRunning <= service->minProcs)
2241 MUTEX_EXIT(&rx_quota_mutex);
2242 rx_atomic_dec(&rx_nWaiting);
2243 /* MUTEX_EXIT(&call->lock); */
2245 /* If there are no eligible incoming calls, add this process
2246 * to the idle server queue, to wait for one */
2249 *socketp = OSI_NULLSOCKET;
2251 sq->socketp = socketp;
2252 opr_queue_Append(&rx_idleServerQueue, &sq->entry);
2256 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2258 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2259 return (struct rx_call *)0;
2262 } while (!(call = sq->newcall)
2263 && !(socketp && *socketp != OSI_NULLSOCKET));
2265 MUTEX_EXIT(&sq->lock);
2267 MUTEX_ENTER(&freeSQEList_lock);
2268 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2269 rx_FreeSQEList = sq;
2270 MUTEX_EXIT(&freeSQEList_lock);
2273 clock_GetTime(&call->startTime);
2274 call->state = RX_STATE_ACTIVE;
2275 call->app.mode = RX_MODE_RECEIVING;
2276 #ifdef RX_KERNEL_TRACE
2277 if (ICL_SETACTIVE(afs_iclSetp)) {
2278 int glockOwner = ISAFS_GLOCK();
2281 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2282 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2289 rxi_calltrace(RX_CALL_START, call);
2290 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2291 call->conn->service->servicePort, call->conn->service->serviceId,
2294 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2301 #endif /* RX_ENABLE_LOCKS */
2305 /* Establish a procedure to be called when a packet arrives for a
2306 * call. This routine will be called at most once after each call,
2307 * and will also be called if there is an error condition on the or
2308 * the call is complete. Used by multi rx to build a selection
2309 * function which determines which of several calls is likely to be a
2310 * good one to read from.
2311 * NOTE: the way this is currently implemented it is probably only a
2312 * good idea to (1) use it immediately after a newcall (clients only)
2313 * and (2) only use it once. Other uses currently void your warranty
2316 rx_SetArrivalProc(struct rx_call *call,
2317 void (*proc) (struct rx_call * call,
2320 void * handle, int arg)
2322 call->arrivalProc = proc;
2323 call->arrivalProcHandle = handle;
2324 call->arrivalProcArg = arg;
2327 /* Call is finished (possibly prematurely). Return rc to the peer, if
2328 * appropriate, and return the final error code from the conversation
2332 rx_EndCall(struct rx_call *call, afs_int32 rc)
2334 struct rx_connection *conn = call->conn;
2338 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2339 call, rc, call->error, call->abortCode));
2342 MUTEX_ENTER(&call->lock);
2344 if (rc == 0 && call->error == 0) {
2345 call->abortCode = 0;
2346 call->abortCount = 0;
2349 call->arrivalProc = (void (*)())0;
2350 if (rc && call->error == 0) {
2351 rxi_CallError(call, rc);
2352 call->app.mode = RX_MODE_ERROR;
2353 /* Send an abort message to the peer if this error code has
2354 * only just been set. If it was set previously, assume the
2355 * peer has already been sent the error code or will request it
2357 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2359 if (conn->type == RX_SERVER_CONNECTION) {
2360 /* Make sure reply or at least dummy reply is sent */
2361 if (call->app.mode == RX_MODE_RECEIVING) {
2362 MUTEX_EXIT(&call->lock);
2363 rxi_WriteProc(call, 0, 0);
2364 MUTEX_ENTER(&call->lock);
2366 if (call->app.mode == RX_MODE_SENDING) {
2367 MUTEX_EXIT(&call->lock);
2368 rxi_FlushWrite(call);
2369 MUTEX_ENTER(&call->lock);
2371 rxi_calltrace(RX_CALL_END, call);
2372 /* Call goes to hold state until reply packets are acknowledged */
2373 if (call->tfirst + call->nSoftAcked < call->tnext) {
2374 call->state = RX_STATE_HOLD;
2376 call->state = RX_STATE_DALLY;
2377 rxi_ClearTransmitQueue(call, 0);
2378 rxi_rto_cancel(call);
2379 rxi_CancelKeepAliveEvent(call);
2381 } else { /* Client connection */
2383 /* Make sure server receives input packets, in the case where
2384 * no reply arguments are expected */
2386 if ((call->app.mode == RX_MODE_SENDING)
2387 || (call->app.mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2388 MUTEX_EXIT(&call->lock);
2389 (void)rxi_ReadProc(call, &dummy, 1);
2390 MUTEX_ENTER(&call->lock);
2393 /* If we had an outstanding delayed ack, be nice to the server
2394 * and force-send it now.
2396 if (call->delayedAckEvent) {
2397 rxi_CancelDelayedAckEvent(call);
2398 rxi_SendDelayedAck(NULL, call, NULL, 0);
2401 /* We need to release the call lock since it's lower than the
2402 * conn_call_lock and we don't want to hold the conn_call_lock
2403 * over the rx_ReadProc call. The conn_call_lock needs to be held
2404 * here for the case where rx_NewCall is perusing the calls on
2405 * the connection structure. We don't want to signal until
2406 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2407 * have checked this call, found it active and by the time it
2408 * goes to sleep, will have missed the signal.
2410 MUTEX_EXIT(&call->lock);
2411 MUTEX_ENTER(&conn->conn_call_lock);
2412 MUTEX_ENTER(&call->lock);
2415 /* While there are some circumstances where a call with an error is
2416 * obviously not on a "busy" channel, be conservative (clearing
2417 * lastBusy is just best-effort to possibly speed up rx_NewCall).
2418 * The call channel is definitely not busy if we just successfully
2419 * completed a call on it. */
2420 conn->lastBusy[call->channel] = 0;
2422 } else if (call->error == RX_CALL_TIMEOUT) {
2423 /* The call is still probably running on the server side, so try to
2424 * avoid this call channel in the future. */
2425 conn->lastBusy[call->channel] = clock_Sec();
2428 MUTEX_ENTER(&conn->conn_data_lock);
2429 conn->flags |= RX_CONN_BUSY;
2430 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2431 MUTEX_EXIT(&conn->conn_data_lock);
2432 #ifdef RX_ENABLE_LOCKS
2433 CV_BROADCAST(&conn->conn_call_cv);
2438 #ifdef RX_ENABLE_LOCKS
2440 MUTEX_EXIT(&conn->conn_data_lock);
2442 #endif /* RX_ENABLE_LOCKS */
2443 call->state = RX_STATE_DALLY;
2445 error = call->error;
2447 /* currentPacket, nLeft, and NFree must be zeroed here, because
2448 * ResetCall cannot: ResetCall may be called at splnet(), in the
2449 * kernel version, and may interrupt the macros rx_Read or
2450 * rx_Write, which run at normal priority for efficiency. */
2451 if (call->app.currentPacket) {
2452 #ifdef RX_TRACK_PACKETS
2453 call->app.currentPacket->flags &= ~RX_PKTFLAG_CP;
2455 rxi_FreePacket(call->app.currentPacket);
2456 call->app.currentPacket = (struct rx_packet *)0;
2459 call->app.nLeft = call->app.nFree = call->app.curlen = 0;
2461 /* Free any packets from the last call to ReadvProc/WritevProc */
2462 #ifdef RXDEBUG_PACKET
2464 #endif /* RXDEBUG_PACKET */
2465 rxi_FreePackets(0, &call->app.iovq);
2466 MUTEX_EXIT(&call->lock);
2468 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2469 if (conn->type == RX_CLIENT_CONNECTION) {
2470 MUTEX_ENTER(&conn->conn_data_lock);
2471 conn->flags &= ~RX_CONN_BUSY;
2472 MUTEX_EXIT(&conn->conn_data_lock);
2473 MUTEX_EXIT(&conn->conn_call_lock);
2477 * Map errors to the local host's errno.h format.
2479 error = ntoh_syserr_conv(error);
2481 /* If the caller said the call failed with some error, we had better
2482 * return an error code. */
2483 osi_Assert(!rc || error);
2487 #if !defined(KERNEL)
2489 /* Call this routine when shutting down a server or client (especially
2490 * clients). This will allow Rx to gracefully garbage collect server
2491 * connections, and reduce the number of retries that a server might
2492 * make to a dead client.
2493 * This is not quite right, since some calls may still be ongoing and
2494 * we can't lock them to destroy them. */
2498 struct rx_connection **conn_ptr, **conn_end;
2501 if (rx_atomic_test_and_set_bit(&rxinit_status, 0))
2502 return; /* Already shutdown. */
2504 rxi_DeleteCachedConnections();
2505 if (rx_connHashTable) {
2506 MUTEX_ENTER(&rx_connHashTable_lock);
2507 for (conn_ptr = &rx_connHashTable[0], conn_end =
2508 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2510 struct rx_connection *conn, *next;
2511 for (conn = *conn_ptr; conn; conn = next) {
2513 if (conn->type == RX_CLIENT_CONNECTION) {
2514 MUTEX_ENTER(&rx_refcnt_mutex);
2516 MUTEX_EXIT(&rx_refcnt_mutex);
2517 #ifdef RX_ENABLE_LOCKS
2518 rxi_DestroyConnectionNoLock(conn);
2519 #else /* RX_ENABLE_LOCKS */
2520 rxi_DestroyConnection(conn);
2521 #endif /* RX_ENABLE_LOCKS */
2525 #ifdef RX_ENABLE_LOCKS
2526 while (rx_connCleanup_list) {
2527 struct rx_connection *conn;
2528 conn = rx_connCleanup_list;
2529 rx_connCleanup_list = rx_connCleanup_list->next;
2530 MUTEX_EXIT(&rx_connHashTable_lock);
2531 rxi_CleanupConnection(conn);
2532 MUTEX_ENTER(&rx_connHashTable_lock);
2534 MUTEX_EXIT(&rx_connHashTable_lock);
2535 #endif /* RX_ENABLE_LOCKS */
2540 afs_winsockCleanup();
2546 /* if we wakeup packet waiter too often, can get in loop with two
2547 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2549 rxi_PacketsUnWait(void)
2551 if (!rx_waitingForPackets) {
2555 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2556 return; /* still over quota */
2559 rx_waitingForPackets = 0;
2560 #ifdef RX_ENABLE_LOCKS
2561 CV_BROADCAST(&rx_waitingForPackets_cv);
2563 osi_rxWakeup(&rx_waitingForPackets);
2569 /* ------------------Internal interfaces------------------------- */
2571 /* Return this process's service structure for the
2572 * specified socket and service */
2573 static struct rx_service *
2574 rxi_FindService(osi_socket socket, u_short serviceId)
2576 struct rx_service **sp;
2577 for (sp = &rx_services[0]; *sp; sp++) {
2578 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2584 #ifdef RXDEBUG_PACKET
2585 #ifdef KDUMP_RX_LOCK
2586 static struct rx_call_rx_lock *rx_allCallsp = 0;
2588 static struct rx_call *rx_allCallsp = 0;
2590 #endif /* RXDEBUG_PACKET */
2592 /* Allocate a call structure, for the indicated channel of the
2593 * supplied connection. The mode and state of the call must be set by
2594 * the caller. Returns the call with mutex locked. */
2595 static struct rx_call *
2596 rxi_NewCall(struct rx_connection *conn, int channel)
2598 struct rx_call *call;
2599 #ifdef RX_ENABLE_LOCKS
2600 struct rx_call *cp; /* Call pointer temp */
2601 struct opr_queue *cursor;
2604 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2606 /* Grab an existing call structure, or allocate a new one.
2607 * Existing call structures are assumed to have been left reset by
2609 MUTEX_ENTER(&rx_freeCallQueue_lock);
2611 #ifdef RX_ENABLE_LOCKS
2613 * EXCEPT that the TQ might not yet be cleared out.
2614 * Skip over those with in-use TQs.
2617 for (opr_queue_Scan(&rx_freeCallQueue, cursor)) {
2618 cp = opr_queue_Entry(cursor, struct rx_call, entry);
2619 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2625 #else /* RX_ENABLE_LOCKS */
2626 if (!opr_queue_IsEmpty(&rx_freeCallQueue)) {
2627 call = opr_queue_First(&rx_freeCallQueue, struct rx_call, entry);
2628 #endif /* RX_ENABLE_LOCKS */
2629 opr_queue_Remove(&call->entry);
2630 if (rx_stats_active)
2631 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2632 MUTEX_EXIT(&rx_freeCallQueue_lock);
2633 MUTEX_ENTER(&call->lock);
2634 CLEAR_CALL_QUEUE_LOCK(call);
2635 #ifdef RX_ENABLE_LOCKS
2636 /* Now, if TQ wasn't cleared earlier, do it now. */
2637 rxi_WaitforTQBusy(call);
2638 if (call->flags & RX_CALL_TQ_CLEARME) {
2639 rxi_ClearTransmitQueue(call, 1);
2640 /*queue_Init(&call->tq);*/
2642 #endif /* RX_ENABLE_LOCKS */
2643 /* Bind the call to its connection structure */
2645 rxi_ResetCall(call, 1);
2648 call = rxi_Alloc(sizeof(struct rx_call));
2649 #ifdef RXDEBUG_PACKET
2650 call->allNextp = rx_allCallsp;
2651 rx_allCallsp = call;
2653 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2654 #else /* RXDEBUG_PACKET */
2655 rx_atomic_inc(&rx_stats.nCallStructs);
2656 #endif /* RXDEBUG_PACKET */
2658 MUTEX_EXIT(&rx_freeCallQueue_lock);
2659 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2660 MUTEX_ENTER(&call->lock);
2661 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2662 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2663 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2665 /* Initialize once-only items */
2666 opr_queue_Init(&call->tq);
2667 opr_queue_Init(&call->rq);
2668 opr_queue_Init(&call->app.iovq);
2669 #ifdef RXDEBUG_PACKET
2670 call->rqc = call->tqc = call->iovqc = 0;
2671 #endif /* RXDEBUG_PACKET */
2672 /* Bind the call to its connection structure (prereq for reset) */
2674 rxi_ResetCall(call, 1);
2676 call->channel = channel;
2677 call->callNumber = &conn->callNumber[channel];
2678 call->rwind = conn->rwind[channel];
2679 call->twind = conn->twind[channel];
2680 /* Note that the next expected call number is retained (in
2681 * conn->callNumber[i]), even if we reallocate the call structure
2683 conn->call[channel] = call;
2684 /* if the channel's never been used (== 0), we should start at 1, otherwise
2685 * the call number is valid from the last time this channel was used */
2686 if (*call->callNumber == 0)
2687 *call->callNumber = 1;
2692 /* A call has been inactive long enough that so we can throw away
2693 * state, including the call structure, which is placed on the call
2696 * call->lock amd rx_refcnt_mutex are held upon entry.
2697 * haveCTLock is set when called from rxi_ReapConnections.
2699 * return 1 if the call is freed, 0 if not.
2702 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2704 int channel = call->channel;
2705 struct rx_connection *conn = call->conn;
2706 u_char state = call->state;
2709 * We are setting the state to RX_STATE_RESET to
2710 * ensure that no one else will attempt to use this
2711 * call once we drop the refcnt lock. We must drop
2712 * the refcnt lock before calling rxi_ResetCall
2713 * because it cannot be held across acquiring the
2714 * freepktQ lock. NewCall does the same.
2716 call->state = RX_STATE_RESET;
2717 MUTEX_EXIT(&rx_refcnt_mutex);
2718 rxi_ResetCall(call, 0);
2720 if (MUTEX_TRYENTER(&conn->conn_call_lock))
2722 if (state == RX_STATE_DALLY || state == RX_STATE_HOLD)
2723 (*call->callNumber)++;
2725 if (call->conn->call[channel] == call)
2726 call->conn->call[channel] = 0;
2727 MUTEX_EXIT(&conn->conn_call_lock);
2730 * We couldn't obtain the conn_call_lock so we can't
2731 * disconnect the call from the connection. Set the
2732 * call state to dally so that the call can be reused.
2734 MUTEX_ENTER(&rx_refcnt_mutex);
2735 call->state = RX_STATE_DALLY;
2739 MUTEX_ENTER(&rx_freeCallQueue_lock);
2740 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2741 #ifdef RX_ENABLE_LOCKS
2742 /* A call may be free even though its transmit queue is still in use.
2743 * Since we search the call list from head to tail, put busy calls at
2744 * the head of the list, and idle calls at the tail.
2746 if (call->flags & RX_CALL_TQ_BUSY)
2747 opr_queue_Prepend(&rx_freeCallQueue, &call->entry);
2749 opr_queue_Append(&rx_freeCallQueue, &call->entry);
2750 #else /* RX_ENABLE_LOCKS */
2751 opr_queue_Append(&rx_freeCallQueue, &call->entry);
2752 #endif /* RX_ENABLE_LOCKS */
2753 if (rx_stats_active)
2754 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2755 MUTEX_EXIT(&rx_freeCallQueue_lock);
2757 /* Destroy the connection if it was previously slated for
2758 * destruction, i.e. the Rx client code previously called
2759 * rx_DestroyConnection (client connections), or
2760 * rxi_ReapConnections called the same routine (server
2761 * connections). Only do this, however, if there are no
2762 * outstanding calls. Note that for fine grain locking, there appears
2763 * to be a deadlock in that rxi_FreeCall has a call locked and
2764 * DestroyConnectionNoLock locks each call in the conn. But note a
2765 * few lines up where we have removed this call from the conn.
2766 * If someone else destroys a connection, they either have no
2767 * call lock held or are going through this section of code.
2769 MUTEX_ENTER(&conn->conn_data_lock);
2770 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2771 MUTEX_ENTER(&rx_refcnt_mutex);
2773 MUTEX_EXIT(&rx_refcnt_mutex);
2774 MUTEX_EXIT(&conn->conn_data_lock);
2775 #ifdef RX_ENABLE_LOCKS
2777 rxi_DestroyConnectionNoLock(conn);
2779 rxi_DestroyConnection(conn);
2780 #else /* RX_ENABLE_LOCKS */
2781 rxi_DestroyConnection(conn);
2782 #endif /* RX_ENABLE_LOCKS */
2784 MUTEX_EXIT(&conn->conn_data_lock);
2786 MUTEX_ENTER(&rx_refcnt_mutex);
2790 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2791 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2794 rxi_Alloc(size_t size)
2798 if (rx_stats_active) {
2799 rx_atomic_add(&rxi_Allocsize, (int) size);
2800 rx_atomic_inc(&rxi_Alloccnt);
2804 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2805 afs_osi_Alloc_NoSleep(size);
2810 osi_Panic("rxi_Alloc error");
2816 rxi_Free(void *addr, size_t size)
2818 if (rx_stats_active) {
2819 rx_atomic_sub(&rxi_Allocsize, (int) size);
2820 rx_atomic_dec(&rxi_Alloccnt);
2822 osi_Free(addr, size);
2826 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2828 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2829 struct rx_peer *next = NULL;
2833 MUTEX_ENTER(&rx_peerHashTable_lock);
2835 peer_ptr = &rx_peerHashTable[0];
2836 peer_end = &rx_peerHashTable[rx_hashTableSize];
2839 for ( ; peer_ptr < peer_end; peer_ptr++) {
2842 for ( ; peer; peer = next) {
2844 if (host == peer->host)
2849 hashIndex = PEER_HASH(host, port);
2850 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2851 if ((peer->host == host) && (peer->port == port))
2856 MUTEX_ENTER(&rx_peerHashTable_lock);
2861 MUTEX_EXIT(&rx_peerHashTable_lock);
2863 MUTEX_ENTER(&peer->peer_lock);
2864 /* We don't handle dropping below min, so don't */
2865 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2866 peer->ifMTU=MIN(mtu, peer->ifMTU);
2867 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2868 /* if we tweaked this down, need to tune our peer MTU too */
2869 peer->MTU = MIN(peer->MTU, peer->natMTU);
2870 /* if we discovered a sub-1500 mtu, degrade */
2871 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2872 peer->maxDgramPackets = 1;
2873 /* We no longer have valid peer packet information */
2874 if (peer->maxPacketSize + RX_HEADER_SIZE > peer->ifMTU)
2875 peer->maxPacketSize = 0;
2876 MUTEX_EXIT(&peer->peer_lock);
2878 MUTEX_ENTER(&rx_peerHashTable_lock);
2880 if (host && !port) {
2882 /* pick up where we left off */
2886 MUTEX_EXIT(&rx_peerHashTable_lock);
2889 #ifdef AFS_RXERRQ_ENV
2891 rxi_SetPeerDead(struct sock_extended_err *err, afs_uint32 host, afs_uint16 port)
2893 int hashIndex = PEER_HASH(host, port);
2894 struct rx_peer *peer;
2896 MUTEX_ENTER(&rx_peerHashTable_lock);
2898 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2899 if (peer->host == host && peer->port == port) {
2905 MUTEX_EXIT(&rx_peerHashTable_lock);
2908 rx_atomic_inc(&peer->neterrs);
2909 MUTEX_ENTER(&peer->peer_lock);
2910 peer->last_err_origin = RX_NETWORK_ERROR_ORIGIN_ICMP;
2911 peer->last_err_type = err->ee_type;
2912 peer->last_err_code = err->ee_code;
2913 MUTEX_EXIT(&peer->peer_lock);
2915 MUTEX_ENTER(&rx_peerHashTable_lock);
2917 MUTEX_EXIT(&rx_peerHashTable_lock);
2922 rxi_ProcessNetError(struct sock_extended_err *err, afs_uint32 addr, afs_uint16 port)
2924 # ifdef AFS_ADAPT_PMTU
2925 if (err->ee_errno == EMSGSIZE && err->ee_info >= 68) {
2926 rxi_SetPeerMtu(NULL, addr, port, err->ee_info - RX_IPUDP_SIZE);
2930 if (err->ee_origin == SO_EE_ORIGIN_ICMP && err->ee_type == ICMP_DEST_UNREACH) {
2931 switch (err->ee_code) {
2932 case ICMP_NET_UNREACH:
2933 case ICMP_HOST_UNREACH:
2934 case ICMP_PORT_UNREACH:
2937 rxi_SetPeerDead(err, addr, port);
2944 rxi_TranslateICMP(int type, int code)
2947 case ICMP_DEST_UNREACH:
2949 case ICMP_NET_UNREACH:
2950 return "Destination Net Unreachable";
2951 case ICMP_HOST_UNREACH:
2952 return "Destination Host Unreachable";
2953 case ICMP_PROT_UNREACH:
2954 return "Destination Protocol Unreachable";
2955 case ICMP_PORT_UNREACH:
2956 return "Destination Port Unreachable";
2958 return "Destination Net Prohibited";
2960 return "Destination Host Prohibited";
2966 #endif /* AFS_RXERRQ_ENV */
2969 * Get the last network error for a connection
2971 * A "network error" here means an error retrieved from ICMP, or some other
2972 * mechanism outside of Rx that informs us of errors in network reachability.
2974 * If a peer associated with the given Rx connection has received a network
2975 * error recently, this function allows the caller to know what error
2976 * specifically occurred. This can be useful to know, since e.g. ICMP errors
2977 * can cause calls to that peer to be quickly aborted. So, this function can
2978 * help see why a call was aborted due to network errors.
2980 * If we have received traffic from a peer since the last network error, we
2981 * treat that peer as if we had not received an network error for it.
2983 * @param[in] conn The Rx connection to examine
2984 * @param[out] err_origin The origin of the last network error (e.g. ICMP);
2985 * one of the RX_NETWORK_ERROR_ORIGIN_* constants
2986 * @param[out] err_type The type of the last error
2987 * @param[out] err_code The code of the last error
2988 * @param[out] msg Human-readable error message, if applicable; NULL otherwise
2990 * @return If we have an error
2991 * @retval -1 No error to get; 'out' params are undefined
2992 * @retval 0 We have an error; 'out' params contain the last error
2995 rx_GetNetworkError(struct rx_connection *conn, int *err_origin, int *err_type,
2996 int *err_code, const char **msg)
2998 #ifdef AFS_RXERRQ_ENV
2999 struct rx_peer *peer = conn->peer;
3000 if (rx_atomic_read(&peer->neterrs)) {
3001 MUTEX_ENTER(&peer->peer_lock);
3002 *err_origin = peer->last_err_origin;
3003 *err_type = peer->last_err_type;
3004 *err_code = peer->last_err_code;
3005 MUTEX_EXIT(&peer->peer_lock);
3008 if (*err_origin == RX_NETWORK_ERROR_ORIGIN_ICMP) {
3009 *msg = rxi_TranslateICMP(*err_type, *err_code);
3018 /* Find the peer process represented by the supplied (host,port)
3019 * combination. If there is no appropriate active peer structure, a
3020 * new one will be allocated and initialized
3023 rxi_FindPeer(afs_uint32 host, u_short port, int create)
3027 hashIndex = PEER_HASH(host, port);
3028 MUTEX_ENTER(&rx_peerHashTable_lock);
3029 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
3030 if ((pp->host == host) && (pp->port == port))
3035 pp = rxi_AllocPeer(); /* This bzero's *pp */
3036 pp->host = host; /* set here or in InitPeerParams is zero */
3038 #ifdef AFS_RXERRQ_ENV
3039 rx_atomic_set(&pp->neterrs, 0);
3041 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
3042 opr_queue_Init(&pp->rpcStats);
3043 pp->next = rx_peerHashTable[hashIndex];
3044 rx_peerHashTable[hashIndex] = pp;
3045 rxi_InitPeerParams(pp);
3046 if (rx_stats_active)
3047 rx_atomic_inc(&rx_stats.nPeerStructs);
3053 MUTEX_EXIT(&rx_peerHashTable_lock);
3058 /* Find the connection at (host, port) started at epoch, and with the
3059 * given connection id. Creates the server connection if necessary.
3060 * The type specifies whether a client connection or a server
3061 * connection is desired. In both cases, (host, port) specify the
3062 * peer's (host, pair) pair. Client connections are not made
3063 * automatically by this routine. The parameter socket gives the
3064 * socket descriptor on which the packet was received. This is used,
3065 * in the case of server connections, to check that *new* connections
3066 * come via a valid (port, serviceId). Finally, the securityIndex
3067 * parameter must match the existing index for the connection. If a
3068 * server connection is created, it will be created using the supplied
3069 * index, if the index is valid for this service */
3070 static struct rx_connection *
3071 rxi_FindConnection(osi_socket socket, afs_uint32 host,
3072 u_short port, u_short serviceId, afs_uint32 cid,
3073 afs_uint32 epoch, int type, u_int securityIndex,
3074 int *unknownService)
3076 int hashindex, flag, i;
3077 struct rx_connection *conn;
3078 *unknownService = 0;
3079 hashindex = CONN_HASH(host, port, cid, epoch, type);
3080 MUTEX_ENTER(&rx_connHashTable_lock);
3081 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
3082 rx_connHashTable[hashindex],
3085 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
3086 && (epoch == conn->epoch)) {
3087 struct rx_peer *pp = conn->peer;
3088 if (securityIndex != conn->securityIndex) {
3089 /* this isn't supposed to happen, but someone could forge a packet
3090 * like this, and there seems to be some CM bug that makes this
3091 * happen from time to time -- in which case, the fileserver
3093 MUTEX_EXIT(&rx_connHashTable_lock);
3094 return (struct rx_connection *)0;
3096 if (pp->host == host && pp->port == port)
3098 if (type == RX_CLIENT_CONNECTION && pp->port == port)
3100 /* So what happens when it's a callback connection? */
3101 if ( /*type == RX_CLIENT_CONNECTION && */
3102 (conn->epoch & 0x80000000))
3106 /* the connection rxLastConn that was used the last time is not the
3107 ** one we are looking for now. Hence, start searching in the hash */
3109 conn = rx_connHashTable[hashindex];
3114 struct rx_service *service;
3115 if (type == RX_CLIENT_CONNECTION) {
3116 MUTEX_EXIT(&rx_connHashTable_lock);
3117 return (struct rx_connection *)0;
3119 service = rxi_FindService(socket, serviceId);
3120 if (!service || (securityIndex >= service->nSecurityObjects)
3121 || (service->securityObjects[securityIndex] == 0)) {
3122 MUTEX_EXIT(&rx_connHashTable_lock);
3123 *unknownService = 1;
3124 return (struct rx_connection *)0;
3126 conn = rxi_AllocConnection(); /* This bzero's the connection */
3127 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
3128 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
3129 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
3130 conn->next = rx_connHashTable[hashindex];
3131 rx_connHashTable[hashindex] = conn;
3132 conn->peer = rxi_FindPeer(host, port, 1);
3133 conn->type = RX_SERVER_CONNECTION;
3134 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
3135 conn->epoch = epoch;
3136 conn->cid = cid & RX_CIDMASK;
3137 conn->ackRate = RX_FAST_ACK_RATE;
3138 conn->service = service;
3139 conn->serviceId = serviceId;
3140 conn->securityIndex = securityIndex;
3141 conn->securityObject = service->securityObjects[securityIndex];
3142 conn->nSpecific = 0;
3143 conn->specific = NULL;
3144 rx_SetConnDeadTime(conn, service->connDeadTime);
3145 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
3146 for (i = 0; i < RX_MAXCALLS; i++) {
3147 conn->twind[i] = rx_initSendWindow;
3148 conn->rwind[i] = rx_initReceiveWindow;
3150 /* Notify security object of the new connection */
3151 RXS_NewConnection(conn->securityObject, conn);
3152 /* XXXX Connection timeout? */
3153 if (service->newConnProc)
3154 (*service->newConnProc) (conn);
3155 if (rx_stats_active)
3156 rx_atomic_inc(&rx_stats.nServerConns);
3159 MUTEX_ENTER(&rx_refcnt_mutex);
3161 MUTEX_EXIT(&rx_refcnt_mutex);
3163 rxLastConn = conn; /* store this connection as the last conn used */
3164 MUTEX_EXIT(&rx_connHashTable_lock);
3169 * Abort the call if the server is over the busy threshold. This
3170 * can be used without requiring a call structure be initialised,
3171 * or connected to a particular channel
3174 rxi_AbortIfServerBusy(osi_socket socket, struct rx_connection *conn,
3175 struct rx_packet *np)
3177 if ((rx_BusyThreshold > 0) &&
3178 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3179 rxi_SendRawAbort(socket, conn->peer->host, conn->peer->port,
3180 rx_BusyError, np, 0);
3181 if (rx_stats_active)
3182 rx_atomic_inc(&rx_stats.nBusies);
3189 static_inline struct rx_call *
3190 rxi_ReceiveClientCall(struct rx_packet *np, struct rx_connection *conn)
3193 struct rx_call *call;
3195 channel = np->header.cid & RX_CHANNELMASK;
3196 MUTEX_ENTER(&conn->conn_call_lock);
3197 call = conn->call[channel];
3198 if (np->header.type == RX_PACKET_TYPE_BUSY) {
3199 conn->lastBusy[channel] = clock_Sec();
3201 if (!call || conn->callNumber[channel] != np->header.callNumber) {
3202 MUTEX_EXIT(&conn->conn_call_lock);
3203 if (rx_stats_active)
3204 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3208 MUTEX_ENTER(&call->lock);
3209 MUTEX_EXIT(&conn->conn_call_lock);
3211 if ((call->state == RX_STATE_DALLY)
3212 && np->header.type == RX_PACKET_TYPE_ACK) {
3213 if (rx_stats_active)
3214 rx_atomic_inc(&rx_stats.ignorePacketDally);
3215 MUTEX_EXIT(&call->lock);
3222 static_inline struct rx_call *
3223 rxi_ReceiveServerCall(osi_socket socket, struct rx_packet *np,
3224 struct rx_connection *conn)
3227 struct rx_call *call;
3229 channel = np->header.cid & RX_CHANNELMASK;
3230 MUTEX_ENTER(&conn->conn_call_lock);
3231 call = conn->call[channel];
3234 if (rxi_AbortIfServerBusy(socket, conn, np)) {
3235 MUTEX_EXIT(&conn->conn_call_lock);
3239 call = rxi_NewCall(conn, channel); /* returns locked call */
3240 *call->callNumber = np->header.callNumber;
3241 MUTEX_EXIT(&conn->conn_call_lock);
3243 call->state = RX_STATE_PRECALL;
3244 clock_GetTime(&call->queueTime);
3245 call->app.bytesSent = 0;
3246 call->app.bytesRcvd = 0;
3247 rxi_KeepAliveOn(call);
3252 if (np->header.callNumber == conn->callNumber[channel]) {
3253 MUTEX_ENTER(&call->lock);
3254 MUTEX_EXIT(&conn->conn_call_lock);
3258 if (np->header.callNumber < conn->callNumber[channel]) {
3259 MUTEX_EXIT(&conn->conn_call_lock);
3260 if (rx_stats_active)
3261 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3265 MUTEX_ENTER(&call->lock);
3266 MUTEX_EXIT(&conn->conn_call_lock);
3268 /* Wait until the transmit queue is idle before deciding
3269 * whether to reset the current call. Chances are that the
3270 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3273 #ifdef RX_ENABLE_LOCKS
3274 if (call->state == RX_STATE_ACTIVE && !call->error) {
3275 rxi_WaitforTQBusy(call);
3276 /* If we entered error state while waiting,
3277 * must call rxi_CallError to permit rxi_ResetCall
3278 * to processed when the tqWaiter count hits zero.
3281 rxi_CallError(call, call->error);
3282 MUTEX_EXIT(&call->lock);
3286 #endif /* RX_ENABLE_LOCKS */
3287 /* If the new call cannot be taken right now send a busy and set
3288 * the error condition in this call, so that it terminates as
3289 * quickly as possible */
3290 if (call->state == RX_STATE_ACTIVE) {
3291 rxi_CallError(call, RX_CALL_DEAD);
3292 rxi_SendSpecial(call, conn, NULL, RX_PACKET_TYPE_BUSY,
3294 MUTEX_EXIT(&call->lock);
3298 if (rxi_AbortIfServerBusy(socket, conn, np)) {
3299 MUTEX_EXIT(&call->lock);
3303 rxi_ResetCall(call, 0);
3304 /* The conn_call_lock is not held but no one else should be
3305 * using this call channel while we are processing this incoming
3306 * packet. This assignment should be safe.
3308 *call->callNumber = np->header.callNumber;
3309 call->state = RX_STATE_PRECALL;
3310 clock_GetTime(&call->queueTime);
3311 call->app.bytesSent = 0;
3312 call->app.bytesRcvd = 0;
3313 rxi_KeepAliveOn(call);
3319 /* There are two packet tracing routines available for testing and monitoring
3320 * Rx. One is called just after every packet is received and the other is
3321 * called just before every packet is sent. Received packets, have had their
3322 * headers decoded, and packets to be sent have not yet had their headers
3323 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
3324 * containing the network address. Both can be modified. The return value, if
3325 * non-zero, indicates that the packet should be dropped. */
3327 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
3328 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
3330 /* A packet has been received off the interface. Np is the packet, socket is
3331 * the socket number it was received from (useful in determining which service
3332 * this packet corresponds to), and (host, port) reflect the host,port of the
3333 * sender. This call returns the packet to the caller if it is finished with
3334 * it, rather than de-allocating it, just as a small performance hack */
3337 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
3338 afs_uint32 host, u_short port, int *tnop,
3339 struct rx_call **newcallp)
3341 struct rx_call *call;
3342 struct rx_connection *conn;
3344 int unknownService = 0;
3348 struct rx_packet *tnp;
3351 /* We don't print out the packet until now because (1) the time may not be
3352 * accurate enough until now in the lwp implementation (rx_Listener only gets
3353 * the time after the packet is read) and (2) from a protocol point of view,
3354 * this is the first time the packet has been seen */
3355 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
3356 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
3357 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT"\n",
3358 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
3359 np->header.epoch, np->header.cid, np->header.callNumber,
3360 np->header.seq, np->header.flags, np));
3363 /* Account for connectionless packets */
3364 if (rx_stats_active &&
3365 ((np->header.type == RX_PACKET_TYPE_VERSION) ||
3366 (np->header.type == RX_PACKET_TYPE_DEBUG))) {
3367 struct rx_peer *peer;
3369 /* Try to look up the peer structure, but don't create one */
3370 peer = rxi_FindPeer(host, port, 0);
3372 /* Since this may not be associated with a connection, it may have
3373 * no refCount, meaning we could race with ReapConnections
3376 if (peer && (peer->refCount > 0)) {
3377 #ifdef AFS_RXERRQ_ENV
3378 if (rx_atomic_read(&peer->neterrs)) {
3379 rx_atomic_set(&peer->neterrs, 0);
3382 MUTEX_ENTER(&peer->peer_lock);
3383 peer->bytesReceived += np->length;
3384 MUTEX_EXIT(&peer->peer_lock);
3388 if (np->header.type == RX_PACKET_TYPE_VERSION) {
3389 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
3392 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
3393 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
3396 /* If an input tracer function is defined, call it with the packet and
3397 * network address. Note this function may modify its arguments. */
3398 if (rx_justReceived) {
3399 struct sockaddr_in addr;
3401 addr.sin_family = AF_INET;
3402 addr.sin_port = port;
3403 addr.sin_addr.s_addr = host;
3404 memset(&addr.sin_zero, 0, sizeof(addr.sin_zero));
3405 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
3406 addr.sin_len = sizeof(addr);
3407 #endif /* AFS_OSF_ENV */
3408 drop = (*rx_justReceived) (np, &addr);
3409 /* drop packet if return value is non-zero */
3412 port = addr.sin_port; /* in case fcn changed addr */
3413 host = addr.sin_addr.s_addr;
3417 /* If packet was not sent by the client, then *we* must be the client */
3418 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
3419 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
3421 /* Find the connection (or fabricate one, if we're the server & if
3422 * necessary) associated with this packet */
3424 rxi_FindConnection(socket, host, port, np->header.serviceId,
3425 np->header.cid, np->header.epoch, type,
3426 np->header.securityIndex, &unknownService);
3428 /* To avoid having 2 connections just abort at each other,
3429 don't abort an abort. */
3431 if (unknownService && (np->header.type != RX_PACKET_TYPE_ABORT))
3432 rxi_SendRawAbort(socket, host, port, RX_INVALID_OPERATION,
3437 #ifdef AFS_RXERRQ_ENV
3438 if (rx_atomic_read(&conn->peer->neterrs)) {
3439 rx_atomic_set(&conn->peer->neterrs, 0);
3443 /* If we're doing statistics, then account for the incoming packet */
3444 if (rx_stats_active) {
3445 MUTEX_ENTER(&conn->peer->peer_lock);
3446 conn->peer->bytesReceived += np->length;
3447 MUTEX_EXIT(&conn->peer->peer_lock);
3450 /* If the connection is in an error state, send an abort packet and ignore
3451 * the incoming packet */
3453 /* Don't respond to an abort packet--we don't want loops! */
3454 MUTEX_ENTER(&conn->conn_data_lock);
3455 if (np->header.type != RX_PACKET_TYPE_ABORT)
3456 np = rxi_SendConnectionAbort(conn, np, 1, 0);
3457 putConnection(conn);
3458 MUTEX_EXIT(&conn->conn_data_lock);
3462 /* Check for connection-only requests (i.e. not call specific). */
3463 if (np->header.callNumber == 0) {
3464 switch (np->header.type) {
3465 case RX_PACKET_TYPE_ABORT: {
3466 /* What if the supplied error is zero? */
3467 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
3468 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
3469 rxi_ConnectionError(conn, errcode);
3470 putConnection(conn);
3473 case RX_PACKET_TYPE_CHALLENGE:
3474 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
3475 putConnection(conn);
3477 case RX_PACKET_TYPE_RESPONSE:
3478 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
3479 putConnection(conn);
3481 case RX_PACKET_TYPE_PARAMS:
3482 case RX_PACKET_TYPE_PARAMS + 1:
3483 case RX_PACKET_TYPE_PARAMS + 2:
3484 /* ignore these packet types for now */
3485 putConnection(conn);
3489 /* Should not reach here, unless the peer is broken: send an
3491 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
3492 MUTEX_ENTER(&conn->conn_data_lock);
3493 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
3494 putConnection(conn);
3495 MUTEX_EXIT(&conn->conn_data_lock);
3500 if (type == RX_SERVER_CONNECTION)
3501 call = rxi_ReceiveServerCall(socket, np, conn);
3503 call = rxi_ReceiveClientCall(np, conn);
3506 putConnection(conn);
3510 MUTEX_ASSERT(&call->lock);
3511 /* Set remote user defined status from packet */
3512 call->remoteStatus = np->header.userStatus;
3514 /* Now do packet type-specific processing */
3515 switch (np->header.type) {
3516 case RX_PACKET_TYPE_DATA:
3517 /* If we're a client, and receiving a response, then all the packets
3518 * we transmitted packets are implicitly acknowledged. */
3519 if (type == RX_CLIENT_CONNECTION && !opr_queue_IsEmpty(&call->tq))
3520 rxi_AckAllInTransmitQueue(call);
3522 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3525 case RX_PACKET_TYPE_ACK:
3526 /* Respond immediately to ack packets requesting acknowledgement
3528 if (np->header.flags & RX_REQUEST_ACK) {
3530 (void)rxi_SendCallAbort(call, 0, 1, 0);
3532 (void)rxi_SendAck(call, 0, np->header.serial,
3533 RX_ACK_PING_RESPONSE, 1);
3535 np = rxi_ReceiveAckPacket(call, np, 1);
3537 case RX_PACKET_TYPE_ABORT: {
3538 /* An abort packet: reset the call, passing the error up to the user. */
3539 /* What if error is zero? */
3540 /* What if the error is -1? the application will treat it as a timeout. */
3541 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3542 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3543 rxi_CallError(call, errdata);
3544 MUTEX_EXIT(&call->lock);
3545 putConnection(conn);
3546 return np; /* xmitting; drop packet */
3548 case RX_PACKET_TYPE_BUSY:
3549 /* Mostly ignore BUSY packets. We will update lastReceiveTime below,
3550 * so we don't think the endpoint is completely dead, but otherwise
3551 * just act as if we never saw anything. If all we get are BUSY packets
3552 * back, then we will eventually error out with RX_CALL_TIMEOUT if the
3553 * connection is configured with idle/hard timeouts. */
3556 case RX_PACKET_TYPE_ACKALL:
3557 /* All packets acknowledged, so we can drop all packets previously
3558 * readied for sending */
3559 rxi_AckAllInTransmitQueue(call);
3562 /* Should not reach here, unless the peer is broken: send an abort
3564 rxi_CallError(call, RX_PROTOCOL_ERROR);
3565 np = rxi_SendCallAbort(call, np, 1, 0);
3568 /* Note when this last legitimate packet was received, for keep-alive
3569 * processing. Note, we delay getting the time until now in the hope that
3570 * the packet will be delivered to the user before any get time is required
3571 * (if not, then the time won't actually be re-evaluated here). */
3572 call->lastReceiveTime = clock_Sec();
3573 MUTEX_EXIT(&call->lock);
3574 putConnection(conn);
3578 /* return true if this is an "interesting" connection from the point of view
3579 of someone trying to debug the system */
3581 rxi_IsConnInteresting(struct rx_connection *aconn)
3584 struct rx_call *tcall;
3586 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3589 for (i = 0; i < RX_MAXCALLS; i++) {
3590 tcall = aconn->call[i];
3592 if ((tcall->state == RX_STATE_PRECALL)
3593 || (tcall->state == RX_STATE_ACTIVE))
3595 if ((tcall->app.mode == RX_MODE_SENDING)
3596 || (tcall->app.mode == RX_MODE_RECEIVING))
3604 /* if this is one of the last few packets AND it wouldn't be used by the
3605 receiving call to immediately satisfy a read request, then drop it on
3606 the floor, since accepting it might prevent a lock-holding thread from
3607 making progress in its reading. If a call has been cleared while in
3608 the precall state then ignore all subsequent packets until the call
3609 is assigned to a thread. */
3612 TooLow(struct rx_packet *ap, struct rx_call *acall)
3616 MUTEX_ENTER(&rx_quota_mutex);
3617 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3618 && (acall->state == RX_STATE_PRECALL))
3619 || ((rx_nFreePackets < rxi_dataQuota + 2)
3620 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3621 && (acall->flags & RX_CALL_READER_WAIT)))) {
3624 MUTEX_EXIT(&rx_quota_mutex);
3630 * Clear the attach wait flag on a connection and proceed.
3632 * Any processing waiting for a connection to be attached should be
3633 * unblocked. We clear the flag and do any other needed tasks.
3636 * the conn to unmark waiting for attach
3638 * @pre conn's conn_data_lock must be locked before calling this function
3642 rxi_ConnClearAttachWait(struct rx_connection *conn)
3644 /* Indicate that rxi_CheckReachEvent is no longer running by
3645 * clearing the flag. Must be atomic under conn_data_lock to
3646 * avoid a new call slipping by: rxi_CheckConnReach holds
3647 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3649 conn->flags &= ~RX_CONN_ATTACHWAIT;
3650 if (conn->flags & RX_CONN_NAT_PING) {
3651 conn->flags &= ~RX_CONN_NAT_PING;
3652 rxi_ScheduleNatKeepAliveEvent(conn);
3657 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2, int dummy)
3659 struct rx_connection *conn = arg1;
3660 struct rx_call *acall = arg2;
3661 struct rx_call *call = acall;
3662 struct clock when, now;
3665 MUTEX_ENTER(&conn->conn_data_lock);
3668 rxevent_Put(&conn->checkReachEvent);
3670 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3672 putConnection(conn);
3674 MUTEX_EXIT(&conn->conn_data_lock);
3678 MUTEX_ENTER(&conn->conn_call_lock);
3679 MUTEX_ENTER(&conn->conn_data_lock);
3680 for (i = 0; i < RX_MAXCALLS; i++) {
3681 struct rx_call *tc = conn->call[i];
3682 if (tc && tc->state == RX_STATE_PRECALL) {
3688 rxi_ConnClearAttachWait(conn);
3689 MUTEX_EXIT(&conn->conn_data_lock);
3690 MUTEX_EXIT(&conn->conn_call_lock);
3695 MUTEX_ENTER(&call->lock);
3696 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3698 MUTEX_EXIT(&call->lock);
3700 clock_GetTime(&now);
3702 when.sec += RX_CHECKREACH_TIMEOUT;
3703 MUTEX_ENTER(&conn->conn_data_lock);
3704 if (!conn->checkReachEvent) {
3705 MUTEX_ENTER(&rx_refcnt_mutex);
3707 MUTEX_EXIT(&rx_refcnt_mutex);
3708 conn->checkReachEvent = rxevent_Post(&when, &now,
3709 rxi_CheckReachEvent, conn,
3712 MUTEX_EXIT(&conn->conn_data_lock);
3718 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3720 struct rx_service *service = conn->service;
3721 struct rx_peer *peer = conn->peer;
3722 afs_uint32 now, lastReach;
3724 if (service->checkReach == 0)
3728 MUTEX_ENTER(&peer->peer_lock);
3729 lastReach = peer->lastReachTime;
3730 MUTEX_EXIT(&peer->peer_lock);
3731 if (now - lastReach < RX_CHECKREACH_TTL)
3734 MUTEX_ENTER(&conn->conn_data_lock);
3735 if (conn->flags & RX_CONN_ATTACHWAIT) {
3736 MUTEX_EXIT(&conn->conn_data_lock);
3739 conn->flags |= RX_CONN_ATTACHWAIT;
3740 MUTEX_EXIT(&conn->conn_data_lock);
3741 if (!conn->checkReachEvent)
3742 rxi_CheckReachEvent(NULL, conn, call, 0);
3747 /* try to attach call, if authentication is complete */
3749 TryAttach(struct rx_call *acall, osi_socket socket,
3750 int *tnop, struct rx_call **newcallp,
3753 struct rx_connection *conn = acall->conn;
3755 if (conn->type == RX_SERVER_CONNECTION
3756 && acall->state == RX_STATE_PRECALL) {
3757 /* Don't attach until we have any req'd. authentication. */
3758 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3759 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3760 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3761 /* Note: this does not necessarily succeed; there
3762 * may not any proc available
3765 rxi_ChallengeOn(acall->conn);
3770 /* A data packet has been received off the interface. This packet is
3771 * appropriate to the call (the call is in the right state, etc.). This
3772 * routine can return a packet to the caller, for re-use */
3774 static struct rx_packet *
3775 rxi_ReceiveDataPacket(struct rx_call *call,
3776 struct rx_packet *np, int istack,
3777 osi_socket socket, afs_uint32 host, u_short port,
3778 int *tnop, struct rx_call **newcallp)
3780 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3785 afs_uint32 serial=0, flags=0;
3787 struct rx_packet *tnp;
3788 if (rx_stats_active)
3789 rx_atomic_inc(&rx_stats.dataPacketsRead);
3792 /* If there are no packet buffers, drop this new packet, unless we can find
3793 * packet buffers from inactive calls */
3795 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3796 MUTEX_ENTER(&rx_freePktQ_lock);
3797 rxi_NeedMorePackets = TRUE;
3798 MUTEX_EXIT(&rx_freePktQ_lock);
3799 if (rx_stats_active)
3800 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3801 rxi_calltrace(RX_TRACE_DROP, call);
3802 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems\n", np));
3803 /* We used to clear the receive queue here, in an attempt to free
3804 * packets. However this is unsafe if the queue has received a
3805 * soft ACK for the final packet */
3806 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
3812 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3813 * packet is one of several packets transmitted as a single
3814 * datagram. Do not send any soft or hard acks until all packets
3815 * in a jumbogram have been processed. Send negative acks right away.
3817 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3818 /* tnp is non-null when there are more packets in the
3819 * current jumbo gram */
3826 seq = np->header.seq;
3827 serial = np->header.serial;
3828 flags = np->header.flags;
3830 /* If the call is in an error state, send an abort message */
3832 return rxi_SendCallAbort(call, np, istack, 0);
3834 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3835 * AFS 3.5 jumbogram. */
3836 if (flags & RX_JUMBO_PACKET) {
3837 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3842 if (np->header.spare != 0) {
3843 MUTEX_ENTER(&call->conn->conn_data_lock);
3844 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3845 MUTEX_EXIT(&call->conn->conn_data_lock);
3848 /* The usual case is that this is the expected next packet */
3849 if (seq == call->rnext) {
3851 /* Check to make sure it is not a duplicate of one already queued */
3852 if (!opr_queue_IsEmpty(&call->rq)
3853 && opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq == seq) {
3854 if (rx_stats_active)
3855 rx_atomic_inc(&rx_stats.dupPacketsRead);
3856 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate\n", np));
3857 rxi_CancelDelayedAckEvent(call);
3858 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3864 /* It's the next packet. Stick it on the receive queue
3865 * for this call. Set newPackets to make sure we wake
3866 * the reader once all packets have been processed */
3867 #ifdef RX_TRACK_PACKETS
3868 np->flags |= RX_PKTFLAG_RQ;
3870 opr_queue_Prepend(&call->rq, &np->entry);
3871 #ifdef RXDEBUG_PACKET
3873 #endif /* RXDEBUG_PACKET */
3875 np = NULL; /* We can't use this anymore */
3878 /* If an ack is requested then set a flag to make sure we
3879 * send an acknowledgement for this packet */
3880 if (flags & RX_REQUEST_ACK) {
3881 ackNeeded = RX_ACK_REQUESTED;
3884 /* Keep track of whether we have received the last packet */
3885 if (flags & RX_LAST_PACKET) {
3886 call->flags |= RX_CALL_HAVE_LAST;
3890 /* Check whether we have all of the packets for this call */
3891 if (call->flags & RX_CALL_HAVE_LAST) {
3892 afs_uint32 tseq; /* temporary sequence number */
3893 struct opr_queue *cursor;
3895 for (tseq = seq, opr_queue_Scan(&call->rq, cursor)) {
3896 struct rx_packet *tp;
3898 tp = opr_queue_Entry(cursor, struct rx_packet, entry);
3899 if (tseq != tp->header.seq)
3901 if (tp->header.flags & RX_LAST_PACKET) {
3902 call->flags |= RX_CALL_RECEIVE_DONE;
3909 /* Provide asynchronous notification for those who want it
3910 * (e.g. multi rx) */
3911 if (call->arrivalProc) {
3912 (*call->arrivalProc) (call, call->arrivalProcHandle,
3913 call->arrivalProcArg);
3914 call->arrivalProc = (void (*)())0;
3917 /* Update last packet received */
3920 /* If there is no server process serving this call, grab
3921 * one, if available. We only need to do this once. If a
3922 * server thread is available, this thread becomes a server
3923 * thread and the server thread becomes a listener thread. */
3925 TryAttach(call, socket, tnop, newcallp, 0);
3928 /* This is not the expected next packet. */
3930 /* Determine whether this is a new or old packet, and if it's
3931 * a new one, whether it fits into the current receive window.
3932 * Also figure out whether the packet was delivered in sequence.
3933 * We use the prev variable to determine whether the new packet
3934 * is the successor of its immediate predecessor in the
3935 * receive queue, and the missing flag to determine whether
3936 * any of this packets predecessors are missing. */
3938 afs_uint32 prev; /* "Previous packet" sequence number */
3939 struct opr_queue *cursor;
3940 int missing; /* Are any predecessors missing? */
3942 /* If the new packet's sequence number has been sent to the
3943 * application already, then this is a duplicate */
3944 if (seq < call->rnext) {
3945 if (rx_stats_active)
3946 rx_atomic_inc(&rx_stats.dupPacketsRead);
3947 rxi_CancelDelayedAckEvent(call);
3948 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3954 /* If the sequence number is greater than what can be
3955 * accomodated by the current window, then send a negative
3956 * acknowledge and drop the packet */
3957 if ((call->rnext + call->rwind) <= seq) {
3958 rxi_CancelDelayedAckEvent(call);
3959 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3966 /* Look for the packet in the queue of old received packets */
3967 prev = call->rnext - 1;
3969 for (opr_queue_Scan(&call->rq, cursor)) {
3970 struct rx_packet *tp
3971 = opr_queue_Entry(cursor, struct rx_packet, entry);
3973 /*Check for duplicate packet */
3974 if (seq == tp->header.seq) {
3975 if (rx_stats_active)
3976 rx_atomic_inc(&rx_stats.dupPacketsRead);
3977 rxi_CancelDelayedAckEvent(call);
3978 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3984 /* If we find a higher sequence packet, break out and
3985 * insert the new packet here. */
3986 if (seq < tp->header.seq)
3988 /* Check for missing packet */
3989 if (tp->header.seq != prev + 1) {
3993 prev = tp->header.seq;
3996 /* Keep track of whether we have received the last packet. */
3997 if (flags & RX_LAST_PACKET) {
3998 call->flags |= RX_CALL_HAVE_LAST;
4001 /* It's within the window: add it to the the receive queue.
4002 * tp is left by the previous loop either pointing at the
4003 * packet before which to insert the new packet, or at the
4004 * queue head if the queue is empty or the packet should be
4006 #ifdef RX_TRACK_PACKETS
4007 np->flags |= RX_PKTFLAG_RQ;
4009 #ifdef RXDEBUG_PACKET
4011 #endif /* RXDEBUG_PACKET */
4012 opr_queue_InsertBefore(cursor, &np->entry);
4016 /* Check whether we have all of the packets for this call */
4017 if ((call->flags & RX_CALL_HAVE_LAST)
4018 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
4019 afs_uint32 tseq; /* temporary sequence number */
4022 for (opr_queue_Scan(&call->rq, cursor)) {
4023 struct rx_packet *tp
4024 = opr_queue_Entry(cursor, struct rx_packet, entry);
4025 if (tseq != tp->header.seq)
4027 if (tp->header.flags & RX_LAST_PACKET) {
4028 call->flags |= RX_CALL_RECEIVE_DONE;
4035 /* We need to send an ack of the packet is out of sequence,
4036 * or if an ack was requested by the peer. */
4037 if (seq != prev + 1 || missing) {
4038 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
4039 } else if (flags & RX_REQUEST_ACK) {
4040 ackNeeded = RX_ACK_REQUESTED;
4043 /* Acknowledge the last packet for each call */
4044 if (flags & RX_LAST_PACKET) {
4055 * If the receiver is waiting for an iovec, fill the iovec
4056 * using the data from the receive queue */
4057 if (call->flags & RX_CALL_IOVEC_WAIT) {
4058 didHardAck = rxi_FillReadVec(call, serial);
4059 /* the call may have been aborted */
4068 /* Wakeup the reader if any */
4069 if ((call->flags & RX_CALL_READER_WAIT)
4070 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
4071 || (call->iovNext >= call->iovMax)
4072 || (call->flags & RX_CALL_RECEIVE_DONE))) {
4073 call->flags &= ~RX_CALL_READER_WAIT;
4074 #ifdef RX_ENABLE_LOCKS
4075 CV_BROADCAST(&call->cv_rq);
4077 osi_rxWakeup(&call->rq);
4083 * Send an ack when requested by the peer, or once every
4084 * rxi_SoftAckRate packets until the last packet has been
4085 * received. Always send a soft ack for the last packet in
4086 * the server's reply. */
4088 rxi_CancelDelayedAckEvent(call);
4089 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
4090 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
4091 rxi_CancelDelayedAckEvent(call);
4092 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
4093 } else if (call->nSoftAcks) {
4094 if (haveLast && !(flags & RX_CLIENT_INITIATED))
4095 rxi_PostDelayedAckEvent(call, &rx_lastAckDelay);
4097 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
4098 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
4099 rxi_CancelDelayedAckEvent(call);
4106 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
4108 struct rx_peer *peer = conn->peer;
4110 MUTEX_ENTER(&peer->peer_lock);
4111 peer->lastReachTime = clock_Sec();
4112 MUTEX_EXIT(&peer->peer_lock);
4114 MUTEX_ENTER(&conn->conn_data_lock);
4115 if (conn->flags & RX_CONN_ATTACHWAIT) {
4118 rxi_ConnClearAttachWait(conn);
4119 MUTEX_EXIT(&conn->conn_data_lock);
4121 for (i = 0; i < RX_MAXCALLS; i++) {
4122 struct rx_call *call = conn->call[i];
4125 MUTEX_ENTER(&call->lock);
4126 /* tnop can be null if newcallp is null */
4127 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
4129 MUTEX_EXIT(&call->lock);
4133 MUTEX_EXIT(&conn->conn_data_lock);
4136 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
4138 rx_ack_reason(int reason)
4141 case RX_ACK_REQUESTED:
4143 case RX_ACK_DUPLICATE:
4145 case RX_ACK_OUT_OF_SEQUENCE:
4147 case RX_ACK_EXCEEDS_WINDOW:
4149 case RX_ACK_NOSPACE:
4153 case RX_ACK_PING_RESPONSE:
4166 /* The real smarts of the whole thing. */
4167 static struct rx_packet *
4168 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
4171 struct rx_ackPacket *ap;
4173 struct rx_packet *tp;
4174 struct rx_connection *conn = call->conn;
4175 struct rx_peer *peer = conn->peer;
4176 struct opr_queue *cursor;
4177 struct clock now; /* Current time, for RTT calculations */
4185 int newAckCount = 0;
4186 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
4187 int pktsize = 0; /* Set if we need to update the peer mtu */
4188 int conn_data_locked = 0;
4190 if (rx_stats_active)
4191 rx_atomic_inc(&rx_stats.ackPacketsRead);
4192 ap = (struct rx_ackPacket *)rx_DataOf(np);
4193 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
4195 return np; /* truncated ack packet */
4197 /* depends on ack packet struct */
4198 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
4199 first = ntohl(ap->firstPacket);
4200 prev = ntohl(ap->previousPacket);
4201 serial = ntohl(ap->serial);
4204 * Ignore ack packets received out of order while protecting
4205 * against peers that set the previousPacket field to a packet
4206 * serial number instead of a sequence number.
4208 if (first < call->tfirst ||
4209 (first == call->tfirst && prev < call->tprev && prev < call->tfirst
4216 if (np->header.flags & RX_SLOW_START_OK) {
4217 call->flags |= RX_CALL_SLOW_START_OK;
4220 if (ap->reason == RX_ACK_PING_RESPONSE)
4221 rxi_UpdatePeerReach(conn, call);
4223 if (conn->lastPacketSizeSeq) {
4224 MUTEX_ENTER(&conn->conn_data_lock);
4225 conn_data_locked = 1;
4226 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
4227 pktsize = conn->lastPacketSize;
4228 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
4231 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
4232 if (!conn_data_locked) {
4233 MUTEX_ENTER(&conn->conn_data_lock);
4234 conn_data_locked = 1;
4236 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
4237 /* process mtu ping ack */
4238 pktsize = conn->lastPingSize;
4239 conn->lastPingSizeSer = conn->lastPingSize = 0;
4243 if (conn_data_locked) {
4244 MUTEX_EXIT(&conn->conn_data_lock);
4245 conn_data_locked = 0;
4249 if (rxdebug_active) {
4253 len = _snprintf(msg, sizeof(msg),
4254 "tid[%d] RACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
4255 GetCurrentThreadId(), rx_ack_reason(ap->reason),
4256 ntohl(ap->serial), ntohl(ap->previousPacket),
4257 (unsigned int)np->header.seq, ntohl(ap->firstPacket),
4258 ap->nAcks, ntohs(ap->bufferSpace) );
4262 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
4263 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4267 OutputDebugString(msg);
4269 #else /* AFS_NT40_ENV */
4272 "RACK: reason %x previous %u seq %u serial %u first %u",
4273 ap->reason, ntohl(ap->previousPacket),
4274 (unsigned int)np->header.seq, (unsigned int)serial,
4275 ntohl(ap->firstPacket));
4278 for (offset = 0; offset < nAcks; offset++)
4279 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4284 #endif /* AFS_NT40_ENV */
4287 MUTEX_ENTER(&peer->peer_lock);
4290 * Start somewhere. Can't assume we can send what we can receive,
4291 * but we are clearly receiving.
4293 if (!peer->maxPacketSize)
4294 peer->maxPacketSize = RX_MIN_PACKET_SIZE - RX_HEADER_SIZE;
4296 if (pktsize > peer->maxPacketSize) {
4297 peer->maxPacketSize = pktsize;
4298 if ((pktsize + RX_HEADER_SIZE > peer->ifMTU)) {
4299 peer->ifMTU = pktsize + RX_HEADER_SIZE;
4300 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4301 rxi_ScheduleGrowMTUEvent(call, 1);
4306 clock_GetTime(&now);
4308 /* The transmit queue splits into 4 sections.
4310 * The first section is packets which have now been acknowledged
4311 * by a window size change in the ack. These have reached the
4312 * application layer, and may be discarded. These are packets
4313 * with sequence numbers < ap->firstPacket.
4315 * The second section is packets which have sequence numbers in
4316 * the range ap->firstPacket to ap->firstPacket + ap->nAcks. The
4317 * contents of the packet's ack array determines whether these
4318 * packets are acknowledged or not.
4320 * The third section is packets which fall above the range
4321 * addressed in the ack packet. These have not yet been received
4324 * The four section is packets which have not yet been transmitted.
4325 * These packets will have a header.serial of 0.
4328 /* First section - implicitly acknowledged packets that can be
4332 tp = opr_queue_First(&call->tq, struct rx_packet, entry);
4333 while(!opr_queue_IsEnd(&call->tq, &tp->entry) && tp->header.seq < first) {
4334 struct rx_packet *next;
4336 next = opr_queue_Next(&tp->entry, struct rx_packet, entry);
4337 call->tfirst = tp->header.seq + 1;
4339 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4341 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4344 #ifdef RX_ENABLE_LOCKS
4345 /* XXX Hack. Because we have to release the global call lock when sending
4346 * packets (osi_NetSend) we drop all acks while we're traversing the tq
4347 * in rxi_Start sending packets out because packets may move to the
4348 * freePacketQueue as result of being here! So we drop these packets until
4349 * we're safely out of the traversing. Really ugly!
4350 * To make it even uglier, if we're using fine grain locking, we can
4351 * set the ack bits in the packets and have rxi_Start remove the packets
4352 * when it's done transmitting.
4354 if (call->flags & RX_CALL_TQ_BUSY) {
4355 tp->flags |= RX_PKTFLAG_ACKED;
4356 call->flags |= RX_CALL_TQ_SOME_ACKED;
4358 #endif /* RX_ENABLE_LOCKS */
4360 opr_queue_Remove(&tp->entry);
4361 #ifdef RX_TRACK_PACKETS
4362 tp->flags &= ~RX_PKTFLAG_TQ;
4364 #ifdef RXDEBUG_PACKET
4366 #endif /* RXDEBUG_PACKET */
4367 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4372 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
4374 /* Second section of the queue - packets for which we are receiving
4377 * Go through the explicit acks/nacks and record the results in
4378 * the waiting packets. These are packets that can't be released
4379 * yet, even with a positive acknowledge. This positive
4380 * acknowledge only means the packet has been received by the
4381 * peer, not that it will be retained long enough to be sent to
4382 * the peer's upper level. In addition, reset the transmit timers
4383 * of any missing packets (those packets that must be missing
4384 * because this packet was out of sequence) */
4386 call->nSoftAcked = 0;
4388 while (!opr_queue_IsEnd(&call->tq, &tp->entry)
4389 && tp->header.seq < first + nAcks) {
4390 /* Set the acknowledge flag per packet based on the
4391 * information in the ack packet. An acknowlegded packet can
4392 * be downgraded when the server has discarded a packet it
4393 * soacked previously, or when an ack packet is received
4394 * out of sequence. */
4395 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4396 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4398 tp->flags |= RX_PKTFLAG_ACKED;
4399 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4406 } else /* RX_ACK_TYPE_NACK */ {
4407 tp->flags &= ~RX_PKTFLAG_ACKED;
4411 tp = opr_queue_Next(&tp->entry, struct rx_packet, entry);
4414 /* We don't need to take any action with the 3rd or 4th section in the
4415 * queue - they're not addressed by the contents of this ACK packet.
4418 /* If the window has been extended by this acknowledge packet,
4419 * then wakeup a sender waiting in alloc for window space, or try
4420 * sending packets now, if he's been sitting on packets due to
4421 * lack of window space */
4422 if (call->tnext < (call->tfirst + call->twind)) {
4423 #ifdef RX_ENABLE_LOCKS
4424 CV_SIGNAL(&call->cv_twind);
4426 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4427 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4428 osi_rxWakeup(&call->twind);
4431 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4432 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4436 /* if the ack packet has a receivelen field hanging off it,
4437 * update our state */
4438 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4441 /* If the ack packet has a "recommended" size that is less than
4442 * what I am using now, reduce my size to match */
4443 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4444 (int)sizeof(afs_int32), &tSize);
4445 tSize = (afs_uint32) ntohl(tSize);
4446 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4448 /* Get the maximum packet size to send to this peer */
4449 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4451 tSize = (afs_uint32) ntohl(tSize);
4452 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4453 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4455 /* sanity check - peer might have restarted with different params.
4456 * If peer says "send less", dammit, send less... Peer should never
4457 * be unable to accept packets of the size that prior AFS versions would
4458 * send without asking. */
4459 if (peer->maxMTU != tSize) {
4460 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4462 peer->maxMTU = tSize;
4463 peer->MTU = MIN(tSize, peer->MTU);
4464 call->MTU = MIN(call->MTU, tSize);
4467 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4470 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4471 (int)sizeof(afs_int32), &tSize);
4472 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4473 if (tSize < call->twind) { /* smaller than our send */
4474 call->twind = tSize; /* window, we must send less... */
4475 call->ssthresh = MIN(call->twind, call->ssthresh);
4476 call->conn->twind[call->channel] = call->twind;
4479 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4480 * network MTU confused with the loopback MTU. Calculate the
4481 * maximum MTU here for use in the slow start code below.
4483 /* Did peer restart with older RX version? */
4484 if (peer->maxDgramPackets > 1) {
4485 peer->maxDgramPackets = 1;
4487 } else if (np->length >=
4488 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4491 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4492 sizeof(afs_int32), &tSize);
4493 tSize = (afs_uint32) ntohl(tSize);
4495 * As of AFS 3.5 we set the send window to match the receive window.
4497 if (tSize < call->twind) {
4498 call->twind = tSize;
4499 call->conn->twind[call->channel] = call->twind;
4500 call->ssthresh = MIN(call->twind, call->ssthresh);
4501 } else if (tSize > call->twind) {
4502 call->twind = tSize;
4503 call->conn->twind[call->channel] = call->twind;
4507 * As of AFS 3.5, a jumbogram is more than one fixed size
4508 * packet transmitted in a single UDP datagram. If the remote
4509 * MTU is smaller than our local MTU then never send a datagram
4510 * larger than the natural MTU.
4513 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4514 (int)sizeof(afs_int32), &tSize);
4515 maxDgramPackets = (afs_uint32) ntohl(tSize);
4516 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4518 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4519 if (maxDgramPackets > 1) {
4520 peer->maxDgramPackets = maxDgramPackets;
4521 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4523 peer->maxDgramPackets = 1;
4524 call->MTU = peer->natMTU;
4526 } else if (peer->maxDgramPackets > 1) {
4527 /* Restarted with lower version of RX */
4528 peer->maxDgramPackets = 1;
4530 } else if (peer->maxDgramPackets > 1
4531 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4532 /* Restarted with lower version of RX */
4533 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4534 peer->natMTU = OLD_MAX_PACKET_SIZE;
4535 peer->MTU = OLD_MAX_PACKET_SIZE;
4536 peer->maxDgramPackets = 1;
4537 peer->nDgramPackets = 1;
4539 call->MTU = OLD_MAX_PACKET_SIZE;
4544 * Calculate how many datagrams were successfully received after
4545 * the first missing packet and adjust the negative ack counter
4550 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4551 if (call->nNacks < nNacked) {
4552 call->nNacks = nNacked;
4555 call->nAcks += newAckCount;
4559 /* If the packet contained new acknowledgements, rather than just
4560 * being a duplicate of one we have previously seen, then we can restart
4563 if (newAckCount > 0)
4564 rxi_rto_packet_acked(call, istack);
4566 if (call->flags & RX_CALL_FAST_RECOVER) {
4567 if (newAckCount == 0) {
4568 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4570 call->flags &= ~RX_CALL_FAST_RECOVER;
4571 call->cwind = call->nextCwind;
4572 call->nextCwind = 0;
4575 call->nCwindAcks = 0;
4576 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4577 /* Three negative acks in a row trigger congestion recovery */
4578 call->flags |= RX_CALL_FAST_RECOVER;
4579 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4581 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4582 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4583 call->nextCwind = call->ssthresh;
4586 peer->MTU = call->MTU;
4587 peer->cwind = call->nextCwind;
4588 peer->nDgramPackets = call->nDgramPackets;
4590 call->congestSeq = peer->congestSeq;
4592 /* Reset the resend times on the packets that were nacked
4593 * so we will retransmit as soon as the window permits
4597 for (opr_queue_ScanBackwards(&call->tq, cursor)) {
4598 struct rx_packet *tp =
4599 opr_queue_Entry(cursor, struct rx_packet, entry);
4601 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4602 tp->flags &= ~RX_PKTFLAG_SENT;
4604 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4609 /* If cwind is smaller than ssthresh, then increase
4610 * the window one packet for each ack we receive (exponential
4612 * If cwind is greater than or equal to ssthresh then increase
4613 * the congestion window by one packet for each cwind acks we
4614 * receive (linear growth). */
4615 if (call->cwind < call->ssthresh) {
4617 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4618 call->nCwindAcks = 0;
4620 call->nCwindAcks += newAckCount;
4621 if (call->nCwindAcks >= call->cwind) {
4622 call->nCwindAcks = 0;
4623 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4627 * If we have received several acknowledgements in a row then
4628 * it is time to increase the size of our datagrams
4630 if ((int)call->nAcks > rx_nDgramThreshold) {
4631 if (peer->maxDgramPackets > 1) {
4632 if (call->nDgramPackets < peer->maxDgramPackets) {
4633 call->nDgramPackets++;
4635 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4636 } else if (call->MTU < peer->maxMTU) {
4637 /* don't upgrade if we can't handle it */
4638 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4639 call->MTU = peer->ifMTU;
4641 call->MTU += peer->natMTU;
4642 call->MTU = MIN(call->MTU, peer->maxMTU);
4649 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4651 /* Servers need to hold the call until all response packets have
4652 * been acknowledged. Soft acks are good enough since clients
4653 * are not allowed to clear their receive queues. */
4654 if (call->state == RX_STATE_HOLD
4655 && call->tfirst + call->nSoftAcked >= call->tnext) {
4656 call->state = RX_STATE_DALLY;
4657 rxi_ClearTransmitQueue(call, 0);
4658 rxi_CancelKeepAliveEvent(call);
4659 } else if (!opr_queue_IsEmpty(&call->tq)) {
4660 rxi_Start(call, istack);
4666 * Schedule a connection abort to be sent after some delay.
4668 * @param[in] conn The connection to send the abort on.
4669 * @param[in] msec The number of milliseconds to wait before sending.
4671 * @pre conn_data_lock must be held
4674 rxi_SendConnectionAbortLater(struct rx_connection *conn, int msec)
4676 struct clock when, now;
4680 if (!conn->delayedAbortEvent) {
4681 clock_GetTime(&now);
4683 clock_Addmsec(&when, msec);
4684 conn->delayedAbortEvent =
4685 rxevent_Post(&when, &now, rxi_SendDelayedConnAbort, conn, NULL, 0);
4689 /* Received a response to a challenge packet */
4690 static struct rx_packet *
4691 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4692 struct rx_packet *np, int istack)
4696 /* Ignore the packet if we're the client */
4697 if (conn->type == RX_CLIENT_CONNECTION)
4700 /* If already authenticated, ignore the packet (it's probably a retry) */
4701 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4704 if (!conn->securityChallengeSent) {
4705 /* We've never sent out a challenge for this connection, so this
4706 * response cannot possibly be correct; ignore it. This can happen
4707 * if we sent a challenge to the client, then we were restarted, and
4708 * then the client sent us a response. If we ignore the response, the
4709 * client will eventually resend a data packet, causing us to send a
4710 * new challenge and the client to send a new response. */
4714 /* Otherwise, have the security object evaluate the response packet */
4715 error = RXS_CheckResponse(conn->securityObject, conn, np);
4717 /* If the response is invalid, reset the connection, sending
4718 * an abort to the peer. Send the abort with a 1 second delay,
4719 * to avoid a peer hammering us by constantly recreating a
4720 * connection with bad credentials. */
4721 rxi_ConnectionError(conn, error);
4722 MUTEX_ENTER(&conn->conn_data_lock);
4723 rxi_SendConnectionAbortLater(conn, 1000);
4724 MUTEX_EXIT(&conn->conn_data_lock);
4727 /* If the response is valid, any calls waiting to attach
4728 * servers can now do so */
4731 for (i = 0; i < RX_MAXCALLS; i++) {
4732 struct rx_call *call = conn->call[i];
4734 MUTEX_ENTER(&call->lock);
4735 if (call->state == RX_STATE_PRECALL)
4736 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4737 /* tnop can be null if newcallp is null */
4738 MUTEX_EXIT(&call->lock);
4742 /* Update the peer reachability information, just in case
4743 * some calls went into attach-wait while we were waiting
4744 * for authentication..
4746 rxi_UpdatePeerReach(conn, NULL);
4751 /* A client has received an authentication challenge: the security
4752 * object is asked to cough up a respectable response packet to send
4753 * back to the server. The server is responsible for retrying the
4754 * challenge if it fails to get a response. */
4756 static struct rx_packet *
4757 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4758 struct rx_packet *np, int istack)
4762 /* Ignore the challenge if we're the server */
4763 if (conn->type == RX_SERVER_CONNECTION)
4766 /* Ignore the challenge if the connection is otherwise idle; someone's
4767 * trying to use us as an oracle. */
4768 if (!rxi_HasActiveCalls(conn))
4771 /* Send the security object the challenge packet. It is expected to fill
4772 * in the response. */
4773 error = RXS_GetResponse(conn->securityObject, conn, np);
4775 /* If the security object is unable to return a valid response, reset the
4776 * connection and send an abort to the peer. Otherwise send the response
4777 * packet to the peer connection. */
4779 rxi_ConnectionError(conn, error);
4780 MUTEX_ENTER(&conn->conn_data_lock);
4781 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4782 MUTEX_EXIT(&conn->conn_data_lock);
4784 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4785 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4791 /* Find an available server process to service the current request in
4792 * the given call structure. If one isn't available, queue up this
4793 * call so it eventually gets one */
4795 rxi_AttachServerProc(struct rx_call *call,
4796 osi_socket socket, int *tnop,
4797 struct rx_call **newcallp)
4799 struct rx_serverQueueEntry *sq;
4800 struct rx_service *service = call->conn->service;
4803 /* May already be attached */
4804 if (call->state == RX_STATE_ACTIVE)
4807 MUTEX_ENTER(&rx_serverPool_lock);
4809 haveQuota = QuotaOK(service);
4810 if ((!haveQuota) || opr_queue_IsEmpty(&rx_idleServerQueue)) {
4811 /* If there are no processes available to service this call,
4812 * put the call on the incoming call queue (unless it's
4813 * already on the queue).
4815 #ifdef RX_ENABLE_LOCKS
4817 ReturnToServerPool(service);
4818 #endif /* RX_ENABLE_LOCKS */
4820 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4821 call->flags |= RX_CALL_WAIT_PROC;
4822 rx_atomic_inc(&rx_nWaiting);
4823 rx_atomic_inc(&rx_nWaited);
4824 rxi_calltrace(RX_CALL_ARRIVAL, call);
4825 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4826 opr_queue_Append(&rx_incomingCallQueue, &call->entry);
4829 sq = opr_queue_Last(&rx_idleServerQueue,
4830 struct rx_serverQueueEntry, entry);
4832 /* If hot threads are enabled, and both newcallp and sq->socketp
4833 * are non-null, then this thread will process the call, and the
4834 * idle server thread will start listening on this threads socket.
4836 opr_queue_Remove(&sq->entry);
4838 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4841 *sq->socketp = socket;
4842 clock_GetTime(&call->startTime);
4843 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4847 if (call->flags & RX_CALL_WAIT_PROC) {
4848 /* Conservative: I don't think this should happen */
4849 call->flags &= ~RX_CALL_WAIT_PROC;
4850 rx_atomic_dec(&rx_nWaiting);
4851 if (opr_queue_IsOnQueue(&call->entry)) {
4852 opr_queue_Remove(&call->entry);
4855 call->state = RX_STATE_ACTIVE;
4856 call->app.mode = RX_MODE_RECEIVING;
4857 #ifdef RX_KERNEL_TRACE
4859 int glockOwner = ISAFS_GLOCK();
4862 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4863 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4869 if (call->flags & RX_CALL_CLEARED) {
4870 /* send an ack now to start the packet flow up again */
4871 call->flags &= ~RX_CALL_CLEARED;
4872 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4874 #ifdef RX_ENABLE_LOCKS
4877 service->nRequestsRunning++;
4878 MUTEX_ENTER(&rx_quota_mutex);
4879 if (service->nRequestsRunning <= service->minProcs)
4882 MUTEX_EXIT(&rx_quota_mutex);
4886 MUTEX_EXIT(&rx_serverPool_lock);
4889 /* Delay the sending of an acknowledge event for a short while, while
4890 * a new call is being prepared (in the case of a client) or a reply
4891 * is being prepared (in the case of a server). Rather than sending
4892 * an ack packet, an ACKALL packet is sent. */
4894 rxi_AckAll(struct rx_call *call)
4896 rxi_SendSpecial(call, call->conn, NULL, RX_PACKET_TYPE_ACKALL,
4898 call->flags |= RX_CALL_ACKALL_SENT;
4902 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused1,
4905 struct rx_call *call = arg1;
4906 #ifdef RX_ENABLE_LOCKS
4908 MUTEX_ENTER(&call->lock);
4909 if (event == call->delayedAckEvent)
4910 rxevent_Put(&call->delayedAckEvent);
4911 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4913 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4915 MUTEX_EXIT(&call->lock);
4916 #else /* RX_ENABLE_LOCKS */
4918 rxevent_Put(&call->delayedAckEvent);
4919 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4920 #endif /* RX_ENABLE_LOCKS */
4923 #ifdef RX_ENABLE_LOCKS
4924 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4925 * clearing them out.
4928 rxi_SetAcksInTransmitQueue(struct rx_call *call)
4930 struct opr_queue *cursor;
4933 for (opr_queue_Scan(&call->tq, cursor)) {
4935 = opr_queue_Entry(cursor, struct rx_packet, entry);
4937 p->flags |= RX_PKTFLAG_ACKED;
4942 call->flags |= RX_CALL_TQ_CLEARME;
4943 call->flags |= RX_CALL_TQ_SOME_ACKED;
4946 rxi_rto_cancel(call);
4948 call->tfirst = call->tnext;
4949 call->nSoftAcked = 0;
4951 if (call->flags & RX_CALL_FAST_RECOVER) {
4952 call->flags &= ~RX_CALL_FAST_RECOVER;
4953 call->cwind = call->nextCwind;
4954 call->nextCwind = 0;
4957 CV_SIGNAL(&call->cv_twind);
4959 #endif /* RX_ENABLE_LOCKS */
4962 * Acknowledge the whole transmit queue.
4964 * If we're running without locks, or the transmit queue isn't busy, then
4965 * we can just clear the queue now. Otherwise, we have to mark all of the
4966 * packets as acknowledged, and let rxi_Start clear it later on
4969 rxi_AckAllInTransmitQueue(struct rx_call *call)
4971 #ifdef RX_ENABLE_LOCKS
4972 if (call->flags & RX_CALL_TQ_BUSY) {
4973 rxi_SetAcksInTransmitQueue(call);
4977 rxi_ClearTransmitQueue(call, 0);
4979 /* Clear out the transmit queue for the current call (all packets have
4980 * been received by peer) */
4982 rxi_ClearTransmitQueue(struct rx_call *call, int force)
4984 #ifdef RX_ENABLE_LOCKS
4985 struct opr_queue *cursor;
4986 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4988 for (opr_queue_Scan(&call->tq, cursor)) {
4990 = opr_queue_Entry(cursor, struct rx_packet, entry);
4992 p->flags |= RX_PKTFLAG_ACKED;
4996 call->flags |= RX_CALL_TQ_CLEARME;
4997 call->flags |= RX_CALL_TQ_SOME_ACKED;
5000 #endif /* RX_ENABLE_LOCKS */
5001 #ifdef RXDEBUG_PACKET
5003 #endif /* RXDEBUG_PACKET */
5004 rxi_FreePackets(0, &call->tq);
5005 rxi_WakeUpTransmitQueue(call);
5006 #ifdef RX_ENABLE_LOCKS
5007 call->flags &= ~RX_CALL_TQ_CLEARME;
5011 rxi_rto_cancel(call);
5012 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
5013 call->nSoftAcked = 0;
5015 if (call->flags & RX_CALL_FAST_RECOVER) {
5016 call->flags &= ~RX_CALL_FAST_RECOVER;
5017 call->cwind = call->nextCwind;
5019 #ifdef RX_ENABLE_LOCKS
5020 CV_SIGNAL(&call->cv_twind);
5022 osi_rxWakeup(&call->twind);
5027 rxi_ClearReceiveQueue(struct rx_call *call)
5029 if (!opr_queue_IsEmpty(&call->rq)) {
5032 count = rxi_FreePackets(0, &call->rq);
5033 rx_packetReclaims += count;
5034 #ifdef RXDEBUG_PACKET
5036 if ( call->rqc != 0 )
5037 dpf(("rxi_ClearReceiveQueue call %"AFS_PTR_FMT" rqc %u != 0\n", call, call->rqc));
5039 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
5041 if (call->state == RX_STATE_PRECALL) {
5042 call->flags |= RX_CALL_CLEARED;
5046 /* Send an abort packet for the specified call */
5047 static struct rx_packet *
5048 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
5049 int istack, int force)
5052 struct clock when, now;
5057 /* Clients should never delay abort messages */
5058 if (rx_IsClientConn(call->conn))
5061 if (call->abortCode != call->error) {
5062 call->abortCode = call->error;
5063 call->abortCount = 0;
5066 if (force || rxi_callAbortThreshhold == 0
5067 || call->abortCount < rxi_callAbortThreshhold) {
5068 rxi_CancelDelayedAbortEvent(call);
5069 error = htonl(call->error);
5072 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5073 (char *)&error, sizeof(error), istack);
5074 } else if (!call->delayedAbortEvent) {
5075 clock_GetTime(&now);
5077 clock_Addmsec(&when, rxi_callAbortDelay);
5078 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
5079 call->delayedAbortEvent =
5080 rxevent_Post(&when, &now, rxi_SendDelayedCallAbort, call, 0, 0);
5086 rxi_CancelDelayedAbortEvent(struct rx_call *call)
5088 if (call->delayedAbortEvent) {
5089 rxevent_Cancel(&call->delayedAbortEvent);
5090 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
5094 /* Send an abort packet for the specified connection. Packet is an
5095 * optional pointer to a packet that can be used to send the abort.
5096 * Once the number of abort messages reaches the threshhold, an
5097 * event is scheduled to send the abort. Setting the force flag
5098 * overrides sending delayed abort messages.
5100 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
5101 * to send the abort packet.
5104 rxi_SendConnectionAbort(struct rx_connection *conn,
5105 struct rx_packet *packet, int istack, int force)
5112 /* Clients should never delay abort messages */
5113 if (rx_IsClientConn(conn))
5116 if (force || rxi_connAbortThreshhold == 0
5117 || conn->abortCount < rxi_connAbortThreshhold) {
5119 rxevent_Cancel(&conn->delayedAbortEvent);
5120 error = htonl(conn->error);
5122 MUTEX_EXIT(&conn->conn_data_lock);
5124 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5125 RX_PACKET_TYPE_ABORT, (char *)&error,
5126 sizeof(error), istack);
5127 MUTEX_ENTER(&conn->conn_data_lock);
5129 rxi_SendConnectionAbortLater(conn, rxi_connAbortDelay);
5134 /* Associate an error all of the calls owned by a connection. Called
5135 * with error non-zero. This is only for really fatal things, like
5136 * bad authentication responses. The connection itself is set in
5137 * error at this point, so that future packets received will be
5140 rxi_ConnectionError(struct rx_connection *conn,
5146 dpf(("rxi_ConnectionError conn %"AFS_PTR_FMT" error %d\n", conn, error));
5148 MUTEX_ENTER(&conn->conn_data_lock);
5149 rxevent_Cancel(&conn->challengeEvent);
5150 rxevent_Cancel(&conn->natKeepAliveEvent);
5151 if (conn->checkReachEvent) {
5152 rxevent_Cancel(&conn->checkReachEvent);
5153 conn->flags &= ~(RX_CONN_ATTACHWAIT|RX_CONN_NAT_PING);
5154 putConnection(conn);
5156 MUTEX_EXIT(&conn->conn_data_lock);
5157 for (i = 0; i < RX_MAXCALLS; i++) {
5158 struct rx_call *call = conn->call[i];
5160 MUTEX_ENTER(&call->lock);
5161 rxi_CallError(call, error);
5162 MUTEX_EXIT(&call->lock);
5165 conn->error = error;
5166 if (rx_stats_active)
5167 rx_atomic_inc(&rx_stats.fatalErrors);
5172 * Interrupt an in-progress call with the specified error and wakeup waiters.
5174 * @param[in] call The call to interrupt
5175 * @param[in] error The error code to send to the peer
5178 rx_InterruptCall(struct rx_call *call, afs_int32 error)
5180 MUTEX_ENTER(&call->lock);
5181 rxi_CallError(call, error);
5182 rxi_SendCallAbort(call, NULL, 0, 1);
5183 MUTEX_EXIT(&call->lock);
5187 rxi_CallError(struct rx_call *call, afs_int32 error)
5189 MUTEX_ASSERT(&call->lock);
5190 dpf(("rxi_CallError call %"AFS_PTR_FMT" error %d call->error %d\n", call, error, call->error));
5192 error = call->error;
5194 #ifdef RX_ENABLE_LOCKS
5195 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
5196 rxi_ResetCall(call, 0);
5199 rxi_ResetCall(call, 0);
5201 call->error = error;
5204 /* Reset various fields in a call structure, and wakeup waiting
5205 * processes. Some fields aren't changed: state & mode are not
5206 * touched (these must be set by the caller), and bufptr, nLeft, and
5207 * nFree are not reset, since these fields are manipulated by
5208 * unprotected macros, and may only be reset by non-interrupting code.
5212 rxi_ResetCall(struct rx_call *call, int newcall)
5215 struct rx_peer *peer;
5216 struct rx_packet *packet;
5218 MUTEX_ASSERT(&call->lock);
5219 dpf(("rxi_ResetCall(call %"AFS_PTR_FMT", newcall %d)\n", call, newcall));
5221 /* Notify anyone who is waiting for asynchronous packet arrival */
5222 if (call->arrivalProc) {
5223 (*call->arrivalProc) (call, call->arrivalProcHandle,
5224 call->arrivalProcArg);
5225 call->arrivalProc = (void (*)())0;
5229 rxi_CancelGrowMTUEvent(call);
5231 if (call->delayedAbortEvent) {
5232 rxi_CancelDelayedAbortEvent(call);
5233 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5235 rxi_SendCallAbort(call, packet, 0, 1);
5236 rxi_FreePacket(packet);
5241 * Update the peer with the congestion information in this call
5242 * so other calls on this connection can pick up where this call
5243 * left off. If the congestion sequence numbers don't match then
5244 * another call experienced a retransmission.
5246 peer = call->conn->peer;
5247 MUTEX_ENTER(&peer->peer_lock);
5249 if (call->congestSeq == peer->congestSeq) {
5250 peer->cwind = MAX(peer->cwind, call->cwind);
5251 peer->MTU = MAX(peer->MTU, call->MTU);
5252 peer->nDgramPackets =
5253 MAX(peer->nDgramPackets, call->nDgramPackets);
5256 call->abortCode = 0;
5257 call->abortCount = 0;
5259 if (peer->maxDgramPackets > 1) {
5260 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
5262 call->MTU = peer->MTU;
5264 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
5265 call->ssthresh = rx_maxSendWindow;
5266 call->nDgramPackets = peer->nDgramPackets;
5267 call->congestSeq = peer->congestSeq;
5268 call->rtt = peer->rtt;
5269 call->rtt_dev = peer->rtt_dev;
5270 clock_Zero(&call->rto);
5271 clock_Addmsec(&call->rto,
5272 MAX(((call->rtt >> 3) + call->rtt_dev), rx_minPeerTimeout) + 200);
5273 MUTEX_EXIT(&peer->peer_lock);
5275 flags = call->flags;
5276 rxi_WaitforTQBusy(call);
5278 rxi_ClearTransmitQueue(call, 1);
5279 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
5280 dpf(("rcall %"AFS_PTR_FMT" has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5284 rxi_ClearReceiveQueue(call);
5285 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
5289 call->twind = call->conn->twind[call->channel];
5290 call->rwind = call->conn->rwind[call->channel];
5291 call->nSoftAcked = 0;
5292 call->nextCwind = 0;
5295 call->nCwindAcks = 0;
5296 call->nSoftAcks = 0;
5297 call->nHardAcks = 0;
5299 call->tfirst = call->rnext = call->tnext = 1;
5302 call->lastAcked = 0;
5303 call->localStatus = call->remoteStatus = 0;
5305 if (flags & RX_CALL_READER_WAIT) {
5306 #ifdef RX_ENABLE_LOCKS
5307 CV_BROADCAST(&call->cv_rq);
5309 osi_rxWakeup(&call->rq);
5312 if (flags & RX_CALL_WAIT_PACKETS) {
5313 MUTEX_ENTER(&rx_freePktQ_lock);
5314 rxi_PacketsUnWait(); /* XXX */
5315 MUTEX_EXIT(&rx_freePktQ_lock);
5317 #ifdef RX_ENABLE_LOCKS
5318 CV_SIGNAL(&call->cv_twind);
5320 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5321 osi_rxWakeup(&call->twind);
5324 if (flags & RX_CALL_WAIT_PROC) {
5325 rx_atomic_dec(&rx_nWaiting);
5327 #ifdef RX_ENABLE_LOCKS
5328 /* The following ensures that we don't mess with any queue while some
5329 * other thread might also be doing so. The call_queue_lock field is
5330 * is only modified under the call lock. If the call is in the process
5331 * of being removed from a queue, the call is not locked until the
5332 * the queue lock is dropped and only then is the call_queue_lock field
5333 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5334 * Note that any other routine which removes a call from a queue has to
5335 * obtain the queue lock before examing the queue and removing the call.
5337 if (call->call_queue_lock) {
5338 MUTEX_ENTER(call->call_queue_lock);
5339 if (opr_queue_IsOnQueue(&call->entry)) {
5340 opr_queue_Remove(&call->entry);
5342 MUTEX_EXIT(call->call_queue_lock);
5343 CLEAR_CALL_QUEUE_LOCK(call);
5345 #else /* RX_ENABLE_LOCKS */
5346 if (opr_queue_IsOnQueue(&call->entry)) {
5347 opr_queue_Remove(&call->entry);
5349 #endif /* RX_ENABLE_LOCKS */
5351 rxi_CancelKeepAliveEvent(call);
5352 rxi_CancelDelayedAckEvent(call);
5355 /* Send an acknowledge for the indicated packet (seq,serial) of the
5356 * indicated call, for the indicated reason (reason). This
5357 * acknowledge will specifically acknowledge receiving the packet, and
5358 * will also specify which other packets for this call have been
5359 * received. This routine returns the packet that was used to the
5360 * caller. The caller is responsible for freeing it or re-using it.
5361 * This acknowledgement also returns the highest sequence number
5362 * actually read out by the higher level to the sender; the sender
5363 * promises to keep around packets that have not been read by the
5364 * higher level yet (unless, of course, the sender decides to abort
5365 * the call altogether). Any of p, seq, serial, pflags, or reason may
5366 * be set to zero without ill effect. That is, if they are zero, they
5367 * will not convey any information.
5368 * NOW there is a trailer field, after the ack where it will safely be
5369 * ignored by mundanes, which indicates the maximum size packet this
5370 * host can swallow. */
5372 struct rx_packet *optionalPacket; use to send ack (or null)
5373 int seq; Sequence number of the packet we are acking
5374 int serial; Serial number of the packet
5375 int pflags; Flags field from packet header
5376 int reason; Reason an acknowledge was prompted
5380 rxi_SendAck(struct rx_call *call,
5381 struct rx_packet *optionalPacket, int serial, int reason,
5384 struct rx_ackPacket *ap;
5385 struct rx_packet *p;
5386 struct opr_queue *cursor;
5389 afs_uint32 padbytes = 0;
5390 #ifdef RX_ENABLE_TSFPQ
5391 struct rx_ts_info_t * rx_ts_info;
5395 * Open the receive window once a thread starts reading packets
5397 if (call->rnext > 1) {
5398 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5401 /* Don't attempt to grow MTU if this is a critical ping */
5402 if (reason == RX_ACK_MTU) {
5403 /* keep track of per-call attempts, if we're over max, do in small
5404 * otherwise in larger? set a size to increment by, decrease
5407 if (call->conn->peer->maxPacketSize &&
5408 (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5410 padbytes = call->conn->peer->maxPacketSize+16;
5412 padbytes = call->conn->peer->maxMTU + 128;
5414 /* do always try a minimum size ping */
5415 padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5417 /* subtract the ack payload */
5418 padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5419 reason = RX_ACK_PING;
5422 call->nHardAcks = 0;
5423 call->nSoftAcks = 0;
5424 if (call->rnext > call->lastAcked)
5425 call->lastAcked = call->rnext;
5429 rx_computelen(p, p->length); /* reset length, you never know */
5430 } /* where that's been... */
5431 #ifdef RX_ENABLE_TSFPQ
5433 RX_TS_INFO_GET(rx_ts_info);
5434 if ((p = rx_ts_info->local_special_packet)) {
5435 rx_computelen(p, p->length);
5436 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5437 rx_ts_info->local_special_packet = p;
5438 } else { /* We won't send the ack, but don't panic. */
5439 return optionalPacket;
5443 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5444 /* We won't send the ack, but don't panic. */
5445 return optionalPacket;
5450 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5453 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5454 #ifndef RX_ENABLE_TSFPQ
5455 if (!optionalPacket)
5458 return optionalPacket;
5460 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5461 if (rx_Contiguous(p) < templ) {
5462 #ifndef RX_ENABLE_TSFPQ
5463 if (!optionalPacket)
5466 return optionalPacket;
5471 /* MTUXXX failing to send an ack is very serious. We should */
5472 /* try as hard as possible to send even a partial ack; it's */
5473 /* better than nothing. */
5474 ap = (struct rx_ackPacket *)rx_DataOf(p);
5475 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5476 ap->reason = reason;
5478 /* The skew computation used to be bogus, I think it's better now. */
5479 /* We should start paying attention to skew. XXX */
5480 ap->serial = htonl(serial);
5481 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
5484 * First packet not yet forwarded to reader. When ACKALL has been
5485 * sent the peer has been told that all received packets will be
5486 * delivered to the reader. The value 'rnext' is used internally
5487 * to refer to the next packet in the receive queue that must be
5488 * delivered to the reader. From the perspective of the peer it
5489 * already has so report the last sequence number plus one if there
5490 * are packets in the receive queue awaiting processing.
5492 if ((call->flags & RX_CALL_ACKALL_SENT) &&
5493 !opr_queue_IsEmpty(&call->rq)) {
5494 ap->firstPacket = htonl(opr_queue_Last(&call->rq, struct rx_packet, entry)->header.seq + 1);
5496 ap->firstPacket = htonl(call->rnext);
5498 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
5500 /* No fear of running out of ack packet here because there can only
5501 * be at most one window full of unacknowledged packets. The window
5502 * size must be constrained to be less than the maximum ack size,
5503 * of course. Also, an ack should always fit into a single packet
5504 * -- it should not ever be fragmented. */
5506 for (opr_queue_Scan(&call->rq, cursor)) {
5507 struct rx_packet *rqp
5508 = opr_queue_Entry(cursor, struct rx_packet, entry);
5510 if (!rqp || !call->rq.next
5511 || (rqp->header.seq > (call->rnext + call->rwind))) {
5512 #ifndef RX_ENABLE_TSFPQ
5513 if (!optionalPacket)
5516 rxi_CallError(call, RX_CALL_DEAD);
5517 return optionalPacket;
5520 while (rqp->header.seq > call->rnext + offset)
5521 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5522 ap->acks[offset++] = RX_ACK_TYPE_ACK;
5524 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5525 #ifndef RX_ENABLE_TSFPQ
5526 if (!optionalPacket)
5529 rxi_CallError(call, RX_CALL_DEAD);
5530 return optionalPacket;
5536 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5538 /* these are new for AFS 3.3 */
5539 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5540 templ = htonl(templ);
5541 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5542 templ = htonl(call->conn->peer->ifMTU);
5543 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5544 sizeof(afs_int32), &templ);
5546 /* new for AFS 3.4 */
5547 templ = htonl(call->rwind);
5548 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5549 sizeof(afs_int32), &templ);
5551 /* new for AFS 3.5 */
5552 templ = htonl(call->conn->peer->ifDgramPackets);
5553 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5554 sizeof(afs_int32), &templ);
5556 p->header.serviceId = call->conn->serviceId;
5557 p->header.cid = (call->conn->cid | call->channel);
5558 p->header.callNumber = *call->callNumber;
5560 p->header.securityIndex = call->conn->securityIndex;
5561 p->header.epoch = call->conn->epoch;
5562 p->header.type = RX_PACKET_TYPE_ACK;
5563 p->header.flags = RX_SLOW_START_OK;
5564 if (reason == RX_ACK_PING) {
5565 p->header.flags |= RX_REQUEST_ACK;
5567 p->length = padbytes +
5568 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32);
5571 /* not fast but we can potentially use this if truncated
5572 * fragments are delivered to figure out the mtu.
5574 rx_packetwrite(p, rx_AckDataSize(offset) + 4 *
5575 sizeof(afs_int32), sizeof(afs_int32),
5579 if (call->conn->type == RX_CLIENT_CONNECTION)
5580 p->header.flags |= RX_CLIENT_INITIATED;
5584 if (rxdebug_active) {
5588 len = _snprintf(msg, sizeof(msg),
5589 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5590 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5591 ntohl(ap->serial), ntohl(ap->previousPacket),
5592 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5593 ap->nAcks, ntohs(ap->bufferSpace) );
5597 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5598 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5602 OutputDebugString(msg);
5604 #else /* AFS_NT40_ENV */
5606 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5607 ap->reason, ntohl(ap->previousPacket),
5608 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5610 for (offset = 0; offset < ap->nAcks; offset++)
5611 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5616 #endif /* AFS_NT40_ENV */
5619 int i, nbytes = p->length;
5621 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5622 if (nbytes <= p->wirevec[i].iov_len) {
5625 savelen = p->wirevec[i].iov_len;
5627 p->wirevec[i].iov_len = nbytes;
5629 rxi_Send(call, p, istack);
5630 p->wirevec[i].iov_len = savelen;
5634 nbytes -= p->wirevec[i].iov_len;
5637 if (rx_stats_active)
5638 rx_atomic_inc(&rx_stats.ackPacketsSent);
5639 #ifndef RX_ENABLE_TSFPQ
5640 if (!optionalPacket)
5643 return optionalPacket; /* Return packet for re-use by caller */
5647 struct rx_packet **list;
5652 /* Send all of the packets in the list in single datagram */
5654 rxi_SendList(struct rx_call *call, struct xmitlist *xmit,
5655 int istack, int moreFlag)
5661 struct rx_connection *conn = call->conn;
5662 struct rx_peer *peer = conn->peer;
5664 MUTEX_ENTER(&peer->peer_lock);
5665 peer->nSent += xmit->len;
5666 if (xmit->resending)
5667 peer->reSends += xmit->len;
5668 MUTEX_EXIT(&peer->peer_lock);
5670 if (rx_stats_active) {
5671 if (xmit->resending)
5672 rx_atomic_add(&rx_stats.dataPacketsReSent, xmit->len);
5674 rx_atomic_add(&rx_stats.dataPacketsSent, xmit->len);
5677 clock_GetTime(&now);
5679 if (xmit->list[xmit->len - 1]->header.flags & RX_LAST_PACKET) {
5683 /* Set the packet flags and schedule the resend events */
5684 /* Only request an ack for the last packet in the list */
5685 for (i = 0; i < xmit->len; i++) {
5686 struct rx_packet *packet = xmit->list[i];
5688 /* Record the time sent */
5689 packet->timeSent = now;
5690 packet->flags |= RX_PKTFLAG_SENT;
5692 /* Ask for an ack on retransmitted packets, on every other packet
5693 * if the peer doesn't support slow start. Ask for an ack on every
5694 * packet until the congestion window reaches the ack rate. */
5695 if (packet->header.serial) {
5698 packet->firstSent = now;
5699 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5700 || (!(call->flags & RX_CALL_SLOW_START_OK)
5701 && (packet->header.seq & 1)))) {
5706 /* Tag this packet as not being the last in this group,
5707 * for the receiver's benefit */
5708 if (i < xmit->len - 1 || moreFlag) {
5709 packet->header.flags |= RX_MORE_PACKETS;
5714 xmit->list[xmit->len - 1]->header.flags |= RX_REQUEST_ACK;
5717 /* Since we're about to send a data packet to the peer, it's
5718 * safe to nuke any scheduled end-of-packets ack */
5719 rxi_CancelDelayedAckEvent(call);
5721 MUTEX_EXIT(&call->lock);
5722 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5723 if (xmit->len > 1) {
5724 rxi_SendPacketList(call, conn, xmit->list, xmit->len, istack);
5726 rxi_SendPacket(call, conn, xmit->list[0], istack);
5728 MUTEX_ENTER(&call->lock);
5729 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5731 /* Tell the RTO calculation engine that we have sent a packet, and
5732 * if it was the last one */
5733 rxi_rto_packet_sent(call, lastPacket, istack);
5735 /* Update last send time for this call (for keep-alive
5736 * processing), and for the connection (so that we can discover
5737 * idle connections) */
5738 conn->lastSendTime = call->lastSendTime = clock_Sec();
5741 /* When sending packets we need to follow these rules:
5742 * 1. Never send more than maxDgramPackets in a jumbogram.
5743 * 2. Never send a packet with more than two iovecs in a jumbogram.
5744 * 3. Never send a retransmitted packet in a jumbogram.
5745 * 4. Never send more than cwind/4 packets in a jumbogram
5746 * We always keep the last list we should have sent so we
5747 * can set the RX_MORE_PACKETS flags correctly.
5751 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5756 struct xmitlist working;
5757 struct xmitlist last;
5759 struct rx_peer *peer = call->conn->peer;
5760 int morePackets = 0;
5762 memset(&last, 0, sizeof(struct xmitlist));
5763 working.list = &list[0];
5765 working.resending = 0;
5767 recovery = call->flags & RX_CALL_FAST_RECOVER;
5769 for (i = 0; i < len; i++) {
5770 /* Does the current packet force us to flush the current list? */
5772 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5773 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5775 /* This sends the 'last' list and then rolls the current working
5776 * set into the 'last' one, and resets the working set */
5779 rxi_SendList(call, &last, istack, 1);
5780 /* If the call enters an error state stop sending, or if
5781 * we entered congestion recovery mode, stop sending */
5783 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5788 working.resending = 0;
5789 working.list = &list[i];
5791 /* Add the current packet to the list if it hasn't been acked.
5792 * Otherwise adjust the list pointer to skip the current packet. */
5793 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5796 if (list[i]->header.serial)
5797 working.resending = 1;
5799 /* Do we need to flush the list? */
5800 if (working.len >= (int)peer->maxDgramPackets
5801 || working.len >= (int)call->nDgramPackets
5802 || working.len >= (int)call->cwind
5803 || list[i]->header.serial
5804 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5806 rxi_SendList(call, &last, istack, 1);
5807 /* If the call enters an error state stop sending, or if
5808 * we entered congestion recovery mode, stop sending */
5810 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5815 working.resending = 0;
5816 working.list = &list[i + 1];
5819 if (working.len != 0) {
5820 osi_Panic("rxi_SendList error");
5822 working.list = &list[i + 1];
5826 /* Send the whole list when the call is in receive mode, when
5827 * the call is in eof mode, when we are in fast recovery mode,
5828 * and when we have the last packet */
5829 /* XXX - The accesses to app.mode aren't safe, as this may be called by
5830 * the listener or event threads
5832 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5833 || (call->flags & RX_CALL_FLUSH)
5834 || (call->flags & RX_CALL_FAST_RECOVER)) {
5835 /* Check for the case where the current list contains
5836 * an acked packet. Since we always send retransmissions
5837 * in a separate packet, we only need to check the first
5838 * packet in the list */
5839 if (working.len > 0 && !(working.list[0]->flags & RX_PKTFLAG_ACKED)) {
5843 rxi_SendList(call, &last, istack, morePackets);
5844 /* If the call enters an error state stop sending, or if
5845 * we entered congestion recovery mode, stop sending */
5847 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5851 rxi_SendList(call, &working, istack, 0);
5853 } else if (last.len > 0) {
5854 rxi_SendList(call, &last, istack, 0);
5855 /* Packets which are in 'working' are not sent by this call */
5860 * Check if the peer for the given call is known to be dead
5862 * If the call's peer appears dead (it has encountered fatal network errors
5863 * since the call started) the call is killed with RX_CALL_DEAD if the call
5864 * is active. Otherwise, we do nothing.
5866 * @param[in] call The call to check
5869 * @retval 0 The call is fine, and we haven't done anything to the call
5870 * @retval nonzero The call's peer appears dead, and the call has been
5871 * terminated if it was active
5873 * @pre call->lock must be locked
5876 rxi_CheckPeerDead(struct rx_call *call)
5878 #ifdef AFS_RXERRQ_ENV
5881 if (call->state == RX_STATE_DALLY) {
5885 peererrs = rx_atomic_read(&call->conn->peer->neterrs);
5886 if (call->neterr_gen < peererrs) {
5887 /* we have received network errors since this call started; kill
5889 if (call->state == RX_STATE_ACTIVE) {
5890 rxi_CallError(call, RX_CALL_DEAD);
5894 if (call->neterr_gen > peererrs) {
5895 /* someone has reset the number of peer errors; set the call error gen
5896 * so we can detect if more errors are encountered */
5897 call->neterr_gen = peererrs;
5904 rxi_Resend(struct rxevent *event, void *arg0, void *arg1, int istack)
5906 struct rx_call *call = arg0;
5907 struct rx_peer *peer;
5908 struct opr_queue *cursor;
5909 struct clock maxTimeout = { 60, 0 };
5911 MUTEX_ENTER(&call->lock);
5913 peer = call->conn->peer;
5915 /* Make sure that the event pointer is removed from the call
5916 * structure, since there is no longer a per-call retransmission
5918 if (event == call->resendEvent) {
5919 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5920 rxevent_Put(&call->resendEvent);
5923 rxi_CheckPeerDead(call);
5925 if (opr_queue_IsEmpty(&call->tq)) {
5926 /* Nothing to do. This means that we've been raced, and that an
5927 * ACK has come in between when we were triggered, and when we
5928 * actually got to run. */
5932 /* We're in loss recovery */
5933 call->flags |= RX_CALL_FAST_RECOVER;
5935 /* Mark all of the pending packets in the queue as being lost */
5936 for (opr_queue_Scan(&call->tq, cursor)) {
5937 struct rx_packet *p = opr_queue_Entry(cursor, struct rx_packet, entry);
5938 if (!(p->flags & RX_PKTFLAG_ACKED))
5939 p->flags &= ~RX_PKTFLAG_SENT;
5942 /* We're resending, so we double the timeout of the call. This will be
5943 * dropped back down by the first successful ACK that we receive.
5945 * We apply a maximum value here of 60 seconds
5947 clock_Add(&call->rto, &call->rto);
5948 if (clock_Gt(&call->rto, &maxTimeout))
5949 call->rto = maxTimeout;
5951 /* Packet loss is most likely due to congestion, so drop our window size
5952 * and start again from the beginning */
5953 if (peer->maxDgramPackets >1) {
5954 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
5955 call->MTU = MIN(peer->natMTU, peer->maxMTU);
5957 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
5958 call->nDgramPackets = 1;
5960 call->nextCwind = 1;
5963 MUTEX_ENTER(&peer->peer_lock);
5964 peer->MTU = call->MTU;
5965 peer->cwind = call->cwind;
5966 peer->nDgramPackets = 1;
5968 call->congestSeq = peer->congestSeq;
5969 MUTEX_EXIT(&peer->peer_lock);
5971 rxi_Start(call, istack);
5974 MUTEX_EXIT(&call->lock);
5977 /* This routine is called when new packets are readied for
5978 * transmission and when retransmission may be necessary, or when the
5979 * transmission window or burst count are favourable. This should be
5980 * better optimized for new packets, the usual case, now that we've
5981 * got rid of queues of send packets. XXXXXXXXXXX */
5983 rxi_Start(struct rx_call *call, int istack)
5985 struct opr_queue *cursor;
5986 #ifdef RX_ENABLE_LOCKS
5987 struct opr_queue *store;
5993 #ifdef RX_ENABLE_LOCKS
5994 if (rx_stats_active)
5995 rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
6000 if (!opr_queue_IsEmpty(&call->tq)) { /* If we have anything to send */
6001 /* Send (or resend) any packets that need it, subject to
6002 * window restrictions and congestion burst control
6003 * restrictions. Ask for an ack on the last packet sent in
6004 * this burst. For now, we're relying upon the window being
6005 * considerably bigger than the largest number of packets that
6006 * are typically sent at once by one initial call to
6007 * rxi_Start. This is probably bogus (perhaps we should ask
6008 * for an ack when we're half way through the current
6009 * window?). Also, for non file transfer applications, this
6010 * may end up asking for an ack for every packet. Bogus. XXXX
6013 * But check whether we're here recursively, and let the other guy
6016 #ifdef RX_ENABLE_LOCKS
6017 if (!(call->flags & RX_CALL_TQ_BUSY)) {
6018 call->flags |= RX_CALL_TQ_BUSY;
6020 #endif /* RX_ENABLE_LOCKS */
6022 #ifdef RX_ENABLE_LOCKS
6023 call->flags &= ~RX_CALL_NEED_START;
6024 #endif /* RX_ENABLE_LOCKS */
6026 maxXmitPackets = MIN(call->twind, call->cwind);
6027 for (opr_queue_Scan(&call->tq, cursor)) {
6029 = opr_queue_Entry(cursor, struct rx_packet, entry);
6031 if (p->flags & RX_PKTFLAG_ACKED) {
6032 /* Since we may block, don't trust this */
6033 if (rx_stats_active)
6034 rx_atomic_inc(&rx_stats.ignoreAckedPacket);
6035 continue; /* Ignore this packet if it has been acknowledged */
6038 /* Turn off all flags except these ones, which are the same
6039 * on each transmission */
6040 p->header.flags &= RX_PRESET_FLAGS;
6042 if (p->header.seq >=
6043 call->tfirst + MIN((int)call->twind,
6044 (int)(call->nSoftAcked +
6046 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
6047 /* Note: if we're waiting for more window space, we can
6048 * still send retransmits; hence we don't return here, but
6049 * break out to schedule a retransmit event */
6050 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
6051 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
6056 /* Transmit the packet if it needs to be sent. */
6057 if (!(p->flags & RX_PKTFLAG_SENT)) {
6058 if (nXmitPackets == maxXmitPackets) {
6059 rxi_SendXmitList(call, call->xmitList,
6060 nXmitPackets, istack);
6063 dpf(("call %d xmit packet %"AFS_PTR_FMT"\n",
6064 *(call->callNumber), p));
6065 call->xmitList[nXmitPackets++] = p;
6067 } /* end of the queue_Scan */
6069 /* xmitList now hold pointers to all of the packets that are
6070 * ready to send. Now we loop to send the packets */
6071 if (nXmitPackets > 0) {
6072 rxi_SendXmitList(call, call->xmitList, nXmitPackets,
6076 #ifdef RX_ENABLE_LOCKS
6078 /* We went into the error state while sending packets. Now is
6079 * the time to reset the call. This will also inform the using
6080 * process that the call is in an error state.
6082 if (rx_stats_active)
6083 rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
6084 call->flags &= ~RX_CALL_TQ_BUSY;
6085 rxi_WakeUpTransmitQueue(call);
6086 rxi_CallError(call, call->error);
6090 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
6092 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
6093 /* Some packets have received acks. If they all have, we can clear
6094 * the transmit queue.
6097 for (opr_queue_ScanSafe(&call->tq, cursor, store)) {
6099 = opr_queue_Entry(cursor, struct rx_packet, entry);
6101 if (p->header.seq < call->tfirst
6102 && (p->flags & RX_PKTFLAG_ACKED)) {
6103 opr_queue_Remove(&p->entry);
6104 #ifdef RX_TRACK_PACKETS
6105 p->flags &= ~RX_PKTFLAG_TQ;
6107 #ifdef RXDEBUG_PACKET
6115 call->flags |= RX_CALL_TQ_CLEARME;
6117 if (call->flags & RX_CALL_TQ_CLEARME)
6118 rxi_ClearTransmitQueue(call, 1);
6119 } while (call->flags & RX_CALL_NEED_START);
6121 * TQ references no longer protected by this flag; they must remain
6122 * protected by the call lock.
6124 call->flags &= ~RX_CALL_TQ_BUSY;
6125 rxi_WakeUpTransmitQueue(call);
6127 call->flags |= RX_CALL_NEED_START;
6129 #endif /* RX_ENABLE_LOCKS */
6131 rxi_rto_cancel(call);
6135 /* Also adjusts the keep alive parameters for the call, to reflect
6136 * that we have just sent a packet (so keep alives aren't sent
6139 rxi_Send(struct rx_call *call, struct rx_packet *p,
6142 struct rx_connection *conn = call->conn;
6144 /* Stamp each packet with the user supplied status */
6145 p->header.userStatus = call->localStatus;
6147 /* Allow the security object controlling this call's security to
6148 * make any last-minute changes to the packet */
6149 RXS_SendPacket(conn->securityObject, call, p);
6151 /* Since we're about to send SOME sort of packet to the peer, it's
6152 * safe to nuke any scheduled end-of-packets ack */
6153 rxi_CancelDelayedAckEvent(call);
6155 /* Actually send the packet, filling in more connection-specific fields */
6156 MUTEX_EXIT(&call->lock);
6157 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6158 rxi_SendPacket(call, conn, p, istack);
6159 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6160 MUTEX_ENTER(&call->lock);
6162 /* Update last send time for this call (for keep-alive
6163 * processing), and for the connection (so that we can discover
6164 * idle connections) */
6165 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6166 (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
6167 (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
6169 conn->lastSendTime = call->lastSendTime = clock_Sec();
6173 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
6174 * that things are fine. Also called periodically to guarantee that nothing
6175 * falls through the cracks (e.g. (error + dally) connections have keepalive
6176 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
6178 * haveCTLock Set if calling from rxi_ReapConnections
6181 rxi_CheckCall(struct rx_call *call, int haveCTLock)
6183 struct rx_connection *conn = call->conn;
6185 afs_uint32 deadTime, idleDeadTime = 0, hardDeadTime = 0;
6186 afs_uint32 fudgeFactor;
6189 int idle_timeout = 0;
6190 afs_int32 clock_diff = 0;
6192 if (rxi_CheckPeerDead(call)) {
6198 /* Large swings in the clock can have a significant impact on
6199 * the performance of RX call processing. Forward clock shifts
6200 * will result in premature event triggering or timeouts.
6201 * Backward shifts can result in calls not completing until
6202 * the clock catches up with the original start clock value.
6204 * If a backward clock shift of more than five minutes is noticed,
6205 * just fail the call.
6207 if (now < call->lastSendTime)
6208 clock_diff = call->lastSendTime - now;
6209 if (now < call->startWait)
6210 clock_diff = MAX(clock_diff, call->startWait - now);
6211 if (now < call->lastReceiveTime)
6212 clock_diff = MAX(clock_diff, call->lastReceiveTime - now);
6213 if (clock_diff > 5 * 60)
6215 if (call->state == RX_STATE_ACTIVE)
6216 rxi_CallError(call, RX_CALL_TIMEOUT);
6220 #ifdef RX_ENABLE_LOCKS
6221 if (call->flags & RX_CALL_TQ_BUSY) {
6222 /* Call is active and will be reset by rxi_Start if it's
6223 * in an error state.
6228 /* RTT + 8*MDEV, rounded up to the next second. */
6229 fudgeFactor = (((afs_uint32) call->rtt >> 3) +
6230 ((afs_uint32) call->rtt_dev << 1) + 1023) >> 10;
6232 deadTime = conn->secondsUntilDead + fudgeFactor;
6233 /* These are computed to the second (+- 1 second). But that's
6234 * good enough for these values, which should be a significant
6235 * number of seconds. */
6236 if (now > (call->lastReceiveTime + deadTime)) {
6237 if (call->state == RX_STATE_ACTIVE) {
6238 cerror = RX_CALL_DEAD;
6241 #ifdef RX_ENABLE_LOCKS
6242 /* Cancel pending events */
6243 rxi_CancelDelayedAckEvent(call);
6244 rxi_rto_cancel(call);
6245 rxi_CancelKeepAliveEvent(call);
6246 rxi_CancelGrowMTUEvent(call);
6247 MUTEX_ENTER(&rx_refcnt_mutex);
6248 /* if rxi_FreeCall returns 1 it has freed the call */
6249 if (call->refCount == 0 &&
6250 rxi_FreeCall(call, haveCTLock))
6252 MUTEX_EXIT(&rx_refcnt_mutex);
6255 MUTEX_EXIT(&rx_refcnt_mutex);
6257 #else /* RX_ENABLE_LOCKS */
6258 rxi_FreeCall(call, 0);
6260 #endif /* RX_ENABLE_LOCKS */
6262 /* Non-active calls are destroyed if they are not responding
6263 * to pings; active calls are simply flagged in error, so the
6264 * attached process can die reasonably gracefully. */
6267 if (conn->idleDeadTime) {
6268 idleDeadTime = conn->idleDeadTime + fudgeFactor;
6272 /* see if we have a non-activity timeout */
6273 if (call->startWait && ((call->startWait + idleDeadTime) < now)) {
6274 if (call->state == RX_STATE_ACTIVE) {
6275 cerror = RX_CALL_TIMEOUT;
6281 if (conn->hardDeadTime) {
6282 hardDeadTime = conn->hardDeadTime + fudgeFactor;
6285 /* see if we have a hard timeout */
6287 && (now > (hardDeadTime + call->startTime.sec))) {
6288 if (call->state == RX_STATE_ACTIVE)
6289 rxi_CallError(call, RX_CALL_TIMEOUT);
6294 if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT && !idle_timeout &&
6295 call->lastReceiveTime) {
6296 int oldMTU = conn->peer->ifMTU;
6298 /* If we thought we could send more, perhaps things got worse.
6299 * Shrink by 128 bytes and try again. */
6300 if (conn->peer->maxPacketSize < conn->lastPacketSize)
6301 /* maxPacketSize will be cleared in rxi_SetPeerMtu */
6302 newmtu = MAX(conn->peer->maxPacketSize + RX_HEADER_SIZE,
6303 conn->lastPacketSize - 128 + RX_HEADER_SIZE);
6305 newmtu = conn->lastPacketSize - 128 + RX_HEADER_SIZE;
6307 /* minimum capped in SetPeerMtu */
6308 rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6311 conn->lastPacketSize = 0;
6313 /* needed so ResetCall doesn't clobber us. */
6314 call->MTU = conn->peer->ifMTU;
6316 /* if we never succeeded, let the error pass out as-is */
6317 if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6318 cerror = conn->msgsizeRetryErr;
6321 rxi_CallError(call, cerror);
6326 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1,
6327 void *dummy, int dummy2)
6329 struct rx_connection *conn = arg1;
6330 struct rx_header theader;
6331 char tbuffer[1 + sizeof(struct rx_header)];
6332 struct sockaddr_in taddr;
6335 struct iovec tmpiov[2];
6338 RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6341 tp = &tbuffer[sizeof(struct rx_header)];
6342 taddr.sin_family = AF_INET;
6343 taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6344 taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6345 memset(&taddr.sin_zero, 0, sizeof(taddr.sin_zero));
6346 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6347 taddr.sin_len = sizeof(struct sockaddr_in);
6349 memset(&theader, 0, sizeof(theader));
6350 theader.epoch = htonl(999);
6352 theader.callNumber = 0;
6355 theader.type = RX_PACKET_TYPE_VERSION;
6356 theader.flags = RX_LAST_PACKET;
6357 theader.serviceId = 0;
6359 memcpy(tbuffer, &theader, sizeof(theader));
6360 memcpy(tp, &a, sizeof(a));
6361 tmpiov[0].iov_base = tbuffer;
6362 tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6364 osi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6366 MUTEX_ENTER(&conn->conn_data_lock);
6367 MUTEX_ENTER(&rx_refcnt_mutex);
6368 /* Only reschedule ourselves if the connection would not be destroyed */
6369 if (conn->refCount <= 1) {
6370 rxevent_Put(&conn->natKeepAliveEvent);
6371 MUTEX_EXIT(&rx_refcnt_mutex);
6372 MUTEX_EXIT(&conn->conn_data_lock);
6373 rx_DestroyConnection(conn); /* drop the reference for this */
6375 conn->refCount--; /* drop the reference for this */
6376 MUTEX_EXIT(&rx_refcnt_mutex);
6377 rxevent_Put(&conn->natKeepAliveEvent);
6378 rxi_ScheduleNatKeepAliveEvent(conn);
6379 MUTEX_EXIT(&conn->conn_data_lock);
6384 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6386 if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6387 struct clock when, now;
6388 clock_GetTime(&now);
6390 when.sec += conn->secondsUntilNatPing;
6391 MUTEX_ENTER(&rx_refcnt_mutex);
6392 conn->refCount++; /* hold a reference for this */
6393 MUTEX_EXIT(&rx_refcnt_mutex);
6394 conn->natKeepAliveEvent =
6395 rxevent_Post(&when, &now, rxi_NatKeepAliveEvent, conn, NULL, 0);
6400 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6402 MUTEX_ENTER(&conn->conn_data_lock);
6403 conn->secondsUntilNatPing = seconds;
6405 if (!(conn->flags & RX_CONN_ATTACHWAIT))
6406 rxi_ScheduleNatKeepAliveEvent(conn);
6408 conn->flags |= RX_CONN_NAT_PING;
6410 MUTEX_EXIT(&conn->conn_data_lock);
6413 /* When a call is in progress, this routine is called occasionally to
6414 * make sure that some traffic has arrived (or been sent to) the peer.
6415 * If nothing has arrived in a reasonable amount of time, the call is
6416 * declared dead; if nothing has been sent for a while, we send a
6417 * keep-alive packet (if we're actually trying to keep the call alive)
6420 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy,
6423 struct rx_call *call = arg1;
6424 struct rx_connection *conn;
6427 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6428 MUTEX_ENTER(&call->lock);
6430 if (event == call->keepAliveEvent)
6431 rxevent_Put(&call->keepAliveEvent);
6435 if (rxi_CheckCall(call, 0)) {
6436 MUTEX_EXIT(&call->lock);
6440 /* Don't try to keep alive dallying calls */
6441 if (call->state == RX_STATE_DALLY) {
6442 MUTEX_EXIT(&call->lock);
6447 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6448 /* Don't try to send keepalives if there is unacknowledged data */
6449 /* the rexmit code should be good enough, this little hack
6450 * doesn't quite work XXX */
6451 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6453 rxi_ScheduleKeepAliveEvent(call);
6454 MUTEX_EXIT(&call->lock);
6457 /* Does what's on the nameplate. */
6459 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy, int dummy2)
6461 struct rx_call *call = arg1;
6462 struct rx_connection *conn;
6464 CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6465 MUTEX_ENTER(&call->lock);
6467 if (event == call->growMTUEvent)
6468 rxevent_Put(&call->growMTUEvent);
6470 if (rxi_CheckCall(call, 0)) {
6471 MUTEX_EXIT(&call->lock);
6475 /* Don't bother with dallying calls */
6476 if (call->state == RX_STATE_DALLY) {
6477 MUTEX_EXIT(&call->lock);
6484 * keep being scheduled, just don't do anything if we're at peak,
6485 * or we're not set up to be properly handled (idle timeout required)
6487 if ((conn->peer->maxPacketSize != 0) &&
6488 (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6490 (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6491 rxi_ScheduleGrowMTUEvent(call, 0);
6492 MUTEX_EXIT(&call->lock);
6496 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6498 if (!call->keepAliveEvent) {
6499 struct clock when, now;
6500 clock_GetTime(&now);
6502 when.sec += call->conn->secondsUntilPing;
6503 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6504 call->keepAliveEvent =
6505 rxevent_Post(&when, &now, rxi_KeepAliveEvent, call, NULL, 0);
6510 rxi_CancelKeepAliveEvent(struct rx_call *call) {
6511 if (call->keepAliveEvent) {
6512 rxevent_Cancel(&call->keepAliveEvent);
6513 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6518 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6520 if (!call->growMTUEvent) {
6521 struct clock when, now;
6523 clock_GetTime(&now);
6526 if (call->conn->secondsUntilPing)
6527 secs = (6*call->conn->secondsUntilPing)-1;
6529 if (call->conn->secondsUntilDead)
6530 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6534 CALL_HOLD(call, RX_CALL_REFCOUNT_MTU);
6535 call->growMTUEvent =
6536 rxevent_Post(&when, &now, rxi_GrowMTUEvent, call, NULL, 0);
6541 rxi_CancelGrowMTUEvent(struct rx_call *call)
6543 if (call->growMTUEvent) {
6544 rxevent_Cancel(&call->growMTUEvent);
6545 CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6550 * Increment the counter for the next connection ID, handling overflow.
6553 update_nextCid(void)
6555 /* Overflow is technically undefined behavior; avoid it. */
6556 if (rx_nextCid > MAX_AFS_INT32 - (1 << RX_CIDSHIFT))
6557 rx_nextCid = -1 * ((MAX_AFS_INT32 / RX_CIDSHIFT) * RX_CIDSHIFT);
6559 rx_nextCid += 1 << RX_CIDSHIFT;
6563 rxi_KeepAliveOn(struct rx_call *call)
6565 /* Pretend last packet received was received now--i.e. if another
6566 * packet isn't received within the keep alive time, then the call
6567 * will die; Initialize last send time to the current time--even
6568 * if a packet hasn't been sent yet. This will guarantee that a
6569 * keep-alive is sent within the ping time */
6570 call->lastReceiveTime = call->lastSendTime = clock_Sec();
6571 rxi_ScheduleKeepAliveEvent(call);
6575 rxi_GrowMTUOn(struct rx_call *call)
6577 struct rx_connection *conn = call->conn;
6578 MUTEX_ENTER(&conn->conn_data_lock);
6579 conn->lastPingSizeSer = conn->lastPingSize = 0;
6580 MUTEX_EXIT(&conn->conn_data_lock);
6581 rxi_ScheduleGrowMTUEvent(call, 1);
6584 /* This routine is called to send connection abort messages
6585 * that have been delayed to throttle looping clients. */
6587 rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1, void *unused,
6590 struct rx_connection *conn = arg1;
6593 struct rx_packet *packet;
6595 MUTEX_ENTER(&conn->conn_data_lock);
6596 rxevent_Put(&conn->delayedAbortEvent);
6597 error = htonl(conn->error);
6599 MUTEX_EXIT(&conn->conn_data_lock);
6600 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6603 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6604 RX_PACKET_TYPE_ABORT, (char *)&error,
6606 rxi_FreePacket(packet);
6610 /* This routine is called to send call abort messages
6611 * that have been delayed to throttle looping clients. */
6613 rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1, void *dummy,
6616 struct rx_call *call = arg1;
6619 struct rx_packet *packet;
6621 MUTEX_ENTER(&call->lock);
6622 rxevent_Put(&call->delayedAbortEvent);
6623 error = htonl(call->error);
6625 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6628 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6629 (char *)&error, sizeof(error), 0);
6630 rxi_FreePacket(packet);
6632 MUTEX_EXIT(&call->lock);
6633 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6636 /* This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6637 * seconds) to ask the client to authenticate itself. The routine
6638 * issues a challenge to the client, which is obtained from the
6639 * security object associated with the connection */
6641 rxi_ChallengeEvent(struct rxevent *event,
6642 void *arg0, void *arg1, int tries)
6644 struct rx_connection *conn = arg0;
6647 rxevent_Put(&conn->challengeEvent);
6649 /* If there are no active calls it is not worth re-issuing the
6650 * challenge. If the client issues another call on this connection
6651 * the challenge can be requested at that time.
6653 if (!rxi_HasActiveCalls(conn))
6656 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6657 struct rx_packet *packet;
6658 struct clock when, now;
6661 /* We've failed to authenticate for too long.
6662 * Reset any calls waiting for authentication;
6663 * they are all in RX_STATE_PRECALL.
6667 MUTEX_ENTER(&conn->conn_call_lock);
6668 for (i = 0; i < RX_MAXCALLS; i++) {
6669 struct rx_call *call = conn->call[i];
6671 MUTEX_ENTER(&call->lock);
6672 if (call->state == RX_STATE_PRECALL) {
6673 rxi_CallError(call, RX_CALL_DEAD);
6674 rxi_SendCallAbort(call, NULL, 0, 0);
6676 MUTEX_EXIT(&call->lock);
6679 MUTEX_EXIT(&conn->conn_call_lock);
6683 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6685 /* If there's no packet available, do this later. */
6686 RXS_GetChallenge(conn->securityObject, conn, packet);
6687 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6688 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6689 rxi_FreePacket(packet);
6690 conn->securityChallengeSent = 1;
6692 clock_GetTime(&now);
6694 when.sec += RX_CHALLENGE_TIMEOUT;
6695 conn->challengeEvent =
6696 rxevent_Post(&when, &now, rxi_ChallengeEvent, conn, 0,
6701 /* Call this routine to start requesting the client to authenticate
6702 * itself. This will continue until authentication is established,
6703 * the call times out, or an invalid response is returned. The
6704 * security object associated with the connection is asked to create
6705 * the challenge at this time. N.B. rxi_ChallengeOff is a macro,
6706 * defined earlier. */
6708 rxi_ChallengeOn(struct rx_connection *conn)
6710 if (!conn->challengeEvent) {
6711 RXS_CreateChallenge(conn->securityObject, conn);
6712 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
6717 /* rxi_ComputeRoundTripTime is called with peer locked. */
6718 /* peer may be null */
6720 rxi_ComputeRoundTripTime(struct rx_packet *p,
6721 struct rx_ackPacket *ack,
6722 struct rx_call *call,
6723 struct rx_peer *peer,
6726 struct clock thisRtt, *sentp;
6730 /* If the ACK is delayed, then do nothing */
6731 if (ack->reason == RX_ACK_DELAY)
6734 /* On the wire, jumbograms are a single UDP packet. We shouldn't count
6735 * their RTT multiple times, so only include the RTT of the last packet
6737 if (p->flags & RX_JUMBO_PACKET)
6740 /* Use the serial number to determine which transmission the ACK is for,
6741 * and set the sent time to match this. If we have no serial number, then
6742 * only use the ACK for RTT calculations if the packet has not been
6746 serial = ntohl(ack->serial);
6748 if (serial == p->header.serial) {
6749 sentp = &p->timeSent;
6750 } else if (serial == p->firstSerial) {
6751 sentp = &p->firstSent;
6752 } else if (clock_Eq(&p->timeSent, &p->firstSent)) {
6753 sentp = &p->firstSent;
6757 if (clock_Eq(&p->timeSent, &p->firstSent)) {
6758 sentp = &p->firstSent;
6765 if (clock_Lt(&thisRtt, sentp))
6766 return; /* somebody set the clock back, don't count this time. */
6768 clock_Sub(&thisRtt, sentp);
6769 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rttp=%d.%06d sec)\n",
6770 p->header.callNumber, p, thisRtt.sec, thisRtt.usec));
6772 if (clock_IsZero(&thisRtt)) {
6774 * The actual round trip time is shorter than the
6775 * clock_GetTime resolution. It is most likely 1ms or 100ns.
6776 * Since we can't tell which at the moment we will assume 1ms.
6778 thisRtt.usec = 1000;
6781 if (rx_stats_active) {
6782 MUTEX_ENTER(&rx_stats_mutex);
6783 if (clock_Lt(&thisRtt, &rx_stats.minRtt))
6784 rx_stats.minRtt = thisRtt;
6785 if (clock_Gt(&thisRtt, &rx_stats.maxRtt)) {
6786 if (thisRtt.sec > 60) {
6787 MUTEX_EXIT(&rx_stats_mutex);
6788 return; /* somebody set the clock ahead */
6790 rx_stats.maxRtt = thisRtt;
6792 clock_Add(&rx_stats.totalRtt, &thisRtt);
6793 rx_atomic_inc(&rx_stats.nRttSamples);
6794 MUTEX_EXIT(&rx_stats_mutex);
6797 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6799 /* Apply VanJacobson round-trip estimations */
6804 * srtt (call->rtt) is in units of one-eighth-milliseconds.
6805 * srtt is stored as fixed point with 3 bits after the binary
6806 * point (i.e., scaled by 8). The following magic is
6807 * equivalent to the smoothing algorithm in rfc793 with an
6808 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
6809 * srtt'*8 = rtt + srtt*7
6810 * srtt'*8 = srtt*8 + rtt - srtt
6811 * srtt' = srtt + rtt/8 - srtt/8
6812 * srtt' = srtt + (rtt - srtt)/8
6815 delta = _8THMSEC(&thisRtt) - call->rtt;
6816 call->rtt += (delta >> 3);
6819 * We accumulate a smoothed rtt variance (actually, a smoothed
6820 * mean difference), then set the retransmit timer to smoothed
6821 * rtt + 4 times the smoothed variance (was 2x in van's original
6822 * paper, but 4x works better for me, and apparently for him as
6824 * rttvar is stored as
6825 * fixed point with 2 bits after the binary point (scaled by
6826 * 4). The following is equivalent to rfc793 smoothing with
6827 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
6828 * rttvar'*4 = rttvar*3 + |delta|
6829 * rttvar'*4 = rttvar*4 + |delta| - rttvar
6830 * rttvar' = rttvar + |delta|/4 - rttvar/4
6831 * rttvar' = rttvar + (|delta| - rttvar)/4
6832 * This replaces rfc793's wired-in beta.
6833 * dev*4 = dev*4 + (|actual - expected| - dev)
6839 delta -= (call->rtt_dev << 1);
6840 call->rtt_dev += (delta >> 3);
6842 /* I don't have a stored RTT so I start with this value. Since I'm
6843 * probably just starting a call, and will be pushing more data down
6844 * this, I expect congestion to increase rapidly. So I fudge a
6845 * little, and I set deviance to half the rtt. In practice,
6846 * deviance tends to approach something a little less than
6847 * half the smoothed rtt. */
6848 call->rtt = _8THMSEC(&thisRtt) + 8;
6849 call->rtt_dev = call->rtt >> 2; /* rtt/2: they're scaled differently */
6851 /* the smoothed RTT time is RTT + 4*MDEV
6853 * We allow a user specified minimum to be set for this, to allow clamping
6854 * at a minimum value in the same way as TCP. In addition, we have to allow
6855 * for the possibility that this packet is answered by a delayed ACK, so we
6856 * add on a fixed 200ms to account for that timer expiring.
6859 rtt_timeout = MAX(((call->rtt >> 3) + call->rtt_dev),
6860 rx_minPeerTimeout) + 200;
6861 clock_Zero(&call->rto);
6862 clock_Addmsec(&call->rto, rtt_timeout);
6864 /* Update the peer, so any new calls start with our values */
6865 peer->rtt_dev = call->rtt_dev;
6866 peer->rtt = call->rtt;
6868 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rtt=%d ms, srtt=%d ms, rtt_dev=%d ms, timeout=%d.%06d sec)\n",
6869 p->header.callNumber, p, MSEC(&thisRtt), call->rtt >> 3, call->rtt_dev >> 2, (call->rto.sec), (call->rto.usec)));
6873 /* Find all server connections that have not been active for a long time, and
6876 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2,
6879 struct clock now, when;
6880 struct rxevent *event;
6881 clock_GetTime(&now);
6883 /* Find server connection structures that haven't been used for
6884 * greater than rx_idleConnectionTime */
6886 struct rx_connection **conn_ptr, **conn_end;
6887 int i, havecalls = 0;
6888 MUTEX_ENTER(&rx_connHashTable_lock);
6889 for (conn_ptr = &rx_connHashTable[0], conn_end =
6890 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
6892 struct rx_connection *conn, *next;
6893 struct rx_call *call;
6897 for (conn = *conn_ptr; conn; conn = next) {
6898 /* XXX -- Shouldn't the connection be locked? */
6901 for (i = 0; i < RX_MAXCALLS; i++) {
6902 call = conn->call[i];
6906 code = MUTEX_TRYENTER(&call->lock);
6909 result = rxi_CheckCall(call, 1);
6910 MUTEX_EXIT(&call->lock);
6912 /* If CheckCall freed the call, it might
6913 * have destroyed the connection as well,
6914 * which screws up the linked lists.
6920 if (conn->type == RX_SERVER_CONNECTION) {
6921 /* This only actually destroys the connection if
6922 * there are no outstanding calls */
6923 MUTEX_ENTER(&conn->conn_data_lock);
6924 MUTEX_ENTER(&rx_refcnt_mutex);
6925 if (!havecalls && !conn->refCount
6926 && ((conn->lastSendTime + rx_idleConnectionTime) <
6928 conn->refCount++; /* it will be decr in rx_DestroyConn */
6929 MUTEX_EXIT(&rx_refcnt_mutex);
6930 MUTEX_EXIT(&conn->conn_data_lock);
6931 #ifdef RX_ENABLE_LOCKS
6932 rxi_DestroyConnectionNoLock(conn);
6933 #else /* RX_ENABLE_LOCKS */
6934 rxi_DestroyConnection(conn);
6935 #endif /* RX_ENABLE_LOCKS */
6937 #ifdef RX_ENABLE_LOCKS
6939 MUTEX_EXIT(&rx_refcnt_mutex);
6940 MUTEX_EXIT(&conn->conn_data_lock);
6942 #endif /* RX_ENABLE_LOCKS */
6946 #ifdef RX_ENABLE_LOCKS
6947 while (rx_connCleanup_list) {
6948 struct rx_connection *conn;
6949 conn = rx_connCleanup_list;
6950 rx_connCleanup_list = rx_connCleanup_list->next;
6951 MUTEX_EXIT(&rx_connHashTable_lock);
6952 rxi_CleanupConnection(conn);
6953 MUTEX_ENTER(&rx_connHashTable_lock);
6955 MUTEX_EXIT(&rx_connHashTable_lock);
6956 #endif /* RX_ENABLE_LOCKS */
6959 /* Find any peer structures that haven't been used (haven't had an
6960 * associated connection) for greater than rx_idlePeerTime */
6962 struct rx_peer **peer_ptr, **peer_end;
6966 * Why do we need to hold the rx_peerHashTable_lock across
6967 * the incrementing of peer_ptr since the rx_peerHashTable
6968 * array is not changing? We don't.
6970 * By dropping the lock periodically we can permit other
6971 * activities to be performed while a rxi_ReapConnections
6972 * call is in progress. The goal of reap connections
6973 * is to clean up quickly without causing large amounts
6974 * of contention. Therefore, it is important that global
6975 * mutexes not be held for extended periods of time.
6977 for (peer_ptr = &rx_peerHashTable[0], peer_end =
6978 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
6980 struct rx_peer *peer, *next, *prev;
6982 MUTEX_ENTER(&rx_peerHashTable_lock);
6983 for (prev = peer = *peer_ptr; peer; peer = next) {
6985 code = MUTEX_TRYENTER(&peer->peer_lock);
6986 if ((code) && (peer->refCount == 0)
6987 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
6988 struct opr_queue *cursor, *store;
6992 * now know that this peer object is one to be
6993 * removed from the hash table. Once it is removed
6994 * it can't be referenced by other threads.
6995 * Lets remove it first and decrement the struct
6996 * nPeerStructs count.
6998 if (peer == *peer_ptr) {
7004 if (rx_stats_active)
7005 rx_atomic_dec(&rx_stats.nPeerStructs);
7008 * Now if we hold references on 'prev' and 'next'
7009 * we can safely drop the rx_peerHashTable_lock
7010 * while we destroy this 'peer' object.
7016 MUTEX_EXIT(&rx_peerHashTable_lock);
7018 MUTEX_EXIT(&peer->peer_lock);
7019 MUTEX_DESTROY(&peer->peer_lock);
7021 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
7022 unsigned int num_funcs;
7023 struct rx_interface_stat *rpc_stat
7024 = opr_queue_Entry(cursor, struct rx_interface_stat,
7029 opr_queue_Remove(&rpc_stat->entry);
7030 opr_queue_Remove(&rpc_stat->entryPeers);
7032 num_funcs = rpc_stat->stats[0].func_total;
7034 sizeof(rx_interface_stat_t) +
7035 rpc_stat->stats[0].func_total *
7036 sizeof(rx_function_entry_v1_t);
7038 rxi_Free(rpc_stat, space);
7040 MUTEX_ENTER(&rx_rpc_stats);
7041 rxi_rpc_peer_stat_cnt -= num_funcs;
7042 MUTEX_EXIT(&rx_rpc_stats);
7047 * Regain the rx_peerHashTable_lock and
7048 * decrement the reference count on 'prev'
7051 MUTEX_ENTER(&rx_peerHashTable_lock);
7058 MUTEX_EXIT(&peer->peer_lock);
7063 MUTEX_EXIT(&rx_peerHashTable_lock);
7067 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
7068 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
7069 * GC, just below. Really, we shouldn't have to keep moving packets from
7070 * one place to another, but instead ought to always know if we can
7071 * afford to hold onto a packet in its particular use. */
7072 MUTEX_ENTER(&rx_freePktQ_lock);
7073 if (rx_waitingForPackets) {
7074 rx_waitingForPackets = 0;
7075 #ifdef RX_ENABLE_LOCKS
7076 CV_BROADCAST(&rx_waitingForPackets_cv);
7078 osi_rxWakeup(&rx_waitingForPackets);
7081 MUTEX_EXIT(&rx_freePktQ_lock);
7084 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
7085 event = rxevent_Post(&when, &now, rxi_ReapConnections, 0, NULL, 0);
7086 rxevent_Put(&event);
7090 /* rxs_Release - This isn't strictly necessary but, since the macro name from
7091 * rx.h is sort of strange this is better. This is called with a security
7092 * object before it is discarded. Each connection using a security object has
7093 * its own refcount to the object so it won't actually be freed until the last
7094 * connection is destroyed.
7096 * This is the only rxs module call. A hold could also be written but no one
7100 rxs_Release(struct rx_securityClass *aobj)
7102 return RXS_Close(aobj);
7110 #define TRACE_OPTION_RX_DEBUG 16
7118 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
7119 0, KEY_QUERY_VALUE, &parmKey);
7120 if (code != ERROR_SUCCESS)
7123 dummyLen = sizeof(TraceOption);
7124 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
7125 (BYTE *) &TraceOption, &dummyLen);
7126 if (code == ERROR_SUCCESS) {
7127 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
7129 RegCloseKey (parmKey);
7130 #endif /* AFS_NT40_ENV */
7135 rx_DebugOnOff(int on)
7139 rxdebug_active = on;
7145 rx_StatsOnOff(int on)
7147 rx_stats_active = on;
7151 /* Don't call this debugging routine directly; use dpf */
7153 rxi_DebugPrint(char *format, ...)
7162 va_start(ap, format);
7164 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7167 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7169 OutputDebugString(msg);
7175 va_start(ap, format);
7177 clock_GetTime(&now);
7178 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7179 (unsigned int)now.usec);
7180 vfprintf(rx_Log, format, ap);
7188 * This function is used to process the rx_stats structure that is local
7189 * to a process as well as an rx_stats structure received from a remote
7190 * process (via rxdebug). Therefore, it needs to do minimal version
7194 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7195 afs_int32 freePackets, char version)
7199 if (size != sizeof(struct rx_statistics)) {
7201 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7202 size, sizeof(struct rx_statistics));
7205 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7208 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7209 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7210 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7211 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7212 s->specialPktAllocFailures);
7214 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7215 s->receivePktAllocFailures, s->sendPktAllocFailures,
7216 s->specialPktAllocFailures);
7220 " greedy %u, " "bogusReads %u (last from host %x), "
7221 "noPackets %u, " "noBuffers %u, " "selects %u, "
7222 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7223 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7224 s->selects, s->sendSelects);
7226 fprintf(file, " packets read: ");
7227 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7228 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7230 fprintf(file, "\n");
7233 " other read counters: data %u, " "ack %u, " "dup %u "
7234 "spurious %u " "dally %u\n", s->dataPacketsRead,
7235 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7236 s->ignorePacketDally);
7238 fprintf(file, " packets sent: ");
7239 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7240 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7242 fprintf(file, "\n");
7245 " other send counters: ack %u, " "data %u (not resends), "
7246 "resends %u, " "pushed %u, " "acked&ignored %u\n",
7247 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7248 s->dataPacketsPushed, s->ignoreAckedPacket);
7251 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7252 s->netSendFailures, (int)s->fatalErrors);
7254 if (s->nRttSamples) {
7255 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
7256 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7258 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
7259 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7263 " %d server connections, " "%d client connections, "
7264 "%d peer structs, " "%d call structs, " "%d free call structs\n",
7265 s->nServerConns, s->nClientConns, s->nPeerStructs,
7266 s->nCallStructs, s->nFreeCallStructs);
7268 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7269 fprintf(file, " %d clock updates\n", clock_nUpdates);
7273 /* for backward compatibility */
7275 rx_PrintStats(FILE * file)
7277 MUTEX_ENTER(&rx_stats_mutex);
7278 rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7279 sizeof(rx_stats), rx_nFreePackets,
7281 MUTEX_EXIT(&rx_stats_mutex);
7285 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7287 fprintf(file, "Peer %x.%d.\n",
7288 ntohl(peer->host), (int)ntohs(peer->port));
7291 " Rtt %d, " "total sent %d, " "resent %d\n",
7292 peer->rtt, peer->nSent, peer->reSends);
7294 fprintf(file, " Packet size %d\n", peer->ifMTU);
7298 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7300 * This mutex protects the following static variables:
7304 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7305 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7307 #define LOCK_RX_DEBUG
7308 #define UNLOCK_RX_DEBUG
7309 #endif /* AFS_PTHREAD_ENV */
7311 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7313 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7314 u_char type, void *inputData, size_t inputLength,
7315 void *outputData, size_t outputLength)
7317 static afs_int32 counter = 100;
7318 time_t waitTime, waitCount;
7319 struct rx_header theader;
7322 struct timeval tv_now, tv_wake, tv_delta;
7323 struct sockaddr_in taddr, faddr;
7337 tp = &tbuffer[sizeof(struct rx_header)];
7338 taddr.sin_family = AF_INET;
7339 taddr.sin_port = remotePort;
7340 taddr.sin_addr.s_addr = remoteAddr;
7341 memset(&taddr.sin_zero, 0, sizeof(taddr.sin_zero));
7342 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7343 taddr.sin_len = sizeof(struct sockaddr_in);
7346 memset(&theader, 0, sizeof(theader));
7347 theader.epoch = htonl(999);
7349 theader.callNumber = htonl(counter);
7352 theader.type = type;
7353 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7354 theader.serviceId = 0;
7356 memcpy(tbuffer, &theader, sizeof(theader));
7357 memcpy(tp, inputData, inputLength);
7359 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7360 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7362 /* see if there's a packet available */
7363 gettimeofday(&tv_wake, NULL);
7364 tv_wake.tv_sec += waitTime;
7367 FD_SET(socket, &imask);
7368 tv_delta.tv_sec = tv_wake.tv_sec;
7369 tv_delta.tv_usec = tv_wake.tv_usec;
7370 gettimeofday(&tv_now, NULL);
7372 if (tv_delta.tv_usec < tv_now.tv_usec) {
7374 tv_delta.tv_usec += 1000000;
7377 tv_delta.tv_usec -= tv_now.tv_usec;
7379 if (tv_delta.tv_sec < tv_now.tv_sec) {
7383 tv_delta.tv_sec -= tv_now.tv_sec;
7386 code = select(0, &imask, 0, 0, &tv_delta);
7387 #else /* AFS_NT40_ENV */
7388 code = select(socket + 1, &imask, 0, 0, &tv_delta);
7389 #endif /* AFS_NT40_ENV */
7390 if (code == 1 && FD_ISSET(socket, &imask)) {
7391 /* now receive a packet */
7392 faddrLen = sizeof(struct sockaddr_in);
7394 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7395 (struct sockaddr *)&faddr, &faddrLen);
7398 memcpy(&theader, tbuffer, sizeof(struct rx_header));
7399 if (counter == ntohl(theader.callNumber))
7407 /* see if we've timed out */
7415 code -= sizeof(struct rx_header);
7416 if (code > outputLength)
7417 code = outputLength;
7418 memcpy(outputData, tp, code);
7421 #endif /* RXDEBUG */
7424 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7425 afs_uint16 remotePort, struct rx_debugStats * stat,
7426 afs_uint32 * supportedValues)
7428 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7430 struct rx_debugIn in;
7432 *supportedValues = 0;
7433 in.type = htonl(RX_DEBUGI_GETSTATS);
7436 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7437 &in, sizeof(in), stat, sizeof(*stat));
7440 * If the call was successful, fixup the version and indicate
7441 * what contents of the stat structure are valid.
7442 * Also do net to host conversion of fields here.
7446 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7447 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7449 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7450 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7452 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7453 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7455 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7456 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7458 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7459 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7461 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7462 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7464 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7465 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7467 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7468 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7470 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7471 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7473 stat->nFreePackets = ntohl(stat->nFreePackets);
7474 stat->packetReclaims = ntohl(stat->packetReclaims);
7475 stat->callsExecuted = ntohl(stat->callsExecuted);
7476 stat->nWaiting = ntohl(stat->nWaiting);
7477 stat->idleThreads = ntohl(stat->idleThreads);
7478 stat->nWaited = ntohl(stat->nWaited);
7479 stat->nPackets = ntohl(stat->nPackets);
7488 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7489 afs_uint16 remotePort, struct rx_statistics * stat,
7490 afs_uint32 * supportedValues)
7492 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7494 struct rx_debugIn in;
7495 afs_int32 *lp = (afs_int32 *) stat;
7499 * supportedValues is currently unused, but added to allow future
7500 * versioning of this function.
7503 *supportedValues = 0;
7504 in.type = htonl(RX_DEBUGI_RXSTATS);
7506 memset(stat, 0, sizeof(*stat));
7508 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7509 &in, sizeof(in), stat, sizeof(*stat));
7514 * Do net to host conversion here
7517 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7528 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7529 afs_uint16 remotePort, size_t version_length,
7532 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7534 return MakeDebugCall(socket, remoteAddr, remotePort,
7535 RX_PACKET_TYPE_VERSION, a, 1, version,
7543 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7544 afs_uint16 remotePort, afs_int32 * nextConnection,
7545 int allConnections, afs_uint32 debugSupportedValues,
7546 struct rx_debugConn * conn,
7547 afs_uint32 * supportedValues)
7549 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7551 struct rx_debugIn in;
7555 * supportedValues is currently unused, but added to allow future
7556 * versioning of this function.
7559 *supportedValues = 0;
7560 if (allConnections) {
7561 in.type = htonl(RX_DEBUGI_GETALLCONN);
7563 in.type = htonl(RX_DEBUGI_GETCONN);
7565 in.index = htonl(*nextConnection);
7566 memset(conn, 0, sizeof(*conn));
7568 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7569 &in, sizeof(in), conn, sizeof(*conn));
7572 *nextConnection += 1;
7575 * Convert old connection format to new structure.
7578 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7579 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7580 #define MOVEvL(a) (conn->a = vL->a)
7582 /* any old or unrecognized version... */
7583 for (i = 0; i < RX_MAXCALLS; i++) {
7584 MOVEvL(callState[i]);
7585 MOVEvL(callMode[i]);
7586 MOVEvL(callFlags[i]);
7587 MOVEvL(callOther[i]);
7589 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7590 MOVEvL(secStats.type);
7591 MOVEvL(secStats.level);
7592 MOVEvL(secStats.flags);
7593 MOVEvL(secStats.expires);
7594 MOVEvL(secStats.packetsReceived);
7595 MOVEvL(secStats.packetsSent);
7596 MOVEvL(secStats.bytesReceived);
7597 MOVEvL(secStats.bytesSent);
7602 * Do net to host conversion here
7604 * I don't convert host or port since we are most likely
7605 * going to want these in NBO.
7607 conn->cid = ntohl(conn->cid);
7608 conn->serial = ntohl(conn->serial);
7609 for (i = 0; i < RX_MAXCALLS; i++) {
7610 conn->callNumber[i] = ntohl(conn->callNumber[i]);
7612 conn->error = ntohl(conn->error);
7613 conn->secStats.flags = ntohl(conn->secStats.flags);
7614 conn->secStats.expires = ntohl(conn->secStats.expires);
7615 conn->secStats.packetsReceived =
7616 ntohl(conn->secStats.packetsReceived);
7617 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7618 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7619 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7620 conn->epoch = ntohl(conn->epoch);
7621 conn->natMTU = ntohl(conn->natMTU);
7630 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7631 afs_uint16 remotePort, afs_int32 * nextPeer,
7632 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7633 afs_uint32 * supportedValues)
7635 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7637 struct rx_debugIn in;
7640 * supportedValues is currently unused, but added to allow future
7641 * versioning of this function.
7644 *supportedValues = 0;
7645 in.type = htonl(RX_DEBUGI_GETPEER);
7646 in.index = htonl(*nextPeer);
7647 memset(peer, 0, sizeof(*peer));
7649 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7650 &in, sizeof(in), peer, sizeof(*peer));
7656 * Do net to host conversion here
7658 * I don't convert host or port since we are most likely
7659 * going to want these in NBO.
7661 peer->ifMTU = ntohs(peer->ifMTU);
7662 peer->idleWhen = ntohl(peer->idleWhen);
7663 peer->refCount = ntohs(peer->refCount);
7664 peer->rtt = ntohl(peer->rtt);
7665 peer->rtt_dev = ntohl(peer->rtt_dev);
7666 peer->timeout.sec = 0;
7667 peer->timeout.usec = 0;
7668 peer->nSent = ntohl(peer->nSent);
7669 peer->reSends = ntohl(peer->reSends);
7670 peer->natMTU = ntohs(peer->natMTU);
7671 peer->maxMTU = ntohs(peer->maxMTU);
7672 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7673 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7674 peer->MTU = ntohs(peer->MTU);
7675 peer->cwind = ntohs(peer->cwind);
7676 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7677 peer->congestSeq = ntohs(peer->congestSeq);
7678 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7679 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7680 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7681 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7690 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7691 struct rx_debugPeer * peerStats)
7694 afs_int32 error = 1; /* default to "did not succeed" */
7695 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7697 MUTEX_ENTER(&rx_peerHashTable_lock);
7698 for(tp = rx_peerHashTable[hashValue];
7699 tp != NULL; tp = tp->next) {
7700 if (tp->host == peerHost)
7706 MUTEX_EXIT(&rx_peerHashTable_lock);
7710 MUTEX_ENTER(&tp->peer_lock);
7711 peerStats->host = tp->host;
7712 peerStats->port = tp->port;
7713 peerStats->ifMTU = tp->ifMTU;
7714 peerStats->idleWhen = tp->idleWhen;
7715 peerStats->refCount = tp->refCount;
7716 peerStats->burstSize = 0;
7717 peerStats->burst = 0;
7718 peerStats->burstWait.sec = 0;
7719 peerStats->burstWait.usec = 0;
7720 peerStats->rtt = tp->rtt;
7721 peerStats->rtt_dev = tp->rtt_dev;
7722 peerStats->timeout.sec = 0;
7723 peerStats->timeout.usec = 0;
7724 peerStats->nSent = tp->nSent;
7725 peerStats->reSends = tp->reSends;
7726 peerStats->natMTU = tp->natMTU;
7727 peerStats->maxMTU = tp->maxMTU;
7728 peerStats->maxDgramPackets = tp->maxDgramPackets;
7729 peerStats->ifDgramPackets = tp->ifDgramPackets;
7730 peerStats->MTU = tp->MTU;
7731 peerStats->cwind = tp->cwind;
7732 peerStats->nDgramPackets = tp->nDgramPackets;
7733 peerStats->congestSeq = tp->congestSeq;
7734 peerStats->bytesSent.high = tp->bytesSent >> 32;
7735 peerStats->bytesSent.low = tp->bytesSent & MAX_AFS_UINT32;
7736 peerStats->bytesReceived.high = tp->bytesReceived >> 32;
7737 peerStats->bytesReceived.low
7738 = tp->bytesReceived & MAX_AFS_UINT32;
7739 MUTEX_EXIT(&tp->peer_lock);
7741 MUTEX_ENTER(&rx_peerHashTable_lock);
7744 MUTEX_EXIT(&rx_peerHashTable_lock);
7752 struct rx_serverQueueEntry *np;
7755 struct rx_call *call;
7756 struct rx_serverQueueEntry *sq;
7759 if (rx_atomic_test_and_set_bit(&rxinit_status, 0))
7760 return; /* Already shutdown. */
7764 #ifndef AFS_PTHREAD_ENV
7765 FD_ZERO(&rx_selectMask);
7766 #endif /* AFS_PTHREAD_ENV */
7767 rxi_dataQuota = RX_MAX_QUOTA;
7768 #ifndef AFS_PTHREAD_ENV
7770 #endif /* AFS_PTHREAD_ENV */
7773 #ifndef AFS_PTHREAD_ENV
7774 #ifndef AFS_USE_GETTIMEOFDAY
7776 #endif /* AFS_USE_GETTIMEOFDAY */
7777 #endif /* AFS_PTHREAD_ENV */
7779 while (!opr_queue_IsEmpty(&rx_freeCallQueue)) {
7780 call = opr_queue_First(&rx_freeCallQueue, struct rx_call, entry);
7781 opr_queue_Remove(&call->entry);
7782 rxi_Free(call, sizeof(struct rx_call));
7785 while (!opr_queue_IsEmpty(&rx_idleServerQueue)) {
7786 sq = opr_queue_First(&rx_idleServerQueue, struct rx_serverQueueEntry,
7788 opr_queue_Remove(&sq->entry);
7793 struct rx_peer **peer_ptr, **peer_end;
7794 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7795 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7797 struct rx_peer *peer, *next;
7799 MUTEX_ENTER(&rx_peerHashTable_lock);
7800 for (peer = *peer_ptr; peer; peer = next) {
7801 struct opr_queue *cursor, *store;
7804 MUTEX_ENTER(&rx_rpc_stats);
7805 MUTEX_ENTER(&peer->peer_lock);
7806 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
7807 unsigned int num_funcs;
7808 struct rx_interface_stat *rpc_stat
7809 = opr_queue_Entry(cursor, struct rx_interface_stat,
7813 opr_queue_Remove(&rpc_stat->entry);
7814 opr_queue_Remove(&rpc_stat->entryPeers);
7815 num_funcs = rpc_stat->stats[0].func_total;
7817 sizeof(rx_interface_stat_t) +
7818 rpc_stat->stats[0].func_total *
7819 sizeof(rx_function_entry_v1_t);
7821 rxi_Free(rpc_stat, space);
7823 /* rx_rpc_stats must be held */
7824 rxi_rpc_peer_stat_cnt -= num_funcs;
7826 MUTEX_EXIT(&peer->peer_lock);
7827 MUTEX_EXIT(&rx_rpc_stats);
7831 if (rx_stats_active)
7832 rx_atomic_dec(&rx_stats.nPeerStructs);
7834 MUTEX_EXIT(&rx_peerHashTable_lock);
7837 for (i = 0; i < RX_MAX_SERVICES; i++) {
7839 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7841 for (i = 0; i < rx_hashTableSize; i++) {
7842 struct rx_connection *tc, *ntc;
7843 MUTEX_ENTER(&rx_connHashTable_lock);
7844 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7846 for (j = 0; j < RX_MAXCALLS; j++) {
7848 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7851 rxi_Free(tc, sizeof(*tc));
7853 MUTEX_EXIT(&rx_connHashTable_lock);
7856 MUTEX_ENTER(&freeSQEList_lock);
7858 while ((np = rx_FreeSQEList)) {
7859 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7860 MUTEX_DESTROY(&np->lock);
7861 rxi_Free(np, sizeof(*np));
7864 MUTEX_EXIT(&freeSQEList_lock);
7865 MUTEX_DESTROY(&freeSQEList_lock);
7866 MUTEX_DESTROY(&rx_freeCallQueue_lock);
7867 MUTEX_DESTROY(&rx_connHashTable_lock);
7868 MUTEX_DESTROY(&rx_peerHashTable_lock);
7869 MUTEX_DESTROY(&rx_serverPool_lock);
7871 osi_Free(rx_connHashTable,
7872 rx_hashTableSize * sizeof(struct rx_connection *));
7873 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7875 UNPIN(rx_connHashTable,
7876 rx_hashTableSize * sizeof(struct rx_connection *));
7877 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7879 rxi_FreeAllPackets();
7881 MUTEX_ENTER(&rx_quota_mutex);
7882 rxi_dataQuota = RX_MAX_QUOTA;
7883 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
7884 MUTEX_EXIT(&rx_quota_mutex);
7890 * Routines to implement connection specific data.
7894 rx_KeyCreate(rx_destructor_t rtn)
7897 MUTEX_ENTER(&rxi_keyCreate_lock);
7898 key = rxi_keyCreate_counter++;
7899 rxi_keyCreate_destructor = (rx_destructor_t *)
7900 realloc((void *)rxi_keyCreate_destructor,
7901 (key + 1) * sizeof(rx_destructor_t));
7902 rxi_keyCreate_destructor[key] = rtn;
7903 MUTEX_EXIT(&rxi_keyCreate_lock);
7908 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
7911 MUTEX_ENTER(&conn->conn_data_lock);
7912 if (!conn->specific) {
7913 conn->specific = malloc((key + 1) * sizeof(void *));
7914 for (i = 0; i < key; i++)
7915 conn->specific[i] = NULL;
7916 conn->nSpecific = key + 1;
7917 conn->specific[key] = ptr;
7918 } else if (key >= conn->nSpecific) {
7919 conn->specific = (void **)
7920 realloc(conn->specific, (key + 1) * sizeof(void *));
7921 for (i = conn->nSpecific; i < key; i++)
7922 conn->specific[i] = NULL;
7923 conn->nSpecific = key + 1;
7924 conn->specific[key] = ptr;
7926 if (conn->specific[key] && rxi_keyCreate_destructor[key])
7927 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
7928 conn->specific[key] = ptr;
7930 MUTEX_EXIT(&conn->conn_data_lock);
7934 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
7937 MUTEX_ENTER(&svc->svc_data_lock);
7938 if (!svc->specific) {
7939 svc->specific = malloc((key + 1) * sizeof(void *));
7940 for (i = 0; i < key; i++)
7941 svc->specific[i] = NULL;
7942 svc->nSpecific = key + 1;
7943 svc->specific[key] = ptr;
7944 } else if (key >= svc->nSpecific) {
7945 svc->specific = (void **)
7946 realloc(svc->specific, (key + 1) * sizeof(void *));
7947 for (i = svc->nSpecific; i < key; i++)
7948 svc->specific[i] = NULL;
7949 svc->nSpecific = key + 1;
7950 svc->specific[key] = ptr;
7952 if (svc->specific[key] && rxi_keyCreate_destructor[key])
7953 (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
7954 svc->specific[key] = ptr;
7956 MUTEX_EXIT(&svc->svc_data_lock);
7960 rx_GetSpecific(struct rx_connection *conn, int key)
7963 MUTEX_ENTER(&conn->conn_data_lock);
7964 if (key >= conn->nSpecific)
7967 ptr = conn->specific[key];
7968 MUTEX_EXIT(&conn->conn_data_lock);
7973 rx_GetServiceSpecific(struct rx_service *svc, int key)
7976 MUTEX_ENTER(&svc->svc_data_lock);
7977 if (key >= svc->nSpecific)
7980 ptr = svc->specific[key];
7981 MUTEX_EXIT(&svc->svc_data_lock);
7986 #endif /* !KERNEL */
7989 * processStats is a queue used to store the statistics for the local
7990 * process. Its contents are similar to the contents of the rpcStats
7991 * queue on a rx_peer structure, but the actual data stored within
7992 * this queue contains totals across the lifetime of the process (assuming
7993 * the stats have not been reset) - unlike the per peer structures
7994 * which can come and go based upon the peer lifetime.
7997 static struct opr_queue processStats = { &processStats, &processStats };
8000 * peerStats is a queue used to store the statistics for all peer structs.
8001 * Its contents are the union of all the peer rpcStats queues.
8004 static struct opr_queue peerStats = { &peerStats, &peerStats };
8007 * rxi_monitor_processStats is used to turn process wide stat collection
8011 static int rxi_monitor_processStats = 0;
8014 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
8017 static int rxi_monitor_peerStats = 0;
8021 rxi_ClearRPCOpStat(rx_function_entry_v1_p rpc_stat)
8023 rpc_stat->invocations = 0;
8024 rpc_stat->bytes_sent = 0;
8025 rpc_stat->bytes_rcvd = 0;
8026 rpc_stat->queue_time_sum.sec = 0;
8027 rpc_stat->queue_time_sum.usec = 0;
8028 rpc_stat->queue_time_sum_sqr.sec = 0;
8029 rpc_stat->queue_time_sum_sqr.usec = 0;
8030 rpc_stat->queue_time_min.sec = 9999999;
8031 rpc_stat->queue_time_min.usec = 9999999;
8032 rpc_stat->queue_time_max.sec = 0;
8033 rpc_stat->queue_time_max.usec = 0;
8034 rpc_stat->execution_time_sum.sec = 0;
8035 rpc_stat->execution_time_sum.usec = 0;
8036 rpc_stat->execution_time_sum_sqr.sec = 0;
8037 rpc_stat->execution_time_sum_sqr.usec = 0;
8038 rpc_stat->execution_time_min.sec = 9999999;
8039 rpc_stat->execution_time_min.usec = 9999999;
8040 rpc_stat->execution_time_max.sec = 0;
8041 rpc_stat->execution_time_max.usec = 0;
8045 * Given all of the information for a particular rpc
8046 * call, find or create (if requested) the stat structure for the rpc.
8049 * the queue of stats that will be updated with the new value
8051 * @param rxInterface
8052 * a unique number that identifies the rpc interface
8055 * the total number of functions in this interface. this is only
8056 * required if create is true
8059 * if true, this invocation was made to a server
8062 * the ip address of the remote host. this is only required if create
8063 * and addToPeerList are true
8066 * the port of the remote host. this is only required if create
8067 * and addToPeerList are true
8069 * @param addToPeerList
8070 * if != 0, add newly created stat to the global peer list
8073 * if a new stats structure is allocated, the counter will
8074 * be updated with the new number of allocated stat structures.
8075 * only required if create is true
8078 * if no stats structure exists, allocate one
8082 static rx_interface_stat_p
8083 rxi_FindRpcStat(struct opr_queue *stats, afs_uint32 rxInterface,
8084 afs_uint32 totalFunc, int isServer, afs_uint32 remoteHost,
8085 afs_uint32 remotePort, int addToPeerList,
8086 unsigned int *counter, int create)
8088 rx_interface_stat_p rpc_stat = NULL;
8089 struct opr_queue *cursor;
8092 * See if there's already a structure for this interface
8095 for (opr_queue_Scan(stats, cursor)) {
8096 rpc_stat = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8098 if ((rpc_stat->stats[0].interfaceId == rxInterface)
8099 && (rpc_stat->stats[0].remote_is_server == isServer))
8103 /* if they didn't ask us to create, we're done */
8105 if (opr_queue_IsEnd(stats, cursor))
8111 /* can't proceed without these */
8112 if (!totalFunc || !counter)
8116 * Didn't find a match so allocate a new structure and add it to the
8120 if (opr_queue_IsEnd(stats, cursor) || (rpc_stat == NULL)
8121 || (rpc_stat->stats[0].interfaceId != rxInterface)
8122 || (rpc_stat->stats[0].remote_is_server != isServer)) {
8127 sizeof(rx_interface_stat_t) +
8128 totalFunc * sizeof(rx_function_entry_v1_t);
8130 rpc_stat = rxi_Alloc(space);
8131 if (rpc_stat == NULL)
8134 *counter += totalFunc;
8135 for (i = 0; i < totalFunc; i++) {
8136 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8137 rpc_stat->stats[i].remote_peer = remoteHost;
8138 rpc_stat->stats[i].remote_port = remotePort;
8139 rpc_stat->stats[i].remote_is_server = isServer;
8140 rpc_stat->stats[i].interfaceId = rxInterface;
8141 rpc_stat->stats[i].func_total = totalFunc;
8142 rpc_stat->stats[i].func_index = i;
8144 opr_queue_Prepend(stats, &rpc_stat->entry);
8145 if (addToPeerList) {
8146 opr_queue_Prepend(&peerStats, &rpc_stat->entryPeers);
8153 rx_ClearProcessRPCStats(afs_int32 rxInterface)
8155 rx_interface_stat_p rpc_stat;
8158 if (rxInterface == -1)
8161 MUTEX_ENTER(&rx_rpc_stats);
8162 rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8165 totalFunc = rpc_stat->stats[0].func_total;
8166 for (i = 0; i < totalFunc; i++)
8167 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8169 MUTEX_EXIT(&rx_rpc_stats);
8174 rx_ClearPeerRPCStats(afs_int32 rxInterface, afs_uint32 peerHost, afs_uint16 peerPort)
8176 rx_interface_stat_p rpc_stat;
8178 struct rx_peer * peer;
8180 if (rxInterface == -1)
8183 peer = rxi_FindPeer(peerHost, peerPort, 0);
8187 MUTEX_ENTER(&rx_rpc_stats);
8188 rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8191 totalFunc = rpc_stat->stats[0].func_total;
8192 for (i = 0; i < totalFunc; i++)
8193 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8195 MUTEX_EXIT(&rx_rpc_stats);
8200 rx_CopyProcessRPCStats(afs_uint64 op)
8202 rx_interface_stat_p rpc_stat;
8203 rx_function_entry_v1_p rpcop_stat =
8204 rxi_Alloc(sizeof(rx_function_entry_v1_t));
8205 int currentFunc = (op & MAX_AFS_UINT32);
8206 afs_int32 rxInterface = (op >> 32);
8208 if (!rxi_monitor_processStats)
8211 if (rxInterface == -1)
8214 if (rpcop_stat == NULL)
8217 MUTEX_ENTER(&rx_rpc_stats);
8218 rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8221 memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8222 sizeof(rx_function_entry_v1_t));
8223 MUTEX_EXIT(&rx_rpc_stats);
8225 rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8232 rx_CopyPeerRPCStats(afs_uint64 op, afs_uint32 peerHost, afs_uint16 peerPort)
8234 rx_interface_stat_p rpc_stat;
8235 rx_function_entry_v1_p rpcop_stat =
8236 rxi_Alloc(sizeof(rx_function_entry_v1_t));
8237 int currentFunc = (op & MAX_AFS_UINT32);
8238 afs_int32 rxInterface = (op >> 32);
8239 struct rx_peer *peer;
8241 if (!rxi_monitor_peerStats)
8244 if (rxInterface == -1)
8247 if (rpcop_stat == NULL)
8250 peer = rxi_FindPeer(peerHost, peerPort, 0);
8254 MUTEX_ENTER(&rx_rpc_stats);
8255 rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8258 memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8259 sizeof(rx_function_entry_v1_t));
8260 MUTEX_EXIT(&rx_rpc_stats);
8262 rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8269 rx_ReleaseRPCStats(void *stats)
8272 rxi_Free(stats, sizeof(rx_function_entry_v1_t));
8276 * Given all of the information for a particular rpc
8277 * call, create (if needed) and update the stat totals for the rpc.
8280 * the queue of stats that will be updated with the new value
8282 * @param rxInterface
8283 * a unique number that identifies the rpc interface
8285 * @param currentFunc
8286 * the index of the function being invoked
8289 * the total number of functions in this interface
8292 * the amount of time this function waited for a thread
8295 * the amount of time this function invocation took to execute
8298 * the number bytes sent by this invocation
8301 * the number bytes received by this invocation
8304 * if true, this invocation was made to a server
8307 * the ip address of the remote host
8310 * the port of the remote host
8312 * @param addToPeerList
8313 * if != 0, add newly created stat to the global peer list
8316 * if a new stats structure is allocated, the counter will
8317 * be updated with the new number of allocated stat structures
8322 rxi_AddRpcStat(struct opr_queue *stats, afs_uint32 rxInterface,
8323 afs_uint32 currentFunc, afs_uint32 totalFunc,
8324 struct clock *queueTime, struct clock *execTime,
8325 afs_uint64 bytesSent, afs_uint64 bytesRcvd, int isServer,
8326 afs_uint32 remoteHost, afs_uint32 remotePort,
8327 int addToPeerList, unsigned int *counter)
8330 rx_interface_stat_p rpc_stat;
8332 rpc_stat = rxi_FindRpcStat(stats, rxInterface, totalFunc, isServer,
8333 remoteHost, remotePort, addToPeerList, counter,
8341 * Increment the stats for this function
8344 rpc_stat->stats[currentFunc].invocations++;
8345 rpc_stat->stats[currentFunc].bytes_sent += bytesSent;
8346 rpc_stat->stats[currentFunc].bytes_rcvd += bytesRcvd;
8347 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8348 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8349 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8350 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8352 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8353 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8355 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8356 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8358 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8359 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8361 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8362 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8370 rxi_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8371 afs_uint32 currentFunc, afs_uint32 totalFunc,
8372 struct clock *queueTime, struct clock *execTime,
8373 afs_uint64 bytesSent, afs_uint64 bytesRcvd,
8377 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8380 MUTEX_ENTER(&rx_rpc_stats);
8382 if (rxi_monitor_peerStats) {
8383 MUTEX_ENTER(&peer->peer_lock);
8384 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8385 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8386 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8387 MUTEX_EXIT(&peer->peer_lock);
8390 if (rxi_monitor_processStats) {
8391 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8392 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8393 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8396 MUTEX_EXIT(&rx_rpc_stats);
8400 * Increment the times and count for a particular rpc function.
8402 * Traditionally this call was invoked from rxgen stubs. Modern stubs
8403 * call rx_RecordCallStatistics instead, so the public version of this
8404 * function is left purely for legacy callers.
8407 * The peer who invoked the rpc
8409 * @param rxInterface
8410 * A unique number that identifies the rpc interface
8412 * @param currentFunc
8413 * The index of the function being invoked
8416 * The total number of functions in this interface
8419 * The amount of time this function waited for a thread
8422 * The amount of time this function invocation took to execute
8425 * The number bytes sent by this invocation
8428 * The number bytes received by this invocation
8431 * If true, this invocation was made to a server
8435 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8436 afs_uint32 currentFunc, afs_uint32 totalFunc,
8437 struct clock *queueTime, struct clock *execTime,
8438 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8444 sent64 = ((afs_uint64)bytesSent->high << 32) + bytesSent->low;
8445 rcvd64 = ((afs_uint64)bytesRcvd->high << 32) + bytesRcvd->low;
8447 rxi_IncrementTimeAndCount(peer, rxInterface, currentFunc, totalFunc,
8448 queueTime, execTime, sent64, rcvd64,
8455 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8459 * IN callerVersion - the rpc stat version of the caller.
8461 * IN count - the number of entries to marshall.
8463 * IN stats - pointer to stats to be marshalled.
8465 * OUT ptr - Where to store the marshalled data.
8472 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8473 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8479 * We only support the first version
8481 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8482 *(ptr++) = stats->remote_peer;
8483 *(ptr++) = stats->remote_port;
8484 *(ptr++) = stats->remote_is_server;
8485 *(ptr++) = stats->interfaceId;
8486 *(ptr++) = stats->func_total;
8487 *(ptr++) = stats->func_index;
8488 *(ptr++) = stats->invocations >> 32;
8489 *(ptr++) = stats->invocations & MAX_AFS_UINT32;
8490 *(ptr++) = stats->bytes_sent >> 32;
8491 *(ptr++) = stats->bytes_sent & MAX_AFS_UINT32;
8492 *(ptr++) = stats->bytes_rcvd >> 32;
8493 *(ptr++) = stats->bytes_rcvd & MAX_AFS_UINT32;
8494 *(ptr++) = stats->queue_time_sum.sec;
8495 *(ptr++) = stats->queue_time_sum.usec;
8496 *(ptr++) = stats->queue_time_sum_sqr.sec;
8497 *(ptr++) = stats->queue_time_sum_sqr.usec;
8498 *(ptr++) = stats->queue_time_min.sec;
8499 *(ptr++) = stats->queue_time_min.usec;
8500 *(ptr++) = stats->queue_time_max.sec;
8501 *(ptr++) = stats->queue_time_max.usec;
8502 *(ptr++) = stats->execution_time_sum.sec;
8503 *(ptr++) = stats->execution_time_sum.usec;
8504 *(ptr++) = stats->execution_time_sum_sqr.sec;
8505 *(ptr++) = stats->execution_time_sum_sqr.usec;
8506 *(ptr++) = stats->execution_time_min.sec;
8507 *(ptr++) = stats->execution_time_min.usec;
8508 *(ptr++) = stats->execution_time_max.sec;
8509 *(ptr++) = stats->execution_time_max.usec;
8515 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8520 * IN callerVersion - the rpc stat version of the caller
8522 * OUT myVersion - the rpc stat version of this function
8524 * OUT clock_sec - local time seconds
8526 * OUT clock_usec - local time microseconds
8528 * OUT allocSize - the number of bytes allocated to contain stats
8530 * OUT statCount - the number stats retrieved from this process.
8532 * OUT stats - the actual stats retrieved from this process.
8536 * Returns void. If successful, stats will != NULL.
8540 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8541 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8542 size_t * allocSize, afs_uint32 * statCount,
8543 afs_uint32 ** stats)
8553 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8556 * Check to see if stats are enabled
8559 MUTEX_ENTER(&rx_rpc_stats);
8560 if (!rxi_monitor_processStats) {
8561 MUTEX_EXIT(&rx_rpc_stats);
8565 clock_GetTime(&now);
8566 *clock_sec = now.sec;
8567 *clock_usec = now.usec;
8570 * Allocate the space based upon the caller version
8572 * If the client is at an older version than we are,
8573 * we return the statistic data in the older data format, but
8574 * we still return our version number so the client knows we
8575 * are maintaining more data than it can retrieve.
8578 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8579 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8580 *statCount = rxi_rpc_process_stat_cnt;
8583 * This can't happen yet, but in the future version changes
8584 * can be handled by adding additional code here
8588 if (space > (size_t) 0) {
8590 ptr = *stats = rxi_Alloc(space);
8593 struct opr_queue *cursor;
8595 for (opr_queue_Scan(&processStats, cursor)) {
8596 struct rx_interface_stat *rpc_stat =
8597 opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8599 * Copy the data based upon the caller version
8601 rx_MarshallProcessRPCStats(callerVersion,
8602 rpc_stat->stats[0].func_total,
8603 rpc_stat->stats, &ptr);
8609 MUTEX_EXIT(&rx_rpc_stats);
8614 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8618 * IN callerVersion - the rpc stat version of the caller
8620 * OUT myVersion - the rpc stat version of this function
8622 * OUT clock_sec - local time seconds
8624 * OUT clock_usec - local time microseconds
8626 * OUT allocSize - the number of bytes allocated to contain stats
8628 * OUT statCount - the number of stats retrieved from the individual
8631 * OUT stats - the actual stats retrieved from the individual peer structures.
8635 * Returns void. If successful, stats will != NULL.
8639 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8640 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8641 size_t * allocSize, afs_uint32 * statCount,
8642 afs_uint32 ** stats)
8652 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8655 * Check to see if stats are enabled
8658 MUTEX_ENTER(&rx_rpc_stats);
8659 if (!rxi_monitor_peerStats) {
8660 MUTEX_EXIT(&rx_rpc_stats);
8664 clock_GetTime(&now);
8665 *clock_sec = now.sec;
8666 *clock_usec = now.usec;
8669 * Allocate the space based upon the caller version
8671 * If the client is at an older version than we are,
8672 * we return the statistic data in the older data format, but
8673 * we still return our version number so the client knows we
8674 * are maintaining more data than it can retrieve.
8677 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8678 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8679 *statCount = rxi_rpc_peer_stat_cnt;
8682 * This can't happen yet, but in the future version changes
8683 * can be handled by adding additional code here
8687 if (space > (size_t) 0) {
8689 ptr = *stats = rxi_Alloc(space);
8692 struct opr_queue *cursor;
8694 for (opr_queue_Scan(&peerStats, cursor)) {
8695 struct rx_interface_stat *rpc_stat
8696 = opr_queue_Entry(cursor, struct rx_interface_stat,
8700 * Copy the data based upon the caller version
8702 rx_MarshallProcessRPCStats(callerVersion,
8703 rpc_stat->stats[0].func_total,
8704 rpc_stat->stats, &ptr);
8710 MUTEX_EXIT(&rx_rpc_stats);
8715 * rx_FreeRPCStats - free memory allocated by
8716 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
8720 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
8721 * rx_RetrievePeerRPCStats
8723 * IN allocSize - the number of bytes in stats.
8731 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
8733 rxi_Free(stats, allocSize);
8737 * rx_queryProcessRPCStats - see if process rpc stat collection is
8738 * currently enabled.
8744 * Returns 0 if stats are not enabled != 0 otherwise
8748 rx_queryProcessRPCStats(void)
8751 MUTEX_ENTER(&rx_rpc_stats);
8752 rc = rxi_monitor_processStats;
8753 MUTEX_EXIT(&rx_rpc_stats);
8758 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
8764 * Returns 0 if stats are not enabled != 0 otherwise
8768 rx_queryPeerRPCStats(void)
8771 MUTEX_ENTER(&rx_rpc_stats);
8772 rc = rxi_monitor_peerStats;
8773 MUTEX_EXIT(&rx_rpc_stats);
8778 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
8788 rx_enableProcessRPCStats(void)
8790 MUTEX_ENTER(&rx_rpc_stats);
8791 rx_enable_stats = 1;
8792 rxi_monitor_processStats = 1;
8793 MUTEX_EXIT(&rx_rpc_stats);
8797 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
8807 rx_enablePeerRPCStats(void)
8809 MUTEX_ENTER(&rx_rpc_stats);
8810 rx_enable_stats = 1;
8811 rxi_monitor_peerStats = 1;
8812 MUTEX_EXIT(&rx_rpc_stats);
8816 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
8826 rx_disableProcessRPCStats(void)
8828 struct opr_queue *cursor, *store;
8831 MUTEX_ENTER(&rx_rpc_stats);
8834 * Turn off process statistics and if peer stats is also off, turn
8838 rxi_monitor_processStats = 0;
8839 if (rxi_monitor_peerStats == 0) {
8840 rx_enable_stats = 0;
8843 for (opr_queue_ScanSafe(&processStats, cursor, store)) {
8844 unsigned int num_funcs = 0;
8845 struct rx_interface_stat *rpc_stat
8846 = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8848 opr_queue_Remove(&rpc_stat->entry);
8850 num_funcs = rpc_stat->stats[0].func_total;
8852 sizeof(rx_interface_stat_t) +
8853 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
8855 rxi_Free(rpc_stat, space);
8856 rxi_rpc_process_stat_cnt -= num_funcs;
8858 MUTEX_EXIT(&rx_rpc_stats);
8862 * rx_disablePeerRPCStats - stop rpc stat collection for peers
8872 rx_disablePeerRPCStats(void)
8874 struct rx_peer **peer_ptr, **peer_end;
8878 * Turn off peer statistics and if process stats is also off, turn
8882 rxi_monitor_peerStats = 0;
8883 if (rxi_monitor_processStats == 0) {
8884 rx_enable_stats = 0;
8887 for (peer_ptr = &rx_peerHashTable[0], peer_end =
8888 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
8890 struct rx_peer *peer, *next, *prev;
8892 MUTEX_ENTER(&rx_peerHashTable_lock);
8893 MUTEX_ENTER(&rx_rpc_stats);
8894 for (prev = peer = *peer_ptr; peer; peer = next) {
8896 code = MUTEX_TRYENTER(&peer->peer_lock);
8899 struct opr_queue *cursor, *store;
8901 if (prev == *peer_ptr) {
8912 MUTEX_EXIT(&rx_peerHashTable_lock);
8914 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
8915 unsigned int num_funcs = 0;
8916 struct rx_interface_stat *rpc_stat
8917 = opr_queue_Entry(cursor, struct rx_interface_stat,
8920 opr_queue_Remove(&rpc_stat->entry);
8921 opr_queue_Remove(&rpc_stat->entryPeers);
8922 num_funcs = rpc_stat->stats[0].func_total;
8924 sizeof(rx_interface_stat_t) +
8925 rpc_stat->stats[0].func_total *
8926 sizeof(rx_function_entry_v1_t);
8928 rxi_Free(rpc_stat, space);
8929 rxi_rpc_peer_stat_cnt -= num_funcs;
8931 MUTEX_EXIT(&peer->peer_lock);
8933 MUTEX_ENTER(&rx_peerHashTable_lock);
8943 MUTEX_EXIT(&rx_rpc_stats);
8944 MUTEX_EXIT(&rx_peerHashTable_lock);
8949 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
8954 * IN clearFlag - flag indicating which stats to clear
8962 rx_clearProcessRPCStats(afs_uint32 clearFlag)
8964 struct opr_queue *cursor;
8966 MUTEX_ENTER(&rx_rpc_stats);
8968 for (opr_queue_Scan(&processStats, cursor)) {
8969 unsigned int num_funcs = 0, i;
8970 struct rx_interface_stat *rpc_stat
8971 = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8973 num_funcs = rpc_stat->stats[0].func_total;
8974 for (i = 0; i < num_funcs; i++) {
8975 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
8976 rpc_stat->stats[i].invocations = 0;
8978 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
8979 rpc_stat->stats[i].bytes_sent = 0;
8981 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
8982 rpc_stat->stats[i].bytes_rcvd = 0;
8984 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
8985 rpc_stat->stats[i].queue_time_sum.sec = 0;
8986 rpc_stat->stats[i].queue_time_sum.usec = 0;
8988 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
8989 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
8990 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
8992 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
8993 rpc_stat->stats[i].queue_time_min.sec = 9999999;
8994 rpc_stat->stats[i].queue_time_min.usec = 9999999;
8996 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
8997 rpc_stat->stats[i].queue_time_max.sec = 0;
8998 rpc_stat->stats[i].queue_time_max.usec = 0;
9000 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9001 rpc_stat->stats[i].execution_time_sum.sec = 0;
9002 rpc_stat->stats[i].execution_time_sum.usec = 0;
9004 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9005 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9006 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9008 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9009 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9010 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9012 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9013 rpc_stat->stats[i].execution_time_max.sec = 0;
9014 rpc_stat->stats[i].execution_time_max.usec = 0;
9019 MUTEX_EXIT(&rx_rpc_stats);
9023 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
9028 * IN clearFlag - flag indicating which stats to clear
9036 rx_clearPeerRPCStats(afs_uint32 clearFlag)
9038 struct opr_queue *cursor;
9040 MUTEX_ENTER(&rx_rpc_stats);
9042 for (opr_queue_Scan(&peerStats, cursor)) {
9043 unsigned int num_funcs, i;
9044 struct rx_interface_stat *rpc_stat
9045 = opr_queue_Entry(cursor, struct rx_interface_stat, entryPeers);
9047 num_funcs = rpc_stat->stats[0].func_total;
9048 for (i = 0; i < num_funcs; i++) {
9049 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9050 rpc_stat->stats[i].invocations = 0;
9052 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9053 rpc_stat->stats[i].bytes_sent = 0;
9055 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9056 rpc_stat->stats[i].bytes_rcvd = 0;
9058 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9059 rpc_stat->stats[i].queue_time_sum.sec = 0;
9060 rpc_stat->stats[i].queue_time_sum.usec = 0;
9062 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9063 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9064 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9066 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9067 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9068 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9070 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9071 rpc_stat->stats[i].queue_time_max.sec = 0;
9072 rpc_stat->stats[i].queue_time_max.usec = 0;
9074 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9075 rpc_stat->stats[i].execution_time_sum.sec = 0;
9076 rpc_stat->stats[i].execution_time_sum.usec = 0;
9078 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9079 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9080 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9082 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9083 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9084 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9086 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9087 rpc_stat->stats[i].execution_time_max.sec = 0;
9088 rpc_stat->stats[i].execution_time_max.usec = 0;
9093 MUTEX_EXIT(&rx_rpc_stats);
9097 * rxi_rxstat_userok points to a routine that returns 1 if the caller
9098 * is authorized to enable/disable/clear RX statistics.
9100 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
9103 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
9105 rxi_rxstat_userok = proc;
9109 rx_RxStatUserOk(struct rx_call *call)
9111 if (!rxi_rxstat_userok)
9113 return rxi_rxstat_userok(call);
9118 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
9119 * function in the MSVC runtime DLL (msvcrt.dll).
9121 * Note: the system serializes calls to this function.
9124 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
9125 DWORD reason, /* reason function is being called */
9126 LPVOID reserved) /* reserved for future use */
9129 case DLL_PROCESS_ATTACH:
9130 /* library is being attached to a process */
9134 case DLL_PROCESS_DETACH:
9141 #endif /* AFS_NT40_ENV */
9144 int rx_DumpCalls(FILE *outputFile, char *cookie)
9146 #ifdef RXDEBUG_PACKET
9147 #ifdef KDUMP_RX_LOCK
9148 struct rx_call_rx_lock *c;
9155 #define RXDPRINTF sprintf
9156 #define RXDPRINTOUT output
9158 #define RXDPRINTF fprintf
9159 #define RXDPRINTOUT outputFile
9162 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
9164 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9167 for (c = rx_allCallsp; c; c = c->allNextp) {
9168 u_short rqc, tqc, iovqc;
9170 MUTEX_ENTER(&c->lock);
9171 rqc = opr_queue_Count(&c->rq);
9172 tqc = opr_queue_Count(&c->tq);
9173 iovqc = opr_queue_Count(&c->app.iovq);
9175 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, "
9176 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
9177 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
9178 "resendEvent=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
9179 "lastSendTime=%u, lastRecvTime=%u"
9180 #ifdef RX_ENABLE_LOCKS
9183 #ifdef RX_REFCOUNT_CHECK
9184 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
9185 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
9188 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,
9189 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
9190 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
9191 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
9192 c->resendEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
9193 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime
9194 #ifdef RX_ENABLE_LOCKS
9195 , (afs_uint32)c->refCount
9197 #ifdef RX_REFCOUNT_CHECK
9198 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
9201 MUTEX_EXIT(&c->lock);
9204 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9207 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
9209 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9211 #endif /* RXDEBUG_PACKET */