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 MUTEX_INIT(&rx_mallocedPktQ_lock, "rx_mallocedPktQ_lock", MUTEX_DEFAULT,
300 #ifdef RX_ENABLE_LOCKS
303 #endif /* RX_LOCKS_DB */
304 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
305 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
307 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
309 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
311 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
313 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
315 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
317 #endif /* RX_ENABLE_LOCKS */
320 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
321 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
323 * The rx_stats_mutex mutex protects the following global variables:
324 * rxi_lowConnRefCount
325 * rxi_lowPeerRefCount
334 * The rx_quota_mutex mutex protects the following global variables:
342 * The rx_freePktQ_lock protects the following global variables:
347 * The rx_packets_mutex mutex protects the following global variables:
355 * The rx_pthread_mutex mutex protects the following global variables:
356 * rxi_fcfs_thread_num
359 #define INIT_PTHREAD_LOCKS
363 /* Variables for handling the minProcs implementation. availProcs gives the
364 * number of threads available in the pool at this moment (not counting dudes
365 * executing right now). totalMin gives the total number of procs required
366 * for handling all minProcs requests. minDeficit is a dynamic variable
367 * tracking the # of procs required to satisfy all of the remaining minProcs
369 * For fine grain locking to work, the quota check and the reservation of
370 * a server thread has to come while rxi_availProcs and rxi_minDeficit
371 * are locked. To this end, the code has been modified under #ifdef
372 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
373 * same time. A new function, ReturnToServerPool() returns the allocation.
375 * A call can be on several queue's (but only one at a time). When
376 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
377 * that no one else is touching the queue. To this end, we store the address
378 * of the queue lock in the call structure (under the call lock) when we
379 * put the call on a queue, and we clear the call_queue_lock when the
380 * call is removed from a queue (once the call lock has been obtained).
381 * This allows rxi_ResetCall to safely synchronize with others wishing
382 * to manipulate the queue.
385 #if defined(RX_ENABLE_LOCKS)
386 static afs_kmutex_t rx_rpc_stats;
389 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
390 ** pretty good that the next packet coming in is from the same connection
391 ** as the last packet, since we're send multiple packets in a transmit window.
393 struct rx_connection *rxLastConn = 0;
395 #ifdef RX_ENABLE_LOCKS
396 /* The locking hierarchy for rx fine grain locking is composed of these
399 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
400 * also protects updates to rx_nextCid
401 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
402 * call->lock - locks call data fields.
403 * These are independent of each other:
404 * rx_freeCallQueue_lock
409 * serverQueueEntry->lock
410 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
412 * peer->lock - locks peer data fields.
413 * conn_data_lock - that more than one thread is not updating a conn data
414 * field at the same time.
425 * Do we need a lock to protect the peer field in the conn structure?
426 * conn->peer was previously a constant for all intents and so has no
427 * lock protecting this field. The multihomed client delta introduced
428 * a RX code change : change the peer field in the connection structure
429 * to that remote interface from which the last packet for this
430 * connection was sent out. This may become an issue if further changes
433 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
434 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
436 /* rxdb_fileID is used to identify the lock location, along with line#. */
437 static int rxdb_fileID = RXDB_FILE_RX;
438 #endif /* RX_LOCKS_DB */
439 #else /* RX_ENABLE_LOCKS */
440 #define SET_CALL_QUEUE_LOCK(C, L)
441 #define CLEAR_CALL_QUEUE_LOCK(C)
442 #endif /* RX_ENABLE_LOCKS */
443 struct rx_serverQueueEntry *rx_waitForPacket = 0;
445 /* ------------Exported Interfaces------------- */
447 /* Initialize rx. A port number may be mentioned, in which case this
448 * becomes the default port number for any service installed later.
449 * If 0 is provided for the port number, a random port will be chosen
450 * by the kernel. Whether this will ever overlap anything in
451 * /etc/services is anybody's guess... Returns 0 on success, -1 on
453 #if !(defined(AFS_NT40_ENV) || defined(RXK_UPCALL_ENV))
456 rx_atomic_t rxinit_status = RX_ATOMIC_INIT(1);
459 rx_InitHost(u_int host, u_int port)
466 char *htable, *ptable;
471 if (!rx_atomic_test_and_clear_bit(&rxinit_status, 0))
472 return 0; /* already started */
478 if (afs_winsockInit() < 0)
484 * Initialize anything necessary to provide a non-premptive threading
487 rxi_InitializeThreadSupport();
490 /* Allocate and initialize a socket for client and perhaps server
493 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
494 if (rx_socket == OSI_NULLSOCKET) {
497 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
500 #endif /* RX_LOCKS_DB */
501 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
502 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
503 MUTEX_INIT(&rx_atomic_mutex, "rx_atomic_mutex", MUTEX_DEFAULT, 0);
504 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
505 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
506 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
507 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
508 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
509 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
510 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
512 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
514 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
516 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
518 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
519 MUTEX_INIT(&rx_mallocedPktQ_lock, "rx_mallocedPktQ_lock", MUTEX_DEFAULT,
522 #if defined(AFS_HPUX110_ENV)
524 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
525 #endif /* AFS_HPUX110_ENV */
526 #endif /* RX_ENABLE_LOCKS && KERNEL */
529 rx_connDeadTime = 12;
530 rx_tranquil = 0; /* reset flag */
531 rxi_ResetStatistics();
532 htable = osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
533 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
534 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
535 ptable = osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
536 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
537 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
539 /* Malloc up a bunch of packets & buffers */
541 opr_queue_Init(&rx_freePacketQueue);
542 rxi_NeedMorePackets = FALSE;
543 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
544 opr_queue_Init(&rx_mallocedPacketQueue);
546 /* enforce a minimum number of allocated packets */
547 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
548 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
550 /* allocate the initial free packet pool */
551 #ifdef RX_ENABLE_TSFPQ
552 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
553 #else /* RX_ENABLE_TSFPQ */
554 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
555 #endif /* RX_ENABLE_TSFPQ */
562 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
563 tv.tv_sec = clock_now.sec;
564 tv.tv_usec = clock_now.usec;
565 srand((unsigned int)tv.tv_usec);
572 #if defined(KERNEL) && !defined(UKERNEL)
573 /* Really, this should never happen in a real kernel */
576 struct sockaddr_in addr;
578 int addrlen = sizeof(addr);
580 socklen_t addrlen = sizeof(addr);
582 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
584 osi_Free(htable, rx_hashTableSize * sizeof(struct rx_connection *));
587 rx_port = addr.sin_port;
590 rx_stats.minRtt.sec = 9999999;
591 if (RAND_bytes(&rx_epoch, sizeof(rx_epoch)) != 1)
593 rx_epoch = (rx_epoch & ~0x40000000) | 0x80000000;
594 if (RAND_bytes(&rx_nextCid, sizeof(rx_nextCid)) != 1)
596 rx_nextCid &= RX_CIDMASK;
597 MUTEX_ENTER(&rx_quota_mutex);
598 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
599 MUTEX_EXIT(&rx_quota_mutex);
600 /* *Slightly* random start time for the cid. This is just to help
601 * out with the hashing function at the peer */
602 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
603 rx_connHashTable = (struct rx_connection **)htable;
604 rx_peerHashTable = (struct rx_peer **)ptable;
606 rx_hardAckDelay.sec = 0;
607 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
609 rxevent_Init(20, rxi_ReScheduleEvents);
611 /* Initialize various global queues */
612 opr_queue_Init(&rx_idleServerQueue);
613 opr_queue_Init(&rx_incomingCallQueue);
614 opr_queue_Init(&rx_freeCallQueue);
616 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
617 /* Initialize our list of usable IP addresses. */
621 /* Start listener process (exact function is dependent on the
622 * implementation environment--kernel or user space) */
626 rx_atomic_clear_bit(&rxinit_status, 0);
633 return rx_InitHost(htonl(INADDR_ANY), port);
639 * The rxi_rto functions implement a TCP (RFC2988) style algorithm for
640 * maintaing the round trip timer.
645 * Start a new RTT timer for a given call and packet.
647 * There must be no resendEvent already listed for this call, otherwise this
648 * will leak events - intended for internal use within the RTO code only
651 * the RX call to start the timer for
652 * @param[in] lastPacket
653 * a flag indicating whether the last packet has been sent or not
655 * @pre call must be locked before calling this function
659 rxi_rto_startTimer(struct rx_call *call, int lastPacket, int istack)
661 struct clock now, retryTime;
666 clock_Add(&retryTime, &call->rto);
668 /* If we're sending the last packet, and we're the client, then the server
669 * may wait for an additional 400ms before returning the ACK, wait for it
670 * rather than hitting a timeout */
671 if (lastPacket && call->conn->type == RX_CLIENT_CONNECTION)
672 clock_Addmsec(&retryTime, 400);
674 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
675 call->resendEvent = rxevent_Post(&retryTime, &now, rxi_Resend,
680 * Cancel an RTT timer for a given call.
684 * the RX call to cancel the timer for
686 * @pre call must be locked before calling this function
691 rxi_rto_cancel(struct rx_call *call)
693 if (rxevent_Cancel(&call->resendEvent))
694 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
698 * Tell the RTO timer that we have sent a packet.
700 * If the timer isn't already running, then start it. If the timer is running,
704 * the RX call that the packet has been sent on
705 * @param[in] lastPacket
706 * A flag which is true if this is the last packet for the call
708 * @pre The call must be locked before calling this function
713 rxi_rto_packet_sent(struct rx_call *call, int lastPacket, int istack)
715 if (call->resendEvent)
718 rxi_rto_startTimer(call, lastPacket, istack);
722 * Tell the RTO timer that we have received an new ACK message
724 * This function should be called whenever a call receives an ACK that
725 * acknowledges new packets. Whatever happens, we stop the current timer.
726 * If there are unacked packets in the queue which have been sent, then
727 * we restart the timer from now. Otherwise, we leave it stopped.
730 * the RX call that the ACK has been received on
734 rxi_rto_packet_acked(struct rx_call *call, int istack)
736 struct opr_queue *cursor;
738 rxi_rto_cancel(call);
740 if (opr_queue_IsEmpty(&call->tq))
743 for (opr_queue_Scan(&call->tq, cursor)) {
744 struct rx_packet *p = opr_queue_Entry(cursor, struct rx_packet, entry);
745 if (p->header.seq > call->tfirst + call->twind)
748 if (!(p->flags & RX_PKTFLAG_ACKED) && p->flags & RX_PKTFLAG_SENT) {
749 rxi_rto_startTimer(call, p->header.flags & RX_LAST_PACKET, istack);
757 * Set an initial round trip timeout for a peer connection
759 * @param[in] secs The timeout to set in seconds
763 rx_rto_setPeerTimeoutSecs(struct rx_peer *peer, int secs) {
764 peer->rtt = secs * 8000;
768 * Set a delayed ack event on the specified call for the given time
770 * @param[in] call - the call on which to set the event
771 * @param[in] offset - the delay from now after which the event fires
774 rxi_PostDelayedAckEvent(struct rx_call *call, struct clock *offset)
776 struct clock now, when;
780 clock_Add(&when, offset);
782 if (clock_Gt(&call->delayedAckTime, &when) &&
783 rxevent_Cancel(&call->delayedAckEvent)) {
784 /* We successfully cancelled an event too far in the future to install
785 * our new one; we can reuse the reference on the call. */
786 call->delayedAckEvent = rxevent_Post(&when, &now, rxi_SendDelayedAck,
789 call->delayedAckTime = when;
790 } else if (call->delayedAckEvent == NULL) {
791 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
792 call->delayedAckEvent = rxevent_Post(&when, &now,
795 call->delayedAckTime = when;
800 rxi_CancelDelayedAckEvent(struct rx_call *call)
802 /* Only drop the ref if we cancelled it before it could run. */
803 if (rxevent_Cancel(&call->delayedAckEvent))
804 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
807 /* called with unincremented nRequestsRunning to see if it is OK to start
808 * a new thread in this service. Could be "no" for two reasons: over the
809 * max quota, or would prevent others from reaching their min quota.
811 #ifdef RX_ENABLE_LOCKS
812 /* This verion of QuotaOK reserves quota if it's ok while the
813 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
816 QuotaOK(struct rx_service *aservice)
818 /* check if over max quota */
819 if (aservice->nRequestsRunning >= aservice->maxProcs) {
823 /* under min quota, we're OK */
824 /* otherwise, can use only if there are enough to allow everyone
825 * to go to their min quota after this guy starts.
828 MUTEX_ENTER(&rx_quota_mutex);
829 if ((aservice->nRequestsRunning < aservice->minProcs)
830 || (rxi_availProcs > rxi_minDeficit)) {
831 aservice->nRequestsRunning++;
832 /* just started call in minProcs pool, need fewer to maintain
834 if (aservice->nRequestsRunning <= aservice->minProcs)
837 MUTEX_EXIT(&rx_quota_mutex);
840 MUTEX_EXIT(&rx_quota_mutex);
846 ReturnToServerPool(struct rx_service *aservice)
848 aservice->nRequestsRunning--;
849 MUTEX_ENTER(&rx_quota_mutex);
850 if (aservice->nRequestsRunning < aservice->minProcs)
853 MUTEX_EXIT(&rx_quota_mutex);
856 #else /* RX_ENABLE_LOCKS */
858 QuotaOK(struct rx_service *aservice)
861 /* under min quota, we're OK */
862 if (aservice->nRequestsRunning < aservice->minProcs)
865 /* check if over max quota */
866 if (aservice->nRequestsRunning >= aservice->maxProcs)
869 /* otherwise, can use only if there are enough to allow everyone
870 * to go to their min quota after this guy starts.
872 MUTEX_ENTER(&rx_quota_mutex);
873 if (rxi_availProcs > rxi_minDeficit)
875 MUTEX_EXIT(&rx_quota_mutex);
878 #endif /* RX_ENABLE_LOCKS */
881 /* Called by rx_StartServer to start up lwp's to service calls.
882 NExistingProcs gives the number of procs already existing, and which
883 therefore needn't be created. */
885 rxi_StartServerProcs(int nExistingProcs)
887 struct rx_service *service;
892 /* For each service, reserve N processes, where N is the "minimum"
893 * number of processes that MUST be able to execute a request in parallel,
894 * at any time, for that process. Also compute the maximum difference
895 * between any service's maximum number of processes that can run
896 * (i.e. the maximum number that ever will be run, and a guarantee
897 * that this number will run if other services aren't running), and its
898 * minimum number. The result is the extra number of processes that
899 * we need in order to provide the latter guarantee */
900 for (i = 0; i < RX_MAX_SERVICES; i++) {
902 service = rx_services[i];
903 if (service == (struct rx_service *)0)
905 nProcs += service->minProcs;
906 diff = service->maxProcs - service->minProcs;
910 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
911 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
912 for (i = 0; i < nProcs; i++) {
913 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
919 /* This routine is only required on Windows */
921 rx_StartClientThread(void)
923 #ifdef AFS_PTHREAD_ENV
925 pid = pthread_self();
926 #endif /* AFS_PTHREAD_ENV */
928 #endif /* AFS_NT40_ENV */
930 /* This routine must be called if any services are exported. If the
931 * donateMe flag is set, the calling process is donated to the server
934 rx_StartServer(int donateMe)
936 struct rx_service *service;
942 /* Start server processes, if necessary (exact function is dependent
943 * on the implementation environment--kernel or user space). DonateMe
944 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
945 * case, one less new proc will be created rx_StartServerProcs.
947 rxi_StartServerProcs(donateMe);
949 /* count up the # of threads in minProcs, and add set the min deficit to
950 * be that value, too.
952 for (i = 0; i < RX_MAX_SERVICES; i++) {
953 service = rx_services[i];
954 if (service == (struct rx_service *)0)
956 MUTEX_ENTER(&rx_quota_mutex);
957 rxi_totalMin += service->minProcs;
958 /* below works even if a thread is running, since minDeficit would
959 * still have been decremented and later re-incremented.
961 rxi_minDeficit += service->minProcs;
962 MUTEX_EXIT(&rx_quota_mutex);
965 /* Turn on reaping of idle server connections */
966 rxi_ReapConnections(NULL, NULL, NULL, 0);
975 #ifdef AFS_PTHREAD_ENV
977 pid = afs_pointer_to_int(pthread_self());
978 #else /* AFS_PTHREAD_ENV */
980 LWP_CurrentProcess(&pid);
981 #endif /* AFS_PTHREAD_ENV */
983 sprintf(name, "srv_%d", ++nProcs);
985 (*registerProgram) (pid, name);
987 #endif /* AFS_NT40_ENV */
988 rx_ServerProc(NULL); /* Never returns */
990 #ifdef RX_ENABLE_TSFPQ
991 /* no use leaving packets around in this thread's local queue if
992 * it isn't getting donated to the server thread pool.
994 rxi_FlushLocalPacketsTSFPQ();
995 #endif /* RX_ENABLE_TSFPQ */
999 /* Create a new client connection to the specified service, using the
1000 * specified security object to implement the security model for this
1002 struct rx_connection *
1003 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
1004 struct rx_securityClass *securityObject,
1005 int serviceSecurityIndex)
1008 struct rx_connection *conn;
1013 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
1014 "serviceSecurityIndex %d)\n",
1015 ntohl(shost), ntohs(sport), sservice, securityObject,
1016 serviceSecurityIndex));
1018 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
1019 * the case of kmem_alloc? */
1020 conn = rxi_AllocConnection();
1021 #ifdef RX_ENABLE_LOCKS
1022 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
1023 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
1024 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
1027 MUTEX_ENTER(&rx_connHashTable_lock);
1028 conn->type = RX_CLIENT_CONNECTION;
1029 conn->epoch = rx_epoch;
1030 conn->cid = rx_nextCid;
1032 conn->peer = rxi_FindPeer(shost, sport, 1);
1033 conn->serviceId = sservice;
1034 conn->securityObject = securityObject;
1035 conn->securityData = (void *) 0;
1036 conn->securityIndex = serviceSecurityIndex;
1037 rx_SetConnDeadTime(conn, rx_connDeadTime);
1038 rx_SetConnSecondsUntilNatPing(conn, 0);
1039 conn->ackRate = RX_FAST_ACK_RATE;
1040 conn->nSpecific = 0;
1041 conn->specific = NULL;
1042 conn->challengeEvent = NULL;
1043 conn->delayedAbortEvent = NULL;
1044 conn->abortCount = 0;
1046 for (i = 0; i < RX_MAXCALLS; i++) {
1047 conn->twind[i] = rx_initSendWindow;
1048 conn->rwind[i] = rx_initReceiveWindow;
1049 conn->lastBusy[i] = 0;
1052 RXS_NewConnection(securityObject, conn);
1054 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
1056 conn->refCount++; /* no lock required since only this thread knows... */
1057 conn->next = rx_connHashTable[hashindex];
1058 rx_connHashTable[hashindex] = conn;
1059 if (rx_stats_active)
1060 rx_atomic_inc(&rx_stats.nClientConns);
1061 MUTEX_EXIT(&rx_connHashTable_lock);
1067 * Ensure a connection's timeout values are valid.
1069 * @param[in] conn The connection to check
1071 * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
1072 * unless idleDeadTime and/or hardDeadTime are not set
1076 rxi_CheckConnTimeouts(struct rx_connection *conn)
1078 /* a connection's timeouts must have the relationship
1079 * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
1080 * total loss of network to a peer may cause an idle timeout instead of a
1081 * dead timeout, simply because the idle timeout gets hit first. Also set
1082 * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
1083 /* this logic is slightly complicated by the fact that
1084 * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
1086 conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
1087 if (conn->idleDeadTime) {
1088 conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
1090 if (conn->hardDeadTime) {
1091 if (conn->idleDeadTime) {
1092 conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
1094 conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
1100 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
1102 /* The idea is to set the dead time to a value that allows several
1103 * keepalives to be dropped without timing out the connection. */
1104 conn->secondsUntilDead = seconds;
1105 rxi_CheckConnTimeouts(conn);
1106 conn->secondsUntilPing = conn->secondsUntilDead / 6;
1110 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
1112 conn->hardDeadTime = seconds;
1113 rxi_CheckConnTimeouts(conn);
1117 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
1119 conn->idleDeadTime = seconds;
1120 rxi_CheckConnTimeouts(conn);
1123 int rxi_lowPeerRefCount = 0;
1124 int rxi_lowConnRefCount = 0;
1127 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
1128 * NOTE: must not be called with rx_connHashTable_lock held.
1131 rxi_CleanupConnection(struct rx_connection *conn)
1133 /* Notify the service exporter, if requested, that this connection
1134 * is being destroyed */
1135 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
1136 (*conn->service->destroyConnProc) (conn);
1138 /* Notify the security module that this connection is being destroyed */
1139 RXS_DestroyConnection(conn->securityObject, conn);
1141 /* If this is the last connection using the rx_peer struct, set its
1142 * idle time to now. rxi_ReapConnections will reap it if it's still
1143 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
1145 MUTEX_ENTER(&rx_peerHashTable_lock);
1146 if (conn->peer->refCount < 2) {
1147 conn->peer->idleWhen = clock_Sec();
1148 if (conn->peer->refCount < 1) {
1149 conn->peer->refCount = 1;
1150 if (rx_stats_active) {
1151 MUTEX_ENTER(&rx_stats_mutex);
1152 rxi_lowPeerRefCount++;
1153 MUTEX_EXIT(&rx_stats_mutex);
1157 conn->peer->refCount--;
1158 MUTEX_EXIT(&rx_peerHashTable_lock);
1160 if (rx_stats_active)
1162 if (conn->type == RX_SERVER_CONNECTION)
1163 rx_atomic_dec(&rx_stats.nServerConns);
1165 rx_atomic_dec(&rx_stats.nClientConns);
1168 if (conn->specific) {
1170 for (i = 0; i < conn->nSpecific; i++) {
1171 if (conn->specific[i] && rxi_keyCreate_destructor[i])
1172 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
1173 conn->specific[i] = NULL;
1175 free(conn->specific);
1177 conn->specific = NULL;
1178 conn->nSpecific = 0;
1179 #endif /* !KERNEL */
1181 MUTEX_DESTROY(&conn->conn_call_lock);
1182 MUTEX_DESTROY(&conn->conn_data_lock);
1183 CV_DESTROY(&conn->conn_call_cv);
1185 rxi_FreeConnection(conn);
1188 /* Destroy the specified connection */
1190 rxi_DestroyConnection(struct rx_connection *conn)
1192 MUTEX_ENTER(&rx_connHashTable_lock);
1193 rxi_DestroyConnectionNoLock(conn);
1194 /* conn should be at the head of the cleanup list */
1195 if (conn == rx_connCleanup_list) {
1196 rx_connCleanup_list = rx_connCleanup_list->next;
1197 MUTEX_EXIT(&rx_connHashTable_lock);
1198 rxi_CleanupConnection(conn);
1200 #ifdef RX_ENABLE_LOCKS
1202 MUTEX_EXIT(&rx_connHashTable_lock);
1204 #endif /* RX_ENABLE_LOCKS */
1208 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1210 struct rx_connection **conn_ptr;
1218 MUTEX_ENTER(&conn->conn_data_lock);
1219 MUTEX_ENTER(&rx_refcnt_mutex);
1220 if (conn->refCount > 0)
1223 #ifdef RX_REFCOUNT_CHECK
1224 osi_Assert(conn->refCount == 0);
1226 if (rx_stats_active) {
1227 MUTEX_ENTER(&rx_stats_mutex);
1228 rxi_lowConnRefCount++;
1229 MUTEX_EXIT(&rx_stats_mutex);
1233 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1234 /* Busy; wait till the last guy before proceeding */
1235 MUTEX_EXIT(&rx_refcnt_mutex);
1236 MUTEX_EXIT(&conn->conn_data_lock);
1241 /* If the client previously called rx_NewCall, but it is still
1242 * waiting, treat this as a running call, and wait to destroy the
1243 * connection later when the call completes. */
1244 if ((conn->type == RX_CLIENT_CONNECTION)
1245 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1246 conn->flags |= RX_CONN_DESTROY_ME;
1247 MUTEX_EXIT(&conn->conn_data_lock);
1251 MUTEX_EXIT(&rx_refcnt_mutex);
1252 MUTEX_EXIT(&conn->conn_data_lock);
1254 /* Check for extant references to this connection */
1255 MUTEX_ENTER(&conn->conn_call_lock);
1256 for (i = 0; i < RX_MAXCALLS; i++) {
1257 struct rx_call *call = conn->call[i];
1260 if (conn->type == RX_CLIENT_CONNECTION) {
1261 MUTEX_ENTER(&call->lock);
1262 if (call->delayedAckEvent) {
1263 /* Push the final acknowledgment out now--there
1264 * won't be a subsequent call to acknowledge the
1265 * last reply packets */
1266 rxi_CancelDelayedAckEvent(call);
1267 if (call->state == RX_STATE_PRECALL
1268 || call->state == RX_STATE_ACTIVE) {
1269 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1274 MUTEX_EXIT(&call->lock);
1278 MUTEX_EXIT(&conn->conn_call_lock);
1280 #ifdef RX_ENABLE_LOCKS
1282 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1283 MUTEX_EXIT(&conn->conn_data_lock);
1285 /* Someone is accessing a packet right now. */
1289 #endif /* RX_ENABLE_LOCKS */
1292 /* Don't destroy the connection if there are any call
1293 * structures still in use */
1294 MUTEX_ENTER(&conn->conn_data_lock);
1295 conn->flags |= RX_CONN_DESTROY_ME;
1296 MUTEX_EXIT(&conn->conn_data_lock);
1301 /* Remove from connection hash table before proceeding */
1303 &rx_connHashTable[CONN_HASH
1304 (peer->host, peer->port, conn->cid, conn->epoch,
1306 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1307 if (*conn_ptr == conn) {
1308 *conn_ptr = conn->next;
1312 /* if the conn that we are destroying was the last connection, then we
1313 * clear rxLastConn as well */
1314 if (rxLastConn == conn)
1317 /* Make sure the connection is completely reset before deleting it. */
1319 * Pending events hold a refcount, so we can't get here if they are
1321 osi_Assert(conn->challengeEvent == NULL);
1322 osi_Assert(conn->delayedAbortEvent == NULL);
1323 osi_Assert(conn->natKeepAliveEvent == NULL);
1324 osi_Assert(conn->checkReachEvent == NULL);
1326 /* Add the connection to the list of destroyed connections that
1327 * need to be cleaned up. This is necessary to avoid deadlocks
1328 * in the routines we call to inform others that this connection is
1329 * being destroyed. */
1330 conn->next = rx_connCleanup_list;
1331 rx_connCleanup_list = conn;
1334 /* Externally available version */
1336 rx_DestroyConnection(struct rx_connection *conn)
1341 rxi_DestroyConnection(conn);
1346 rx_GetConnection(struct rx_connection *conn)
1351 MUTEX_ENTER(&rx_refcnt_mutex);
1353 MUTEX_EXIT(&rx_refcnt_mutex);
1357 #ifdef RX_ENABLE_LOCKS
1358 /* Wait for the transmit queue to no longer be busy.
1359 * requires the call->lock to be held */
1361 rxi_WaitforTQBusy(struct rx_call *call) {
1362 while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1363 call->flags |= RX_CALL_TQ_WAIT;
1365 MUTEX_ASSERT(&call->lock);
1366 CV_WAIT(&call->cv_tq, &call->lock);
1368 if (call->tqWaiters == 0) {
1369 call->flags &= ~RX_CALL_TQ_WAIT;
1376 rxi_WakeUpTransmitQueue(struct rx_call *call)
1378 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1379 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
1380 call, call->tqWaiters, call->flags));
1381 #ifdef RX_ENABLE_LOCKS
1382 MUTEX_ASSERT(&call->lock);
1383 CV_BROADCAST(&call->cv_tq);
1384 #else /* RX_ENABLE_LOCKS */
1385 osi_rxWakeup(&call->tq);
1386 #endif /* RX_ENABLE_LOCKS */
1390 /* Start a new rx remote procedure call, on the specified connection.
1391 * If wait is set to 1, wait for a free call channel; otherwise return
1392 * 0. Maxtime gives the maximum number of seconds this call may take,
1393 * after rx_NewCall returns. After this time interval, a call to any
1394 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1395 * For fine grain locking, we hold the conn_call_lock in order to
1396 * to ensure that we don't get signalle after we found a call in an active
1397 * state and before we go to sleep.
1400 rx_NewCall(struct rx_connection *conn)
1402 int i, wait, ignoreBusy = 1;
1403 struct rx_call *call;
1404 struct clock queueTime;
1405 afs_uint32 leastBusy = 0;
1409 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1412 clock_GetTime(&queueTime);
1414 * Check if there are others waiting for a new call.
1415 * If so, let them go first to avoid starving them.
1416 * This is a fairly simple scheme, and might not be
1417 * a complete solution for large numbers of waiters.
1419 * makeCallWaiters keeps track of the number of
1420 * threads waiting to make calls and the
1421 * RX_CONN_MAKECALL_WAITING flag bit is used to
1422 * indicate that there are indeed calls waiting.
1423 * The flag is set when the waiter is incremented.
1424 * It is only cleared when makeCallWaiters is 0.
1425 * This prevents us from accidently destroying the
1426 * connection while it is potentially about to be used.
1428 MUTEX_ENTER(&conn->conn_call_lock);
1429 MUTEX_ENTER(&conn->conn_data_lock);
1430 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1431 conn->flags |= RX_CONN_MAKECALL_WAITING;
1432 conn->makeCallWaiters++;
1433 MUTEX_EXIT(&conn->conn_data_lock);
1435 #ifdef RX_ENABLE_LOCKS
1436 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1440 MUTEX_ENTER(&conn->conn_data_lock);
1441 conn->makeCallWaiters--;
1442 if (conn->makeCallWaiters == 0)
1443 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1446 /* We are now the active thread in rx_NewCall */
1447 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1448 MUTEX_EXIT(&conn->conn_data_lock);
1453 for (i = 0; i < RX_MAXCALLS; i++) {
1454 call = conn->call[i];
1456 if (!ignoreBusy && conn->lastBusy[i] != leastBusy) {
1457 /* we're not ignoring busy call slots; only look at the
1458 * call slot that is the "least" busy */
1462 if (call->state == RX_STATE_DALLY) {
1463 MUTEX_ENTER(&call->lock);
1464 if (call->state == RX_STATE_DALLY) {
1465 if (ignoreBusy && conn->lastBusy[i]) {
1466 /* if we're ignoring busy call slots, skip any ones that
1467 * have lastBusy set */
1468 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1469 leastBusy = conn->lastBusy[i];
1471 MUTEX_EXIT(&call->lock);
1476 * We are setting the state to RX_STATE_RESET to
1477 * ensure that no one else will attempt to use this
1478 * call once we drop the conn->conn_call_lock and
1479 * call->lock. We must drop the conn->conn_call_lock
1480 * before calling rxi_ResetCall because the process
1481 * of clearing the transmit queue can block for an
1482 * extended period of time. If we block while holding
1483 * the conn->conn_call_lock, then all rx_EndCall
1484 * processing will block as well. This has a detrimental
1485 * effect on overall system performance.
1487 call->state = RX_STATE_RESET;
1488 (*call->callNumber)++;
1489 MUTEX_EXIT(&conn->conn_call_lock);
1490 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1491 rxi_ResetCall(call, 0);
1492 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1496 * If we failed to be able to safely obtain the
1497 * conn->conn_call_lock we will have to drop the
1498 * call->lock to avoid a deadlock. When the call->lock
1499 * is released the state of the call can change. If it
1500 * is no longer RX_STATE_RESET then some other thread is
1503 MUTEX_EXIT(&call->lock);
1504 MUTEX_ENTER(&conn->conn_call_lock);
1505 MUTEX_ENTER(&call->lock);
1507 if (call->state == RX_STATE_RESET)
1511 * If we get here it means that after dropping
1512 * the conn->conn_call_lock and call->lock that
1513 * the call is no longer ours. If we can't find
1514 * a free call in the remaining slots we should
1515 * not go immediately to RX_CONN_MAKECALL_WAITING
1516 * because by dropping the conn->conn_call_lock
1517 * we have given up synchronization with rx_EndCall.
1518 * Instead, cycle through one more time to see if
1519 * we can find a call that can call our own.
1521 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1524 MUTEX_EXIT(&call->lock);
1527 if (ignoreBusy && conn->lastBusy[i]) {
1528 /* if we're ignoring busy call slots, skip any ones that
1529 * have lastBusy set */
1530 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1531 leastBusy = conn->lastBusy[i];
1536 /* rxi_NewCall returns with mutex locked */
1537 call = rxi_NewCall(conn, i);
1538 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1542 if (i < RX_MAXCALLS) {
1543 conn->lastBusy[i] = 0;
1548 if (leastBusy && ignoreBusy) {
1549 /* we didn't find a useable call slot, but we did see at least one
1550 * 'busy' slot; look again and only use a slot with the 'least
1556 MUTEX_ENTER(&conn->conn_data_lock);
1557 conn->flags |= RX_CONN_MAKECALL_WAITING;
1558 conn->makeCallWaiters++;
1559 MUTEX_EXIT(&conn->conn_data_lock);
1561 #ifdef RX_ENABLE_LOCKS
1562 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1566 MUTEX_ENTER(&conn->conn_data_lock);
1567 conn->makeCallWaiters--;
1568 if (conn->makeCallWaiters == 0)
1569 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1570 MUTEX_EXIT(&conn->conn_data_lock);
1572 /* Client is initially in send mode */
1573 call->state = RX_STATE_ACTIVE;
1574 call->error = conn->error;
1576 call->app.mode = RX_MODE_ERROR;
1578 call->app.mode = RX_MODE_SENDING;
1580 #ifdef AFS_RXERRQ_ENV
1581 /* remember how many network errors the peer has when we started, so if
1582 * more errors are encountered after the call starts, we know the other endpoint won't be
1583 * responding to us */
1584 call->neterr_gen = rx_atomic_read(&conn->peer->neterrs);
1587 /* remember start time for call in case we have hard dead time limit */
1588 call->queueTime = queueTime;
1589 clock_GetTime(&call->startTime);
1590 call->app.bytesSent = 0;
1591 call->app.bytesRcvd = 0;
1593 /* Turn on busy protocol. */
1594 rxi_KeepAliveOn(call);
1596 /* Attempt MTU discovery */
1597 rxi_GrowMTUOn(call);
1600 * We are no longer the active thread in rx_NewCall
1602 MUTEX_ENTER(&conn->conn_data_lock);
1603 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1604 MUTEX_EXIT(&conn->conn_data_lock);
1607 * Wake up anyone else who might be giving us a chance to
1608 * run (see code above that avoids resource starvation).
1610 #ifdef RX_ENABLE_LOCKS
1611 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1612 osi_Panic("rx_NewCall call about to be used without an empty tq");
1615 CV_BROADCAST(&conn->conn_call_cv);
1619 MUTEX_EXIT(&conn->conn_call_lock);
1620 MUTEX_EXIT(&call->lock);
1623 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1628 rxi_HasActiveCalls(struct rx_connection *aconn)
1631 struct rx_call *tcall;
1635 for (i = 0; i < RX_MAXCALLS; i++) {
1636 if ((tcall = aconn->call[i])) {
1637 if ((tcall->state == RX_STATE_ACTIVE)
1638 || (tcall->state == RX_STATE_PRECALL)) {
1649 rxi_GetCallNumberVector(struct rx_connection *aconn,
1650 afs_int32 * aint32s)
1653 struct rx_call *tcall;
1657 MUTEX_ENTER(&aconn->conn_call_lock);
1658 for (i = 0; i < RX_MAXCALLS; i++) {
1659 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1660 aint32s[i] = aconn->callNumber[i] + 1;
1662 aint32s[i] = aconn->callNumber[i];
1664 MUTEX_EXIT(&aconn->conn_call_lock);
1670 rxi_SetCallNumberVector(struct rx_connection *aconn,
1671 afs_int32 * aint32s)
1674 struct rx_call *tcall;
1678 MUTEX_ENTER(&aconn->conn_call_lock);
1679 for (i = 0; i < RX_MAXCALLS; i++) {
1680 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1681 aconn->callNumber[i] = aint32s[i] - 1;
1683 aconn->callNumber[i] = aint32s[i];
1685 MUTEX_EXIT(&aconn->conn_call_lock);
1690 /* Advertise a new service. A service is named locally by a UDP port
1691 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1694 char *serviceName; Name for identification purposes (e.g. the
1695 service name might be used for probing for
1698 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1699 char *serviceName, struct rx_securityClass **securityObjects,
1700 int nSecurityObjects,
1701 afs_int32(*serviceProc) (struct rx_call * acall))
1703 osi_socket socket = OSI_NULLSOCKET;
1704 struct rx_service *tservice;
1710 if (serviceId == 0) {
1712 "rx_NewService: service id for service %s is not non-zero.\n",
1719 "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",
1727 tservice = rxi_AllocService();
1730 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1732 for (i = 0; i < RX_MAX_SERVICES; i++) {
1733 struct rx_service *service = rx_services[i];
1735 if (port == service->servicePort && host == service->serviceHost) {
1736 if (service->serviceId == serviceId) {
1737 /* The identical service has already been
1738 * installed; if the caller was intending to
1739 * change the security classes used by this
1740 * service, he/she loses. */
1742 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1743 serviceName, serviceId, service->serviceName);
1745 rxi_FreeService(tservice);
1748 /* Different service, same port: re-use the socket
1749 * which is bound to the same port */
1750 socket = service->socket;
1753 if (socket == OSI_NULLSOCKET) {
1754 /* If we don't already have a socket (from another
1755 * service on same port) get a new one */
1756 socket = rxi_GetHostUDPSocket(host, port);
1757 if (socket == OSI_NULLSOCKET) {
1759 rxi_FreeService(tservice);
1764 service->socket = socket;
1765 service->serviceHost = host;
1766 service->servicePort = port;
1767 service->serviceId = serviceId;
1768 service->serviceName = serviceName;
1769 service->nSecurityObjects = nSecurityObjects;
1770 service->securityObjects = securityObjects;
1771 service->minProcs = 0;
1772 service->maxProcs = 1;
1773 service->idleDeadTime = 60;
1774 service->connDeadTime = rx_connDeadTime;
1775 service->executeRequestProc = serviceProc;
1776 service->checkReach = 0;
1777 service->nSpecific = 0;
1778 service->specific = NULL;
1779 rx_services[i] = service; /* not visible until now */
1785 rxi_FreeService(tservice);
1786 (osi_Msg "rx_NewService: cannot support > %d services\n",
1791 /* Set configuration options for all of a service's security objects */
1794 rx_SetSecurityConfiguration(struct rx_service *service,
1795 rx_securityConfigVariables type,
1799 for (i = 0; i<service->nSecurityObjects; i++) {
1800 if (service->securityObjects[i]) {
1801 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1809 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1810 struct rx_securityClass **securityObjects, int nSecurityObjects,
1811 afs_int32(*serviceProc) (struct rx_call * acall))
1813 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1816 /* Generic request processing loop. This routine should be called
1817 * by the implementation dependent rx_ServerProc. If socketp is
1818 * non-null, it will be set to the file descriptor that this thread
1819 * is now listening on. If socketp is null, this routine will never
1822 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1824 struct rx_call *call;
1826 struct rx_service *tservice = NULL;
1833 call = rx_GetCall(threadID, tservice, socketp);
1834 if (socketp && *socketp != OSI_NULLSOCKET) {
1835 /* We are now a listener thread */
1841 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1842 #ifdef RX_ENABLE_LOCKS
1844 #endif /* RX_ENABLE_LOCKS */
1845 afs_termState = AFSOP_STOP_AFS;
1846 afs_osi_Wakeup(&afs_termState);
1847 #ifdef RX_ENABLE_LOCKS
1849 #endif /* RX_ENABLE_LOCKS */
1854 /* if server is restarting( typically smooth shutdown) then do not
1855 * allow any new calls.
1858 if (rx_tranquil && (call != NULL)) {
1862 MUTEX_ENTER(&call->lock);
1864 rxi_CallError(call, RX_RESTARTING);
1865 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1867 MUTEX_EXIT(&call->lock);
1872 tservice = call->conn->service;
1874 if (tservice->beforeProc)
1875 (*tservice->beforeProc) (call);
1877 code = tservice->executeRequestProc(call);
1879 if (tservice->afterProc)
1880 (*tservice->afterProc) (call, code);
1882 rx_EndCall(call, code);
1884 if (tservice->postProc)
1885 (*tservice->postProc) (code);
1887 if (rx_stats_active) {
1888 MUTEX_ENTER(&rx_stats_mutex);
1890 MUTEX_EXIT(&rx_stats_mutex);
1897 rx_WakeupServerProcs(void)
1899 struct rx_serverQueueEntry *np, *tqp;
1900 struct opr_queue *cursor;
1904 MUTEX_ENTER(&rx_serverPool_lock);
1906 #ifdef RX_ENABLE_LOCKS
1907 if (rx_waitForPacket)
1908 CV_BROADCAST(&rx_waitForPacket->cv);
1909 #else /* RX_ENABLE_LOCKS */
1910 if (rx_waitForPacket)
1911 osi_rxWakeup(rx_waitForPacket);
1912 #endif /* RX_ENABLE_LOCKS */
1913 MUTEX_ENTER(&freeSQEList_lock);
1914 for (np = rx_FreeSQEList; np; np = tqp) {
1915 tqp = *(struct rx_serverQueueEntry **)np;
1916 #ifdef RX_ENABLE_LOCKS
1917 CV_BROADCAST(&np->cv);
1918 #else /* RX_ENABLE_LOCKS */
1920 #endif /* RX_ENABLE_LOCKS */
1922 MUTEX_EXIT(&freeSQEList_lock);
1923 for (opr_queue_Scan(&rx_idleServerQueue, cursor)) {
1924 np = opr_queue_Entry(cursor, struct rx_serverQueueEntry, entry);
1925 #ifdef RX_ENABLE_LOCKS
1926 CV_BROADCAST(&np->cv);
1927 #else /* RX_ENABLE_LOCKS */
1929 #endif /* RX_ENABLE_LOCKS */
1931 MUTEX_EXIT(&rx_serverPool_lock);
1936 * One thing that seems to happen is that all the server threads get
1937 * tied up on some empty or slow call, and then a whole bunch of calls
1938 * arrive at once, using up the packet pool, so now there are more
1939 * empty calls. The most critical resources here are server threads
1940 * and the free packet pool. The "doreclaim" code seems to help in
1941 * general. I think that eventually we arrive in this state: there
1942 * are lots of pending calls which do have all their packets present,
1943 * so they won't be reclaimed, are multi-packet calls, so they won't
1944 * be scheduled until later, and thus are tying up most of the free
1945 * packet pool for a very long time.
1947 * 1. schedule multi-packet calls if all the packets are present.
1948 * Probably CPU-bound operation, useful to return packets to pool.
1949 * Do what if there is a full window, but the last packet isn't here?
1950 * 3. preserve one thread which *only* runs "best" calls, otherwise
1951 * it sleeps and waits for that type of call.
1952 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1953 * the current dataquota business is badly broken. The quota isn't adjusted
1954 * to reflect how many packets are presently queued for a running call.
1955 * So, when we schedule a queued call with a full window of packets queued
1956 * up for it, that *should* free up a window full of packets for other 2d-class
1957 * calls to be able to use from the packet pool. But it doesn't.
1959 * NB. Most of the time, this code doesn't run -- since idle server threads
1960 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
1961 * as a new call arrives.
1963 /* Sleep until a call arrives. Returns a pointer to the call, ready
1964 * for an rx_Read. */
1965 #ifdef RX_ENABLE_LOCKS
1967 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
1969 struct rx_serverQueueEntry *sq;
1970 struct rx_call *call = (struct rx_call *)0;
1971 struct rx_service *service = NULL;
1973 MUTEX_ENTER(&freeSQEList_lock);
1975 if ((sq = rx_FreeSQEList)) {
1976 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
1977 MUTEX_EXIT(&freeSQEList_lock);
1978 } else { /* otherwise allocate a new one and return that */
1979 MUTEX_EXIT(&freeSQEList_lock);
1980 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
1981 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
1982 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
1985 MUTEX_ENTER(&rx_serverPool_lock);
1986 if (cur_service != NULL) {
1987 ReturnToServerPool(cur_service);
1990 if (!opr_queue_IsEmpty(&rx_incomingCallQueue)) {
1991 struct rx_call *tcall, *choice2 = NULL;
1992 struct opr_queue *cursor;
1994 /* Scan for eligible incoming calls. A call is not eligible
1995 * if the maximum number of calls for its service type are
1996 * already executing */
1997 /* One thread will process calls FCFS (to prevent starvation),
1998 * while the other threads may run ahead looking for calls which
1999 * have all their input data available immediately. This helps
2000 * keep threads from blocking, waiting for data from the client. */
2001 for (opr_queue_Scan(&rx_incomingCallQueue, cursor)) {
2002 tcall = opr_queue_Entry(cursor, struct rx_call, entry);
2004 service = tcall->conn->service;
2005 if (!QuotaOK(service)) {
2008 MUTEX_ENTER(&rx_pthread_mutex);
2009 if (tno == rxi_fcfs_thread_num
2010 || opr_queue_IsEnd(&rx_incomingCallQueue, cursor)) {
2011 MUTEX_EXIT(&rx_pthread_mutex);
2012 /* If we're the fcfs thread , then we'll just use
2013 * this call. If we haven't been able to find an optimal
2014 * choice, and we're at the end of the list, then use a
2015 * 2d choice if one has been identified. Otherwise... */
2016 call = (choice2 ? choice2 : tcall);
2017 service = call->conn->service;
2019 MUTEX_EXIT(&rx_pthread_mutex);
2020 if (!opr_queue_IsEmpty(&tcall->rq)) {
2021 struct rx_packet *rp;
2022 rp = opr_queue_First(&tcall->rq, struct rx_packet,
2024 if (rp->header.seq == 1) {
2026 || (rp->header.flags & RX_LAST_PACKET)) {
2028 } else if (rxi_2dchoice && !choice2
2029 && !(tcall->flags & RX_CALL_CLEARED)
2030 && (tcall->rprev > rxi_HardAckRate)) {
2040 ReturnToServerPool(service);
2046 opr_queue_Remove(&call->entry);
2047 MUTEX_EXIT(&rx_serverPool_lock);
2048 MUTEX_ENTER(&call->lock);
2050 if (call->flags & RX_CALL_WAIT_PROC) {
2051 call->flags &= ~RX_CALL_WAIT_PROC;
2052 rx_atomic_dec(&rx_nWaiting);
2055 if (call->state != RX_STATE_PRECALL || call->error) {
2056 MUTEX_EXIT(&call->lock);
2057 MUTEX_ENTER(&rx_serverPool_lock);
2058 ReturnToServerPool(service);
2063 if (opr_queue_IsEmpty(&call->rq)
2064 || opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq != 1)
2065 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2067 CLEAR_CALL_QUEUE_LOCK(call);
2070 /* If there are no eligible incoming calls, add this process
2071 * to the idle server queue, to wait for one */
2075 *socketp = OSI_NULLSOCKET;
2077 sq->socketp = socketp;
2078 opr_queue_Append(&rx_idleServerQueue, &sq->entry);
2079 #ifndef AFS_AIX41_ENV
2080 rx_waitForPacket = sq;
2081 #endif /* AFS_AIX41_ENV */
2083 CV_WAIT(&sq->cv, &rx_serverPool_lock);
2085 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2086 MUTEX_EXIT(&rx_serverPool_lock);
2087 return (struct rx_call *)0;
2090 } while (!(call = sq->newcall)
2091 && !(socketp && *socketp != OSI_NULLSOCKET));
2092 MUTEX_EXIT(&rx_serverPool_lock);
2094 MUTEX_ENTER(&call->lock);
2100 MUTEX_ENTER(&freeSQEList_lock);
2101 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2102 rx_FreeSQEList = sq;
2103 MUTEX_EXIT(&freeSQEList_lock);
2106 clock_GetTime(&call->startTime);
2107 call->state = RX_STATE_ACTIVE;
2108 call->app.mode = RX_MODE_RECEIVING;
2109 #ifdef RX_KERNEL_TRACE
2110 if (ICL_SETACTIVE(afs_iclSetp)) {
2111 int glockOwner = ISAFS_GLOCK();
2114 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2115 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2122 rxi_calltrace(RX_CALL_START, call);
2123 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
2124 call->conn->service->servicePort, call->conn->service->serviceId,
2127 MUTEX_EXIT(&call->lock);
2128 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
2130 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2135 #else /* RX_ENABLE_LOCKS */
2137 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2139 struct rx_serverQueueEntry *sq;
2140 struct rx_call *call = (struct rx_call *)0, *choice2;
2141 struct rx_service *service = NULL;
2145 MUTEX_ENTER(&freeSQEList_lock);
2147 if ((sq = rx_FreeSQEList)) {
2148 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
2149 MUTEX_EXIT(&freeSQEList_lock);
2150 } else { /* otherwise allocate a new one and return that */
2151 MUTEX_EXIT(&freeSQEList_lock);
2152 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2153 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2154 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2156 MUTEX_ENTER(&sq->lock);
2158 if (cur_service != NULL) {
2159 cur_service->nRequestsRunning--;
2160 MUTEX_ENTER(&rx_quota_mutex);
2161 if (cur_service->nRequestsRunning < cur_service->minProcs)
2164 MUTEX_EXIT(&rx_quota_mutex);
2166 if (!opr_queue_IsEmpty(&rx_incomingCallQueue)) {
2167 struct rx_call *tcall;
2168 struct opr_queue *cursor;
2169 /* Scan for eligible incoming calls. A call is not eligible
2170 * if the maximum number of calls for its service type are
2171 * already executing */
2172 /* One thread will process calls FCFS (to prevent starvation),
2173 * while the other threads may run ahead looking for calls which
2174 * have all their input data available immediately. This helps
2175 * keep threads from blocking, waiting for data from the client. */
2176 choice2 = (struct rx_call *)0;
2177 for (opr_queue_Scan(&rx_incomingCallQueue, cursor)) {
2178 tcall = opr_queue_Entry(cursor, struct rx_call, entry);
2179 service = tcall->conn->service;
2180 if (QuotaOK(service)) {
2181 MUTEX_ENTER(&rx_pthread_mutex);
2182 /* XXX - If tcall->entry.next is NULL, then we're no longer
2183 * on a queue at all. This shouldn't happen. */
2184 if (tno == rxi_fcfs_thread_num || !tcall->entry.next) {
2185 MUTEX_EXIT(&rx_pthread_mutex);
2186 /* If we're the fcfs thread, then we'll just use
2187 * this call. If we haven't been able to find an optimal
2188 * choice, and we're at the end of the list, then use a
2189 * 2d choice if one has been identified. Otherwise... */
2190 call = (choice2 ? choice2 : tcall);
2191 service = call->conn->service;
2193 MUTEX_EXIT(&rx_pthread_mutex);
2194 if (!opr_queue_IsEmpty(&tcall->rq)) {
2195 struct rx_packet *rp;
2196 rp = opr_queue_First(&tcall->rq, struct rx_packet,
2198 if (rp->header.seq == 1
2200 || (rp->header.flags & RX_LAST_PACKET))) {
2202 } else if (rxi_2dchoice && !choice2
2203 && !(tcall->flags & RX_CALL_CLEARED)
2204 && (tcall->rprev > rxi_HardAckRate)) {
2217 opr_queue_Remove(&call->entry);
2218 /* we can't schedule a call if there's no data!!! */
2219 /* send an ack if there's no data, if we're missing the
2220 * first packet, or we're missing something between first
2221 * and last -- there's a "hole" in the incoming data. */
2222 if (opr_queue_IsEmpty(&call->rq)
2223 || opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq != 1
2224 || call->rprev != opr_queue_Last(&call->rq, struct rx_packet, entry)->header.seq)
2225 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2227 call->flags &= (~RX_CALL_WAIT_PROC);
2228 service->nRequestsRunning++;
2229 /* just started call in minProcs pool, need fewer to maintain
2231 MUTEX_ENTER(&rx_quota_mutex);
2232 if (service->nRequestsRunning <= service->minProcs)
2235 MUTEX_EXIT(&rx_quota_mutex);
2236 rx_atomic_dec(&rx_nWaiting);
2237 /* MUTEX_EXIT(&call->lock); */
2239 /* If there are no eligible incoming calls, add this process
2240 * to the idle server queue, to wait for one */
2243 *socketp = OSI_NULLSOCKET;
2245 sq->socketp = socketp;
2246 opr_queue_Append(&rx_idleServerQueue, &sq->entry);
2250 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2252 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2253 return (struct rx_call *)0;
2256 } while (!(call = sq->newcall)
2257 && !(socketp && *socketp != OSI_NULLSOCKET));
2259 MUTEX_EXIT(&sq->lock);
2261 MUTEX_ENTER(&freeSQEList_lock);
2262 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2263 rx_FreeSQEList = sq;
2264 MUTEX_EXIT(&freeSQEList_lock);
2267 clock_GetTime(&call->startTime);
2268 call->state = RX_STATE_ACTIVE;
2269 call->app.mode = RX_MODE_RECEIVING;
2270 #ifdef RX_KERNEL_TRACE
2271 if (ICL_SETACTIVE(afs_iclSetp)) {
2272 int glockOwner = ISAFS_GLOCK();
2275 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2276 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2283 rxi_calltrace(RX_CALL_START, call);
2284 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2285 call->conn->service->servicePort, call->conn->service->serviceId,
2288 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2295 #endif /* RX_ENABLE_LOCKS */
2299 /* Establish a procedure to be called when a packet arrives for a
2300 * call. This routine will be called at most once after each call,
2301 * and will also be called if there is an error condition on the or
2302 * the call is complete. Used by multi rx to build a selection
2303 * function which determines which of several calls is likely to be a
2304 * good one to read from.
2305 * NOTE: the way this is currently implemented it is probably only a
2306 * good idea to (1) use it immediately after a newcall (clients only)
2307 * and (2) only use it once. Other uses currently void your warranty
2310 rx_SetArrivalProc(struct rx_call *call,
2311 void (*proc) (struct rx_call * call,
2314 void * handle, int arg)
2316 call->arrivalProc = proc;
2317 call->arrivalProcHandle = handle;
2318 call->arrivalProcArg = arg;
2321 /* Call is finished (possibly prematurely). Return rc to the peer, if
2322 * appropriate, and return the final error code from the conversation
2326 rx_EndCall(struct rx_call *call, afs_int32 rc)
2328 struct rx_connection *conn = call->conn;
2332 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2333 call, rc, call->error, call->abortCode));
2336 MUTEX_ENTER(&call->lock);
2338 if (rc == 0 && call->error == 0) {
2339 call->abortCode = 0;
2340 call->abortCount = 0;
2343 call->arrivalProc = (void (*)())0;
2344 if (rc && call->error == 0) {
2345 rxi_CallError(call, rc);
2346 call->app.mode = RX_MODE_ERROR;
2347 /* Send an abort message to the peer if this error code has
2348 * only just been set. If it was set previously, assume the
2349 * peer has already been sent the error code or will request it
2351 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2353 if (conn->type == RX_SERVER_CONNECTION) {
2354 /* Make sure reply or at least dummy reply is sent */
2355 if (call->app.mode == RX_MODE_RECEIVING) {
2356 MUTEX_EXIT(&call->lock);
2357 rxi_WriteProc(call, 0, 0);
2358 MUTEX_ENTER(&call->lock);
2360 if (call->app.mode == RX_MODE_SENDING) {
2361 rxi_FlushWriteLocked(call);
2363 rxi_calltrace(RX_CALL_END, call);
2364 /* Call goes to hold state until reply packets are acknowledged */
2365 if (call->tfirst + call->nSoftAcked < call->tnext) {
2366 call->state = RX_STATE_HOLD;
2368 call->state = RX_STATE_DALLY;
2369 rxi_ClearTransmitQueue(call, 0);
2370 rxi_rto_cancel(call);
2371 rxi_CancelKeepAliveEvent(call);
2373 } else { /* Client connection */
2375 /* Make sure server receives input packets, in the case where
2376 * no reply arguments are expected */
2378 if ((call->app.mode == RX_MODE_SENDING)
2379 || (call->app.mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2380 MUTEX_EXIT(&call->lock);
2381 (void)rxi_ReadProc(call, &dummy, 1);
2382 MUTEX_ENTER(&call->lock);
2385 /* If we had an outstanding delayed ack, be nice to the server
2386 * and force-send it now.
2388 if (call->delayedAckEvent) {
2389 rxi_CancelDelayedAckEvent(call);
2390 rxi_SendDelayedAck(NULL, call, NULL, 0);
2393 /* We need to release the call lock since it's lower than the
2394 * conn_call_lock and we don't want to hold the conn_call_lock
2395 * over the rx_ReadProc call. The conn_call_lock needs to be held
2396 * here for the case where rx_NewCall is perusing the calls on
2397 * the connection structure. We don't want to signal until
2398 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2399 * have checked this call, found it active and by the time it
2400 * goes to sleep, will have missed the signal.
2402 MUTEX_EXIT(&call->lock);
2403 MUTEX_ENTER(&conn->conn_call_lock);
2404 MUTEX_ENTER(&call->lock);
2407 /* While there are some circumstances where a call with an error is
2408 * obviously not on a "busy" channel, be conservative (clearing
2409 * lastBusy is just best-effort to possibly speed up rx_NewCall).
2410 * The call channel is definitely not busy if we just successfully
2411 * completed a call on it. */
2412 conn->lastBusy[call->channel] = 0;
2414 } else if (call->error == RX_CALL_TIMEOUT) {
2415 /* The call is still probably running on the server side, so try to
2416 * avoid this call channel in the future. */
2417 conn->lastBusy[call->channel] = clock_Sec();
2420 MUTEX_ENTER(&conn->conn_data_lock);
2421 conn->flags |= RX_CONN_BUSY;
2422 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2423 MUTEX_EXIT(&conn->conn_data_lock);
2424 #ifdef RX_ENABLE_LOCKS
2425 CV_BROADCAST(&conn->conn_call_cv);
2430 #ifdef RX_ENABLE_LOCKS
2432 MUTEX_EXIT(&conn->conn_data_lock);
2434 #endif /* RX_ENABLE_LOCKS */
2435 call->state = RX_STATE_DALLY;
2437 error = call->error;
2439 /* currentPacket, nLeft, and NFree must be zeroed here, because
2440 * ResetCall cannot: ResetCall may be called at splnet(), in the
2441 * kernel version, and may interrupt the macros rx_Read or
2442 * rx_Write, which run at normal priority for efficiency. */
2443 if (call->app.currentPacket) {
2444 #ifdef RX_TRACK_PACKETS
2445 call->app.currentPacket->flags &= ~RX_PKTFLAG_CP;
2447 rxi_FreePacket(call->app.currentPacket);
2448 call->app.currentPacket = (struct rx_packet *)0;
2451 call->app.nLeft = call->app.nFree = call->app.curlen = 0;
2453 /* Free any packets from the last call to ReadvProc/WritevProc */
2454 #ifdef RXDEBUG_PACKET
2456 #endif /* RXDEBUG_PACKET */
2457 rxi_FreePackets(0, &call->app.iovq);
2458 MUTEX_EXIT(&call->lock);
2460 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2461 if (conn->type == RX_CLIENT_CONNECTION) {
2462 MUTEX_ENTER(&conn->conn_data_lock);
2463 conn->flags &= ~RX_CONN_BUSY;
2464 MUTEX_EXIT(&conn->conn_data_lock);
2465 MUTEX_EXIT(&conn->conn_call_lock);
2469 * Map errors to the local host's errno.h format.
2471 error = ntoh_syserr_conv(error);
2473 /* If the caller said the call failed with some error, we had better
2474 * return an error code. */
2475 osi_Assert(!rc || error);
2479 #if !defined(KERNEL)
2481 /* Call this routine when shutting down a server or client (especially
2482 * clients). This will allow Rx to gracefully garbage collect server
2483 * connections, and reduce the number of retries that a server might
2484 * make to a dead client.
2485 * This is not quite right, since some calls may still be ongoing and
2486 * we can't lock them to destroy them. */
2490 struct rx_connection **conn_ptr, **conn_end;
2493 if (rx_atomic_test_and_set_bit(&rxinit_status, 0))
2494 return; /* Already shutdown. */
2496 rxi_DeleteCachedConnections();
2497 if (rx_connHashTable) {
2498 MUTEX_ENTER(&rx_connHashTable_lock);
2499 for (conn_ptr = &rx_connHashTable[0], conn_end =
2500 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2502 struct rx_connection *conn, *next;
2503 for (conn = *conn_ptr; conn; conn = next) {
2505 if (conn->type == RX_CLIENT_CONNECTION) {
2506 MUTEX_ENTER(&rx_refcnt_mutex);
2508 MUTEX_EXIT(&rx_refcnt_mutex);
2509 #ifdef RX_ENABLE_LOCKS
2510 rxi_DestroyConnectionNoLock(conn);
2511 #else /* RX_ENABLE_LOCKS */
2512 rxi_DestroyConnection(conn);
2513 #endif /* RX_ENABLE_LOCKS */
2517 #ifdef RX_ENABLE_LOCKS
2518 while (rx_connCleanup_list) {
2519 struct rx_connection *conn;
2520 conn = rx_connCleanup_list;
2521 rx_connCleanup_list = rx_connCleanup_list->next;
2522 MUTEX_EXIT(&rx_connHashTable_lock);
2523 rxi_CleanupConnection(conn);
2524 MUTEX_ENTER(&rx_connHashTable_lock);
2526 MUTEX_EXIT(&rx_connHashTable_lock);
2527 #endif /* RX_ENABLE_LOCKS */
2532 afs_winsockCleanup();
2538 /* if we wakeup packet waiter too often, can get in loop with two
2539 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2541 rxi_PacketsUnWait(void)
2543 if (!rx_waitingForPackets) {
2547 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2548 return; /* still over quota */
2551 rx_waitingForPackets = 0;
2552 #ifdef RX_ENABLE_LOCKS
2553 CV_BROADCAST(&rx_waitingForPackets_cv);
2555 osi_rxWakeup(&rx_waitingForPackets);
2561 /* ------------------Internal interfaces------------------------- */
2563 /* Return this process's service structure for the
2564 * specified socket and service */
2565 static struct rx_service *
2566 rxi_FindService(osi_socket socket, u_short serviceId)
2568 struct rx_service **sp;
2569 for (sp = &rx_services[0]; *sp; sp++) {
2570 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2576 #ifdef RXDEBUG_PACKET
2577 #ifdef KDUMP_RX_LOCK
2578 static struct rx_call_rx_lock *rx_allCallsp = 0;
2580 static struct rx_call *rx_allCallsp = 0;
2582 #endif /* RXDEBUG_PACKET */
2584 /* Allocate a call structure, for the indicated channel of the
2585 * supplied connection. The mode and state of the call must be set by
2586 * the caller. Returns the call with mutex locked. */
2587 static struct rx_call *
2588 rxi_NewCall(struct rx_connection *conn, int channel)
2590 struct rx_call *call;
2591 #ifdef RX_ENABLE_LOCKS
2592 struct rx_call *cp; /* Call pointer temp */
2593 struct opr_queue *cursor;
2596 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2598 /* Grab an existing call structure, or allocate a new one.
2599 * Existing call structures are assumed to have been left reset by
2601 MUTEX_ENTER(&rx_freeCallQueue_lock);
2603 #ifdef RX_ENABLE_LOCKS
2605 * EXCEPT that the TQ might not yet be cleared out.
2606 * Skip over those with in-use TQs.
2609 for (opr_queue_Scan(&rx_freeCallQueue, cursor)) {
2610 cp = opr_queue_Entry(cursor, struct rx_call, entry);
2611 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2617 #else /* RX_ENABLE_LOCKS */
2618 if (!opr_queue_IsEmpty(&rx_freeCallQueue)) {
2619 call = opr_queue_First(&rx_freeCallQueue, struct rx_call, entry);
2620 #endif /* RX_ENABLE_LOCKS */
2621 opr_queue_Remove(&call->entry);
2622 if (rx_stats_active)
2623 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2624 MUTEX_EXIT(&rx_freeCallQueue_lock);
2625 MUTEX_ENTER(&call->lock);
2626 CLEAR_CALL_QUEUE_LOCK(call);
2627 #ifdef RX_ENABLE_LOCKS
2628 /* Now, if TQ wasn't cleared earlier, do it now. */
2629 rxi_WaitforTQBusy(call);
2630 if (call->flags & RX_CALL_TQ_CLEARME) {
2631 rxi_ClearTransmitQueue(call, 1);
2632 /*queue_Init(&call->tq);*/
2634 #endif /* RX_ENABLE_LOCKS */
2635 /* Bind the call to its connection structure */
2637 rxi_ResetCall(call, 1);
2640 call = rxi_Alloc(sizeof(struct rx_call));
2641 #ifdef RXDEBUG_PACKET
2642 call->allNextp = rx_allCallsp;
2643 rx_allCallsp = call;
2645 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2646 #else /* RXDEBUG_PACKET */
2647 rx_atomic_inc(&rx_stats.nCallStructs);
2648 #endif /* RXDEBUG_PACKET */
2650 MUTEX_EXIT(&rx_freeCallQueue_lock);
2651 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2652 MUTEX_ENTER(&call->lock);
2653 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2654 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2655 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2657 /* Initialize once-only items */
2658 opr_queue_Init(&call->tq);
2659 opr_queue_Init(&call->rq);
2660 opr_queue_Init(&call->app.iovq);
2661 #ifdef RXDEBUG_PACKET
2662 call->rqc = call->tqc = call->iovqc = 0;
2663 #endif /* RXDEBUG_PACKET */
2664 /* Bind the call to its connection structure (prereq for reset) */
2666 rxi_ResetCall(call, 1);
2668 call->channel = channel;
2669 call->callNumber = &conn->callNumber[channel];
2670 call->rwind = conn->rwind[channel];
2671 call->twind = conn->twind[channel];
2672 /* Note that the next expected call number is retained (in
2673 * conn->callNumber[i]), even if we reallocate the call structure
2675 conn->call[channel] = call;
2676 /* if the channel's never been used (== 0), we should start at 1, otherwise
2677 * the call number is valid from the last time this channel was used */
2678 if (*call->callNumber == 0)
2679 *call->callNumber = 1;
2684 /* A call has been inactive long enough that so we can throw away
2685 * state, including the call structure, which is placed on the call
2688 * call->lock amd rx_refcnt_mutex are held upon entry.
2689 * haveCTLock is set when called from rxi_ReapConnections.
2691 * return 1 if the call is freed, 0 if not.
2694 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2696 int channel = call->channel;
2697 struct rx_connection *conn = call->conn;
2698 u_char state = call->state;
2701 * We are setting the state to RX_STATE_RESET to
2702 * ensure that no one else will attempt to use this
2703 * call once we drop the refcnt lock. We must drop
2704 * the refcnt lock before calling rxi_ResetCall
2705 * because it cannot be held across acquiring the
2706 * freepktQ lock. NewCall does the same.
2708 call->state = RX_STATE_RESET;
2709 MUTEX_EXIT(&rx_refcnt_mutex);
2710 rxi_ResetCall(call, 0);
2712 if (MUTEX_TRYENTER(&conn->conn_call_lock))
2714 if (state == RX_STATE_DALLY || state == RX_STATE_HOLD)
2715 (*call->callNumber)++;
2717 if (call->conn->call[channel] == call)
2718 call->conn->call[channel] = 0;
2719 MUTEX_EXIT(&conn->conn_call_lock);
2722 * We couldn't obtain the conn_call_lock so we can't
2723 * disconnect the call from the connection. Set the
2724 * call state to dally so that the call can be reused.
2726 MUTEX_ENTER(&rx_refcnt_mutex);
2727 call->state = RX_STATE_DALLY;
2731 MUTEX_ENTER(&rx_freeCallQueue_lock);
2732 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2733 #ifdef RX_ENABLE_LOCKS
2734 /* A call may be free even though its transmit queue is still in use.
2735 * Since we search the call list from head to tail, put busy calls at
2736 * the head of the list, and idle calls at the tail.
2738 if (call->flags & RX_CALL_TQ_BUSY)
2739 opr_queue_Prepend(&rx_freeCallQueue, &call->entry);
2741 opr_queue_Append(&rx_freeCallQueue, &call->entry);
2742 #else /* RX_ENABLE_LOCKS */
2743 opr_queue_Append(&rx_freeCallQueue, &call->entry);
2744 #endif /* RX_ENABLE_LOCKS */
2745 if (rx_stats_active)
2746 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2747 MUTEX_EXIT(&rx_freeCallQueue_lock);
2749 /* Destroy the connection if it was previously slated for
2750 * destruction, i.e. the Rx client code previously called
2751 * rx_DestroyConnection (client connections), or
2752 * rxi_ReapConnections called the same routine (server
2753 * connections). Only do this, however, if there are no
2754 * outstanding calls. Note that for fine grain locking, there appears
2755 * to be a deadlock in that rxi_FreeCall has a call locked and
2756 * DestroyConnectionNoLock locks each call in the conn. But note a
2757 * few lines up where we have removed this call from the conn.
2758 * If someone else destroys a connection, they either have no
2759 * call lock held or are going through this section of code.
2761 MUTEX_ENTER(&conn->conn_data_lock);
2762 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2763 MUTEX_ENTER(&rx_refcnt_mutex);
2765 MUTEX_EXIT(&rx_refcnt_mutex);
2766 MUTEX_EXIT(&conn->conn_data_lock);
2767 #ifdef RX_ENABLE_LOCKS
2769 rxi_DestroyConnectionNoLock(conn);
2771 rxi_DestroyConnection(conn);
2772 #else /* RX_ENABLE_LOCKS */
2773 rxi_DestroyConnection(conn);
2774 #endif /* RX_ENABLE_LOCKS */
2776 MUTEX_EXIT(&conn->conn_data_lock);
2778 MUTEX_ENTER(&rx_refcnt_mutex);
2782 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2783 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2786 rxi_Alloc(size_t size)
2790 if (rx_stats_active) {
2791 rx_atomic_add(&rxi_Allocsize, (int) size);
2792 rx_atomic_inc(&rxi_Alloccnt);
2796 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2797 afs_osi_Alloc_NoSleep(size);
2802 osi_Panic("rxi_Alloc error");
2808 rxi_Free(void *addr, size_t size)
2810 if (rx_stats_active) {
2811 rx_atomic_sub(&rxi_Allocsize, (int) size);
2812 rx_atomic_dec(&rxi_Alloccnt);
2814 osi_Free(addr, size);
2818 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2820 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2821 struct rx_peer *next = NULL;
2825 MUTEX_ENTER(&rx_peerHashTable_lock);
2827 peer_ptr = &rx_peerHashTable[0];
2828 peer_end = &rx_peerHashTable[rx_hashTableSize];
2831 for ( ; peer_ptr < peer_end; peer_ptr++) {
2834 for ( ; peer; peer = next) {
2836 if (host == peer->host)
2841 hashIndex = PEER_HASH(host, port);
2842 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2843 if ((peer->host == host) && (peer->port == port))
2848 MUTEX_ENTER(&rx_peerHashTable_lock);
2853 MUTEX_EXIT(&rx_peerHashTable_lock);
2855 MUTEX_ENTER(&peer->peer_lock);
2856 /* We don't handle dropping below min, so don't */
2857 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2858 peer->ifMTU=MIN(mtu, peer->ifMTU);
2859 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2860 /* if we tweaked this down, need to tune our peer MTU too */
2861 peer->MTU = MIN(peer->MTU, peer->natMTU);
2862 /* if we discovered a sub-1500 mtu, degrade */
2863 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2864 peer->maxDgramPackets = 1;
2865 /* We no longer have valid peer packet information */
2866 if (peer->maxPacketSize + RX_HEADER_SIZE > peer->ifMTU)
2867 peer->maxPacketSize = 0;
2868 MUTEX_EXIT(&peer->peer_lock);
2870 MUTEX_ENTER(&rx_peerHashTable_lock);
2872 if (host && !port) {
2874 /* pick up where we left off */
2878 MUTEX_EXIT(&rx_peerHashTable_lock);
2881 #ifdef AFS_RXERRQ_ENV
2883 rxi_SetPeerDead(struct sock_extended_err *err, afs_uint32 host, afs_uint16 port)
2885 int hashIndex = PEER_HASH(host, port);
2886 struct rx_peer *peer;
2888 MUTEX_ENTER(&rx_peerHashTable_lock);
2890 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2891 if (peer->host == host && peer->port == port) {
2897 MUTEX_EXIT(&rx_peerHashTable_lock);
2900 rx_atomic_inc(&peer->neterrs);
2901 MUTEX_ENTER(&peer->peer_lock);
2902 peer->last_err_origin = RX_NETWORK_ERROR_ORIGIN_ICMP;
2903 peer->last_err_type = err->ee_type;
2904 peer->last_err_code = err->ee_code;
2905 MUTEX_EXIT(&peer->peer_lock);
2907 MUTEX_ENTER(&rx_peerHashTable_lock);
2909 MUTEX_EXIT(&rx_peerHashTable_lock);
2914 rxi_ProcessNetError(struct sock_extended_err *err, afs_uint32 addr, afs_uint16 port)
2916 # ifdef AFS_ADAPT_PMTU
2917 if (err->ee_errno == EMSGSIZE && err->ee_info >= 68) {
2918 rxi_SetPeerMtu(NULL, addr, port, err->ee_info - RX_IPUDP_SIZE);
2922 if (err->ee_origin == SO_EE_ORIGIN_ICMP && err->ee_type == ICMP_DEST_UNREACH) {
2923 switch (err->ee_code) {
2924 case ICMP_NET_UNREACH:
2925 case ICMP_HOST_UNREACH:
2926 case ICMP_PORT_UNREACH:
2929 rxi_SetPeerDead(err, addr, port);
2936 rxi_TranslateICMP(int type, int code)
2939 case ICMP_DEST_UNREACH:
2941 case ICMP_NET_UNREACH:
2942 return "Destination Net Unreachable";
2943 case ICMP_HOST_UNREACH:
2944 return "Destination Host Unreachable";
2945 case ICMP_PROT_UNREACH:
2946 return "Destination Protocol Unreachable";
2947 case ICMP_PORT_UNREACH:
2948 return "Destination Port Unreachable";
2950 return "Destination Net Prohibited";
2952 return "Destination Host Prohibited";
2958 #endif /* AFS_RXERRQ_ENV */
2961 * Get the last network error for a connection
2963 * A "network error" here means an error retrieved from ICMP, or some other
2964 * mechanism outside of Rx that informs us of errors in network reachability.
2966 * If a peer associated with the given Rx connection has received a network
2967 * error recently, this function allows the caller to know what error
2968 * specifically occurred. This can be useful to know, since e.g. ICMP errors
2969 * can cause calls to that peer to be quickly aborted. So, this function can
2970 * help see why a call was aborted due to network errors.
2972 * If we have received traffic from a peer since the last network error, we
2973 * treat that peer as if we had not received an network error for it.
2975 * @param[in] conn The Rx connection to examine
2976 * @param[out] err_origin The origin of the last network error (e.g. ICMP);
2977 * one of the RX_NETWORK_ERROR_ORIGIN_* constants
2978 * @param[out] err_type The type of the last error
2979 * @param[out] err_code The code of the last error
2980 * @param[out] msg Human-readable error message, if applicable; NULL otherwise
2982 * @return If we have an error
2983 * @retval -1 No error to get; 'out' params are undefined
2984 * @retval 0 We have an error; 'out' params contain the last error
2987 rx_GetNetworkError(struct rx_connection *conn, int *err_origin, int *err_type,
2988 int *err_code, const char **msg)
2990 #ifdef AFS_RXERRQ_ENV
2991 struct rx_peer *peer = conn->peer;
2992 if (rx_atomic_read(&peer->neterrs)) {
2993 MUTEX_ENTER(&peer->peer_lock);
2994 *err_origin = peer->last_err_origin;
2995 *err_type = peer->last_err_type;
2996 *err_code = peer->last_err_code;
2997 MUTEX_EXIT(&peer->peer_lock);
3000 if (*err_origin == RX_NETWORK_ERROR_ORIGIN_ICMP) {
3001 *msg = rxi_TranslateICMP(*err_type, *err_code);
3010 /* Find the peer process represented by the supplied (host,port)
3011 * combination. If there is no appropriate active peer structure, a
3012 * new one will be allocated and initialized
3015 rxi_FindPeer(afs_uint32 host, u_short port, int create)
3019 hashIndex = PEER_HASH(host, port);
3020 MUTEX_ENTER(&rx_peerHashTable_lock);
3021 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
3022 if ((pp->host == host) && (pp->port == port))
3027 pp = rxi_AllocPeer(); /* This bzero's *pp */
3028 pp->host = host; /* set here or in InitPeerParams is zero */
3030 #ifdef AFS_RXERRQ_ENV
3031 rx_atomic_set(&pp->neterrs, 0);
3033 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
3034 opr_queue_Init(&pp->rpcStats);
3035 pp->next = rx_peerHashTable[hashIndex];
3036 rx_peerHashTable[hashIndex] = pp;
3037 rxi_InitPeerParams(pp);
3038 if (rx_stats_active)
3039 rx_atomic_inc(&rx_stats.nPeerStructs);
3045 MUTEX_EXIT(&rx_peerHashTable_lock);
3050 /* Find the connection at (host, port) started at epoch, and with the
3051 * given connection id. Creates the server connection if necessary.
3052 * The type specifies whether a client connection or a server
3053 * connection is desired. In both cases, (host, port) specify the
3054 * peer's (host, pair) pair. Client connections are not made
3055 * automatically by this routine. The parameter socket gives the
3056 * socket descriptor on which the packet was received. This is used,
3057 * in the case of server connections, to check that *new* connections
3058 * come via a valid (port, serviceId). Finally, the securityIndex
3059 * parameter must match the existing index for the connection. If a
3060 * server connection is created, it will be created using the supplied
3061 * index, if the index is valid for this service */
3062 static struct rx_connection *
3063 rxi_FindConnection(osi_socket socket, afs_uint32 host,
3064 u_short port, u_short serviceId, afs_uint32 cid,
3065 afs_uint32 epoch, int type, u_int securityIndex,
3066 int *unknownService)
3068 int hashindex, flag, i;
3069 struct rx_connection *conn;
3070 *unknownService = 0;
3071 hashindex = CONN_HASH(host, port, cid, epoch, type);
3072 MUTEX_ENTER(&rx_connHashTable_lock);
3073 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
3074 rx_connHashTable[hashindex],
3077 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
3078 && (epoch == conn->epoch)) {
3079 struct rx_peer *pp = conn->peer;
3080 if (securityIndex != conn->securityIndex) {
3081 /* this isn't supposed to happen, but someone could forge a packet
3082 * like this, and there seems to be some CM bug that makes this
3083 * happen from time to time -- in which case, the fileserver
3085 MUTEX_EXIT(&rx_connHashTable_lock);
3086 return (struct rx_connection *)0;
3088 if (pp->host == host && pp->port == port)
3090 if (type == RX_CLIENT_CONNECTION && pp->port == port)
3092 /* So what happens when it's a callback connection? */
3093 if ( /*type == RX_CLIENT_CONNECTION && */
3094 (conn->epoch & 0x80000000))
3098 /* the connection rxLastConn that was used the last time is not the
3099 ** one we are looking for now. Hence, start searching in the hash */
3101 conn = rx_connHashTable[hashindex];
3106 struct rx_service *service;
3107 if (type == RX_CLIENT_CONNECTION) {
3108 MUTEX_EXIT(&rx_connHashTable_lock);
3109 return (struct rx_connection *)0;
3111 service = rxi_FindService(socket, serviceId);
3112 if (!service || (securityIndex >= service->nSecurityObjects)
3113 || (service->securityObjects[securityIndex] == 0)) {
3114 MUTEX_EXIT(&rx_connHashTable_lock);
3115 *unknownService = 1;
3116 return (struct rx_connection *)0;
3118 conn = rxi_AllocConnection(); /* This bzero's the connection */
3119 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
3120 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
3121 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
3122 conn->next = rx_connHashTable[hashindex];
3123 rx_connHashTable[hashindex] = conn;
3124 conn->peer = rxi_FindPeer(host, port, 1);
3125 conn->type = RX_SERVER_CONNECTION;
3126 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
3127 conn->epoch = epoch;
3128 conn->cid = cid & RX_CIDMASK;
3129 conn->ackRate = RX_FAST_ACK_RATE;
3130 conn->service = service;
3131 conn->serviceId = serviceId;
3132 conn->securityIndex = securityIndex;
3133 conn->securityObject = service->securityObjects[securityIndex];
3134 conn->nSpecific = 0;
3135 conn->specific = NULL;
3136 rx_SetConnDeadTime(conn, service->connDeadTime);
3137 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
3138 for (i = 0; i < RX_MAXCALLS; i++) {
3139 conn->twind[i] = rx_initSendWindow;
3140 conn->rwind[i] = rx_initReceiveWindow;
3142 /* Notify security object of the new connection */
3143 RXS_NewConnection(conn->securityObject, conn);
3144 /* XXXX Connection timeout? */
3145 if (service->newConnProc)
3146 (*service->newConnProc) (conn);
3147 if (rx_stats_active)
3148 rx_atomic_inc(&rx_stats.nServerConns);
3151 MUTEX_ENTER(&rx_refcnt_mutex);
3153 MUTEX_EXIT(&rx_refcnt_mutex);
3155 rxLastConn = conn; /* store this connection as the last conn used */
3156 MUTEX_EXIT(&rx_connHashTable_lock);
3161 * Abort the call if the server is over the busy threshold. This
3162 * can be used without requiring a call structure be initialised,
3163 * or connected to a particular channel
3166 rxi_AbortIfServerBusy(osi_socket socket, struct rx_connection *conn,
3167 struct rx_packet *np)
3169 if ((rx_BusyThreshold > 0) &&
3170 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3171 rxi_SendRawAbort(socket, conn->peer->host, conn->peer->port,
3172 rx_BusyError, np, 0);
3173 if (rx_stats_active)
3174 rx_atomic_inc(&rx_stats.nBusies);
3181 static_inline struct rx_call *
3182 rxi_ReceiveClientCall(struct rx_packet *np, struct rx_connection *conn)
3185 struct rx_call *call;
3187 channel = np->header.cid & RX_CHANNELMASK;
3188 MUTEX_ENTER(&conn->conn_call_lock);
3189 call = conn->call[channel];
3190 if (np->header.type == RX_PACKET_TYPE_BUSY) {
3191 conn->lastBusy[channel] = clock_Sec();
3193 if (!call || conn->callNumber[channel] != np->header.callNumber) {
3194 MUTEX_EXIT(&conn->conn_call_lock);
3195 if (rx_stats_active)
3196 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3200 MUTEX_ENTER(&call->lock);
3201 MUTEX_EXIT(&conn->conn_call_lock);
3203 if ((call->state == RX_STATE_DALLY)
3204 && np->header.type == RX_PACKET_TYPE_ACK) {
3205 if (rx_stats_active)
3206 rx_atomic_inc(&rx_stats.ignorePacketDally);
3207 MUTEX_EXIT(&call->lock);
3214 static_inline struct rx_call *
3215 rxi_ReceiveServerCall(osi_socket socket, struct rx_packet *np,
3216 struct rx_connection *conn)
3219 struct rx_call *call;
3221 channel = np->header.cid & RX_CHANNELMASK;
3222 MUTEX_ENTER(&conn->conn_call_lock);
3223 call = conn->call[channel];
3226 if (rxi_AbortIfServerBusy(socket, conn, np)) {
3227 MUTEX_EXIT(&conn->conn_call_lock);
3231 call = rxi_NewCall(conn, channel); /* returns locked call */
3232 *call->callNumber = np->header.callNumber;
3233 MUTEX_EXIT(&conn->conn_call_lock);
3235 call->state = RX_STATE_PRECALL;
3236 clock_GetTime(&call->queueTime);
3237 call->app.bytesSent = 0;
3238 call->app.bytesRcvd = 0;
3239 rxi_KeepAliveOn(call);
3244 if (np->header.callNumber == conn->callNumber[channel]) {
3245 MUTEX_ENTER(&call->lock);
3246 MUTEX_EXIT(&conn->conn_call_lock);
3250 if (np->header.callNumber < conn->callNumber[channel]) {
3251 MUTEX_EXIT(&conn->conn_call_lock);
3252 if (rx_stats_active)
3253 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3257 MUTEX_ENTER(&call->lock);
3258 MUTEX_EXIT(&conn->conn_call_lock);
3260 /* Wait until the transmit queue is idle before deciding
3261 * whether to reset the current call. Chances are that the
3262 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3265 #ifdef RX_ENABLE_LOCKS
3266 if (call->state == RX_STATE_ACTIVE && !call->error) {
3267 rxi_WaitforTQBusy(call);
3268 /* If we entered error state while waiting,
3269 * must call rxi_CallError to permit rxi_ResetCall
3270 * to processed when the tqWaiter count hits zero.
3273 rxi_CallError(call, call->error);
3274 MUTEX_EXIT(&call->lock);
3278 #endif /* RX_ENABLE_LOCKS */
3279 /* If the new call cannot be taken right now send a busy and set
3280 * the error condition in this call, so that it terminates as
3281 * quickly as possible */
3282 if (call->state == RX_STATE_ACTIVE) {
3283 rxi_CallError(call, RX_CALL_DEAD);
3284 rxi_SendSpecial(call, conn, NULL, RX_PACKET_TYPE_BUSY,
3286 MUTEX_EXIT(&call->lock);
3290 if (rxi_AbortIfServerBusy(socket, conn, np)) {
3291 MUTEX_EXIT(&call->lock);
3295 rxi_ResetCall(call, 0);
3296 /* The conn_call_lock is not held but no one else should be
3297 * using this call channel while we are processing this incoming
3298 * packet. This assignment should be safe.
3300 *call->callNumber = np->header.callNumber;
3301 call->state = RX_STATE_PRECALL;
3302 clock_GetTime(&call->queueTime);
3303 call->app.bytesSent = 0;
3304 call->app.bytesRcvd = 0;
3305 rxi_KeepAliveOn(call);
3311 /* There are two packet tracing routines available for testing and monitoring
3312 * Rx. One is called just after every packet is received and the other is
3313 * called just before every packet is sent. Received packets, have had their
3314 * headers decoded, and packets to be sent have not yet had their headers
3315 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
3316 * containing the network address. Both can be modified. The return value, if
3317 * non-zero, indicates that the packet should be dropped. */
3319 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
3320 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
3322 /* A packet has been received off the interface. Np is the packet, socket is
3323 * the socket number it was received from (useful in determining which service
3324 * this packet corresponds to), and (host, port) reflect the host,port of the
3325 * sender. This call returns the packet to the caller if it is finished with
3326 * it, rather than de-allocating it, just as a small performance hack */
3329 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
3330 afs_uint32 host, u_short port, int *tnop,
3331 struct rx_call **newcallp)
3333 struct rx_call *call;
3334 struct rx_connection *conn;
3336 int unknownService = 0;
3340 struct rx_packet *tnp;
3343 /* We don't print out the packet until now because (1) the time may not be
3344 * accurate enough until now in the lwp implementation (rx_Listener only gets
3345 * the time after the packet is read) and (2) from a protocol point of view,
3346 * this is the first time the packet has been seen */
3347 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
3348 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
3349 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT"\n",
3350 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
3351 np->header.epoch, np->header.cid, np->header.callNumber,
3352 np->header.seq, np->header.flags, np));
3355 /* Account for connectionless packets */
3356 if (rx_stats_active &&
3357 ((np->header.type == RX_PACKET_TYPE_VERSION) ||
3358 (np->header.type == RX_PACKET_TYPE_DEBUG))) {
3359 struct rx_peer *peer;
3361 /* Try to look up the peer structure, but don't create one */
3362 peer = rxi_FindPeer(host, port, 0);
3364 /* Since this may not be associated with a connection, it may have
3365 * no refCount, meaning we could race with ReapConnections
3368 if (peer && (peer->refCount > 0)) {
3369 #ifdef AFS_RXERRQ_ENV
3370 if (rx_atomic_read(&peer->neterrs)) {
3371 rx_atomic_set(&peer->neterrs, 0);
3374 MUTEX_ENTER(&peer->peer_lock);
3375 peer->bytesReceived += np->length;
3376 MUTEX_EXIT(&peer->peer_lock);
3380 if (np->header.type == RX_PACKET_TYPE_VERSION) {
3381 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
3384 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
3385 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
3388 /* If an input tracer function is defined, call it with the packet and
3389 * network address. Note this function may modify its arguments. */
3390 if (rx_justReceived) {
3391 struct sockaddr_in addr;
3393 addr.sin_family = AF_INET;
3394 addr.sin_port = port;
3395 addr.sin_addr.s_addr = host;
3396 memset(&addr.sin_zero, 0, sizeof(addr.sin_zero));
3397 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
3398 addr.sin_len = sizeof(addr);
3399 #endif /* AFS_OSF_ENV */
3400 drop = (*rx_justReceived) (np, &addr);
3401 /* drop packet if return value is non-zero */
3404 port = addr.sin_port; /* in case fcn changed addr */
3405 host = addr.sin_addr.s_addr;
3409 /* If packet was not sent by the client, then *we* must be the client */
3410 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
3411 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
3413 /* Find the connection (or fabricate one, if we're the server & if
3414 * necessary) associated with this packet */
3416 rxi_FindConnection(socket, host, port, np->header.serviceId,
3417 np->header.cid, np->header.epoch, type,
3418 np->header.securityIndex, &unknownService);
3420 /* To avoid having 2 connections just abort at each other,
3421 don't abort an abort. */
3423 if (unknownService && (np->header.type != RX_PACKET_TYPE_ABORT))
3424 rxi_SendRawAbort(socket, host, port, RX_INVALID_OPERATION,
3429 #ifdef AFS_RXERRQ_ENV
3430 if (rx_atomic_read(&conn->peer->neterrs)) {
3431 rx_atomic_set(&conn->peer->neterrs, 0);
3435 /* If we're doing statistics, then account for the incoming packet */
3436 if (rx_stats_active) {
3437 MUTEX_ENTER(&conn->peer->peer_lock);
3438 conn->peer->bytesReceived += np->length;
3439 MUTEX_EXIT(&conn->peer->peer_lock);
3442 /* If the connection is in an error state, send an abort packet and ignore
3443 * the incoming packet */
3445 /* Don't respond to an abort packet--we don't want loops! */
3446 MUTEX_ENTER(&conn->conn_data_lock);
3447 if (np->header.type != RX_PACKET_TYPE_ABORT)
3448 np = rxi_SendConnectionAbort(conn, np, 1, 0);
3449 putConnection(conn);
3450 MUTEX_EXIT(&conn->conn_data_lock);
3454 /* Check for connection-only requests (i.e. not call specific). */
3455 if (np->header.callNumber == 0) {
3456 switch (np->header.type) {
3457 case RX_PACKET_TYPE_ABORT: {
3458 /* What if the supplied error is zero? */
3459 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
3460 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
3461 rxi_ConnectionError(conn, errcode);
3462 putConnection(conn);
3465 case RX_PACKET_TYPE_CHALLENGE:
3466 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
3467 putConnection(conn);
3469 case RX_PACKET_TYPE_RESPONSE:
3470 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
3471 putConnection(conn);
3473 case RX_PACKET_TYPE_PARAMS:
3474 case RX_PACKET_TYPE_PARAMS + 1:
3475 case RX_PACKET_TYPE_PARAMS + 2:
3476 /* ignore these packet types for now */
3477 putConnection(conn);
3481 /* Should not reach here, unless the peer is broken: send an
3483 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
3484 MUTEX_ENTER(&conn->conn_data_lock);
3485 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
3486 putConnection(conn);
3487 MUTEX_EXIT(&conn->conn_data_lock);
3492 if (type == RX_SERVER_CONNECTION)
3493 call = rxi_ReceiveServerCall(socket, np, conn);
3495 call = rxi_ReceiveClientCall(np, conn);
3498 putConnection(conn);
3502 MUTEX_ASSERT(&call->lock);
3503 /* Set remote user defined status from packet */
3504 call->remoteStatus = np->header.userStatus;
3506 /* Now do packet type-specific processing */
3507 switch (np->header.type) {
3508 case RX_PACKET_TYPE_DATA:
3509 /* If we're a client, and receiving a response, then all the packets
3510 * we transmitted packets are implicitly acknowledged. */
3511 if (type == RX_CLIENT_CONNECTION && !opr_queue_IsEmpty(&call->tq))
3512 rxi_AckAllInTransmitQueue(call);
3514 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3517 case RX_PACKET_TYPE_ACK:
3518 /* Respond immediately to ack packets requesting acknowledgement
3520 if (np->header.flags & RX_REQUEST_ACK) {
3522 (void)rxi_SendCallAbort(call, 0, 1, 0);
3524 (void)rxi_SendAck(call, 0, np->header.serial,
3525 RX_ACK_PING_RESPONSE, 1);
3527 np = rxi_ReceiveAckPacket(call, np, 1);
3529 case RX_PACKET_TYPE_ABORT: {
3530 /* An abort packet: reset the call, passing the error up to the user. */
3531 /* What if error is zero? */
3532 /* What if the error is -1? the application will treat it as a timeout. */
3533 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3534 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3535 rxi_CallError(call, errdata);
3536 MUTEX_EXIT(&call->lock);
3537 putConnection(conn);
3538 return np; /* xmitting; drop packet */
3540 case RX_PACKET_TYPE_BUSY:
3541 /* Mostly ignore BUSY packets. We will update lastReceiveTime below,
3542 * so we don't think the endpoint is completely dead, but otherwise
3543 * just act as if we never saw anything. If all we get are BUSY packets
3544 * back, then we will eventually error out with RX_CALL_TIMEOUT if the
3545 * connection is configured with idle/hard timeouts. */
3548 case RX_PACKET_TYPE_ACKALL:
3549 /* All packets acknowledged, so we can drop all packets previously
3550 * readied for sending */
3551 rxi_AckAllInTransmitQueue(call);
3554 /* Should not reach here, unless the peer is broken: send an abort
3556 rxi_CallError(call, RX_PROTOCOL_ERROR);
3557 np = rxi_SendCallAbort(call, np, 1, 0);
3560 /* Note when this last legitimate packet was received, for keep-alive
3561 * processing. Note, we delay getting the time until now in the hope that
3562 * the packet will be delivered to the user before any get time is required
3563 * (if not, then the time won't actually be re-evaluated here). */
3564 call->lastReceiveTime = clock_Sec();
3565 MUTEX_EXIT(&call->lock);
3566 putConnection(conn);
3570 /* return true if this is an "interesting" connection from the point of view
3571 of someone trying to debug the system */
3573 rxi_IsConnInteresting(struct rx_connection *aconn)
3576 struct rx_call *tcall;
3578 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3581 for (i = 0; i < RX_MAXCALLS; i++) {
3582 tcall = aconn->call[i];
3584 if ((tcall->state == RX_STATE_PRECALL)
3585 || (tcall->state == RX_STATE_ACTIVE))
3587 if ((tcall->app.mode == RX_MODE_SENDING)
3588 || (tcall->app.mode == RX_MODE_RECEIVING))
3596 /* if this is one of the last few packets AND it wouldn't be used by the
3597 receiving call to immediately satisfy a read request, then drop it on
3598 the floor, since accepting it might prevent a lock-holding thread from
3599 making progress in its reading. If a call has been cleared while in
3600 the precall state then ignore all subsequent packets until the call
3601 is assigned to a thread. */
3604 TooLow(struct rx_packet *ap, struct rx_call *acall)
3608 MUTEX_ENTER(&rx_quota_mutex);
3609 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3610 && (acall->state == RX_STATE_PRECALL))
3611 || ((rx_nFreePackets < rxi_dataQuota + 2)
3612 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3613 && (acall->flags & RX_CALL_READER_WAIT)))) {
3616 MUTEX_EXIT(&rx_quota_mutex);
3622 * Clear the attach wait flag on a connection and proceed.
3624 * Any processing waiting for a connection to be attached should be
3625 * unblocked. We clear the flag and do any other needed tasks.
3628 * the conn to unmark waiting for attach
3630 * @pre conn's conn_data_lock must be locked before calling this function
3634 rxi_ConnClearAttachWait(struct rx_connection *conn)
3636 /* Indicate that rxi_CheckReachEvent is no longer running by
3637 * clearing the flag. Must be atomic under conn_data_lock to
3638 * avoid a new call slipping by: rxi_CheckConnReach holds
3639 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3641 conn->flags &= ~RX_CONN_ATTACHWAIT;
3642 if (conn->flags & RX_CONN_NAT_PING) {
3643 conn->flags &= ~RX_CONN_NAT_PING;
3644 rxi_ScheduleNatKeepAliveEvent(conn);
3649 * Event handler function for connection-specific events for checking
3650 * reachability. Also called directly from main code with |event| == NULL
3651 * in order to trigger the initial reachability check.
3653 * When |event| == NULL, must be called with the connection data lock held,
3654 * but returns with the lock unlocked.
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;
3666 MUTEX_ENTER(&conn->conn_data_lock);
3668 if (event != NULL && event == conn->checkReachEvent)
3669 rxevent_Put(&conn->checkReachEvent);
3670 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3671 MUTEX_EXIT(&conn->conn_data_lock);
3675 MUTEX_ENTER(&conn->conn_call_lock);
3676 MUTEX_ENTER(&conn->conn_data_lock);
3677 for (i = 0; i < RX_MAXCALLS; i++) {
3678 struct rx_call *tc = conn->call[i];
3679 if (tc && tc->state == RX_STATE_PRECALL) {
3685 rxi_ConnClearAttachWait(conn);
3686 MUTEX_EXIT(&conn->conn_data_lock);
3687 MUTEX_EXIT(&conn->conn_call_lock);
3692 MUTEX_ENTER(&call->lock);
3693 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3695 MUTEX_EXIT(&call->lock);
3697 clock_GetTime(&now);
3699 when.sec += RX_CHECKREACH_TIMEOUT;
3700 MUTEX_ENTER(&conn->conn_data_lock);
3701 if (!conn->checkReachEvent) {
3702 rx_GetConnection(conn);
3703 conn->checkReachEvent = rxevent_Post(&when, &now,
3704 rxi_CheckReachEvent, conn,
3707 MUTEX_EXIT(&conn->conn_data_lock);
3710 /* If fired as an event handler, drop our refcount on the connection. */
3712 putConnection(conn);
3716 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3718 struct rx_service *service = conn->service;
3719 struct rx_peer *peer = conn->peer;
3720 afs_uint32 now, lastReach;
3722 if (service->checkReach == 0)
3726 MUTEX_ENTER(&peer->peer_lock);
3727 lastReach = peer->lastReachTime;
3728 MUTEX_EXIT(&peer->peer_lock);
3729 if (now - lastReach < RX_CHECKREACH_TTL)
3732 MUTEX_ENTER(&conn->conn_data_lock);
3733 if (conn->flags & RX_CONN_ATTACHWAIT) {
3734 MUTEX_EXIT(&conn->conn_data_lock);
3737 conn->flags |= RX_CONN_ATTACHWAIT;
3738 if (conn->checkReachEvent == NULL) {
3739 /* rxi_CheckReachEvent(NULL, ...) will drop the lock. */
3740 rxi_CheckReachEvent(NULL, conn, call, 0);
3742 MUTEX_EXIT(&conn->conn_data_lock);
3748 /* try to attach call, if authentication is complete */
3750 TryAttach(struct rx_call *acall, osi_socket socket,
3751 int *tnop, struct rx_call **newcallp,
3754 struct rx_connection *conn = acall->conn;
3756 if (conn->type == RX_SERVER_CONNECTION
3757 && acall->state == RX_STATE_PRECALL) {
3758 /* Don't attach until we have any req'd. authentication. */
3759 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3760 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3761 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3762 /* Note: this does not necessarily succeed; there
3763 * may not any proc available
3766 rxi_ChallengeOn(acall->conn);
3771 /* A data packet has been received off the interface. This packet is
3772 * appropriate to the call (the call is in the right state, etc.). This
3773 * routine can return a packet to the caller, for re-use */
3775 static struct rx_packet *
3776 rxi_ReceiveDataPacket(struct rx_call *call,
3777 struct rx_packet *np, int istack,
3778 osi_socket socket, afs_uint32 host, u_short port,
3779 int *tnop, struct rx_call **newcallp)
3781 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3786 afs_uint32 serial=0, flags=0;
3788 struct rx_packet *tnp;
3789 if (rx_stats_active)
3790 rx_atomic_inc(&rx_stats.dataPacketsRead);
3793 /* If there are no packet buffers, drop this new packet, unless we can find
3794 * packet buffers from inactive calls */
3796 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3797 MUTEX_ENTER(&rx_freePktQ_lock);
3798 rxi_NeedMorePackets = TRUE;
3799 MUTEX_EXIT(&rx_freePktQ_lock);
3800 if (rx_stats_active)
3801 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3802 rxi_calltrace(RX_TRACE_DROP, call);
3803 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems\n", np));
3804 /* We used to clear the receive queue here, in an attempt to free
3805 * packets. However this is unsafe if the queue has received a
3806 * soft ACK for the final packet */
3807 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
3813 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3814 * packet is one of several packets transmitted as a single
3815 * datagram. Do not send any soft or hard acks until all packets
3816 * in a jumbogram have been processed. Send negative acks right away.
3818 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3819 /* tnp is non-null when there are more packets in the
3820 * current jumbo gram */
3827 seq = np->header.seq;
3828 serial = np->header.serial;
3829 flags = np->header.flags;
3831 /* If the call is in an error state, send an abort message */
3833 return rxi_SendCallAbort(call, np, istack, 0);
3835 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3836 * AFS 3.5 jumbogram. */
3837 if (flags & RX_JUMBO_PACKET) {
3838 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3843 if (np->header.spare != 0) {
3844 MUTEX_ENTER(&call->conn->conn_data_lock);
3845 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3846 MUTEX_EXIT(&call->conn->conn_data_lock);
3849 /* The usual case is that this is the expected next packet */
3850 if (seq == call->rnext) {
3852 /* Check to make sure it is not a duplicate of one already queued */
3853 if (!opr_queue_IsEmpty(&call->rq)
3854 && opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq == seq) {
3855 if (rx_stats_active)
3856 rx_atomic_inc(&rx_stats.dupPacketsRead);
3857 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate\n", np));
3858 rxi_CancelDelayedAckEvent(call);
3859 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3865 /* It's the next packet. Stick it on the receive queue
3866 * for this call. Set newPackets to make sure we wake
3867 * the reader once all packets have been processed */
3868 #ifdef RX_TRACK_PACKETS
3869 np->flags |= RX_PKTFLAG_RQ;
3871 opr_queue_Prepend(&call->rq, &np->entry);
3872 #ifdef RXDEBUG_PACKET
3874 #endif /* RXDEBUG_PACKET */
3876 np = NULL; /* We can't use this anymore */
3879 /* If an ack is requested then set a flag to make sure we
3880 * send an acknowledgement for this packet */
3881 if (flags & RX_REQUEST_ACK) {
3882 ackNeeded = RX_ACK_REQUESTED;
3885 /* Keep track of whether we have received the last packet */
3886 if (flags & RX_LAST_PACKET) {
3887 call->flags |= RX_CALL_HAVE_LAST;
3891 /* Check whether we have all of the packets for this call */
3892 if (call->flags & RX_CALL_HAVE_LAST) {
3893 afs_uint32 tseq; /* temporary sequence number */
3894 struct opr_queue *cursor;
3896 for (tseq = seq, opr_queue_Scan(&call->rq, cursor)) {
3897 struct rx_packet *tp;
3899 tp = opr_queue_Entry(cursor, struct rx_packet, entry);
3900 if (tseq != tp->header.seq)
3902 if (tp->header.flags & RX_LAST_PACKET) {
3903 call->flags |= RX_CALL_RECEIVE_DONE;
3910 /* Provide asynchronous notification for those who want it
3911 * (e.g. multi rx) */
3912 if (call->arrivalProc) {
3913 (*call->arrivalProc) (call, call->arrivalProcHandle,
3914 call->arrivalProcArg);
3915 call->arrivalProc = (void (*)())0;
3918 /* Update last packet received */
3921 /* If there is no server process serving this call, grab
3922 * one, if available. We only need to do this once. If a
3923 * server thread is available, this thread becomes a server
3924 * thread and the server thread becomes a listener thread. */
3926 TryAttach(call, socket, tnop, newcallp, 0);
3929 /* This is not the expected next packet. */
3931 /* Determine whether this is a new or old packet, and if it's
3932 * a new one, whether it fits into the current receive window.
3933 * Also figure out whether the packet was delivered in sequence.
3934 * We use the prev variable to determine whether the new packet
3935 * is the successor of its immediate predecessor in the
3936 * receive queue, and the missing flag to determine whether
3937 * any of this packets predecessors are missing. */
3939 afs_uint32 prev; /* "Previous packet" sequence number */
3940 struct opr_queue *cursor;
3941 int missing; /* Are any predecessors missing? */
3943 /* If the new packet's sequence number has been sent to the
3944 * application already, then this is a duplicate */
3945 if (seq < call->rnext) {
3946 if (rx_stats_active)
3947 rx_atomic_inc(&rx_stats.dupPacketsRead);
3948 rxi_CancelDelayedAckEvent(call);
3949 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3955 /* If the sequence number is greater than what can be
3956 * accomodated by the current window, then send a negative
3957 * acknowledge and drop the packet */
3958 if ((call->rnext + call->rwind) <= seq) {
3959 rxi_CancelDelayedAckEvent(call);
3960 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
3967 /* Look for the packet in the queue of old received packets */
3968 prev = call->rnext - 1;
3970 for (opr_queue_Scan(&call->rq, cursor)) {
3971 struct rx_packet *tp
3972 = opr_queue_Entry(cursor, struct rx_packet, entry);
3974 /*Check for duplicate packet */
3975 if (seq == tp->header.seq) {
3976 if (rx_stats_active)
3977 rx_atomic_inc(&rx_stats.dupPacketsRead);
3978 rxi_CancelDelayedAckEvent(call);
3979 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
3985 /* If we find a higher sequence packet, break out and
3986 * insert the new packet here. */
3987 if (seq < tp->header.seq)
3989 /* Check for missing packet */
3990 if (tp->header.seq != prev + 1) {
3994 prev = tp->header.seq;
3997 /* Keep track of whether we have received the last packet. */
3998 if (flags & RX_LAST_PACKET) {
3999 call->flags |= RX_CALL_HAVE_LAST;
4002 /* It's within the window: add it to the the receive queue.
4003 * tp is left by the previous loop either pointing at the
4004 * packet before which to insert the new packet, or at the
4005 * queue head if the queue is empty or the packet should be
4007 #ifdef RX_TRACK_PACKETS
4008 np->flags |= RX_PKTFLAG_RQ;
4010 #ifdef RXDEBUG_PACKET
4012 #endif /* RXDEBUG_PACKET */
4013 opr_queue_InsertBefore(cursor, &np->entry);
4017 /* Check whether we have all of the packets for this call */
4018 if ((call->flags & RX_CALL_HAVE_LAST)
4019 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
4020 afs_uint32 tseq; /* temporary sequence number */
4023 for (opr_queue_Scan(&call->rq, cursor)) {
4024 struct rx_packet *tp
4025 = opr_queue_Entry(cursor, struct rx_packet, entry);
4026 if (tseq != tp->header.seq)
4028 if (tp->header.flags & RX_LAST_PACKET) {
4029 call->flags |= RX_CALL_RECEIVE_DONE;
4036 /* We need to send an ack of the packet is out of sequence,
4037 * or if an ack was requested by the peer. */
4038 if (seq != prev + 1 || missing) {
4039 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
4040 } else if (flags & RX_REQUEST_ACK) {
4041 ackNeeded = RX_ACK_REQUESTED;
4044 /* Acknowledge the last packet for each call */
4045 if (flags & RX_LAST_PACKET) {
4056 * If the receiver is waiting for an iovec, fill the iovec
4057 * using the data from the receive queue */
4058 if (call->flags & RX_CALL_IOVEC_WAIT) {
4059 didHardAck = rxi_FillReadVec(call, serial);
4060 /* the call may have been aborted */
4069 /* Wakeup the reader if any */
4070 if ((call->flags & RX_CALL_READER_WAIT)
4071 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
4072 || (call->iovNext >= call->iovMax)
4073 || (call->flags & RX_CALL_RECEIVE_DONE))) {
4074 call->flags &= ~RX_CALL_READER_WAIT;
4075 #ifdef RX_ENABLE_LOCKS
4076 CV_BROADCAST(&call->cv_rq);
4078 osi_rxWakeup(&call->rq);
4084 * Send an ack when requested by the peer, or once every
4085 * rxi_SoftAckRate packets until the last packet has been
4086 * received. Always send a soft ack for the last packet in
4087 * the server's reply. */
4089 rxi_CancelDelayedAckEvent(call);
4090 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
4091 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
4092 rxi_CancelDelayedAckEvent(call);
4093 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
4094 } else if (call->nSoftAcks) {
4095 if (haveLast && !(flags & RX_CLIENT_INITIATED))
4096 rxi_PostDelayedAckEvent(call, &rx_lastAckDelay);
4098 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
4099 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
4100 rxi_CancelDelayedAckEvent(call);
4107 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
4109 struct rx_peer *peer = conn->peer;
4111 MUTEX_ENTER(&peer->peer_lock);
4112 peer->lastReachTime = clock_Sec();
4113 MUTEX_EXIT(&peer->peer_lock);
4115 MUTEX_ENTER(&conn->conn_data_lock);
4116 if (conn->flags & RX_CONN_ATTACHWAIT) {
4119 rxi_ConnClearAttachWait(conn);
4120 MUTEX_EXIT(&conn->conn_data_lock);
4122 for (i = 0; i < RX_MAXCALLS; i++) {
4123 struct rx_call *call = conn->call[i];
4126 MUTEX_ENTER(&call->lock);
4127 /* tnop can be null if newcallp is null */
4128 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
4130 MUTEX_EXIT(&call->lock);
4134 MUTEX_EXIT(&conn->conn_data_lock);
4137 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
4139 rx_ack_reason(int reason)
4142 case RX_ACK_REQUESTED:
4144 case RX_ACK_DUPLICATE:
4146 case RX_ACK_OUT_OF_SEQUENCE:
4148 case RX_ACK_EXCEEDS_WINDOW:
4150 case RX_ACK_NOSPACE:
4154 case RX_ACK_PING_RESPONSE:
4167 /* The real smarts of the whole thing. */
4168 static struct rx_packet *
4169 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
4172 struct rx_ackPacket *ap;
4174 struct rx_packet *tp;
4175 struct rx_connection *conn = call->conn;
4176 struct rx_peer *peer = conn->peer;
4177 struct opr_queue *cursor;
4178 struct clock now; /* Current time, for RTT calculations */
4186 int newAckCount = 0;
4187 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
4188 int pktsize = 0; /* Set if we need to update the peer mtu */
4189 int conn_data_locked = 0;
4191 if (rx_stats_active)
4192 rx_atomic_inc(&rx_stats.ackPacketsRead);
4193 ap = (struct rx_ackPacket *)rx_DataOf(np);
4194 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
4196 return np; /* truncated ack packet */
4198 /* depends on ack packet struct */
4199 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
4200 first = ntohl(ap->firstPacket);
4201 prev = ntohl(ap->previousPacket);
4202 serial = ntohl(ap->serial);
4205 * Ignore ack packets received out of order while protecting
4206 * against peers that set the previousPacket field to a packet
4207 * serial number instead of a sequence number.
4209 if (first < call->tfirst ||
4210 (first == call->tfirst && prev < call->tprev && prev < call->tfirst
4217 if (np->header.flags & RX_SLOW_START_OK) {
4218 call->flags |= RX_CALL_SLOW_START_OK;
4221 if (ap->reason == RX_ACK_PING_RESPONSE)
4222 rxi_UpdatePeerReach(conn, call);
4224 if (conn->lastPacketSizeSeq) {
4225 MUTEX_ENTER(&conn->conn_data_lock);
4226 conn_data_locked = 1;
4227 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
4228 pktsize = conn->lastPacketSize;
4229 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
4232 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
4233 if (!conn_data_locked) {
4234 MUTEX_ENTER(&conn->conn_data_lock);
4235 conn_data_locked = 1;
4237 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
4238 /* process mtu ping ack */
4239 pktsize = conn->lastPingSize;
4240 conn->lastPingSizeSer = conn->lastPingSize = 0;
4244 if (conn_data_locked) {
4245 MUTEX_EXIT(&conn->conn_data_lock);
4246 conn_data_locked = 0;
4250 if (rxdebug_active) {
4254 len = _snprintf(msg, sizeof(msg),
4255 "tid[%d] RACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
4256 GetCurrentThreadId(), rx_ack_reason(ap->reason),
4257 ntohl(ap->serial), ntohl(ap->previousPacket),
4258 (unsigned int)np->header.seq, ntohl(ap->firstPacket),
4259 ap->nAcks, ntohs(ap->bufferSpace) );
4263 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
4264 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4268 OutputDebugString(msg);
4270 #else /* AFS_NT40_ENV */
4273 "RACK: reason %x previous %u seq %u serial %u first %u",
4274 ap->reason, ntohl(ap->previousPacket),
4275 (unsigned int)np->header.seq, (unsigned int)serial,
4276 ntohl(ap->firstPacket));
4279 for (offset = 0; offset < nAcks; offset++)
4280 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4285 #endif /* AFS_NT40_ENV */
4288 MUTEX_ENTER(&peer->peer_lock);
4291 * Start somewhere. Can't assume we can send what we can receive,
4292 * but we are clearly receiving.
4294 if (!peer->maxPacketSize)
4295 peer->maxPacketSize = RX_MIN_PACKET_SIZE - RX_HEADER_SIZE;
4297 if (pktsize > peer->maxPacketSize) {
4298 peer->maxPacketSize = pktsize;
4299 if ((pktsize + RX_HEADER_SIZE > peer->ifMTU)) {
4300 peer->ifMTU = pktsize + RX_HEADER_SIZE;
4301 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4302 rxi_ScheduleGrowMTUEvent(call, 1);
4307 clock_GetTime(&now);
4309 /* The transmit queue splits into 4 sections.
4311 * The first section is packets which have now been acknowledged
4312 * by a window size change in the ack. These have reached the
4313 * application layer, and may be discarded. These are packets
4314 * with sequence numbers < ap->firstPacket.
4316 * The second section is packets which have sequence numbers in
4317 * the range ap->firstPacket to ap->firstPacket + ap->nAcks. The
4318 * contents of the packet's ack array determines whether these
4319 * packets are acknowledged or not.
4321 * The third section is packets which fall above the range
4322 * addressed in the ack packet. These have not yet been received
4325 * The four section is packets which have not yet been transmitted.
4326 * These packets will have a header.serial of 0.
4329 /* First section - implicitly acknowledged packets that can be
4333 tp = opr_queue_First(&call->tq, struct rx_packet, entry);
4334 while(!opr_queue_IsEnd(&call->tq, &tp->entry) && tp->header.seq < first) {
4335 struct rx_packet *next;
4337 next = opr_queue_Next(&tp->entry, struct rx_packet, entry);
4338 call->tfirst = tp->header.seq + 1;
4340 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4342 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4345 #ifdef RX_ENABLE_LOCKS
4346 /* XXX Hack. Because we have to release the global call lock when sending
4347 * packets (osi_NetSend) we drop all acks while we're traversing the tq
4348 * in rxi_Start sending packets out because packets may move to the
4349 * freePacketQueue as result of being here! So we drop these packets until
4350 * we're safely out of the traversing. Really ugly!
4351 * To make it even uglier, if we're using fine grain locking, we can
4352 * set the ack bits in the packets and have rxi_Start remove the packets
4353 * when it's done transmitting.
4355 if (call->flags & RX_CALL_TQ_BUSY) {
4356 tp->flags |= RX_PKTFLAG_ACKED;
4357 call->flags |= RX_CALL_TQ_SOME_ACKED;
4359 #endif /* RX_ENABLE_LOCKS */
4361 opr_queue_Remove(&tp->entry);
4362 #ifdef RX_TRACK_PACKETS
4363 tp->flags &= ~RX_PKTFLAG_TQ;
4365 #ifdef RXDEBUG_PACKET
4367 #endif /* RXDEBUG_PACKET */
4368 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4373 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
4375 /* Second section of the queue - packets for which we are receiving
4378 * Go through the explicit acks/nacks and record the results in
4379 * the waiting packets. These are packets that can't be released
4380 * yet, even with a positive acknowledge. This positive
4381 * acknowledge only means the packet has been received by the
4382 * peer, not that it will be retained long enough to be sent to
4383 * the peer's upper level. In addition, reset the transmit timers
4384 * of any missing packets (those packets that must be missing
4385 * because this packet was out of sequence) */
4387 call->nSoftAcked = 0;
4389 while (!opr_queue_IsEnd(&call->tq, &tp->entry)
4390 && tp->header.seq < first + nAcks) {
4391 /* Set the acknowledge flag per packet based on the
4392 * information in the ack packet. An acknowlegded packet can
4393 * be downgraded when the server has discarded a packet it
4394 * soacked previously, or when an ack packet is received
4395 * out of sequence. */
4396 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4397 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4399 tp->flags |= RX_PKTFLAG_ACKED;
4400 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4407 } else /* RX_ACK_TYPE_NACK */ {
4408 tp->flags &= ~RX_PKTFLAG_ACKED;
4412 tp = opr_queue_Next(&tp->entry, struct rx_packet, entry);
4415 /* We don't need to take any action with the 3rd or 4th section in the
4416 * queue - they're not addressed by the contents of this ACK packet.
4419 /* if the ack packet has a receivelen field hanging off it,
4420 * update our state */
4421 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4424 /* If the ack packet has a "recommended" size that is less than
4425 * what I am using now, reduce my size to match */
4426 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4427 (int)sizeof(afs_int32), &tSize);
4428 tSize = (afs_uint32) ntohl(tSize);
4429 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4431 /* Get the maximum packet size to send to this peer */
4432 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4434 tSize = (afs_uint32) ntohl(tSize);
4435 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4436 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4438 /* sanity check - peer might have restarted with different params.
4439 * If peer says "send less", dammit, send less... Peer should never
4440 * be unable to accept packets of the size that prior AFS versions would
4441 * send without asking. */
4442 if (peer->maxMTU != tSize) {
4443 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4445 peer->maxMTU = tSize;
4446 peer->MTU = MIN(tSize, peer->MTU);
4447 call->MTU = MIN(call->MTU, tSize);
4450 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4453 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4454 (int)sizeof(afs_int32), &tSize);
4455 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4456 if (tSize < call->twind) { /* smaller than our send */
4457 call->twind = tSize; /* window, we must send less... */
4458 call->ssthresh = MIN(call->twind, call->ssthresh);
4459 call->conn->twind[call->channel] = call->twind;
4462 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4463 * network MTU confused with the loopback MTU. Calculate the
4464 * maximum MTU here for use in the slow start code below.
4466 /* Did peer restart with older RX version? */
4467 if (peer->maxDgramPackets > 1) {
4468 peer->maxDgramPackets = 1;
4470 } else if (np->length >=
4471 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4474 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4475 sizeof(afs_int32), &tSize);
4476 tSize = (afs_uint32) ntohl(tSize);
4478 * As of AFS 3.5 we set the send window to match the receive window.
4480 if (tSize < call->twind) {
4481 call->twind = tSize;
4482 call->conn->twind[call->channel] = call->twind;
4483 call->ssthresh = MIN(call->twind, call->ssthresh);
4484 } else if (tSize > call->twind) {
4485 call->twind = tSize;
4486 call->conn->twind[call->channel] = call->twind;
4490 * As of AFS 3.5, a jumbogram is more than one fixed size
4491 * packet transmitted in a single UDP datagram. If the remote
4492 * MTU is smaller than our local MTU then never send a datagram
4493 * larger than the natural MTU.
4496 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4497 (int)sizeof(afs_int32), &tSize);
4498 maxDgramPackets = (afs_uint32) ntohl(tSize);
4499 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4501 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4502 if (maxDgramPackets > 1) {
4503 peer->maxDgramPackets = maxDgramPackets;
4504 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4506 peer->maxDgramPackets = 1;
4507 call->MTU = peer->natMTU;
4509 } else if (peer->maxDgramPackets > 1) {
4510 /* Restarted with lower version of RX */
4511 peer->maxDgramPackets = 1;
4513 } else if (peer->maxDgramPackets > 1
4514 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4515 /* Restarted with lower version of RX */
4516 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4517 peer->natMTU = OLD_MAX_PACKET_SIZE;
4518 peer->MTU = OLD_MAX_PACKET_SIZE;
4519 peer->maxDgramPackets = 1;
4520 peer->nDgramPackets = 1;
4522 call->MTU = OLD_MAX_PACKET_SIZE;
4525 /* If the window has been extended by this acknowledge packet,
4526 * then wakeup a sender waiting in alloc for window space, or try
4527 * sending packets now, if he's been sitting on packets due to
4528 * lack of window space */
4529 if (call->tnext < (call->tfirst + call->twind)) {
4530 #ifdef RX_ENABLE_LOCKS
4531 CV_SIGNAL(&call->cv_twind);
4533 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4534 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4535 osi_rxWakeup(&call->twind);
4538 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4539 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4545 * Calculate how many datagrams were successfully received after
4546 * the first missing packet and adjust the negative ack counter
4551 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4552 if (call->nNacks < nNacked) {
4553 call->nNacks = nNacked;
4556 call->nAcks += newAckCount;
4560 /* If the packet contained new acknowledgements, rather than just
4561 * being a duplicate of one we have previously seen, then we can restart
4564 if (newAckCount > 0)
4565 rxi_rto_packet_acked(call, istack);
4567 if (call->flags & RX_CALL_FAST_RECOVER) {
4568 if (newAckCount == 0) {
4569 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4571 call->flags &= ~RX_CALL_FAST_RECOVER;
4572 call->cwind = call->nextCwind;
4573 call->nextCwind = 0;
4576 call->nCwindAcks = 0;
4577 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4578 /* Three negative acks in a row trigger congestion recovery */
4579 call->flags |= RX_CALL_FAST_RECOVER;
4580 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4582 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4583 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4584 call->nextCwind = call->ssthresh;
4587 peer->MTU = call->MTU;
4588 peer->cwind = call->nextCwind;
4589 peer->nDgramPackets = call->nDgramPackets;
4591 call->congestSeq = peer->congestSeq;
4593 /* Reset the resend times on the packets that were nacked
4594 * so we will retransmit as soon as the window permits
4598 for (opr_queue_ScanBackwards(&call->tq, cursor)) {
4599 struct rx_packet *tp =
4600 opr_queue_Entry(cursor, struct rx_packet, entry);
4602 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4603 tp->flags &= ~RX_PKTFLAG_SENT;
4605 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4610 /* If cwind is smaller than ssthresh, then increase
4611 * the window one packet for each ack we receive (exponential
4613 * If cwind is greater than or equal to ssthresh then increase
4614 * the congestion window by one packet for each cwind acks we
4615 * receive (linear growth). */
4616 if (call->cwind < call->ssthresh) {
4618 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4619 call->nCwindAcks = 0;
4621 call->nCwindAcks += newAckCount;
4622 if (call->nCwindAcks >= call->cwind) {
4623 call->nCwindAcks = 0;
4624 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4628 * If we have received several acknowledgements in a row then
4629 * it is time to increase the size of our datagrams
4631 if ((int)call->nAcks > rx_nDgramThreshold) {
4632 if (peer->maxDgramPackets > 1) {
4633 if (call->nDgramPackets < peer->maxDgramPackets) {
4634 call->nDgramPackets++;
4636 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4637 } else if (call->MTU < peer->maxMTU) {
4638 /* don't upgrade if we can't handle it */
4639 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4640 call->MTU = peer->ifMTU;
4642 call->MTU += peer->natMTU;
4643 call->MTU = MIN(call->MTU, peer->maxMTU);
4650 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4652 /* Servers need to hold the call until all response packets have
4653 * been acknowledged. Soft acks are good enough since clients
4654 * are not allowed to clear their receive queues. */
4655 if (call->state == RX_STATE_HOLD
4656 && call->tfirst + call->nSoftAcked >= call->tnext) {
4657 call->state = RX_STATE_DALLY;
4658 rxi_ClearTransmitQueue(call, 0);
4659 rxi_CancelKeepAliveEvent(call);
4660 } else if (!opr_queue_IsEmpty(&call->tq)) {
4661 rxi_Start(call, istack);
4667 * Schedule a connection abort to be sent after some delay.
4669 * @param[in] conn The connection to send the abort on.
4670 * @param[in] msec The number of milliseconds to wait before sending.
4672 * @pre conn_data_lock must be held
4675 rxi_SendConnectionAbortLater(struct rx_connection *conn, int msec)
4677 struct clock when, now;
4681 if (!conn->delayedAbortEvent) {
4682 clock_GetTime(&now);
4684 clock_Addmsec(&when, msec);
4685 rx_GetConnection(conn);
4686 conn->delayedAbortEvent =
4687 rxevent_Post(&when, &now, rxi_SendDelayedConnAbort, conn, NULL, 0);
4691 /* Received a response to a challenge packet */
4692 static struct rx_packet *
4693 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4694 struct rx_packet *np, int istack)
4698 /* Ignore the packet if we're the client */
4699 if (conn->type == RX_CLIENT_CONNECTION)
4702 /* If already authenticated, ignore the packet (it's probably a retry) */
4703 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4706 if (!conn->securityChallengeSent) {
4707 /* We've never sent out a challenge for this connection, so this
4708 * response cannot possibly be correct; ignore it. This can happen
4709 * if we sent a challenge to the client, then we were restarted, and
4710 * then the client sent us a response. If we ignore the response, the
4711 * client will eventually resend a data packet, causing us to send a
4712 * new challenge and the client to send a new response. */
4716 /* Otherwise, have the security object evaluate the response packet */
4717 error = RXS_CheckResponse(conn->securityObject, conn, np);
4719 /* If the response is invalid, reset the connection, sending
4720 * an abort to the peer. Send the abort with a 1 second delay,
4721 * to avoid a peer hammering us by constantly recreating a
4722 * connection with bad credentials. */
4723 rxi_ConnectionError(conn, error);
4724 MUTEX_ENTER(&conn->conn_data_lock);
4725 rxi_SendConnectionAbortLater(conn, 1000);
4726 MUTEX_EXIT(&conn->conn_data_lock);
4729 /* If the response is valid, any calls waiting to attach
4730 * servers can now do so */
4733 for (i = 0; i < RX_MAXCALLS; i++) {
4734 struct rx_call *call = conn->call[i];
4736 MUTEX_ENTER(&call->lock);
4737 if (call->state == RX_STATE_PRECALL)
4738 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4739 /* tnop can be null if newcallp is null */
4740 MUTEX_EXIT(&call->lock);
4744 /* Update the peer reachability information, just in case
4745 * some calls went into attach-wait while we were waiting
4746 * for authentication..
4748 rxi_UpdatePeerReach(conn, NULL);
4753 /* A client has received an authentication challenge: the security
4754 * object is asked to cough up a respectable response packet to send
4755 * back to the server. The server is responsible for retrying the
4756 * challenge if it fails to get a response. */
4758 static struct rx_packet *
4759 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4760 struct rx_packet *np, int istack)
4764 /* Ignore the challenge if we're the server */
4765 if (conn->type == RX_SERVER_CONNECTION)
4768 /* Ignore the challenge if the connection is otherwise idle; someone's
4769 * trying to use us as an oracle. */
4770 if (!rxi_HasActiveCalls(conn))
4773 /* Send the security object the challenge packet. It is expected to fill
4774 * in the response. */
4775 error = RXS_GetResponse(conn->securityObject, conn, np);
4777 /* If the security object is unable to return a valid response, reset the
4778 * connection and send an abort to the peer. Otherwise send the response
4779 * packet to the peer connection. */
4781 rxi_ConnectionError(conn, error);
4782 MUTEX_ENTER(&conn->conn_data_lock);
4783 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4784 MUTEX_EXIT(&conn->conn_data_lock);
4786 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4787 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4793 /* Find an available server process to service the current request in
4794 * the given call structure. If one isn't available, queue up this
4795 * call so it eventually gets one */
4797 rxi_AttachServerProc(struct rx_call *call,
4798 osi_socket socket, int *tnop,
4799 struct rx_call **newcallp)
4801 struct rx_serverQueueEntry *sq;
4802 struct rx_service *service = call->conn->service;
4805 /* May already be attached */
4806 if (call->state == RX_STATE_ACTIVE)
4809 MUTEX_ENTER(&rx_serverPool_lock);
4811 haveQuota = QuotaOK(service);
4812 if ((!haveQuota) || opr_queue_IsEmpty(&rx_idleServerQueue)) {
4813 /* If there are no processes available to service this call,
4814 * put the call on the incoming call queue (unless it's
4815 * already on the queue).
4817 #ifdef RX_ENABLE_LOCKS
4819 ReturnToServerPool(service);
4820 #endif /* RX_ENABLE_LOCKS */
4822 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4823 call->flags |= RX_CALL_WAIT_PROC;
4824 rx_atomic_inc(&rx_nWaiting);
4825 rx_atomic_inc(&rx_nWaited);
4826 rxi_calltrace(RX_CALL_ARRIVAL, call);
4827 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4828 opr_queue_Append(&rx_incomingCallQueue, &call->entry);
4831 sq = opr_queue_Last(&rx_idleServerQueue,
4832 struct rx_serverQueueEntry, entry);
4834 /* If hot threads are enabled, and both newcallp and sq->socketp
4835 * are non-null, then this thread will process the call, and the
4836 * idle server thread will start listening on this threads socket.
4838 opr_queue_Remove(&sq->entry);
4840 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4843 *sq->socketp = socket;
4844 clock_GetTime(&call->startTime);
4845 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4849 if (call->flags & RX_CALL_WAIT_PROC) {
4850 /* Conservative: I don't think this should happen */
4851 call->flags &= ~RX_CALL_WAIT_PROC;
4852 rx_atomic_dec(&rx_nWaiting);
4853 if (opr_queue_IsOnQueue(&call->entry)) {
4854 opr_queue_Remove(&call->entry);
4857 call->state = RX_STATE_ACTIVE;
4858 call->app.mode = RX_MODE_RECEIVING;
4859 #ifdef RX_KERNEL_TRACE
4861 int glockOwner = ISAFS_GLOCK();
4864 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4865 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4871 if (call->flags & RX_CALL_CLEARED) {
4872 /* send an ack now to start the packet flow up again */
4873 call->flags &= ~RX_CALL_CLEARED;
4874 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4876 #ifdef RX_ENABLE_LOCKS
4879 service->nRequestsRunning++;
4880 MUTEX_ENTER(&rx_quota_mutex);
4881 if (service->nRequestsRunning <= service->minProcs)
4884 MUTEX_EXIT(&rx_quota_mutex);
4888 MUTEX_EXIT(&rx_serverPool_lock);
4891 /* Delay the sending of an acknowledge event for a short while, while
4892 * a new call is being prepared (in the case of a client) or a reply
4893 * is being prepared (in the case of a server). Rather than sending
4894 * an ack packet, an ACKALL packet is sent. */
4896 rxi_AckAll(struct rx_call *call)
4898 rxi_SendSpecial(call, call->conn, NULL, RX_PACKET_TYPE_ACKALL,
4900 call->flags |= RX_CALL_ACKALL_SENT;
4904 * Event handler for per-call delayed acks.
4905 * Also called synchronously, with |event| == NULL, to send a "delayed" ack
4909 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused1,
4912 struct rx_call *call = arg1;
4913 #ifdef RX_ENABLE_LOCKS
4915 MUTEX_ENTER(&call->lock);
4916 if (event == call->delayedAckEvent)
4917 rxevent_Put(&call->delayedAckEvent);
4919 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4921 MUTEX_EXIT(&call->lock);
4922 #else /* RX_ENABLE_LOCKS */
4924 rxevent_Put(&call->delayedAckEvent);
4925 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4926 #endif /* RX_ENABLE_LOCKS */
4927 /* Release the call reference for the event that fired. */
4929 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4932 #ifdef RX_ENABLE_LOCKS
4933 /* Set ack in all packets in transmit queue. rxi_Start will deal with
4934 * clearing them out.
4937 rxi_SetAcksInTransmitQueue(struct rx_call *call)
4939 struct opr_queue *cursor;
4942 for (opr_queue_Scan(&call->tq, cursor)) {
4944 = opr_queue_Entry(cursor, struct rx_packet, entry);
4946 p->flags |= RX_PKTFLAG_ACKED;
4951 call->flags |= RX_CALL_TQ_CLEARME;
4952 call->flags |= RX_CALL_TQ_SOME_ACKED;
4955 rxi_rto_cancel(call);
4957 call->tfirst = call->tnext;
4958 call->nSoftAcked = 0;
4960 if (call->flags & RX_CALL_FAST_RECOVER) {
4961 call->flags &= ~RX_CALL_FAST_RECOVER;
4962 call->cwind = call->nextCwind;
4963 call->nextCwind = 0;
4966 CV_SIGNAL(&call->cv_twind);
4968 #endif /* RX_ENABLE_LOCKS */
4971 * Acknowledge the whole transmit queue.
4973 * If we're running without locks, or the transmit queue isn't busy, then
4974 * we can just clear the queue now. Otherwise, we have to mark all of the
4975 * packets as acknowledged, and let rxi_Start clear it later on
4978 rxi_AckAllInTransmitQueue(struct rx_call *call)
4980 #ifdef RX_ENABLE_LOCKS
4981 if (call->flags & RX_CALL_TQ_BUSY) {
4982 rxi_SetAcksInTransmitQueue(call);
4986 rxi_ClearTransmitQueue(call, 0);
4988 /* Clear out the transmit queue for the current call (all packets have
4989 * been received by peer) */
4991 rxi_ClearTransmitQueue(struct rx_call *call, int force)
4993 #ifdef RX_ENABLE_LOCKS
4994 struct opr_queue *cursor;
4995 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
4997 for (opr_queue_Scan(&call->tq, cursor)) {
4999 = opr_queue_Entry(cursor, struct rx_packet, entry);
5001 p->flags |= RX_PKTFLAG_ACKED;
5005 call->flags |= RX_CALL_TQ_CLEARME;
5006 call->flags |= RX_CALL_TQ_SOME_ACKED;
5009 #endif /* RX_ENABLE_LOCKS */
5010 #ifdef RXDEBUG_PACKET
5012 #endif /* RXDEBUG_PACKET */
5013 rxi_FreePackets(0, &call->tq);
5014 rxi_WakeUpTransmitQueue(call);
5015 #ifdef RX_ENABLE_LOCKS
5016 call->flags &= ~RX_CALL_TQ_CLEARME;
5020 rxi_rto_cancel(call);
5021 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
5022 call->nSoftAcked = 0;
5024 if (call->flags & RX_CALL_FAST_RECOVER) {
5025 call->flags &= ~RX_CALL_FAST_RECOVER;
5026 call->cwind = call->nextCwind;
5028 #ifdef RX_ENABLE_LOCKS
5029 CV_SIGNAL(&call->cv_twind);
5031 osi_rxWakeup(&call->twind);
5036 rxi_ClearReceiveQueue(struct rx_call *call)
5038 if (!opr_queue_IsEmpty(&call->rq)) {
5041 count = rxi_FreePackets(0, &call->rq);
5042 rx_packetReclaims += count;
5043 #ifdef RXDEBUG_PACKET
5045 if ( call->rqc != 0 )
5046 dpf(("rxi_ClearReceiveQueue call %"AFS_PTR_FMT" rqc %u != 0\n", call, call->rqc));
5048 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
5050 if (call->state == RX_STATE_PRECALL) {
5051 call->flags |= RX_CALL_CLEARED;
5055 /* Send an abort packet for the specified call */
5056 static struct rx_packet *
5057 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
5058 int istack, int force)
5061 struct clock when, now;
5066 /* Clients should never delay abort messages */
5067 if (rx_IsClientConn(call->conn))
5070 if (call->abortCode != call->error) {
5071 call->abortCode = call->error;
5072 call->abortCount = 0;
5075 if (force || rxi_callAbortThreshhold == 0
5076 || call->abortCount < rxi_callAbortThreshhold) {
5077 rxi_CancelDelayedAbortEvent(call);
5078 error = htonl(call->error);
5081 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5082 (char *)&error, sizeof(error), istack);
5083 } else if (!call->delayedAbortEvent) {
5084 clock_GetTime(&now);
5086 clock_Addmsec(&when, rxi_callAbortDelay);
5087 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
5088 call->delayedAbortEvent =
5089 rxevent_Post(&when, &now, rxi_SendDelayedCallAbort, call, 0, 0);
5095 rxi_CancelDelayedAbortEvent(struct rx_call *call)
5097 if (rxevent_Cancel(&call->delayedAbortEvent))
5098 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
5101 /* Send an abort packet for the specified connection. Packet is an
5102 * optional pointer to a packet that can be used to send the abort.
5103 * Once the number of abort messages reaches the threshhold, an
5104 * event is scheduled to send the abort. Setting the force flag
5105 * overrides sending delayed abort messages.
5107 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
5108 * to send the abort packet.
5111 rxi_SendConnectionAbort(struct rx_connection *conn,
5112 struct rx_packet *packet, int istack, int force)
5119 /* Clients should never delay abort messages */
5120 if (rx_IsClientConn(conn))
5123 if (force || rxi_connAbortThreshhold == 0
5124 || conn->abortCount < rxi_connAbortThreshhold) {
5126 if (rxevent_Cancel(&conn->delayedAbortEvent))
5127 putConnection(conn);
5128 error = htonl(conn->error);
5130 MUTEX_EXIT(&conn->conn_data_lock);
5132 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5133 RX_PACKET_TYPE_ABORT, (char *)&error,
5134 sizeof(error), istack);
5135 MUTEX_ENTER(&conn->conn_data_lock);
5137 rxi_SendConnectionAbortLater(conn, rxi_connAbortDelay);
5142 /* Associate an error all of the calls owned by a connection. Called
5143 * with error non-zero. This is only for really fatal things, like
5144 * bad authentication responses. The connection itself is set in
5145 * error at this point, so that future packets received will be
5148 rxi_ConnectionError(struct rx_connection *conn,
5154 dpf(("rxi_ConnectionError conn %"AFS_PTR_FMT" error %d\n", conn, error));
5156 MUTEX_ENTER(&conn->conn_data_lock);
5157 if (rxevent_Cancel(&conn->challengeEvent))
5158 putConnection(conn);
5159 if (rxevent_Cancel(&conn->natKeepAliveEvent))
5160 putConnection(conn);
5161 if (rxevent_Cancel(&conn->checkReachEvent)) {
5162 conn->flags &= ~(RX_CONN_ATTACHWAIT|RX_CONN_NAT_PING);
5163 putConnection(conn);
5165 MUTEX_EXIT(&conn->conn_data_lock);
5166 for (i = 0; i < RX_MAXCALLS; i++) {
5167 struct rx_call *call = conn->call[i];
5169 MUTEX_ENTER(&call->lock);
5170 rxi_CallError(call, error);
5171 MUTEX_EXIT(&call->lock);
5174 conn->error = error;
5175 if (rx_stats_active)
5176 rx_atomic_inc(&rx_stats.fatalErrors);
5181 * Interrupt an in-progress call with the specified error and wakeup waiters.
5183 * @param[in] call The call to interrupt
5184 * @param[in] error The error code to send to the peer
5187 rx_InterruptCall(struct rx_call *call, afs_int32 error)
5189 MUTEX_ENTER(&call->lock);
5190 rxi_CallError(call, error);
5191 rxi_SendCallAbort(call, NULL, 0, 1);
5192 MUTEX_EXIT(&call->lock);
5196 rxi_CallError(struct rx_call *call, afs_int32 error)
5198 MUTEX_ASSERT(&call->lock);
5199 dpf(("rxi_CallError call %"AFS_PTR_FMT" error %d call->error %d\n", call, error, call->error));
5201 error = call->error;
5203 #ifdef RX_ENABLE_LOCKS
5204 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
5205 rxi_ResetCall(call, 0);
5208 rxi_ResetCall(call, 0);
5210 call->error = error;
5213 /* Reset various fields in a call structure, and wakeup waiting
5214 * processes. Some fields aren't changed: state & mode are not
5215 * touched (these must be set by the caller), and bufptr, nLeft, and
5216 * nFree are not reset, since these fields are manipulated by
5217 * unprotected macros, and may only be reset by non-interrupting code.
5221 rxi_ResetCall(struct rx_call *call, int newcall)
5224 struct rx_peer *peer;
5225 struct rx_packet *packet;
5227 MUTEX_ASSERT(&call->lock);
5228 dpf(("rxi_ResetCall(call %"AFS_PTR_FMT", newcall %d)\n", call, newcall));
5230 /* Notify anyone who is waiting for asynchronous packet arrival */
5231 if (call->arrivalProc) {
5232 (*call->arrivalProc) (call, call->arrivalProcHandle,
5233 call->arrivalProcArg);
5234 call->arrivalProc = (void (*)())0;
5238 rxi_CancelGrowMTUEvent(call);
5240 if (call->delayedAbortEvent) {
5241 rxi_CancelDelayedAbortEvent(call);
5242 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5244 rxi_SendCallAbort(call, packet, 0, 1);
5245 rxi_FreePacket(packet);
5250 * Update the peer with the congestion information in this call
5251 * so other calls on this connection can pick up where this call
5252 * left off. If the congestion sequence numbers don't match then
5253 * another call experienced a retransmission.
5255 peer = call->conn->peer;
5256 MUTEX_ENTER(&peer->peer_lock);
5258 if (call->congestSeq == peer->congestSeq) {
5259 peer->cwind = MAX(peer->cwind, call->cwind);
5260 peer->MTU = MAX(peer->MTU, call->MTU);
5261 peer->nDgramPackets =
5262 MAX(peer->nDgramPackets, call->nDgramPackets);
5265 call->abortCode = 0;
5266 call->abortCount = 0;
5268 if (peer->maxDgramPackets > 1) {
5269 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
5271 call->MTU = peer->MTU;
5273 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
5274 call->ssthresh = rx_maxSendWindow;
5275 call->nDgramPackets = peer->nDgramPackets;
5276 call->congestSeq = peer->congestSeq;
5277 call->rtt = peer->rtt;
5278 call->rtt_dev = peer->rtt_dev;
5279 clock_Zero(&call->rto);
5280 clock_Addmsec(&call->rto,
5281 MAX(((call->rtt >> 3) + call->rtt_dev), rx_minPeerTimeout) + 200);
5282 MUTEX_EXIT(&peer->peer_lock);
5284 flags = call->flags;
5285 rxi_WaitforTQBusy(call);
5287 rxi_ClearTransmitQueue(call, 1);
5288 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
5289 dpf(("rcall %"AFS_PTR_FMT" has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5293 rxi_ClearReceiveQueue(call);
5294 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
5298 call->twind = call->conn->twind[call->channel];
5299 call->rwind = call->conn->rwind[call->channel];
5300 call->nSoftAcked = 0;
5301 call->nextCwind = 0;
5304 call->nCwindAcks = 0;
5305 call->nSoftAcks = 0;
5306 call->nHardAcks = 0;
5308 call->tfirst = call->rnext = call->tnext = 1;
5311 call->lastAcked = 0;
5312 call->localStatus = call->remoteStatus = 0;
5314 if (flags & RX_CALL_READER_WAIT) {
5315 #ifdef RX_ENABLE_LOCKS
5316 CV_BROADCAST(&call->cv_rq);
5318 osi_rxWakeup(&call->rq);
5321 if (flags & RX_CALL_WAIT_PACKETS) {
5322 MUTEX_ENTER(&rx_freePktQ_lock);
5323 rxi_PacketsUnWait(); /* XXX */
5324 MUTEX_EXIT(&rx_freePktQ_lock);
5326 #ifdef RX_ENABLE_LOCKS
5327 CV_SIGNAL(&call->cv_twind);
5329 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5330 osi_rxWakeup(&call->twind);
5333 if (flags & RX_CALL_WAIT_PROC) {
5334 rx_atomic_dec(&rx_nWaiting);
5336 #ifdef RX_ENABLE_LOCKS
5337 /* The following ensures that we don't mess with any queue while some
5338 * other thread might also be doing so. The call_queue_lock field is
5339 * is only modified under the call lock. If the call is in the process
5340 * of being removed from a queue, the call is not locked until the
5341 * the queue lock is dropped and only then is the call_queue_lock field
5342 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5343 * Note that any other routine which removes a call from a queue has to
5344 * obtain the queue lock before examing the queue and removing the call.
5346 if (call->call_queue_lock) {
5347 MUTEX_ENTER(call->call_queue_lock);
5348 if (opr_queue_IsOnQueue(&call->entry)) {
5349 opr_queue_Remove(&call->entry);
5351 MUTEX_EXIT(call->call_queue_lock);
5352 CLEAR_CALL_QUEUE_LOCK(call);
5354 #else /* RX_ENABLE_LOCKS */
5355 if (opr_queue_IsOnQueue(&call->entry)) {
5356 opr_queue_Remove(&call->entry);
5358 #endif /* RX_ENABLE_LOCKS */
5360 rxi_CancelKeepAliveEvent(call);
5361 rxi_CancelDelayedAckEvent(call);
5364 /* Send an acknowledge for the indicated packet (seq,serial) of the
5365 * indicated call, for the indicated reason (reason). This
5366 * acknowledge will specifically acknowledge receiving the packet, and
5367 * will also specify which other packets for this call have been
5368 * received. This routine returns the packet that was used to the
5369 * caller. The caller is responsible for freeing it or re-using it.
5370 * This acknowledgement also returns the highest sequence number
5371 * actually read out by the higher level to the sender; the sender
5372 * promises to keep around packets that have not been read by the
5373 * higher level yet (unless, of course, the sender decides to abort
5374 * the call altogether). Any of p, seq, serial, pflags, or reason may
5375 * be set to zero without ill effect. That is, if they are zero, they
5376 * will not convey any information.
5377 * NOW there is a trailer field, after the ack where it will safely be
5378 * ignored by mundanes, which indicates the maximum size packet this
5379 * host can swallow. */
5381 struct rx_packet *optionalPacket; use to send ack (or null)
5382 int seq; Sequence number of the packet we are acking
5383 int serial; Serial number of the packet
5384 int pflags; Flags field from packet header
5385 int reason; Reason an acknowledge was prompted
5388 #define RX_ZEROS 1024
5389 static char rx_zeros[RX_ZEROS];
5392 rxi_SendAck(struct rx_call *call,
5393 struct rx_packet *optionalPacket, int serial, int reason,
5396 struct rx_ackPacket *ap;
5397 struct rx_packet *p;
5398 struct opr_queue *cursor;
5401 afs_uint32 padbytes = 0;
5402 #ifdef RX_ENABLE_TSFPQ
5403 struct rx_ts_info_t * rx_ts_info;
5407 * Open the receive window once a thread starts reading packets
5409 if (call->rnext > 1) {
5410 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5413 /* Don't attempt to grow MTU if this is a critical ping */
5414 if (reason == RX_ACK_MTU) {
5415 /* keep track of per-call attempts, if we're over max, do in small
5416 * otherwise in larger? set a size to increment by, decrease
5419 if (call->conn->peer->maxPacketSize &&
5420 (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5422 padbytes = call->conn->peer->maxPacketSize+16;
5424 padbytes = call->conn->peer->maxMTU + 128;
5426 /* do always try a minimum size ping */
5427 padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5429 /* subtract the ack payload */
5430 padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5431 reason = RX_ACK_PING;
5434 call->nHardAcks = 0;
5435 call->nSoftAcks = 0;
5436 if (call->rnext > call->lastAcked)
5437 call->lastAcked = call->rnext;
5441 rx_computelen(p, p->length); /* reset length, you never know */
5442 } /* where that's been... */
5443 #ifdef RX_ENABLE_TSFPQ
5445 RX_TS_INFO_GET(rx_ts_info);
5446 if ((p = rx_ts_info->local_special_packet)) {
5447 rx_computelen(p, p->length);
5448 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5449 rx_ts_info->local_special_packet = p;
5450 } else { /* We won't send the ack, but don't panic. */
5451 return optionalPacket;
5455 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5456 /* We won't send the ack, but don't panic. */
5457 return optionalPacket;
5462 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5465 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5466 #ifndef RX_ENABLE_TSFPQ
5467 if (!optionalPacket)
5470 return optionalPacket;
5472 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5473 if (rx_Contiguous(p) < templ) {
5474 #ifndef RX_ENABLE_TSFPQ
5475 if (!optionalPacket)
5478 return optionalPacket;
5483 /* MTUXXX failing to send an ack is very serious. We should */
5484 /* try as hard as possible to send even a partial ack; it's */
5485 /* better than nothing. */
5486 ap = (struct rx_ackPacket *)rx_DataOf(p);
5487 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5488 ap->reason = reason;
5490 /* The skew computation used to be bogus, I think it's better now. */
5491 /* We should start paying attention to skew. XXX */
5492 ap->serial = htonl(serial);
5493 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
5496 * First packet not yet forwarded to reader. When ACKALL has been
5497 * sent the peer has been told that all received packets will be
5498 * delivered to the reader. The value 'rnext' is used internally
5499 * to refer to the next packet in the receive queue that must be
5500 * delivered to the reader. From the perspective of the peer it
5501 * already has so report the last sequence number plus one if there
5502 * are packets in the receive queue awaiting processing.
5504 if ((call->flags & RX_CALL_ACKALL_SENT) &&
5505 !opr_queue_IsEmpty(&call->rq)) {
5506 ap->firstPacket = htonl(opr_queue_Last(&call->rq, struct rx_packet, entry)->header.seq + 1);
5508 ap->firstPacket = htonl(call->rnext);
5510 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
5512 /* No fear of running out of ack packet here because there can only
5513 * be at most one window full of unacknowledged packets. The window
5514 * size must be constrained to be less than the maximum ack size,
5515 * of course. Also, an ack should always fit into a single packet
5516 * -- it should not ever be fragmented. */
5518 for (opr_queue_Scan(&call->rq, cursor)) {
5519 struct rx_packet *rqp
5520 = opr_queue_Entry(cursor, struct rx_packet, entry);
5522 if (!rqp || !call->rq.next
5523 || (rqp->header.seq > (call->rnext + call->rwind))) {
5524 #ifndef RX_ENABLE_TSFPQ
5525 if (!optionalPacket)
5528 rxi_CallError(call, RX_CALL_DEAD);
5529 return optionalPacket;
5532 while (rqp->header.seq > call->rnext + offset)
5533 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5534 ap->acks[offset++] = RX_ACK_TYPE_ACK;
5536 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5537 #ifndef RX_ENABLE_TSFPQ
5538 if (!optionalPacket)
5541 rxi_CallError(call, RX_CALL_DEAD);
5542 return optionalPacket;
5548 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5550 /* Must zero the 3 octets that rx_AckDataSize skips at the end of the
5553 rx_packetwrite(p, rx_AckDataSize(offset) - 3, 3, rx_zeros);
5555 /* these are new for AFS 3.3 */
5556 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5557 templ = htonl(templ);
5558 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5559 templ = htonl(call->conn->peer->ifMTU);
5560 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5561 sizeof(afs_int32), &templ);
5563 /* new for AFS 3.4 */
5564 templ = htonl(call->rwind);
5565 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5566 sizeof(afs_int32), &templ);
5568 /* new for AFS 3.5 */
5569 templ = htonl(call->conn->peer->ifDgramPackets);
5570 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5571 sizeof(afs_int32), &templ);
5573 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5575 p->header.serviceId = call->conn->serviceId;
5576 p->header.cid = (call->conn->cid | call->channel);
5577 p->header.callNumber = *call->callNumber;
5579 p->header.securityIndex = call->conn->securityIndex;
5580 p->header.epoch = call->conn->epoch;
5581 p->header.type = RX_PACKET_TYPE_ACK;
5582 p->header.flags = RX_SLOW_START_OK;
5583 if (reason == RX_ACK_PING)
5584 p->header.flags |= RX_REQUEST_ACK;
5586 while (padbytes > 0) {
5587 if (padbytes > RX_ZEROS) {
5588 rx_packetwrite(p, p->length, RX_ZEROS, rx_zeros);
5589 p->length += RX_ZEROS;
5590 padbytes -= RX_ZEROS;
5592 rx_packetwrite(p, p->length, padbytes, rx_zeros);
5593 p->length += padbytes;
5598 if (call->conn->type == RX_CLIENT_CONNECTION)
5599 p->header.flags |= RX_CLIENT_INITIATED;
5603 if (rxdebug_active) {
5607 len = _snprintf(msg, sizeof(msg),
5608 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5609 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5610 ntohl(ap->serial), ntohl(ap->previousPacket),
5611 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5612 ap->nAcks, ntohs(ap->bufferSpace) );
5616 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5617 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5621 OutputDebugString(msg);
5623 #else /* AFS_NT40_ENV */
5625 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5626 ap->reason, ntohl(ap->previousPacket),
5627 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5629 for (offset = 0; offset < ap->nAcks; offset++)
5630 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5635 #endif /* AFS_NT40_ENV */
5638 int i, nbytes = p->length;
5640 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5641 if (nbytes <= p->wirevec[i].iov_len) {
5644 savelen = p->wirevec[i].iov_len;
5646 p->wirevec[i].iov_len = nbytes;
5648 rxi_Send(call, p, istack);
5649 p->wirevec[i].iov_len = savelen;
5653 nbytes -= p->wirevec[i].iov_len;
5656 if (rx_stats_active)
5657 rx_atomic_inc(&rx_stats.ackPacketsSent);
5658 #ifndef RX_ENABLE_TSFPQ
5659 if (!optionalPacket)
5662 return optionalPacket; /* Return packet for re-use by caller */
5666 struct rx_packet **list;
5671 /* Send all of the packets in the list in single datagram */
5673 rxi_SendList(struct rx_call *call, struct xmitlist *xmit,
5674 int istack, int moreFlag)
5680 struct rx_connection *conn = call->conn;
5681 struct rx_peer *peer = conn->peer;
5683 MUTEX_ENTER(&peer->peer_lock);
5684 peer->nSent += xmit->len;
5685 if (xmit->resending)
5686 peer->reSends += xmit->len;
5687 MUTEX_EXIT(&peer->peer_lock);
5689 if (rx_stats_active) {
5690 if (xmit->resending)
5691 rx_atomic_add(&rx_stats.dataPacketsReSent, xmit->len);
5693 rx_atomic_add(&rx_stats.dataPacketsSent, xmit->len);
5696 clock_GetTime(&now);
5698 if (xmit->list[xmit->len - 1]->header.flags & RX_LAST_PACKET) {
5702 /* Set the packet flags and schedule the resend events */
5703 /* Only request an ack for the last packet in the list */
5704 for (i = 0; i < xmit->len; i++) {
5705 struct rx_packet *packet = xmit->list[i];
5707 /* Record the time sent */
5708 packet->timeSent = now;
5709 packet->flags |= RX_PKTFLAG_SENT;
5711 /* Ask for an ack on retransmitted packets, on every other packet
5712 * if the peer doesn't support slow start. Ask for an ack on every
5713 * packet until the congestion window reaches the ack rate. */
5714 if (packet->header.serial) {
5717 packet->firstSent = now;
5718 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5719 || (!(call->flags & RX_CALL_SLOW_START_OK)
5720 && (packet->header.seq & 1)))) {
5725 /* Tag this packet as not being the last in this group,
5726 * for the receiver's benefit */
5727 if (i < xmit->len - 1 || moreFlag) {
5728 packet->header.flags |= RX_MORE_PACKETS;
5733 xmit->list[xmit->len - 1]->header.flags |= RX_REQUEST_ACK;
5736 /* Since we're about to send a data packet to the peer, it's
5737 * safe to nuke any scheduled end-of-packets ack */
5738 rxi_CancelDelayedAckEvent(call);
5740 MUTEX_EXIT(&call->lock);
5741 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5742 if (xmit->len > 1) {
5743 rxi_SendPacketList(call, conn, xmit->list, xmit->len, istack);
5745 rxi_SendPacket(call, conn, xmit->list[0], istack);
5747 MUTEX_ENTER(&call->lock);
5748 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5750 /* Tell the RTO calculation engine that we have sent a packet, and
5751 * if it was the last one */
5752 rxi_rto_packet_sent(call, lastPacket, istack);
5754 /* Update last send time for this call (for keep-alive
5755 * processing), and for the connection (so that we can discover
5756 * idle connections) */
5757 conn->lastSendTime = call->lastSendTime = clock_Sec();
5760 /* When sending packets we need to follow these rules:
5761 * 1. Never send more than maxDgramPackets in a jumbogram.
5762 * 2. Never send a packet with more than two iovecs in a jumbogram.
5763 * 3. Never send a retransmitted packet in a jumbogram.
5764 * 4. Never send more than cwind/4 packets in a jumbogram
5765 * We always keep the last list we should have sent so we
5766 * can set the RX_MORE_PACKETS flags correctly.
5770 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5775 struct xmitlist working;
5776 struct xmitlist last;
5778 struct rx_peer *peer = call->conn->peer;
5779 int morePackets = 0;
5781 memset(&last, 0, sizeof(struct xmitlist));
5782 working.list = &list[0];
5784 working.resending = 0;
5786 recovery = call->flags & RX_CALL_FAST_RECOVER;
5788 for (i = 0; i < len; i++) {
5789 /* Does the current packet force us to flush the current list? */
5791 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5792 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5794 /* This sends the 'last' list and then rolls the current working
5795 * set into the 'last' one, and resets the working set */
5798 rxi_SendList(call, &last, istack, 1);
5799 /* If the call enters an error state stop sending, or if
5800 * we entered congestion recovery mode, stop sending */
5802 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5807 working.resending = 0;
5808 working.list = &list[i];
5810 /* Add the current packet to the list if it hasn't been acked.
5811 * Otherwise adjust the list pointer to skip the current packet. */
5812 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5815 if (list[i]->header.serial)
5816 working.resending = 1;
5818 /* Do we need to flush the list? */
5819 if (working.len >= (int)peer->maxDgramPackets
5820 || working.len >= (int)call->nDgramPackets
5821 || working.len >= (int)call->cwind
5822 || list[i]->header.serial
5823 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5825 rxi_SendList(call, &last, istack, 1);
5826 /* If the call enters an error state stop sending, or if
5827 * we entered congestion recovery mode, stop sending */
5829 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5834 working.resending = 0;
5835 working.list = &list[i + 1];
5838 if (working.len != 0) {
5839 osi_Panic("rxi_SendList error");
5841 working.list = &list[i + 1];
5845 /* Send the whole list when the call is in receive mode, when
5846 * the call is in eof mode, when we are in fast recovery mode,
5847 * and when we have the last packet */
5848 /* XXX - The accesses to app.mode aren't safe, as this may be called by
5849 * the listener or event threads
5851 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5852 || (call->flags & RX_CALL_FLUSH)
5853 || (call->flags & RX_CALL_FAST_RECOVER)) {
5854 /* Check for the case where the current list contains
5855 * an acked packet. Since we always send retransmissions
5856 * in a separate packet, we only need to check the first
5857 * packet in the list */
5858 if (working.len > 0 && !(working.list[0]->flags & RX_PKTFLAG_ACKED)) {
5862 rxi_SendList(call, &last, istack, morePackets);
5863 /* If the call enters an error state stop sending, or if
5864 * we entered congestion recovery mode, stop sending */
5866 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5870 rxi_SendList(call, &working, istack, 0);
5872 } else if (last.len > 0) {
5873 rxi_SendList(call, &last, istack, 0);
5874 /* Packets which are in 'working' are not sent by this call */
5879 * Check if the peer for the given call is known to be dead
5881 * If the call's peer appears dead (it has encountered fatal network errors
5882 * since the call started) the call is killed with RX_CALL_DEAD if the call
5883 * is active. Otherwise, we do nothing.
5885 * @param[in] call The call to check
5888 * @retval 0 The call is fine, and we haven't done anything to the call
5889 * @retval nonzero The call's peer appears dead, and the call has been
5890 * terminated if it was active
5892 * @pre call->lock must be locked
5895 rxi_CheckPeerDead(struct rx_call *call)
5897 #ifdef AFS_RXERRQ_ENV
5900 if (call->state == RX_STATE_DALLY) {
5904 peererrs = rx_atomic_read(&call->conn->peer->neterrs);
5905 if (call->neterr_gen < peererrs) {
5906 /* we have received network errors since this call started; kill
5908 if (call->state == RX_STATE_ACTIVE) {
5909 rxi_CallError(call, RX_CALL_DEAD);
5913 if (call->neterr_gen > peererrs) {
5914 /* someone has reset the number of peer errors; set the call error gen
5915 * so we can detect if more errors are encountered */
5916 call->neterr_gen = peererrs;
5923 rxi_Resend(struct rxevent *event, void *arg0, void *arg1, int istack)
5925 struct rx_call *call = arg0;
5926 struct rx_peer *peer;
5927 struct opr_queue *cursor;
5928 struct clock maxTimeout = { 60, 0 };
5930 MUTEX_ENTER(&call->lock);
5932 peer = call->conn->peer;
5934 /* Make sure that the event pointer is removed from the call
5935 * structure, since there is no longer a per-call retransmission
5937 if (event == call->resendEvent)
5938 rxevent_Put(&call->resendEvent);
5940 rxi_CheckPeerDead(call);
5942 if (opr_queue_IsEmpty(&call->tq)) {
5943 /* Nothing to do. This means that we've been raced, and that an
5944 * ACK has come in between when we were triggered, and when we
5945 * actually got to run. */
5949 /* We're in loss recovery */
5950 call->flags |= RX_CALL_FAST_RECOVER;
5952 /* Mark all of the pending packets in the queue as being lost */
5953 for (opr_queue_Scan(&call->tq, cursor)) {
5954 struct rx_packet *p = opr_queue_Entry(cursor, struct rx_packet, entry);
5955 if (!(p->flags & RX_PKTFLAG_ACKED))
5956 p->flags &= ~RX_PKTFLAG_SENT;
5959 /* We're resending, so we double the timeout of the call. This will be
5960 * dropped back down by the first successful ACK that we receive.
5962 * We apply a maximum value here of 60 seconds
5964 clock_Add(&call->rto, &call->rto);
5965 if (clock_Gt(&call->rto, &maxTimeout))
5966 call->rto = maxTimeout;
5968 /* Packet loss is most likely due to congestion, so drop our window size
5969 * and start again from the beginning */
5970 if (peer->maxDgramPackets >1) {
5971 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
5972 call->MTU = MIN(peer->natMTU, peer->maxMTU);
5974 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
5975 call->nDgramPackets = 1;
5977 call->nextCwind = 1;
5980 MUTEX_ENTER(&peer->peer_lock);
5981 peer->MTU = call->MTU;
5982 peer->cwind = call->cwind;
5983 peer->nDgramPackets = 1;
5985 call->congestSeq = peer->congestSeq;
5986 MUTEX_EXIT(&peer->peer_lock);
5988 rxi_Start(call, istack);
5991 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
5992 MUTEX_EXIT(&call->lock);
5995 /* This routine is called when new packets are readied for
5996 * transmission and when retransmission may be necessary, or when the
5997 * transmission window or burst count are favourable. This should be
5998 * better optimized for new packets, the usual case, now that we've
5999 * got rid of queues of send packets. XXXXXXXXXXX */
6001 rxi_Start(struct rx_call *call, int istack)
6003 struct opr_queue *cursor;
6004 #ifdef RX_ENABLE_LOCKS
6005 struct opr_queue *store;
6011 #ifdef RX_ENABLE_LOCKS
6012 if (rx_stats_active)
6013 rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
6018 if (!opr_queue_IsEmpty(&call->tq)) { /* If we have anything to send */
6019 /* Send (or resend) any packets that need it, subject to
6020 * window restrictions and congestion burst control
6021 * restrictions. Ask for an ack on the last packet sent in
6022 * this burst. For now, we're relying upon the window being
6023 * considerably bigger than the largest number of packets that
6024 * are typically sent at once by one initial call to
6025 * rxi_Start. This is probably bogus (perhaps we should ask
6026 * for an ack when we're half way through the current
6027 * window?). Also, for non file transfer applications, this
6028 * may end up asking for an ack for every packet. Bogus. XXXX
6031 * But check whether we're here recursively, and let the other guy
6034 #ifdef RX_ENABLE_LOCKS
6035 if (!(call->flags & RX_CALL_TQ_BUSY)) {
6036 call->flags |= RX_CALL_TQ_BUSY;
6038 #endif /* RX_ENABLE_LOCKS */
6040 #ifdef RX_ENABLE_LOCKS
6041 call->flags &= ~RX_CALL_NEED_START;
6042 #endif /* RX_ENABLE_LOCKS */
6044 maxXmitPackets = MIN(call->twind, call->cwind);
6045 for (opr_queue_Scan(&call->tq, cursor)) {
6047 = opr_queue_Entry(cursor, struct rx_packet, entry);
6049 if (p->flags & RX_PKTFLAG_ACKED) {
6050 /* Since we may block, don't trust this */
6051 if (rx_stats_active)
6052 rx_atomic_inc(&rx_stats.ignoreAckedPacket);
6053 continue; /* Ignore this packet if it has been acknowledged */
6056 /* Turn off all flags except these ones, which are the same
6057 * on each transmission */
6058 p->header.flags &= RX_PRESET_FLAGS;
6060 if (p->header.seq >=
6061 call->tfirst + MIN((int)call->twind,
6062 (int)(call->nSoftAcked +
6064 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
6065 /* Note: if we're waiting for more window space, we can
6066 * still send retransmits; hence we don't return here, but
6067 * break out to schedule a retransmit event */
6068 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
6069 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
6074 /* Transmit the packet if it needs to be sent. */
6075 if (!(p->flags & RX_PKTFLAG_SENT)) {
6076 if (nXmitPackets == maxXmitPackets) {
6077 rxi_SendXmitList(call, call->xmitList,
6078 nXmitPackets, istack);
6081 dpf(("call %d xmit packet %"AFS_PTR_FMT"\n",
6082 *(call->callNumber), p));
6083 call->xmitList[nXmitPackets++] = p;
6085 } /* end of the queue_Scan */
6087 /* xmitList now hold pointers to all of the packets that are
6088 * ready to send. Now we loop to send the packets */
6089 if (nXmitPackets > 0) {
6090 rxi_SendXmitList(call, call->xmitList, nXmitPackets,
6094 #ifdef RX_ENABLE_LOCKS
6096 /* We went into the error state while sending packets. Now is
6097 * the time to reset the call. This will also inform the using
6098 * process that the call is in an error state.
6100 if (rx_stats_active)
6101 rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
6102 call->flags &= ~RX_CALL_TQ_BUSY;
6103 rxi_WakeUpTransmitQueue(call);
6104 rxi_CallError(call, call->error);
6108 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
6110 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
6111 /* Some packets have received acks. If they all have, we can clear
6112 * the transmit queue.
6115 for (opr_queue_ScanSafe(&call->tq, cursor, store)) {
6117 = opr_queue_Entry(cursor, struct rx_packet, entry);
6119 if (p->header.seq < call->tfirst
6120 && (p->flags & RX_PKTFLAG_ACKED)) {
6121 opr_queue_Remove(&p->entry);
6122 #ifdef RX_TRACK_PACKETS
6123 p->flags &= ~RX_PKTFLAG_TQ;
6125 #ifdef RXDEBUG_PACKET
6133 call->flags |= RX_CALL_TQ_CLEARME;
6135 if (call->flags & RX_CALL_TQ_CLEARME)
6136 rxi_ClearTransmitQueue(call, 1);
6137 } while (call->flags & RX_CALL_NEED_START);
6139 * TQ references no longer protected by this flag; they must remain
6140 * protected by the call lock.
6142 call->flags &= ~RX_CALL_TQ_BUSY;
6143 rxi_WakeUpTransmitQueue(call);
6145 call->flags |= RX_CALL_NEED_START;
6147 #endif /* RX_ENABLE_LOCKS */
6149 rxi_rto_cancel(call);
6153 /* Also adjusts the keep alive parameters for the call, to reflect
6154 * that we have just sent a packet (so keep alives aren't sent
6157 rxi_Send(struct rx_call *call, struct rx_packet *p,
6160 struct rx_connection *conn = call->conn;
6162 /* Stamp each packet with the user supplied status */
6163 p->header.userStatus = call->localStatus;
6165 /* Allow the security object controlling this call's security to
6166 * make any last-minute changes to the packet */
6167 RXS_SendPacket(conn->securityObject, call, p);
6169 /* Since we're about to send SOME sort of packet to the peer, it's
6170 * safe to nuke any scheduled end-of-packets ack */
6171 rxi_CancelDelayedAckEvent(call);
6173 /* Actually send the packet, filling in more connection-specific fields */
6174 MUTEX_EXIT(&call->lock);
6175 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6176 rxi_SendPacket(call, conn, p, istack);
6177 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6178 MUTEX_ENTER(&call->lock);
6180 /* Update last send time for this call (for keep-alive
6181 * processing), and for the connection (so that we can discover
6182 * idle connections) */
6183 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6184 (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
6185 (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
6187 conn->lastSendTime = call->lastSendTime = clock_Sec();
6191 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
6192 * that things are fine. Also called periodically to guarantee that nothing
6193 * falls through the cracks (e.g. (error + dally) connections have keepalive
6194 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
6196 * haveCTLock Set if calling from rxi_ReapConnections
6199 rxi_CheckCall(struct rx_call *call, int haveCTLock)
6201 struct rx_connection *conn = call->conn;
6203 afs_uint32 deadTime, idleDeadTime = 0, hardDeadTime = 0;
6204 afs_uint32 fudgeFactor;
6207 int idle_timeout = 0;
6208 afs_int32 clock_diff = 0;
6210 if (rxi_CheckPeerDead(call)) {
6216 /* Large swings in the clock can have a significant impact on
6217 * the performance of RX call processing. Forward clock shifts
6218 * will result in premature event triggering or timeouts.
6219 * Backward shifts can result in calls not completing until
6220 * the clock catches up with the original start clock value.
6222 * If a backward clock shift of more than five minutes is noticed,
6223 * just fail the call.
6225 if (now < call->lastSendTime)
6226 clock_diff = call->lastSendTime - now;
6227 if (now < call->startWait)
6228 clock_diff = MAX(clock_diff, call->startWait - now);
6229 if (now < call->lastReceiveTime)
6230 clock_diff = MAX(clock_diff, call->lastReceiveTime - now);
6231 if (clock_diff > 5 * 60)
6233 if (call->state == RX_STATE_ACTIVE)
6234 rxi_CallError(call, RX_CALL_TIMEOUT);
6238 #ifdef RX_ENABLE_LOCKS
6239 if (call->flags & RX_CALL_TQ_BUSY) {
6240 /* Call is active and will be reset by rxi_Start if it's
6241 * in an error state.
6246 /* RTT + 8*MDEV, rounded up to the next second. */
6247 fudgeFactor = (((afs_uint32) call->rtt >> 3) +
6248 ((afs_uint32) call->rtt_dev << 1) + 1023) >> 10;
6250 deadTime = conn->secondsUntilDead + fudgeFactor;
6251 /* These are computed to the second (+- 1 second). But that's
6252 * good enough for these values, which should be a significant
6253 * number of seconds. */
6254 if (now > (call->lastReceiveTime + deadTime)) {
6255 if (call->state == RX_STATE_ACTIVE) {
6256 cerror = RX_CALL_DEAD;
6259 #ifdef RX_ENABLE_LOCKS
6260 /* Cancel pending events */
6261 rxi_CancelDelayedAckEvent(call);
6262 rxi_rto_cancel(call);
6263 rxi_CancelKeepAliveEvent(call);
6264 rxi_CancelGrowMTUEvent(call);
6265 MUTEX_ENTER(&rx_refcnt_mutex);
6266 /* if rxi_FreeCall returns 1 it has freed the call */
6267 if (call->refCount == 0 &&
6268 rxi_FreeCall(call, haveCTLock))
6270 MUTEX_EXIT(&rx_refcnt_mutex);
6273 MUTEX_EXIT(&rx_refcnt_mutex);
6275 #else /* RX_ENABLE_LOCKS */
6276 rxi_FreeCall(call, 0);
6278 #endif /* RX_ENABLE_LOCKS */
6280 /* Non-active calls are destroyed if they are not responding
6281 * to pings; active calls are simply flagged in error, so the
6282 * attached process can die reasonably gracefully. */
6285 if (conn->idleDeadTime) {
6286 idleDeadTime = conn->idleDeadTime + fudgeFactor;
6290 /* see if we have a non-activity timeout */
6291 if (call->startWait && ((call->startWait + idleDeadTime) < now)) {
6292 if (call->state == RX_STATE_ACTIVE) {
6293 cerror = RX_CALL_TIMEOUT;
6299 if (conn->hardDeadTime) {
6300 hardDeadTime = conn->hardDeadTime + fudgeFactor;
6303 /* see if we have a hard timeout */
6305 && (now > (hardDeadTime + call->startTime.sec))) {
6306 if (call->state == RX_STATE_ACTIVE)
6307 rxi_CallError(call, RX_CALL_TIMEOUT);
6312 if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT && !idle_timeout &&
6313 call->lastReceiveTime) {
6314 int oldMTU = conn->peer->ifMTU;
6316 /* If we thought we could send more, perhaps things got worse.
6317 * Shrink by 128 bytes and try again. */
6318 if (conn->peer->maxPacketSize < conn->lastPacketSize)
6319 /* maxPacketSize will be cleared in rxi_SetPeerMtu */
6320 newmtu = MAX(conn->peer->maxPacketSize + RX_HEADER_SIZE,
6321 conn->lastPacketSize - 128 + RX_HEADER_SIZE);
6323 newmtu = conn->lastPacketSize - 128 + RX_HEADER_SIZE;
6325 /* minimum capped in SetPeerMtu */
6326 rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6329 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
6331 /* needed so ResetCall doesn't clobber us. */
6332 call->MTU = conn->peer->ifMTU;
6334 /* if we never succeeded, let the error pass out as-is */
6335 if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6336 cerror = conn->msgsizeRetryErr;
6339 rxi_CallError(call, cerror);
6344 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1,
6345 void *dummy, int dummy2)
6347 struct rx_connection *conn = arg1;
6348 struct rx_header theader;
6349 char tbuffer[1 + sizeof(struct rx_header)];
6350 struct sockaddr_in taddr;
6354 struct iovec tmpiov[2];
6357 RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6360 tp = &tbuffer[sizeof(struct rx_header)];
6361 taddr.sin_family = AF_INET;
6362 taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6363 taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6364 memset(&taddr.sin_zero, 0, sizeof(taddr.sin_zero));
6365 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6366 taddr.sin_len = sizeof(struct sockaddr_in);
6368 memset(&theader, 0, sizeof(theader));
6369 theader.epoch = htonl(999);
6371 theader.callNumber = 0;
6374 theader.type = RX_PACKET_TYPE_VERSION;
6375 theader.flags = RX_LAST_PACKET;
6376 theader.serviceId = 0;
6378 memcpy(tbuffer, &theader, sizeof(theader));
6379 memcpy(tp, &a, sizeof(a));
6380 tmpiov[0].iov_base = tbuffer;
6381 tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6383 osi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6385 MUTEX_ENTER(&conn->conn_data_lock);
6386 /* We ran, so the handle is no longer needed to try to cancel ourselves. */
6387 if (event == conn->natKeepAliveEvent)
6388 rxevent_Put(&conn->natKeepAliveEvent);
6389 MUTEX_ENTER(&rx_refcnt_mutex);
6390 /* Only reschedule ourselves if the connection would not be destroyed */
6391 if (conn->refCount > 1)
6393 if (conn->refCount <= 0) {
6394 #ifdef RX_REFCOUNT_CHECK
6395 osi_Assert(conn->refCount == 0);
6397 if (rx_stats_active) {
6398 MUTEX_ENTER(&rx_stats_mutex);
6399 rxi_lowConnRefCount++;
6400 MUTEX_EXIT(&rx_stats_mutex);
6403 MUTEX_EXIT(&rx_refcnt_mutex);
6405 rxi_ScheduleNatKeepAliveEvent(conn);
6406 MUTEX_EXIT(&conn->conn_data_lock);
6407 putConnection(conn);
6411 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6413 if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6414 struct clock when, now;
6415 clock_GetTime(&now);
6417 when.sec += conn->secondsUntilNatPing;
6418 rx_GetConnection(conn);
6419 conn->natKeepAliveEvent =
6420 rxevent_Post(&when, &now, rxi_NatKeepAliveEvent, conn, NULL, 0);
6425 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6427 MUTEX_ENTER(&conn->conn_data_lock);
6428 conn->secondsUntilNatPing = seconds;
6430 if (!(conn->flags & RX_CONN_ATTACHWAIT))
6431 rxi_ScheduleNatKeepAliveEvent(conn);
6433 conn->flags |= RX_CONN_NAT_PING;
6435 MUTEX_EXIT(&conn->conn_data_lock);
6438 /* When a call is in progress, this routine is called occasionally to
6439 * make sure that some traffic has arrived (or been sent to) the peer.
6440 * If nothing has arrived in a reasonable amount of time, the call is
6441 * declared dead; if nothing has been sent for a while, we send a
6442 * keep-alive packet (if we're actually trying to keep the call alive)
6445 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy,
6448 struct rx_call *call = arg1;
6449 struct rx_connection *conn;
6452 MUTEX_ENTER(&call->lock);
6454 if (event == call->keepAliveEvent)
6455 rxevent_Put(&call->keepAliveEvent);
6459 if (rxi_CheckCall(call, 0)) {
6460 MUTEX_EXIT(&call->lock);
6464 /* Don't try to keep alive dallying calls */
6465 if (call->state == RX_STATE_DALLY) {
6466 MUTEX_EXIT(&call->lock);
6467 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6472 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6473 /* Don't try to send keepalives if there is unacknowledged data */
6474 /* the rexmit code should be good enough, this little hack
6475 * doesn't quite work XXX */
6476 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6478 rxi_ScheduleKeepAliveEvent(call);
6479 MUTEX_EXIT(&call->lock);
6480 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6483 /* Does what's on the nameplate. */
6485 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy, int dummy2)
6487 struct rx_call *call = arg1;
6488 struct rx_connection *conn;
6490 MUTEX_ENTER(&call->lock);
6492 if (event == call->growMTUEvent)
6493 rxevent_Put(&call->growMTUEvent);
6495 if (rxi_CheckCall(call, 0))
6498 /* Don't bother with dallying calls */
6499 if (call->state == RX_STATE_DALLY)
6505 * keep being scheduled, just don't do anything if we're at peak,
6506 * or we're not set up to be properly handled (idle timeout required)
6508 if ((conn->peer->maxPacketSize != 0) &&
6509 (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6511 (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6512 rxi_ScheduleGrowMTUEvent(call, 0);
6514 MUTEX_EXIT(&call->lock);
6515 CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6519 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6521 if (!call->keepAliveEvent) {
6522 struct clock when, now;
6523 clock_GetTime(&now);
6525 when.sec += call->conn->secondsUntilPing;
6526 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6527 call->keepAliveEvent =
6528 rxevent_Post(&when, &now, rxi_KeepAliveEvent, call, NULL, 0);
6533 rxi_CancelKeepAliveEvent(struct rx_call *call) {
6534 if (rxevent_Cancel(&call->keepAliveEvent))
6535 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6539 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6541 if (!call->growMTUEvent) {
6542 struct clock when, now;
6544 clock_GetTime(&now);
6547 if (call->conn->secondsUntilPing)
6548 secs = (6*call->conn->secondsUntilPing)-1;
6550 if (call->conn->secondsUntilDead)
6551 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6555 CALL_HOLD(call, RX_CALL_REFCOUNT_MTU);
6556 call->growMTUEvent =
6557 rxevent_Post(&when, &now, rxi_GrowMTUEvent, call, NULL, 0);
6562 rxi_CancelGrowMTUEvent(struct rx_call *call)
6564 if (rxevent_Cancel(&call->growMTUEvent))
6565 CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6569 * Increment the counter for the next connection ID, handling overflow.
6572 update_nextCid(void)
6574 /* Overflow is technically undefined behavior; avoid it. */
6575 if (rx_nextCid > MAX_AFS_INT32 - (1 << RX_CIDSHIFT))
6576 rx_nextCid = -1 * ((MAX_AFS_INT32 / RX_CIDSHIFT) * RX_CIDSHIFT);
6578 rx_nextCid += 1 << RX_CIDSHIFT;
6582 rxi_KeepAliveOn(struct rx_call *call)
6584 /* Pretend last packet received was received now--i.e. if another
6585 * packet isn't received within the keep alive time, then the call
6586 * will die; Initialize last send time to the current time--even
6587 * if a packet hasn't been sent yet. This will guarantee that a
6588 * keep-alive is sent within the ping time */
6589 call->lastReceiveTime = call->lastSendTime = clock_Sec();
6590 rxi_ScheduleKeepAliveEvent(call);
6594 rxi_GrowMTUOn(struct rx_call *call)
6596 struct rx_connection *conn = call->conn;
6597 MUTEX_ENTER(&conn->conn_data_lock);
6598 conn->lastPingSizeSer = conn->lastPingSize = 0;
6599 MUTEX_EXIT(&conn->conn_data_lock);
6600 rxi_ScheduleGrowMTUEvent(call, 1);
6603 /* This routine is called to send connection abort messages
6604 * that have been delayed to throttle looping clients. */
6606 rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1, void *unused,
6609 struct rx_connection *conn = arg1;
6612 struct rx_packet *packet;
6614 MUTEX_ENTER(&conn->conn_data_lock);
6615 if (event == conn->delayedAbortEvent)
6616 rxevent_Put(&conn->delayedAbortEvent);
6617 error = htonl(conn->error);
6619 MUTEX_EXIT(&conn->conn_data_lock);
6620 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6623 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6624 RX_PACKET_TYPE_ABORT, (char *)&error,
6626 rxi_FreePacket(packet);
6628 putConnection(conn);
6631 /* This routine is called to send call abort messages
6632 * that have been delayed to throttle looping clients. */
6634 rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1, void *dummy,
6637 struct rx_call *call = arg1;
6640 struct rx_packet *packet;
6642 MUTEX_ENTER(&call->lock);
6643 if (event == call->delayedAbortEvent)
6644 rxevent_Put(&call->delayedAbortEvent);
6645 error = htonl(call->error);
6647 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6650 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6651 (char *)&error, sizeof(error), 0);
6652 rxi_FreePacket(packet);
6654 MUTEX_EXIT(&call->lock);
6655 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6659 * This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6660 * seconds) to ask the client to authenticate itself. The routine
6661 * issues a challenge to the client, which is obtained from the
6662 * security object associated with the connection
6664 * This routine is both an event handler and a function called directly;
6665 * when called directly the passed |event| is NULL and the
6666 * conn->conn->data>lock must must not be held.
6669 rxi_ChallengeEvent(struct rxevent *event,
6670 void *arg0, void *arg1, int tries)
6672 struct rx_connection *conn = arg0;
6674 MUTEX_ENTER(&conn->conn_data_lock);
6675 if (event != NULL && event == conn->challengeEvent)
6676 rxevent_Put(&conn->challengeEvent);
6677 MUTEX_EXIT(&conn->conn_data_lock);
6679 /* If there are no active calls it is not worth re-issuing the
6680 * challenge. If the client issues another call on this connection
6681 * the challenge can be requested at that time.
6683 if (!rxi_HasActiveCalls(conn)) {
6684 putConnection(conn);
6688 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6689 struct rx_packet *packet;
6690 struct clock when, now;
6693 /* We've failed to authenticate for too long.
6694 * Reset any calls waiting for authentication;
6695 * they are all in RX_STATE_PRECALL.
6699 MUTEX_ENTER(&conn->conn_call_lock);
6700 for (i = 0; i < RX_MAXCALLS; i++) {
6701 struct rx_call *call = conn->call[i];
6703 MUTEX_ENTER(&call->lock);
6704 if (call->state == RX_STATE_PRECALL) {
6705 rxi_CallError(call, RX_CALL_DEAD);
6706 rxi_SendCallAbort(call, NULL, 0, 0);
6708 MUTEX_EXIT(&call->lock);
6711 MUTEX_EXIT(&conn->conn_call_lock);
6712 putConnection(conn);
6716 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6718 /* If there's no packet available, do this later. */
6719 RXS_GetChallenge(conn->securityObject, conn, packet);
6720 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6721 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6722 rxi_FreePacket(packet);
6723 conn->securityChallengeSent = 1;
6725 clock_GetTime(&now);
6727 when.sec += RX_CHALLENGE_TIMEOUT;
6728 MUTEX_ENTER(&conn->conn_data_lock);
6729 /* Only reschedule ourselves if not already pending. */
6730 if (conn->challengeEvent == NULL) {
6731 rx_GetConnection(conn);
6732 conn->challengeEvent =
6733 rxevent_Post(&when, &now, rxi_ChallengeEvent, conn, 0,
6736 MUTEX_EXIT(&conn->conn_data_lock);
6738 putConnection(conn);
6741 /* Call this routine to start requesting the client to authenticate
6742 * itself. This will continue until authentication is established,
6743 * the call times out, or an invalid response is returned. The
6744 * security object associated with the connection is asked to create
6745 * the challenge at this time. */
6747 rxi_ChallengeOn(struct rx_connection *conn)
6750 MUTEX_ENTER(&conn->conn_data_lock);
6751 if (!conn->challengeEvent)
6753 MUTEX_EXIT(&conn->conn_data_lock);
6755 RXS_CreateChallenge(conn->securityObject, conn);
6756 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
6761 /* rxi_ComputeRoundTripTime is called with peer locked. */
6762 /* peer may be null */
6764 rxi_ComputeRoundTripTime(struct rx_packet *p,
6765 struct rx_ackPacket *ack,
6766 struct rx_call *call,
6767 struct rx_peer *peer,
6770 struct clock thisRtt, *sentp;
6774 /* If the ACK is delayed, then do nothing */
6775 if (ack->reason == RX_ACK_DELAY)
6778 /* On the wire, jumbograms are a single UDP packet. We shouldn't count
6779 * their RTT multiple times, so only include the RTT of the last packet
6781 if (p->flags & RX_JUMBO_PACKET)
6784 /* Use the serial number to determine which transmission the ACK is for,
6785 * and set the sent time to match this. If we have no serial number, then
6786 * only use the ACK for RTT calculations if the packet has not been
6790 serial = ntohl(ack->serial);
6792 if (serial == p->header.serial) {
6793 sentp = &p->timeSent;
6794 } else if (serial == p->firstSerial) {
6795 sentp = &p->firstSent;
6796 } else if (clock_Eq(&p->timeSent, &p->firstSent)) {
6797 sentp = &p->firstSent;
6801 if (clock_Eq(&p->timeSent, &p->firstSent)) {
6802 sentp = &p->firstSent;
6809 if (clock_Lt(&thisRtt, sentp))
6810 return; /* somebody set the clock back, don't count this time. */
6812 clock_Sub(&thisRtt, sentp);
6813 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rttp=%d.%06d sec)\n",
6814 p->header.callNumber, p, thisRtt.sec, thisRtt.usec));
6816 if (clock_IsZero(&thisRtt)) {
6818 * The actual round trip time is shorter than the
6819 * clock_GetTime resolution. It is most likely 1ms or 100ns.
6820 * Since we can't tell which at the moment we will assume 1ms.
6822 thisRtt.usec = 1000;
6825 if (rx_stats_active) {
6826 MUTEX_ENTER(&rx_stats_mutex);
6827 if (clock_Lt(&thisRtt, &rx_stats.minRtt))
6828 rx_stats.minRtt = thisRtt;
6829 if (clock_Gt(&thisRtt, &rx_stats.maxRtt)) {
6830 if (thisRtt.sec > 60) {
6831 MUTEX_EXIT(&rx_stats_mutex);
6832 return; /* somebody set the clock ahead */
6834 rx_stats.maxRtt = thisRtt;
6836 clock_Add(&rx_stats.totalRtt, &thisRtt);
6837 rx_atomic_inc(&rx_stats.nRttSamples);
6838 MUTEX_EXIT(&rx_stats_mutex);
6841 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6843 /* Apply VanJacobson round-trip estimations */
6848 * srtt (call->rtt) is in units of one-eighth-milliseconds.
6849 * srtt is stored as fixed point with 3 bits after the binary
6850 * point (i.e., scaled by 8). The following magic is
6851 * equivalent to the smoothing algorithm in rfc793 with an
6852 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
6853 * srtt'*8 = rtt + srtt*7
6854 * srtt'*8 = srtt*8 + rtt - srtt
6855 * srtt' = srtt + rtt/8 - srtt/8
6856 * srtt' = srtt + (rtt - srtt)/8
6859 delta = _8THMSEC(&thisRtt) - call->rtt;
6860 call->rtt += (delta >> 3);
6863 * We accumulate a smoothed rtt variance (actually, a smoothed
6864 * mean difference), then set the retransmit timer to smoothed
6865 * rtt + 4 times the smoothed variance (was 2x in van's original
6866 * paper, but 4x works better for me, and apparently for him as
6868 * rttvar is stored as
6869 * fixed point with 2 bits after the binary point (scaled by
6870 * 4). The following is equivalent to rfc793 smoothing with
6871 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
6872 * rttvar'*4 = rttvar*3 + |delta|
6873 * rttvar'*4 = rttvar*4 + |delta| - rttvar
6874 * rttvar' = rttvar + |delta|/4 - rttvar/4
6875 * rttvar' = rttvar + (|delta| - rttvar)/4
6876 * This replaces rfc793's wired-in beta.
6877 * dev*4 = dev*4 + (|actual - expected| - dev)
6883 delta -= (call->rtt_dev << 1);
6884 call->rtt_dev += (delta >> 3);
6886 /* I don't have a stored RTT so I start with this value. Since I'm
6887 * probably just starting a call, and will be pushing more data down
6888 * this, I expect congestion to increase rapidly. So I fudge a
6889 * little, and I set deviance to half the rtt. In practice,
6890 * deviance tends to approach something a little less than
6891 * half the smoothed rtt. */
6892 call->rtt = _8THMSEC(&thisRtt) + 8;
6893 call->rtt_dev = call->rtt >> 2; /* rtt/2: they're scaled differently */
6895 /* the smoothed RTT time is RTT + 4*MDEV
6897 * We allow a user specified minimum to be set for this, to allow clamping
6898 * at a minimum value in the same way as TCP. In addition, we have to allow
6899 * for the possibility that this packet is answered by a delayed ACK, so we
6900 * add on a fixed 200ms to account for that timer expiring.
6903 rtt_timeout = MAX(((call->rtt >> 3) + call->rtt_dev),
6904 rx_minPeerTimeout) + 200;
6905 clock_Zero(&call->rto);
6906 clock_Addmsec(&call->rto, rtt_timeout);
6908 /* Update the peer, so any new calls start with our values */
6909 peer->rtt_dev = call->rtt_dev;
6910 peer->rtt = call->rtt;
6912 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rtt=%d ms, srtt=%d ms, rtt_dev=%d ms, timeout=%d.%06d sec)\n",
6913 p->header.callNumber, p, MSEC(&thisRtt), call->rtt >> 3, call->rtt_dev >> 2, (call->rto.sec), (call->rto.usec)));
6917 /* Find all server connections that have not been active for a long time, and
6920 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2,
6923 struct clock now, when;
6924 struct rxevent *event;
6925 clock_GetTime(&now);
6927 /* Find server connection structures that haven't been used for
6928 * greater than rx_idleConnectionTime */
6930 struct rx_connection **conn_ptr, **conn_end;
6931 int i, havecalls = 0;
6932 MUTEX_ENTER(&rx_connHashTable_lock);
6933 for (conn_ptr = &rx_connHashTable[0], conn_end =
6934 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
6936 struct rx_connection *conn, *next;
6937 struct rx_call *call;
6941 for (conn = *conn_ptr; conn; conn = next) {
6942 /* XXX -- Shouldn't the connection be locked? */
6945 for (i = 0; i < RX_MAXCALLS; i++) {
6946 call = conn->call[i];
6950 code = MUTEX_TRYENTER(&call->lock);
6953 result = rxi_CheckCall(call, 1);
6954 MUTEX_EXIT(&call->lock);
6956 /* If CheckCall freed the call, it might
6957 * have destroyed the connection as well,
6958 * which screws up the linked lists.
6964 if (conn->type == RX_SERVER_CONNECTION) {
6965 /* This only actually destroys the connection if
6966 * there are no outstanding calls */
6967 MUTEX_ENTER(&conn->conn_data_lock);
6968 MUTEX_ENTER(&rx_refcnt_mutex);
6969 if (!havecalls && !conn->refCount
6970 && ((conn->lastSendTime + rx_idleConnectionTime) <
6972 conn->refCount++; /* it will be decr in rx_DestroyConn */
6973 MUTEX_EXIT(&rx_refcnt_mutex);
6974 MUTEX_EXIT(&conn->conn_data_lock);
6975 #ifdef RX_ENABLE_LOCKS
6976 rxi_DestroyConnectionNoLock(conn);
6977 #else /* RX_ENABLE_LOCKS */
6978 rxi_DestroyConnection(conn);
6979 #endif /* RX_ENABLE_LOCKS */
6981 #ifdef RX_ENABLE_LOCKS
6983 MUTEX_EXIT(&rx_refcnt_mutex);
6984 MUTEX_EXIT(&conn->conn_data_lock);
6986 #endif /* RX_ENABLE_LOCKS */
6990 #ifdef RX_ENABLE_LOCKS
6991 while (rx_connCleanup_list) {
6992 struct rx_connection *conn;
6993 conn = rx_connCleanup_list;
6994 rx_connCleanup_list = rx_connCleanup_list->next;
6995 MUTEX_EXIT(&rx_connHashTable_lock);
6996 rxi_CleanupConnection(conn);
6997 MUTEX_ENTER(&rx_connHashTable_lock);
6999 MUTEX_EXIT(&rx_connHashTable_lock);
7000 #endif /* RX_ENABLE_LOCKS */
7003 /* Find any peer structures that haven't been used (haven't had an
7004 * associated connection) for greater than rx_idlePeerTime */
7006 struct rx_peer **peer_ptr, **peer_end;
7010 * Why do we need to hold the rx_peerHashTable_lock across
7011 * the incrementing of peer_ptr since the rx_peerHashTable
7012 * array is not changing? We don't.
7014 * By dropping the lock periodically we can permit other
7015 * activities to be performed while a rxi_ReapConnections
7016 * call is in progress. The goal of reap connections
7017 * is to clean up quickly without causing large amounts
7018 * of contention. Therefore, it is important that global
7019 * mutexes not be held for extended periods of time.
7021 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7022 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7024 struct rx_peer *peer, *next, *prev;
7026 MUTEX_ENTER(&rx_peerHashTable_lock);
7027 for (prev = peer = *peer_ptr; peer; peer = next) {
7029 code = MUTEX_TRYENTER(&peer->peer_lock);
7030 if ((code) && (peer->refCount == 0)
7031 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
7032 struct opr_queue *cursor, *store;
7036 * now know that this peer object is one to be
7037 * removed from the hash table. Once it is removed
7038 * it can't be referenced by other threads.
7039 * Lets remove it first and decrement the struct
7040 * nPeerStructs count.
7042 if (peer == *peer_ptr) {
7048 if (rx_stats_active)
7049 rx_atomic_dec(&rx_stats.nPeerStructs);
7052 * Now if we hold references on 'prev' and 'next'
7053 * we can safely drop the rx_peerHashTable_lock
7054 * while we destroy this 'peer' object.
7060 MUTEX_EXIT(&rx_peerHashTable_lock);
7062 MUTEX_EXIT(&peer->peer_lock);
7063 MUTEX_DESTROY(&peer->peer_lock);
7065 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
7066 unsigned int num_funcs;
7067 struct rx_interface_stat *rpc_stat
7068 = opr_queue_Entry(cursor, struct rx_interface_stat,
7073 opr_queue_Remove(&rpc_stat->entry);
7074 opr_queue_Remove(&rpc_stat->entryPeers);
7076 num_funcs = rpc_stat->stats[0].func_total;
7078 sizeof(rx_interface_stat_t) +
7079 rpc_stat->stats[0].func_total *
7080 sizeof(rx_function_entry_v1_t);
7082 rxi_Free(rpc_stat, space);
7084 MUTEX_ENTER(&rx_rpc_stats);
7085 rxi_rpc_peer_stat_cnt -= num_funcs;
7086 MUTEX_EXIT(&rx_rpc_stats);
7091 * Regain the rx_peerHashTable_lock and
7092 * decrement the reference count on 'prev'
7095 MUTEX_ENTER(&rx_peerHashTable_lock);
7102 MUTEX_EXIT(&peer->peer_lock);
7107 MUTEX_EXIT(&rx_peerHashTable_lock);
7111 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
7112 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
7113 * GC, just below. Really, we shouldn't have to keep moving packets from
7114 * one place to another, but instead ought to always know if we can
7115 * afford to hold onto a packet in its particular use. */
7116 MUTEX_ENTER(&rx_freePktQ_lock);
7117 if (rx_waitingForPackets) {
7118 rx_waitingForPackets = 0;
7119 #ifdef RX_ENABLE_LOCKS
7120 CV_BROADCAST(&rx_waitingForPackets_cv);
7122 osi_rxWakeup(&rx_waitingForPackets);
7125 MUTEX_EXIT(&rx_freePktQ_lock);
7128 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
7129 event = rxevent_Post(&when, &now, rxi_ReapConnections, 0, NULL, 0);
7130 rxevent_Put(&event);
7134 /* rxs_Release - This isn't strictly necessary but, since the macro name from
7135 * rx.h is sort of strange this is better. This is called with a security
7136 * object before it is discarded. Each connection using a security object has
7137 * its own refcount to the object so it won't actually be freed until the last
7138 * connection is destroyed.
7140 * This is the only rxs module call. A hold could also be written but no one
7144 rxs_Release(struct rx_securityClass *aobj)
7146 return RXS_Close(aobj);
7154 #define TRACE_OPTION_RX_DEBUG 16
7162 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
7163 0, KEY_QUERY_VALUE, &parmKey);
7164 if (code != ERROR_SUCCESS)
7167 dummyLen = sizeof(TraceOption);
7168 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
7169 (BYTE *) &TraceOption, &dummyLen);
7170 if (code == ERROR_SUCCESS) {
7171 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
7173 RegCloseKey (parmKey);
7174 #endif /* AFS_NT40_ENV */
7179 rx_DebugOnOff(int on)
7183 rxdebug_active = on;
7189 rx_StatsOnOff(int on)
7191 rx_stats_active = on;
7195 /* Don't call this debugging routine directly; use dpf */
7197 rxi_DebugPrint(char *format, ...)
7206 va_start(ap, format);
7208 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7211 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7213 OutputDebugString(msg);
7219 va_start(ap, format);
7221 clock_GetTime(&now);
7222 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7223 (unsigned int)now.usec);
7224 vfprintf(rx_Log, format, ap);
7232 * This function is used to process the rx_stats structure that is local
7233 * to a process as well as an rx_stats structure received from a remote
7234 * process (via rxdebug). Therefore, it needs to do minimal version
7238 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7239 afs_int32 freePackets, char version)
7243 if (size != sizeof(struct rx_statistics)) {
7245 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7246 size, sizeof(struct rx_statistics));
7249 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7252 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7253 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7254 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7255 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7256 s->specialPktAllocFailures);
7258 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7259 s->receivePktAllocFailures, s->sendPktAllocFailures,
7260 s->specialPktAllocFailures);
7264 " greedy %u, " "bogusReads %u (last from host %x), "
7265 "noPackets %u, " "noBuffers %u, " "selects %u, "
7266 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7267 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7268 s->selects, s->sendSelects);
7270 fprintf(file, " packets read: ");
7271 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7272 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7274 fprintf(file, "\n");
7277 " other read counters: data %u, " "ack %u, " "dup %u "
7278 "spurious %u " "dally %u\n", s->dataPacketsRead,
7279 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7280 s->ignorePacketDally);
7282 fprintf(file, " packets sent: ");
7283 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7284 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7286 fprintf(file, "\n");
7289 " other send counters: ack %u, " "data %u (not resends), "
7290 "resends %u, " "pushed %u, " "acked&ignored %u\n",
7291 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7292 s->dataPacketsPushed, s->ignoreAckedPacket);
7295 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7296 s->netSendFailures, (int)s->fatalErrors);
7298 if (s->nRttSamples) {
7299 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
7300 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7302 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
7303 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7307 " %d server connections, " "%d client connections, "
7308 "%d peer structs, " "%d call structs, " "%d free call structs\n",
7309 s->nServerConns, s->nClientConns, s->nPeerStructs,
7310 s->nCallStructs, s->nFreeCallStructs);
7312 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7313 fprintf(file, " %d clock updates\n", clock_nUpdates);
7317 /* for backward compatibility */
7319 rx_PrintStats(FILE * file)
7321 MUTEX_ENTER(&rx_stats_mutex);
7322 rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7323 sizeof(rx_stats), rx_nFreePackets,
7325 MUTEX_EXIT(&rx_stats_mutex);
7329 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7331 fprintf(file, "Peer %x.%d.\n",
7332 ntohl(peer->host), (int)ntohs(peer->port));
7335 " Rtt %d, " "total sent %d, " "resent %d\n",
7336 peer->rtt, peer->nSent, peer->reSends);
7338 fprintf(file, " Packet size %d\n", peer->ifMTU);
7342 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7344 * This mutex protects the following static variables:
7348 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7349 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7351 #define LOCK_RX_DEBUG
7352 #define UNLOCK_RX_DEBUG
7353 #endif /* AFS_PTHREAD_ENV */
7355 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7357 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7358 u_char type, void *inputData, size_t inputLength,
7359 void *outputData, size_t outputLength)
7361 static afs_int32 counter = 100;
7362 time_t waitTime, waitCount;
7363 struct rx_header theader;
7366 struct timeval tv_now, tv_wake, tv_delta;
7367 struct sockaddr_in taddr, faddr;
7381 tp = &tbuffer[sizeof(struct rx_header)];
7382 taddr.sin_family = AF_INET;
7383 taddr.sin_port = remotePort;
7384 taddr.sin_addr.s_addr = remoteAddr;
7385 memset(&taddr.sin_zero, 0, sizeof(taddr.sin_zero));
7386 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7387 taddr.sin_len = sizeof(struct sockaddr_in);
7390 memset(&theader, 0, sizeof(theader));
7391 theader.epoch = htonl(999);
7393 theader.callNumber = htonl(counter);
7396 theader.type = type;
7397 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7398 theader.serviceId = 0;
7400 memcpy(tbuffer, &theader, sizeof(theader));
7401 memcpy(tp, inputData, inputLength);
7403 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7404 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7406 /* see if there's a packet available */
7407 gettimeofday(&tv_wake, NULL);
7408 tv_wake.tv_sec += waitTime;
7411 FD_SET(socket, &imask);
7412 tv_delta.tv_sec = tv_wake.tv_sec;
7413 tv_delta.tv_usec = tv_wake.tv_usec;
7414 gettimeofday(&tv_now, NULL);
7416 if (tv_delta.tv_usec < tv_now.tv_usec) {
7418 tv_delta.tv_usec += 1000000;
7421 tv_delta.tv_usec -= tv_now.tv_usec;
7423 if (tv_delta.tv_sec < tv_now.tv_sec) {
7427 tv_delta.tv_sec -= tv_now.tv_sec;
7430 code = select(0, &imask, 0, 0, &tv_delta);
7431 #else /* AFS_NT40_ENV */
7432 code = select(socket + 1, &imask, 0, 0, &tv_delta);
7433 #endif /* AFS_NT40_ENV */
7434 if (code == 1 && FD_ISSET(socket, &imask)) {
7435 /* now receive a packet */
7436 faddrLen = sizeof(struct sockaddr_in);
7438 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7439 (struct sockaddr *)&faddr, &faddrLen);
7442 memcpy(&theader, tbuffer, sizeof(struct rx_header));
7443 if (counter == ntohl(theader.callNumber))
7451 /* see if we've timed out */
7459 code -= sizeof(struct rx_header);
7460 if (code > outputLength)
7461 code = outputLength;
7462 memcpy(outputData, tp, code);
7465 #endif /* RXDEBUG */
7468 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7469 afs_uint16 remotePort, struct rx_debugStats * stat,
7470 afs_uint32 * supportedValues)
7472 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7474 struct rx_debugIn in;
7476 *supportedValues = 0;
7477 in.type = htonl(RX_DEBUGI_GETSTATS);
7480 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7481 &in, sizeof(in), stat, sizeof(*stat));
7484 * If the call was successful, fixup the version and indicate
7485 * what contents of the stat structure are valid.
7486 * Also do net to host conversion of fields here.
7490 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7491 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7493 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7494 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7496 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7497 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7499 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7500 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7502 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7503 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7505 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7506 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7508 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7509 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7511 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7512 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7514 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7515 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7517 stat->nFreePackets = ntohl(stat->nFreePackets);
7518 stat->packetReclaims = ntohl(stat->packetReclaims);
7519 stat->callsExecuted = ntohl(stat->callsExecuted);
7520 stat->nWaiting = ntohl(stat->nWaiting);
7521 stat->idleThreads = ntohl(stat->idleThreads);
7522 stat->nWaited = ntohl(stat->nWaited);
7523 stat->nPackets = ntohl(stat->nPackets);
7532 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7533 afs_uint16 remotePort, struct rx_statistics * stat,
7534 afs_uint32 * supportedValues)
7536 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7538 struct rx_debugIn in;
7539 afs_int32 *lp = (afs_int32 *) stat;
7543 * supportedValues is currently unused, but added to allow future
7544 * versioning of this function.
7547 *supportedValues = 0;
7548 in.type = htonl(RX_DEBUGI_RXSTATS);
7550 memset(stat, 0, sizeof(*stat));
7552 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7553 &in, sizeof(in), stat, sizeof(*stat));
7558 * Do net to host conversion here
7561 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7572 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7573 afs_uint16 remotePort, size_t version_length,
7576 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7578 return MakeDebugCall(socket, remoteAddr, remotePort,
7579 RX_PACKET_TYPE_VERSION, a, 1, version,
7587 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7588 afs_uint16 remotePort, afs_int32 * nextConnection,
7589 int allConnections, afs_uint32 debugSupportedValues,
7590 struct rx_debugConn * conn,
7591 afs_uint32 * supportedValues)
7593 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7595 struct rx_debugIn in;
7599 * supportedValues is currently unused, but added to allow future
7600 * versioning of this function.
7603 *supportedValues = 0;
7604 if (allConnections) {
7605 in.type = htonl(RX_DEBUGI_GETALLCONN);
7607 in.type = htonl(RX_DEBUGI_GETCONN);
7609 in.index = htonl(*nextConnection);
7610 memset(conn, 0, sizeof(*conn));
7612 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7613 &in, sizeof(in), conn, sizeof(*conn));
7616 *nextConnection += 1;
7619 * Convert old connection format to new structure.
7622 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7623 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7624 #define MOVEvL(a) (conn->a = vL->a)
7626 /* any old or unrecognized version... */
7627 for (i = 0; i < RX_MAXCALLS; i++) {
7628 MOVEvL(callState[i]);
7629 MOVEvL(callMode[i]);
7630 MOVEvL(callFlags[i]);
7631 MOVEvL(callOther[i]);
7633 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7634 MOVEvL(secStats.type);
7635 MOVEvL(secStats.level);
7636 MOVEvL(secStats.flags);
7637 MOVEvL(secStats.expires);
7638 MOVEvL(secStats.packetsReceived);
7639 MOVEvL(secStats.packetsSent);
7640 MOVEvL(secStats.bytesReceived);
7641 MOVEvL(secStats.bytesSent);
7646 * Do net to host conversion here
7648 * I don't convert host or port since we are most likely
7649 * going to want these in NBO.
7651 conn->cid = ntohl(conn->cid);
7652 conn->serial = ntohl(conn->serial);
7653 for (i = 0; i < RX_MAXCALLS; i++) {
7654 conn->callNumber[i] = ntohl(conn->callNumber[i]);
7656 conn->error = ntohl(conn->error);
7657 conn->secStats.flags = ntohl(conn->secStats.flags);
7658 conn->secStats.expires = ntohl(conn->secStats.expires);
7659 conn->secStats.packetsReceived =
7660 ntohl(conn->secStats.packetsReceived);
7661 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7662 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7663 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7664 conn->epoch = ntohl(conn->epoch);
7665 conn->natMTU = ntohl(conn->natMTU);
7674 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7675 afs_uint16 remotePort, afs_int32 * nextPeer,
7676 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7677 afs_uint32 * supportedValues)
7679 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7681 struct rx_debugIn in;
7684 * supportedValues is currently unused, but added to allow future
7685 * versioning of this function.
7688 *supportedValues = 0;
7689 in.type = htonl(RX_DEBUGI_GETPEER);
7690 in.index = htonl(*nextPeer);
7691 memset(peer, 0, sizeof(*peer));
7693 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7694 &in, sizeof(in), peer, sizeof(*peer));
7700 * Do net to host conversion here
7702 * I don't convert host or port since we are most likely
7703 * going to want these in NBO.
7705 peer->ifMTU = ntohs(peer->ifMTU);
7706 peer->idleWhen = ntohl(peer->idleWhen);
7707 peer->refCount = ntohs(peer->refCount);
7708 peer->rtt = ntohl(peer->rtt);
7709 peer->rtt_dev = ntohl(peer->rtt_dev);
7710 peer->timeout.sec = 0;
7711 peer->timeout.usec = 0;
7712 peer->nSent = ntohl(peer->nSent);
7713 peer->reSends = ntohl(peer->reSends);
7714 peer->natMTU = ntohs(peer->natMTU);
7715 peer->maxMTU = ntohs(peer->maxMTU);
7716 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7717 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7718 peer->MTU = ntohs(peer->MTU);
7719 peer->cwind = ntohs(peer->cwind);
7720 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7721 peer->congestSeq = ntohs(peer->congestSeq);
7722 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7723 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7724 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7725 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7734 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7735 struct rx_debugPeer * peerStats)
7738 afs_int32 error = 1; /* default to "did not succeed" */
7739 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7741 MUTEX_ENTER(&rx_peerHashTable_lock);
7742 for(tp = rx_peerHashTable[hashValue];
7743 tp != NULL; tp = tp->next) {
7744 if (tp->host == peerHost)
7750 MUTEX_EXIT(&rx_peerHashTable_lock);
7754 MUTEX_ENTER(&tp->peer_lock);
7755 peerStats->host = tp->host;
7756 peerStats->port = tp->port;
7757 peerStats->ifMTU = tp->ifMTU;
7758 peerStats->idleWhen = tp->idleWhen;
7759 peerStats->refCount = tp->refCount;
7760 peerStats->burstSize = 0;
7761 peerStats->burst = 0;
7762 peerStats->burstWait.sec = 0;
7763 peerStats->burstWait.usec = 0;
7764 peerStats->rtt = tp->rtt;
7765 peerStats->rtt_dev = tp->rtt_dev;
7766 peerStats->timeout.sec = 0;
7767 peerStats->timeout.usec = 0;
7768 peerStats->nSent = tp->nSent;
7769 peerStats->reSends = tp->reSends;
7770 peerStats->natMTU = tp->natMTU;
7771 peerStats->maxMTU = tp->maxMTU;
7772 peerStats->maxDgramPackets = tp->maxDgramPackets;
7773 peerStats->ifDgramPackets = tp->ifDgramPackets;
7774 peerStats->MTU = tp->MTU;
7775 peerStats->cwind = tp->cwind;
7776 peerStats->nDgramPackets = tp->nDgramPackets;
7777 peerStats->congestSeq = tp->congestSeq;
7778 peerStats->bytesSent.high = tp->bytesSent >> 32;
7779 peerStats->bytesSent.low = tp->bytesSent & MAX_AFS_UINT32;
7780 peerStats->bytesReceived.high = tp->bytesReceived >> 32;
7781 peerStats->bytesReceived.low
7782 = tp->bytesReceived & MAX_AFS_UINT32;
7783 MUTEX_EXIT(&tp->peer_lock);
7785 MUTEX_ENTER(&rx_peerHashTable_lock);
7788 MUTEX_EXIT(&rx_peerHashTable_lock);
7796 struct rx_serverQueueEntry *np;
7799 struct rx_call *call;
7800 struct rx_serverQueueEntry *sq;
7803 if (rx_atomic_test_and_set_bit(&rxinit_status, 0))
7804 return; /* Already shutdown. */
7808 #ifndef AFS_PTHREAD_ENV
7809 FD_ZERO(&rx_selectMask);
7810 #endif /* AFS_PTHREAD_ENV */
7811 rxi_dataQuota = RX_MAX_QUOTA;
7812 #ifndef AFS_PTHREAD_ENV
7814 #endif /* AFS_PTHREAD_ENV */
7817 #ifndef AFS_PTHREAD_ENV
7818 #ifndef AFS_USE_GETTIMEOFDAY
7820 #endif /* AFS_USE_GETTIMEOFDAY */
7821 #endif /* AFS_PTHREAD_ENV */
7823 while (!opr_queue_IsEmpty(&rx_freeCallQueue)) {
7824 call = opr_queue_First(&rx_freeCallQueue, struct rx_call, entry);
7825 opr_queue_Remove(&call->entry);
7826 rxi_Free(call, sizeof(struct rx_call));
7829 while (!opr_queue_IsEmpty(&rx_idleServerQueue)) {
7830 sq = opr_queue_First(&rx_idleServerQueue, struct rx_serverQueueEntry,
7832 opr_queue_Remove(&sq->entry);
7837 struct rx_peer **peer_ptr, **peer_end;
7838 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7839 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7841 struct rx_peer *peer, *next;
7843 MUTEX_ENTER(&rx_peerHashTable_lock);
7844 for (peer = *peer_ptr; peer; peer = next) {
7845 struct opr_queue *cursor, *store;
7848 MUTEX_ENTER(&rx_rpc_stats);
7849 MUTEX_ENTER(&peer->peer_lock);
7850 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
7851 unsigned int num_funcs;
7852 struct rx_interface_stat *rpc_stat
7853 = opr_queue_Entry(cursor, struct rx_interface_stat,
7857 opr_queue_Remove(&rpc_stat->entry);
7858 opr_queue_Remove(&rpc_stat->entryPeers);
7859 num_funcs = rpc_stat->stats[0].func_total;
7861 sizeof(rx_interface_stat_t) +
7862 rpc_stat->stats[0].func_total *
7863 sizeof(rx_function_entry_v1_t);
7865 rxi_Free(rpc_stat, space);
7867 /* rx_rpc_stats must be held */
7868 rxi_rpc_peer_stat_cnt -= num_funcs;
7870 MUTEX_EXIT(&peer->peer_lock);
7871 MUTEX_EXIT(&rx_rpc_stats);
7875 if (rx_stats_active)
7876 rx_atomic_dec(&rx_stats.nPeerStructs);
7878 MUTEX_EXIT(&rx_peerHashTable_lock);
7881 for (i = 0; i < RX_MAX_SERVICES; i++) {
7883 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7885 for (i = 0; i < rx_hashTableSize; i++) {
7886 struct rx_connection *tc, *ntc;
7887 MUTEX_ENTER(&rx_connHashTable_lock);
7888 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7890 for (j = 0; j < RX_MAXCALLS; j++) {
7892 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7895 rxi_Free(tc, sizeof(*tc));
7897 MUTEX_EXIT(&rx_connHashTable_lock);
7900 MUTEX_ENTER(&freeSQEList_lock);
7902 while ((np = rx_FreeSQEList)) {
7903 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7904 MUTEX_DESTROY(&np->lock);
7905 rxi_Free(np, sizeof(*np));
7908 MUTEX_EXIT(&freeSQEList_lock);
7909 MUTEX_DESTROY(&freeSQEList_lock);
7910 MUTEX_DESTROY(&rx_freeCallQueue_lock);
7911 MUTEX_DESTROY(&rx_connHashTable_lock);
7912 MUTEX_DESTROY(&rx_peerHashTable_lock);
7913 MUTEX_DESTROY(&rx_serverPool_lock);
7915 osi_Free(rx_connHashTable,
7916 rx_hashTableSize * sizeof(struct rx_connection *));
7917 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7919 UNPIN(rx_connHashTable,
7920 rx_hashTableSize * sizeof(struct rx_connection *));
7921 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
7923 MUTEX_ENTER(&rx_quota_mutex);
7924 rxi_dataQuota = RX_MAX_QUOTA;
7925 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
7926 MUTEX_EXIT(&rx_quota_mutex);
7932 * Routines to implement connection specific data.
7936 rx_KeyCreate(rx_destructor_t rtn)
7939 MUTEX_ENTER(&rxi_keyCreate_lock);
7940 key = rxi_keyCreate_counter++;
7941 rxi_keyCreate_destructor = (rx_destructor_t *)
7942 realloc((void *)rxi_keyCreate_destructor,
7943 (key + 1) * sizeof(rx_destructor_t));
7944 rxi_keyCreate_destructor[key] = rtn;
7945 MUTEX_EXIT(&rxi_keyCreate_lock);
7950 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
7953 MUTEX_ENTER(&conn->conn_data_lock);
7954 if (!conn->specific) {
7955 conn->specific = malloc((key + 1) * sizeof(void *));
7956 for (i = 0; i < key; i++)
7957 conn->specific[i] = NULL;
7958 conn->nSpecific = key + 1;
7959 conn->specific[key] = ptr;
7960 } else if (key >= conn->nSpecific) {
7961 conn->specific = (void **)
7962 realloc(conn->specific, (key + 1) * sizeof(void *));
7963 for (i = conn->nSpecific; i < key; i++)
7964 conn->specific[i] = NULL;
7965 conn->nSpecific = key + 1;
7966 conn->specific[key] = ptr;
7968 if (conn->specific[key] && rxi_keyCreate_destructor[key])
7969 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
7970 conn->specific[key] = ptr;
7972 MUTEX_EXIT(&conn->conn_data_lock);
7976 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
7979 MUTEX_ENTER(&svc->svc_data_lock);
7980 if (!svc->specific) {
7981 svc->specific = malloc((key + 1) * sizeof(void *));
7982 for (i = 0; i < key; i++)
7983 svc->specific[i] = NULL;
7984 svc->nSpecific = key + 1;
7985 svc->specific[key] = ptr;
7986 } else if (key >= svc->nSpecific) {
7987 svc->specific = (void **)
7988 realloc(svc->specific, (key + 1) * sizeof(void *));
7989 for (i = svc->nSpecific; i < key; i++)
7990 svc->specific[i] = NULL;
7991 svc->nSpecific = key + 1;
7992 svc->specific[key] = ptr;
7994 if (svc->specific[key] && rxi_keyCreate_destructor[key])
7995 (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
7996 svc->specific[key] = ptr;
7998 MUTEX_EXIT(&svc->svc_data_lock);
8002 rx_GetSpecific(struct rx_connection *conn, int key)
8005 MUTEX_ENTER(&conn->conn_data_lock);
8006 if (key >= conn->nSpecific)
8009 ptr = conn->specific[key];
8010 MUTEX_EXIT(&conn->conn_data_lock);
8015 rx_GetServiceSpecific(struct rx_service *svc, int key)
8018 MUTEX_ENTER(&svc->svc_data_lock);
8019 if (key >= svc->nSpecific)
8022 ptr = svc->specific[key];
8023 MUTEX_EXIT(&svc->svc_data_lock);
8028 #endif /* !KERNEL */
8031 * processStats is a queue used to store the statistics for the local
8032 * process. Its contents are similar to the contents of the rpcStats
8033 * queue on a rx_peer structure, but the actual data stored within
8034 * this queue contains totals across the lifetime of the process (assuming
8035 * the stats have not been reset) - unlike the per peer structures
8036 * which can come and go based upon the peer lifetime.
8039 static struct opr_queue processStats = { &processStats, &processStats };
8042 * peerStats is a queue used to store the statistics for all peer structs.
8043 * Its contents are the union of all the peer rpcStats queues.
8046 static struct opr_queue peerStats = { &peerStats, &peerStats };
8049 * rxi_monitor_processStats is used to turn process wide stat collection
8053 static int rxi_monitor_processStats = 0;
8056 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
8059 static int rxi_monitor_peerStats = 0;
8063 rxi_ClearRPCOpStat(rx_function_entry_v1_p rpc_stat)
8065 rpc_stat->invocations = 0;
8066 rpc_stat->bytes_sent = 0;
8067 rpc_stat->bytes_rcvd = 0;
8068 rpc_stat->queue_time_sum.sec = 0;
8069 rpc_stat->queue_time_sum.usec = 0;
8070 rpc_stat->queue_time_sum_sqr.sec = 0;
8071 rpc_stat->queue_time_sum_sqr.usec = 0;
8072 rpc_stat->queue_time_min.sec = 9999999;
8073 rpc_stat->queue_time_min.usec = 9999999;
8074 rpc_stat->queue_time_max.sec = 0;
8075 rpc_stat->queue_time_max.usec = 0;
8076 rpc_stat->execution_time_sum.sec = 0;
8077 rpc_stat->execution_time_sum.usec = 0;
8078 rpc_stat->execution_time_sum_sqr.sec = 0;
8079 rpc_stat->execution_time_sum_sqr.usec = 0;
8080 rpc_stat->execution_time_min.sec = 9999999;
8081 rpc_stat->execution_time_min.usec = 9999999;
8082 rpc_stat->execution_time_max.sec = 0;
8083 rpc_stat->execution_time_max.usec = 0;
8087 * Given all of the information for a particular rpc
8088 * call, find or create (if requested) the stat structure for the rpc.
8091 * the queue of stats that will be updated with the new value
8093 * @param rxInterface
8094 * a unique number that identifies the rpc interface
8097 * the total number of functions in this interface. this is only
8098 * required if create is true
8101 * if true, this invocation was made to a server
8104 * the ip address of the remote host. this is only required if create
8105 * and addToPeerList are true
8108 * the port of the remote host. this is only required if create
8109 * and addToPeerList are true
8111 * @param addToPeerList
8112 * if != 0, add newly created stat to the global peer list
8115 * if a new stats structure is allocated, the counter will
8116 * be updated with the new number of allocated stat structures.
8117 * only required if create is true
8120 * if no stats structure exists, allocate one
8124 static rx_interface_stat_p
8125 rxi_FindRpcStat(struct opr_queue *stats, afs_uint32 rxInterface,
8126 afs_uint32 totalFunc, int isServer, afs_uint32 remoteHost,
8127 afs_uint32 remotePort, int addToPeerList,
8128 unsigned int *counter, int create)
8130 rx_interface_stat_p rpc_stat = NULL;
8131 struct opr_queue *cursor;
8134 * See if there's already a structure for this interface
8137 for (opr_queue_Scan(stats, cursor)) {
8138 rpc_stat = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8140 if ((rpc_stat->stats[0].interfaceId == rxInterface)
8141 && (rpc_stat->stats[0].remote_is_server == isServer))
8145 /* if they didn't ask us to create, we're done */
8147 if (opr_queue_IsEnd(stats, cursor))
8153 /* can't proceed without these */
8154 if (!totalFunc || !counter)
8158 * Didn't find a match so allocate a new structure and add it to the
8162 if (opr_queue_IsEnd(stats, cursor) || (rpc_stat == NULL)
8163 || (rpc_stat->stats[0].interfaceId != rxInterface)
8164 || (rpc_stat->stats[0].remote_is_server != isServer)) {
8169 sizeof(rx_interface_stat_t) +
8170 totalFunc * sizeof(rx_function_entry_v1_t);
8172 rpc_stat = rxi_Alloc(space);
8173 if (rpc_stat == NULL)
8176 *counter += totalFunc;
8177 for (i = 0; i < totalFunc; i++) {
8178 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8179 rpc_stat->stats[i].remote_peer = remoteHost;
8180 rpc_stat->stats[i].remote_port = remotePort;
8181 rpc_stat->stats[i].remote_is_server = isServer;
8182 rpc_stat->stats[i].interfaceId = rxInterface;
8183 rpc_stat->stats[i].func_total = totalFunc;
8184 rpc_stat->stats[i].func_index = i;
8186 opr_queue_Prepend(stats, &rpc_stat->entry);
8187 if (addToPeerList) {
8188 opr_queue_Prepend(&peerStats, &rpc_stat->entryPeers);
8195 rx_ClearProcessRPCStats(afs_int32 rxInterface)
8197 rx_interface_stat_p rpc_stat;
8200 if (rxInterface == -1)
8203 MUTEX_ENTER(&rx_rpc_stats);
8204 rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8207 totalFunc = rpc_stat->stats[0].func_total;
8208 for (i = 0; i < totalFunc; i++)
8209 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8211 MUTEX_EXIT(&rx_rpc_stats);
8216 rx_ClearPeerRPCStats(afs_int32 rxInterface, afs_uint32 peerHost, afs_uint16 peerPort)
8218 rx_interface_stat_p rpc_stat;
8220 struct rx_peer * peer;
8222 if (rxInterface == -1)
8225 peer = rxi_FindPeer(peerHost, peerPort, 0);
8229 MUTEX_ENTER(&rx_rpc_stats);
8230 rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8233 totalFunc = rpc_stat->stats[0].func_total;
8234 for (i = 0; i < totalFunc; i++)
8235 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8237 MUTEX_EXIT(&rx_rpc_stats);
8242 rx_CopyProcessRPCStats(afs_uint64 op)
8244 rx_interface_stat_p rpc_stat;
8245 rx_function_entry_v1_p rpcop_stat =
8246 rxi_Alloc(sizeof(rx_function_entry_v1_t));
8247 int currentFunc = (op & MAX_AFS_UINT32);
8248 afs_int32 rxInterface = (op >> 32);
8250 if (!rxi_monitor_processStats)
8253 if (rxInterface == -1)
8256 if (rpcop_stat == NULL)
8259 MUTEX_ENTER(&rx_rpc_stats);
8260 rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8263 memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8264 sizeof(rx_function_entry_v1_t));
8265 MUTEX_EXIT(&rx_rpc_stats);
8267 rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8274 rx_CopyPeerRPCStats(afs_uint64 op, afs_uint32 peerHost, afs_uint16 peerPort)
8276 rx_interface_stat_p rpc_stat;
8277 rx_function_entry_v1_p rpcop_stat =
8278 rxi_Alloc(sizeof(rx_function_entry_v1_t));
8279 int currentFunc = (op & MAX_AFS_UINT32);
8280 afs_int32 rxInterface = (op >> 32);
8281 struct rx_peer *peer;
8283 if (!rxi_monitor_peerStats)
8286 if (rxInterface == -1)
8289 if (rpcop_stat == NULL)
8292 peer = rxi_FindPeer(peerHost, peerPort, 0);
8296 MUTEX_ENTER(&rx_rpc_stats);
8297 rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8300 memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8301 sizeof(rx_function_entry_v1_t));
8302 MUTEX_EXIT(&rx_rpc_stats);
8304 rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8311 rx_ReleaseRPCStats(void *stats)
8314 rxi_Free(stats, sizeof(rx_function_entry_v1_t));
8318 * Given all of the information for a particular rpc
8319 * call, create (if needed) and update the stat totals for the rpc.
8322 * the queue of stats that will be updated with the new value
8324 * @param rxInterface
8325 * a unique number that identifies the rpc interface
8327 * @param currentFunc
8328 * the index of the function being invoked
8331 * the total number of functions in this interface
8334 * the amount of time this function waited for a thread
8337 * the amount of time this function invocation took to execute
8340 * the number bytes sent by this invocation
8343 * the number bytes received by this invocation
8346 * if true, this invocation was made to a server
8349 * the ip address of the remote host
8352 * the port of the remote host
8354 * @param addToPeerList
8355 * if != 0, add newly created stat to the global peer list
8358 * if a new stats structure is allocated, the counter will
8359 * be updated with the new number of allocated stat structures
8364 rxi_AddRpcStat(struct opr_queue *stats, afs_uint32 rxInterface,
8365 afs_uint32 currentFunc, afs_uint32 totalFunc,
8366 struct clock *queueTime, struct clock *execTime,
8367 afs_uint64 bytesSent, afs_uint64 bytesRcvd, int isServer,
8368 afs_uint32 remoteHost, afs_uint32 remotePort,
8369 int addToPeerList, unsigned int *counter)
8372 rx_interface_stat_p rpc_stat;
8374 rpc_stat = rxi_FindRpcStat(stats, rxInterface, totalFunc, isServer,
8375 remoteHost, remotePort, addToPeerList, counter,
8383 * Increment the stats for this function
8386 rpc_stat->stats[currentFunc].invocations++;
8387 rpc_stat->stats[currentFunc].bytes_sent += bytesSent;
8388 rpc_stat->stats[currentFunc].bytes_rcvd += bytesRcvd;
8389 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8390 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8391 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8392 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8394 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8395 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8397 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8398 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8400 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8401 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8403 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8404 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8412 rxi_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8413 afs_uint32 currentFunc, afs_uint32 totalFunc,
8414 struct clock *queueTime, struct clock *execTime,
8415 afs_uint64 bytesSent, afs_uint64 bytesRcvd,
8419 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8422 MUTEX_ENTER(&rx_rpc_stats);
8424 if (rxi_monitor_peerStats) {
8425 MUTEX_ENTER(&peer->peer_lock);
8426 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8427 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8428 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8429 MUTEX_EXIT(&peer->peer_lock);
8432 if (rxi_monitor_processStats) {
8433 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8434 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8435 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8438 MUTEX_EXIT(&rx_rpc_stats);
8442 * Increment the times and count for a particular rpc function.
8444 * Traditionally this call was invoked from rxgen stubs. Modern stubs
8445 * call rx_RecordCallStatistics instead, so the public version of this
8446 * function is left purely for legacy callers.
8449 * The peer who invoked the rpc
8451 * @param rxInterface
8452 * A unique number that identifies the rpc interface
8454 * @param currentFunc
8455 * The index of the function being invoked
8458 * The total number of functions in this interface
8461 * The amount of time this function waited for a thread
8464 * The amount of time this function invocation took to execute
8467 * The number bytes sent by this invocation
8470 * The number bytes received by this invocation
8473 * If true, this invocation was made to a server
8477 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8478 afs_uint32 currentFunc, afs_uint32 totalFunc,
8479 struct clock *queueTime, struct clock *execTime,
8480 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8486 sent64 = ((afs_uint64)bytesSent->high << 32) + bytesSent->low;
8487 rcvd64 = ((afs_uint64)bytesRcvd->high << 32) + bytesRcvd->low;
8489 rxi_IncrementTimeAndCount(peer, rxInterface, currentFunc, totalFunc,
8490 queueTime, execTime, sent64, rcvd64,
8497 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8501 * IN callerVersion - the rpc stat version of the caller.
8503 * IN count - the number of entries to marshall.
8505 * IN stats - pointer to stats to be marshalled.
8507 * OUT ptr - Where to store the marshalled data.
8514 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8515 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8521 * We only support the first version
8523 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8524 *(ptr++) = stats->remote_peer;
8525 *(ptr++) = stats->remote_port;
8526 *(ptr++) = stats->remote_is_server;
8527 *(ptr++) = stats->interfaceId;
8528 *(ptr++) = stats->func_total;
8529 *(ptr++) = stats->func_index;
8530 *(ptr++) = stats->invocations >> 32;
8531 *(ptr++) = stats->invocations & MAX_AFS_UINT32;
8532 *(ptr++) = stats->bytes_sent >> 32;
8533 *(ptr++) = stats->bytes_sent & MAX_AFS_UINT32;
8534 *(ptr++) = stats->bytes_rcvd >> 32;
8535 *(ptr++) = stats->bytes_rcvd & MAX_AFS_UINT32;
8536 *(ptr++) = stats->queue_time_sum.sec;
8537 *(ptr++) = stats->queue_time_sum.usec;
8538 *(ptr++) = stats->queue_time_sum_sqr.sec;
8539 *(ptr++) = stats->queue_time_sum_sqr.usec;
8540 *(ptr++) = stats->queue_time_min.sec;
8541 *(ptr++) = stats->queue_time_min.usec;
8542 *(ptr++) = stats->queue_time_max.sec;
8543 *(ptr++) = stats->queue_time_max.usec;
8544 *(ptr++) = stats->execution_time_sum.sec;
8545 *(ptr++) = stats->execution_time_sum.usec;
8546 *(ptr++) = stats->execution_time_sum_sqr.sec;
8547 *(ptr++) = stats->execution_time_sum_sqr.usec;
8548 *(ptr++) = stats->execution_time_min.sec;
8549 *(ptr++) = stats->execution_time_min.usec;
8550 *(ptr++) = stats->execution_time_max.sec;
8551 *(ptr++) = stats->execution_time_max.usec;
8557 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8562 * IN callerVersion - the rpc stat version of the caller
8564 * OUT myVersion - the rpc stat version of this function
8566 * OUT clock_sec - local time seconds
8568 * OUT clock_usec - local time microseconds
8570 * OUT allocSize - the number of bytes allocated to contain stats
8572 * OUT statCount - the number stats retrieved from this process.
8574 * OUT stats - the actual stats retrieved from this process.
8578 * Returns void. If successful, stats will != NULL.
8582 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8583 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8584 size_t * allocSize, afs_uint32 * statCount,
8585 afs_uint32 ** stats)
8595 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8598 * Check to see if stats are enabled
8601 MUTEX_ENTER(&rx_rpc_stats);
8602 if (!rxi_monitor_processStats) {
8603 MUTEX_EXIT(&rx_rpc_stats);
8607 clock_GetTime(&now);
8608 *clock_sec = now.sec;
8609 *clock_usec = now.usec;
8612 * Allocate the space based upon the caller version
8614 * If the client is at an older version than we are,
8615 * we return the statistic data in the older data format, but
8616 * we still return our version number so the client knows we
8617 * are maintaining more data than it can retrieve.
8620 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8621 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8622 *statCount = rxi_rpc_process_stat_cnt;
8625 * This can't happen yet, but in the future version changes
8626 * can be handled by adding additional code here
8630 if (space > (size_t) 0) {
8632 ptr = *stats = rxi_Alloc(space);
8635 struct opr_queue *cursor;
8637 for (opr_queue_Scan(&processStats, cursor)) {
8638 struct rx_interface_stat *rpc_stat =
8639 opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8641 * Copy the data based upon the caller version
8643 rx_MarshallProcessRPCStats(callerVersion,
8644 rpc_stat->stats[0].func_total,
8645 rpc_stat->stats, &ptr);
8651 MUTEX_EXIT(&rx_rpc_stats);
8656 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8660 * IN callerVersion - the rpc stat version of the caller
8662 * OUT myVersion - the rpc stat version of this function
8664 * OUT clock_sec - local time seconds
8666 * OUT clock_usec - local time microseconds
8668 * OUT allocSize - the number of bytes allocated to contain stats
8670 * OUT statCount - the number of stats retrieved from the individual
8673 * OUT stats - the actual stats retrieved from the individual peer structures.
8677 * Returns void. If successful, stats will != NULL.
8681 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8682 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8683 size_t * allocSize, afs_uint32 * statCount,
8684 afs_uint32 ** stats)
8694 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8697 * Check to see if stats are enabled
8700 MUTEX_ENTER(&rx_rpc_stats);
8701 if (!rxi_monitor_peerStats) {
8702 MUTEX_EXIT(&rx_rpc_stats);
8706 clock_GetTime(&now);
8707 *clock_sec = now.sec;
8708 *clock_usec = now.usec;
8711 * Allocate the space based upon the caller version
8713 * If the client is at an older version than we are,
8714 * we return the statistic data in the older data format, but
8715 * we still return our version number so the client knows we
8716 * are maintaining more data than it can retrieve.
8719 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8720 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8721 *statCount = rxi_rpc_peer_stat_cnt;
8724 * This can't happen yet, but in the future version changes
8725 * can be handled by adding additional code here
8729 if (space > (size_t) 0) {
8731 ptr = *stats = rxi_Alloc(space);
8734 struct opr_queue *cursor;
8736 for (opr_queue_Scan(&peerStats, cursor)) {
8737 struct rx_interface_stat *rpc_stat
8738 = opr_queue_Entry(cursor, struct rx_interface_stat,
8742 * Copy the data based upon the caller version
8744 rx_MarshallProcessRPCStats(callerVersion,
8745 rpc_stat->stats[0].func_total,
8746 rpc_stat->stats, &ptr);
8752 MUTEX_EXIT(&rx_rpc_stats);
8757 * rx_FreeRPCStats - free memory allocated by
8758 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
8762 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
8763 * rx_RetrievePeerRPCStats
8765 * IN allocSize - the number of bytes in stats.
8773 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
8775 rxi_Free(stats, allocSize);
8779 * rx_queryProcessRPCStats - see if process rpc stat collection is
8780 * currently enabled.
8786 * Returns 0 if stats are not enabled != 0 otherwise
8790 rx_queryProcessRPCStats(void)
8793 MUTEX_ENTER(&rx_rpc_stats);
8794 rc = rxi_monitor_processStats;
8795 MUTEX_EXIT(&rx_rpc_stats);
8800 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
8806 * Returns 0 if stats are not enabled != 0 otherwise
8810 rx_queryPeerRPCStats(void)
8813 MUTEX_ENTER(&rx_rpc_stats);
8814 rc = rxi_monitor_peerStats;
8815 MUTEX_EXIT(&rx_rpc_stats);
8820 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
8830 rx_enableProcessRPCStats(void)
8832 MUTEX_ENTER(&rx_rpc_stats);
8833 rx_enable_stats = 1;
8834 rxi_monitor_processStats = 1;
8835 MUTEX_EXIT(&rx_rpc_stats);
8839 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
8849 rx_enablePeerRPCStats(void)
8851 MUTEX_ENTER(&rx_rpc_stats);
8852 rx_enable_stats = 1;
8853 rxi_monitor_peerStats = 1;
8854 MUTEX_EXIT(&rx_rpc_stats);
8858 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
8868 rx_disableProcessRPCStats(void)
8870 struct opr_queue *cursor, *store;
8873 MUTEX_ENTER(&rx_rpc_stats);
8876 * Turn off process statistics and if peer stats is also off, turn
8880 rxi_monitor_processStats = 0;
8881 if (rxi_monitor_peerStats == 0) {
8882 rx_enable_stats = 0;
8885 for (opr_queue_ScanSafe(&processStats, cursor, store)) {
8886 unsigned int num_funcs = 0;
8887 struct rx_interface_stat *rpc_stat
8888 = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8890 opr_queue_Remove(&rpc_stat->entry);
8892 num_funcs = rpc_stat->stats[0].func_total;
8894 sizeof(rx_interface_stat_t) +
8895 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
8897 rxi_Free(rpc_stat, space);
8898 rxi_rpc_process_stat_cnt -= num_funcs;
8900 MUTEX_EXIT(&rx_rpc_stats);
8904 * rx_disablePeerRPCStats - stop rpc stat collection for peers
8914 rx_disablePeerRPCStats(void)
8916 struct rx_peer **peer_ptr, **peer_end;
8920 * Turn off peer statistics and if process stats is also off, turn
8924 rxi_monitor_peerStats = 0;
8925 if (rxi_monitor_processStats == 0) {
8926 rx_enable_stats = 0;
8929 for (peer_ptr = &rx_peerHashTable[0], peer_end =
8930 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
8932 struct rx_peer *peer, *next, *prev;
8934 MUTEX_ENTER(&rx_peerHashTable_lock);
8935 MUTEX_ENTER(&rx_rpc_stats);
8936 for (prev = peer = *peer_ptr; peer; peer = next) {
8938 code = MUTEX_TRYENTER(&peer->peer_lock);
8941 struct opr_queue *cursor, *store;
8943 if (prev == *peer_ptr) {
8954 MUTEX_EXIT(&rx_peerHashTable_lock);
8956 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
8957 unsigned int num_funcs = 0;
8958 struct rx_interface_stat *rpc_stat
8959 = opr_queue_Entry(cursor, struct rx_interface_stat,
8962 opr_queue_Remove(&rpc_stat->entry);
8963 opr_queue_Remove(&rpc_stat->entryPeers);
8964 num_funcs = rpc_stat->stats[0].func_total;
8966 sizeof(rx_interface_stat_t) +
8967 rpc_stat->stats[0].func_total *
8968 sizeof(rx_function_entry_v1_t);
8970 rxi_Free(rpc_stat, space);
8971 rxi_rpc_peer_stat_cnt -= num_funcs;
8973 MUTEX_EXIT(&peer->peer_lock);
8975 MUTEX_ENTER(&rx_peerHashTable_lock);
8985 MUTEX_EXIT(&rx_rpc_stats);
8986 MUTEX_EXIT(&rx_peerHashTable_lock);
8991 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
8996 * IN clearFlag - flag indicating which stats to clear
9004 rx_clearProcessRPCStats(afs_uint32 clearFlag)
9006 struct opr_queue *cursor;
9008 MUTEX_ENTER(&rx_rpc_stats);
9010 for (opr_queue_Scan(&processStats, cursor)) {
9011 unsigned int num_funcs = 0, i;
9012 struct rx_interface_stat *rpc_stat
9013 = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
9015 num_funcs = rpc_stat->stats[0].func_total;
9016 for (i = 0; i < num_funcs; i++) {
9017 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9018 rpc_stat->stats[i].invocations = 0;
9020 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9021 rpc_stat->stats[i].bytes_sent = 0;
9023 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9024 rpc_stat->stats[i].bytes_rcvd = 0;
9026 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9027 rpc_stat->stats[i].queue_time_sum.sec = 0;
9028 rpc_stat->stats[i].queue_time_sum.usec = 0;
9030 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9031 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9032 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9034 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9035 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9036 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9038 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9039 rpc_stat->stats[i].queue_time_max.sec = 0;
9040 rpc_stat->stats[i].queue_time_max.usec = 0;
9042 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9043 rpc_stat->stats[i].execution_time_sum.sec = 0;
9044 rpc_stat->stats[i].execution_time_sum.usec = 0;
9046 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9047 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9048 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9050 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9051 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9052 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9054 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9055 rpc_stat->stats[i].execution_time_max.sec = 0;
9056 rpc_stat->stats[i].execution_time_max.usec = 0;
9061 MUTEX_EXIT(&rx_rpc_stats);
9065 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
9070 * IN clearFlag - flag indicating which stats to clear
9078 rx_clearPeerRPCStats(afs_uint32 clearFlag)
9080 struct opr_queue *cursor;
9082 MUTEX_ENTER(&rx_rpc_stats);
9084 for (opr_queue_Scan(&peerStats, cursor)) {
9085 unsigned int num_funcs, i;
9086 struct rx_interface_stat *rpc_stat
9087 = opr_queue_Entry(cursor, struct rx_interface_stat, entryPeers);
9089 num_funcs = rpc_stat->stats[0].func_total;
9090 for (i = 0; i < num_funcs; i++) {
9091 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9092 rpc_stat->stats[i].invocations = 0;
9094 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9095 rpc_stat->stats[i].bytes_sent = 0;
9097 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9098 rpc_stat->stats[i].bytes_rcvd = 0;
9100 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9101 rpc_stat->stats[i].queue_time_sum.sec = 0;
9102 rpc_stat->stats[i].queue_time_sum.usec = 0;
9104 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9105 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9106 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9108 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9109 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9110 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9112 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9113 rpc_stat->stats[i].queue_time_max.sec = 0;
9114 rpc_stat->stats[i].queue_time_max.usec = 0;
9116 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9117 rpc_stat->stats[i].execution_time_sum.sec = 0;
9118 rpc_stat->stats[i].execution_time_sum.usec = 0;
9120 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9121 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9122 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9124 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9125 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9126 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9128 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9129 rpc_stat->stats[i].execution_time_max.sec = 0;
9130 rpc_stat->stats[i].execution_time_max.usec = 0;
9135 MUTEX_EXIT(&rx_rpc_stats);
9139 * rxi_rxstat_userok points to a routine that returns 1 if the caller
9140 * is authorized to enable/disable/clear RX statistics.
9142 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
9145 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
9147 rxi_rxstat_userok = proc;
9151 rx_RxStatUserOk(struct rx_call *call)
9153 if (!rxi_rxstat_userok)
9155 return rxi_rxstat_userok(call);
9160 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
9161 * function in the MSVC runtime DLL (msvcrt.dll).
9163 * Note: the system serializes calls to this function.
9166 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
9167 DWORD reason, /* reason function is being called */
9168 LPVOID reserved) /* reserved for future use */
9171 case DLL_PROCESS_ATTACH:
9172 /* library is being attached to a process */
9176 case DLL_PROCESS_DETACH:
9183 #endif /* AFS_NT40_ENV */
9186 int rx_DumpCalls(FILE *outputFile, char *cookie)
9188 #ifdef RXDEBUG_PACKET
9189 #ifdef KDUMP_RX_LOCK
9190 struct rx_call_rx_lock *c;
9197 #define RXDPRINTF sprintf
9198 #define RXDPRINTOUT output
9200 #define RXDPRINTF fprintf
9201 #define RXDPRINTOUT outputFile
9204 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
9206 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9209 for (c = rx_allCallsp; c; c = c->allNextp) {
9210 u_short rqc, tqc, iovqc;
9212 MUTEX_ENTER(&c->lock);
9213 rqc = opr_queue_Count(&c->rq);
9214 tqc = opr_queue_Count(&c->tq);
9215 iovqc = opr_queue_Count(&c->app.iovq);
9217 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, "
9218 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
9219 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
9220 "resendEvent=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
9221 "lastSendTime=%u, lastRecvTime=%u"
9222 #ifdef RX_ENABLE_LOCKS
9225 #ifdef RX_REFCOUNT_CHECK
9226 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
9227 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
9230 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,
9231 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
9232 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
9233 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
9234 c->resendEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
9235 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime
9236 #ifdef RX_ENABLE_LOCKS
9237 , (afs_uint32)c->refCount
9239 #ifdef RX_REFCOUNT_CHECK
9240 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
9243 MUTEX_EXIT(&c->lock);
9246 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9249 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
9251 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9253 #endif /* RXDEBUG_PACKET */