2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
10 /* RX: Extended Remote Procedure Call */
12 #include <afsconfig.h>
13 #include <afs/param.h>
16 # include "afs/sysincludes.h"
17 # include "afsincludes.h"
22 # ifdef AFS_LINUX20_ENV
23 # include "h/socket.h"
25 # include "netinet/in.h"
27 # include "netinet/ip6.h"
28 # include "inet/common.h"
30 # include "inet/ip_ire.h"
32 # include "afs/afs_args.h"
33 # include "afs/afs_osi.h"
34 # ifdef RX_KERNEL_TRACE
35 # include "rx_kcommon.h"
37 # if defined(AFS_AIX_ENV)
41 # undef RXDEBUG /* turn off debugging */
43 # if defined(AFS_SGI_ENV)
44 # include "sys/debug.h"
47 # include "afs/sysincludes.h"
48 # include "afsincludes.h"
49 # endif /* !UKERNEL */
50 # include "afs/lock.h"
51 # include "rx_kmutex.h"
52 # include "rx_kernel.h"
53 # define AFSOP_STOP_RXCALLBACK 210 /* Stop CALLBACK process */
54 # define AFSOP_STOP_AFS 211 /* Stop AFS process */
55 # define AFSOP_STOP_BKG 212 /* Stop BKG process */
56 extern afs_int32 afs_termState;
58 # include "sys/lockl.h"
59 # include "sys/lock_def.h"
60 # endif /* AFS_AIX41_ENV */
61 # include "afs/rxgen_consts.h"
66 # include <afs/afsutil.h>
67 # include <WINNT\afsreg.h>
75 #include <opr/queue.h>
76 #include <hcrypto/rand.h>
80 #include "rx_atomic.h"
81 #include "rx_globals.h"
83 #include "rx_internal.h"
90 #include "rx_packet.h"
91 #include "rx_server.h"
93 #include <afs/rxgen_consts.h>
96 #ifdef AFS_PTHREAD_ENV
98 int (*registerProgram) (pid_t, char *) = 0;
99 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
102 int (*registerProgram) (PROCESS, char *) = 0;
103 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
107 /* Local static routines */
108 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
109 static void rxi_ComputeRoundTripTime(struct rx_packet *, struct rx_ackPacket *,
110 struct rx_call *, struct rx_peer *,
112 static void rxi_Resend(struct rxevent *event, void *arg0, void *arg1,
114 static void rxi_SendDelayedAck(struct rxevent *event, void *call,
115 void *dummy, int dummy2);
116 static void rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1,
117 void *dummy, int dummy2);
118 static void rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1,
119 void *unused, int unused2);
120 static void rxi_ReapConnections(struct rxevent *unused, void *unused1,
121 void *unused2, int unused3);
122 static struct rx_packet *rxi_SendCallAbort(struct rx_call *call,
123 struct rx_packet *packet,
124 int istack, int force);
125 static void rxi_AckAll(struct rx_call *call);
126 static struct rx_connection
127 *rxi_FindConnection(osi_socket socket, afs_uint32 host, u_short port,
128 u_short serviceId, afs_uint32 cid,
129 afs_uint32 epoch, int type, u_int securityIndex,
130 int *unknownService);
131 static struct rx_packet
132 *rxi_ReceiveDataPacket(struct rx_call *call, struct rx_packet *np,
133 int istack, osi_socket socket,
134 afs_uint32 host, u_short port, int *tnop,
135 struct rx_call **newcallp);
136 static struct rx_packet
137 *rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
139 static struct rx_packet
140 *rxi_ReceiveResponsePacket(struct rx_connection *conn,
141 struct rx_packet *np, int istack);
142 static struct rx_packet
143 *rxi_ReceiveChallengePacket(struct rx_connection *conn,
144 struct rx_packet *np, int istack);
145 static void rxi_AttachServerProc(struct rx_call *call, osi_socket socket,
146 int *tnop, struct rx_call **newcallp);
147 static void rxi_ClearTransmitQueue(struct rx_call *call, int force);
148 static void rxi_ClearReceiveQueue(struct rx_call *call);
149 static void rxi_ResetCall(struct rx_call *call, int newcall);
150 static void rxi_ScheduleKeepAliveEvent(struct rx_call *call);
151 static void rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn);
152 static void rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs);
153 static void rxi_KeepAliveOn(struct rx_call *call);
154 static void rxi_GrowMTUOn(struct rx_call *call);
155 static int rxi_ChallengeOn(struct rx_connection *conn);
156 static int rxi_CheckCall(struct rx_call *call, int haveCTLock);
157 static void rxi_AckAllInTransmitQueue(struct rx_call *call);
158 static void rxi_CancelKeepAliveEvent(struct rx_call *call);
159 static void rxi_CancelDelayedAbortEvent(struct rx_call *call);
160 static void rxi_CancelGrowMTUEvent(struct rx_call *call);
161 static void update_nextCid(void);
164 static void rxi_Finalize_locked(void);
165 #elif defined(UKERNEL)
166 # define rxi_Finalize_locked() do { } while (0)
169 #ifdef RX_ENABLE_LOCKS
171 rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
172 rx_atomic_t rxi_start_in_error;
174 #endif /* RX_ENABLE_LOCKS */
176 /* Constant delay time before sending an acknowledge of the last packet
177 * received. This is to avoid sending an extra acknowledge when the
178 * client is about to make another call, anyway, or the server is
181 * The lastAckDelay may not exceeed 400ms without causing peers to
182 * unecessarily timeout.
184 struct clock rx_lastAckDelay = {0, 400000};
186 /* Constant delay time before sending a soft ack when none was requested.
187 * This is to make sure we send soft acks before the sender times out,
188 * Normally we wait and send a hard ack when the receiver consumes the packet
190 * This value has been 100ms in all shipping versions of OpenAFS. Changing it
191 * will require changes to the peer's RTT calculations.
193 struct clock rx_softAckDelay = {0, 100000};
196 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
197 * currently allocated within rx. This number is used to allocate the
198 * memory required to return the statistics when queried.
199 * Protected by the rx_rpc_stats mutex.
202 static unsigned int rxi_rpc_peer_stat_cnt;
205 * rxi_rpc_process_stat_cnt counts the total number of local process stat
206 * structures currently allocated within rx. The number is used to allocate
207 * the memory required to return the statistics when queried.
208 * Protected by the rx_rpc_stats mutex.
211 static unsigned int rxi_rpc_process_stat_cnt;
213 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
214 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
216 /* Incoming calls wait on this queue when there are no available
217 * server processes */
218 struct opr_queue rx_incomingCallQueue;
220 /* Server processes wait on this queue when there are no appropriate
221 * calls to process */
222 struct opr_queue rx_idleServerQueue;
224 /* List of free rx_serverQueueEntry structs */
225 struct opr_queue rx_freeServerQueue;
227 #if !defined(offsetof)
228 #include <stddef.h> /* for definition of offsetof() */
231 #ifdef RX_ENABLE_LOCKS
232 afs_kmutex_t rx_atomic_mutex;
233 static afs_kmutex_t freeSQEList_lock;
236 /* Forward prototypes */
237 static struct rx_call * rxi_NewCall(struct rx_connection *, int);
240 putConnection (struct rx_connection *conn) {
241 MUTEX_ENTER(&rx_refcnt_mutex);
243 MUTEX_EXIT(&rx_refcnt_mutex);
246 #ifdef AFS_PTHREAD_ENV
249 * Use procedural initialization of mutexes/condition variables
253 extern afs_kmutex_t rx_quota_mutex;
254 extern afs_kmutex_t rx_pthread_mutex;
255 extern afs_kmutex_t rx_packets_mutex;
256 extern afs_kmutex_t rx_refcnt_mutex;
257 extern afs_kmutex_t des_init_mutex;
258 extern afs_kmutex_t des_random_mutex;
260 extern afs_kmutex_t rx_clock_mutex;
261 extern afs_kmutex_t rxi_connCacheMutex;
262 extern afs_kmutex_t event_handler_mutex;
263 extern afs_kmutex_t listener_mutex;
264 extern afs_kmutex_t rx_if_init_mutex;
265 extern afs_kmutex_t rx_if_mutex;
267 extern afs_kcondvar_t rx_event_handler_cond;
268 extern afs_kcondvar_t rx_listener_cond;
271 static afs_kmutex_t epoch_mutex;
272 static afs_kmutex_t rx_init_mutex;
273 static afs_kmutex_t rx_debug_mutex;
274 static afs_kmutex_t rx_rpc_stats;
277 rxi_InitPthread(void)
279 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
280 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
281 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
282 MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
284 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
285 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
286 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
287 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
288 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
289 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
291 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
292 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
293 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
294 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
295 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
298 CV_INIT(&rx_event_handler_cond, "evhand", CV_DEFAULT, 0);
299 CV_INIT(&rx_listener_cond, "rxlisten", CV_DEFAULT, 0);
302 osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
303 osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
305 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
306 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
307 MUTEX_INIT(&rx_mallocedPktQ_lock, "rx_mallocedPktQ_lock", MUTEX_DEFAULT,
310 #ifdef RX_ENABLE_LOCKS
313 #endif /* RX_LOCKS_DB */
314 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
315 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
317 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
319 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
321 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
323 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
325 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
327 #endif /* RX_ENABLE_LOCKS */
330 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
331 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
333 * The rx_stats_mutex mutex protects the following global variables:
334 * rxi_lowConnRefCount
335 * rxi_lowPeerRefCount
344 * The rx_quota_mutex mutex protects the following global variables:
352 * The rx_freePktQ_lock protects the following global variables:
357 * The rx_packets_mutex mutex protects the following global variables:
365 * The rx_pthread_mutex mutex protects the following global variables:
366 * rxi_fcfs_thread_num
369 #define INIT_PTHREAD_LOCKS
373 /* Variables for handling the minProcs implementation. availProcs gives the
374 * number of threads available in the pool at this moment (not counting dudes
375 * executing right now). totalMin gives the total number of procs required
376 * for handling all minProcs requests. minDeficit is a dynamic variable
377 * tracking the # of procs required to satisfy all of the remaining minProcs
379 * For fine grain locking to work, the quota check and the reservation of
380 * a server thread has to come while rxi_availProcs and rxi_minDeficit
381 * are locked. To this end, the code has been modified under #ifdef
382 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
383 * same time. A new function, ReturnToServerPool() returns the allocation.
385 * A call can be on several queue's (but only one at a time). When
386 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
387 * that no one else is touching the queue. To this end, we store the address
388 * of the queue lock in the call structure (under the call lock) when we
389 * put the call on a queue, and we clear the call_queue_lock when the
390 * call is removed from a queue (once the call lock has been obtained).
391 * This allows rxi_ResetCall to safely synchronize with others wishing
392 * to manipulate the queue.
395 #if defined(RX_ENABLE_LOCKS)
396 static afs_kmutex_t rx_rpc_stats;
399 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
400 ** pretty good that the next packet coming in is from the same connection
401 ** as the last packet, since we're send multiple packets in a transmit window.
403 struct rx_connection *rxLastConn = 0;
405 #ifdef RX_ENABLE_LOCKS
406 /* The locking hierarchy for rx fine grain locking is composed of these
409 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
410 * also protects updates to rx_nextCid
411 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
412 * call->lock - locks call data fields.
413 * These are independent of each other:
414 * rx_freeCallQueue_lock
419 * serverQueueEntry->lock
420 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
422 * peer->lock - locks peer data fields.
423 * conn_data_lock - that more than one thread is not updating a conn data
424 * field at the same time.
435 * Do we need a lock to protect the peer field in the conn structure?
436 * conn->peer was previously a constant for all intents and so has no
437 * lock protecting this field. The multihomed client delta introduced
438 * a RX code change : change the peer field in the connection structure
439 * to that remote interface from which the last packet for this
440 * connection was sent out. This may become an issue if further changes
443 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
444 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
446 /* rxdb_fileID is used to identify the lock location, along with line#. */
447 static int rxdb_fileID = RXDB_FILE_RX;
448 #endif /* RX_LOCKS_DB */
449 #else /* RX_ENABLE_LOCKS */
450 #define SET_CALL_QUEUE_LOCK(C, L)
451 #define CLEAR_CALL_QUEUE_LOCK(C)
452 #endif /* RX_ENABLE_LOCKS */
453 struct rx_serverQueueEntry *rx_waitForPacket = 0;
456 * This mutex serializes calls to our initialization and shutdown routines
457 * (rx_InitHost, rx_Finalize and shutdown_rx). Only one thread can be running
458 * these at any time; all other threads must wait for it to finish running, and
459 * then examine the value of rxi_running afterwards.
461 #ifdef AFS_PTHREAD_ENV
462 # define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
463 # define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
465 # define LOCK_RX_INIT
466 # define UNLOCK_RX_INIT
469 /* ------------Exported Interfaces------------- */
471 static rx_atomic_t rxi_running = RX_ATOMIC_INIT(0);
475 return rx_atomic_read(&rxi_running);
478 /* Initialize rx. A port number may be mentioned, in which case this
479 * becomes the default port number for any service installed later.
480 * If 0 is provided for the port number, a random port will be chosen
481 * by the kernel. Whether this will ever overlap anything in
482 * /etc/services is anybody's guess... Returns 0 on success, -1 on
485 rx_InitHost(u_int host, u_int port)
492 char *htable, *ptable;
498 if (rxi_IsRunning()) {
500 return 0; /* already started */
506 if (afs_winsockInit() < 0)
512 * Initialize anything necessary to provide a non-premptive threading
515 rxi_InitializeThreadSupport();
518 /* Allocate and initialize a socket for client and perhaps server
521 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
522 if (rx_socket == OSI_NULLSOCKET) {
525 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
528 #endif /* RX_LOCKS_DB */
529 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
530 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
531 MUTEX_INIT(&rx_atomic_mutex, "rx_atomic_mutex", MUTEX_DEFAULT, 0);
532 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
533 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
534 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
535 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
536 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
537 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
538 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
540 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
542 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
544 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
546 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
547 MUTEX_INIT(&rx_mallocedPktQ_lock, "rx_mallocedPktQ_lock", MUTEX_DEFAULT,
550 #if defined(AFS_HPUX110_ENV)
552 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
553 #endif /* AFS_HPUX110_ENV */
554 #endif /* RX_ENABLE_LOCKS && KERNEL */
557 rx_connDeadTime = 12;
558 rx_tranquil = 0; /* reset flag */
559 rxi_ResetStatistics();
560 htable = osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
561 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
562 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
563 ptable = osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
564 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
565 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
567 /* Malloc up a bunch of packets & buffers */
569 opr_queue_Init(&rx_freePacketQueue);
570 rxi_NeedMorePackets = FALSE;
571 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
572 opr_queue_Init(&rx_mallocedPacketQueue);
574 /* enforce a minimum number of allocated packets */
575 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
576 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
578 /* allocate the initial free packet pool */
579 #ifdef RX_ENABLE_TSFPQ
580 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
581 #else /* RX_ENABLE_TSFPQ */
582 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
583 #endif /* RX_ENABLE_TSFPQ */
590 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
591 tv.tv_sec = clock_now.sec;
592 tv.tv_usec = clock_now.usec;
593 srand((unsigned int)tv.tv_usec);
600 #if defined(KERNEL) && !defined(UKERNEL)
601 /* Really, this should never happen in a real kernel */
604 struct sockaddr_in addr;
606 int addrlen = sizeof(addr);
608 socklen_t addrlen = sizeof(addr);
610 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
611 rxi_Finalize_locked();
612 osi_Free(htable, rx_hashTableSize * sizeof(struct rx_connection *));
615 rx_port = addr.sin_port;
618 rx_stats.minRtt.sec = 9999999;
619 if (RAND_bytes(&rx_epoch, sizeof(rx_epoch)) != 1)
621 rx_epoch = (rx_epoch & ~0x40000000) | 0x80000000;
622 if (RAND_bytes(&rx_nextCid, sizeof(rx_nextCid)) != 1)
624 rx_nextCid &= RX_CIDMASK;
625 MUTEX_ENTER(&rx_quota_mutex);
626 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
627 MUTEX_EXIT(&rx_quota_mutex);
628 /* *Slightly* random start time for the cid. This is just to help
629 * out with the hashing function at the peer */
630 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
631 rx_connHashTable = (struct rx_connection **)htable;
632 rx_peerHashTable = (struct rx_peer **)ptable;
634 rx_hardAckDelay.sec = 0;
635 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
637 rxevent_Init(20, rxi_ReScheduleEvents);
639 /* Initialize various global queues */
640 opr_queue_Init(&rx_idleServerQueue);
641 opr_queue_Init(&rx_freeServerQueue);
642 opr_queue_Init(&rx_incomingCallQueue);
643 opr_queue_Init(&rx_freeCallQueue);
645 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
646 /* Initialize our list of usable IP addresses. */
650 /* Start listener process (exact function is dependent on the
651 * implementation environment--kernel or user space) */
656 rx_atomic_set(&rxi_running, 1);
673 return rx_InitHost(htonl(INADDR_ANY), port);
679 * The rxi_rto functions implement a TCP (RFC2988) style algorithm for
680 * maintaing the round trip timer.
685 * Start a new RTT timer for a given call and packet.
687 * There must be no resendEvent already listed for this call, otherwise this
688 * will leak events - intended for internal use within the RTO code only
691 * the RX call to start the timer for
692 * @param[in] lastPacket
693 * a flag indicating whether the last packet has been sent or not
695 * @pre call must be locked before calling this function
699 rxi_rto_startTimer(struct rx_call *call, int lastPacket, int istack)
701 struct clock now, retryTime;
703 MUTEX_ASSERT(&call->lock);
707 clock_Add(&retryTime, &call->rto);
709 /* If we're sending the last packet, and we're the client, then the server
710 * may wait for an additional 400ms before returning the ACK, wait for it
711 * rather than hitting a timeout */
712 if (lastPacket && call->conn->type == RX_CLIENT_CONNECTION)
713 clock_Addmsec(&retryTime, 400);
715 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
716 call->resendEvent = rxevent_Post(&retryTime, &now, rxi_Resend,
721 * Cancel an RTT timer for a given call.
725 * the RX call to cancel the timer for
727 * @pre call must be locked before calling this function
732 rxi_rto_cancel(struct rx_call *call)
734 MUTEX_ASSERT(&call->lock);
735 if (rxevent_Cancel(&call->resendEvent))
736 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
740 * Tell the RTO timer that we have sent a packet.
742 * If the timer isn't already running, then start it. If the timer is running,
746 * the RX call that the packet has been sent on
747 * @param[in] lastPacket
748 * A flag which is true if this is the last packet for the call
750 * @pre The call must be locked before calling this function
755 rxi_rto_packet_sent(struct rx_call *call, int lastPacket, int istack)
757 if (call->resendEvent)
760 rxi_rto_startTimer(call, lastPacket, istack);
764 * Tell the RTO timer that we have received an new ACK message
766 * This function should be called whenever a call receives an ACK that
767 * acknowledges new packets. Whatever happens, we stop the current timer.
768 * If there are unacked packets in the queue which have been sent, then
769 * we restart the timer from now. Otherwise, we leave it stopped.
772 * the RX call that the ACK has been received on
776 rxi_rto_packet_acked(struct rx_call *call, int istack)
778 struct opr_queue *cursor;
780 rxi_rto_cancel(call);
782 if (opr_queue_IsEmpty(&call->tq))
785 for (opr_queue_Scan(&call->tq, cursor)) {
786 struct rx_packet *p = opr_queue_Entry(cursor, struct rx_packet, entry);
787 if (p->header.seq > call->tfirst + call->twind)
790 if (!(p->flags & RX_PKTFLAG_ACKED) && p->flags & RX_PKTFLAG_SENT) {
791 rxi_rto_startTimer(call, p->header.flags & RX_LAST_PACKET, istack);
799 * Set an initial round trip timeout for a peer connection
801 * @param[in] secs The timeout to set in seconds
805 rx_rto_setPeerTimeoutSecs(struct rx_peer *peer, int secs) {
806 peer->rtt = secs * 8000;
810 * Set a delayed ack event on the specified call for the given time
812 * @param[in] call - the call on which to set the event
813 * @param[in] offset - the delay from now after which the event fires
816 rxi_PostDelayedAckEvent(struct rx_call *call, struct clock *offset)
818 struct clock now, when;
820 MUTEX_ASSERT(&call->lock);
823 clock_Add(&when, offset);
825 if (clock_Gt(&call->delayedAckTime, &when) &&
826 rxevent_Cancel(&call->delayedAckEvent)) {
827 /* We successfully cancelled an event too far in the future to install
828 * our new one; we can reuse the reference on the call. */
829 call->delayedAckEvent = rxevent_Post(&when, &now, rxi_SendDelayedAck,
832 call->delayedAckTime = when;
833 } else if (call->delayedAckEvent == NULL) {
834 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
835 call->delayedAckEvent = rxevent_Post(&when, &now,
838 call->delayedAckTime = when;
843 rxi_CancelDelayedAckEvent(struct rx_call *call)
845 MUTEX_ASSERT(&call->lock);
846 /* Only drop the ref if we cancelled it before it could run. */
847 if (rxevent_Cancel(&call->delayedAckEvent))
848 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
851 /* called with unincremented nRequestsRunning to see if it is OK to start
852 * a new thread in this service. Could be "no" for two reasons: over the
853 * max quota, or would prevent others from reaching their min quota.
855 #ifdef RX_ENABLE_LOCKS
856 /* This verion of QuotaOK reserves quota if it's ok while the
857 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
860 QuotaOK(struct rx_service *aservice)
862 /* check if over max quota */
863 if (aservice->nRequestsRunning >= aservice->maxProcs) {
867 /* under min quota, we're OK */
868 /* otherwise, can use only if there are enough to allow everyone
869 * to go to their min quota after this guy starts.
872 MUTEX_ENTER(&rx_quota_mutex);
873 if ((aservice->nRequestsRunning < aservice->minProcs)
874 || (rxi_availProcs > rxi_minDeficit)) {
875 aservice->nRequestsRunning++;
876 /* just started call in minProcs pool, need fewer to maintain
878 if (aservice->nRequestsRunning <= aservice->minProcs)
881 MUTEX_EXIT(&rx_quota_mutex);
884 MUTEX_EXIT(&rx_quota_mutex);
890 ReturnToServerPool(struct rx_service *aservice)
892 aservice->nRequestsRunning--;
893 MUTEX_ENTER(&rx_quota_mutex);
894 if (aservice->nRequestsRunning < aservice->minProcs)
897 MUTEX_EXIT(&rx_quota_mutex);
900 #else /* RX_ENABLE_LOCKS */
902 QuotaOK(struct rx_service *aservice)
905 /* under min quota, we're OK */
906 if (aservice->nRequestsRunning < aservice->minProcs)
909 /* check if over max quota */
910 if (aservice->nRequestsRunning >= aservice->maxProcs)
913 /* otherwise, can use only if there are enough to allow everyone
914 * to go to their min quota after this guy starts.
916 MUTEX_ENTER(&rx_quota_mutex);
917 if (rxi_availProcs > rxi_minDeficit)
919 MUTEX_EXIT(&rx_quota_mutex);
922 #endif /* RX_ENABLE_LOCKS */
925 /* Called by rx_StartServer to start up lwp's to service calls.
926 NExistingProcs gives the number of procs already existing, and which
927 therefore needn't be created. */
929 rxi_StartServerProcs(int nExistingProcs)
931 struct rx_service *service;
936 /* For each service, reserve N processes, where N is the "minimum"
937 * number of processes that MUST be able to execute a request in parallel,
938 * at any time, for that process. Also compute the maximum difference
939 * between any service's maximum number of processes that can run
940 * (i.e. the maximum number that ever will be run, and a guarantee
941 * that this number will run if other services aren't running), and its
942 * minimum number. The result is the extra number of processes that
943 * we need in order to provide the latter guarantee */
944 for (i = 0; i < RX_MAX_SERVICES; i++) {
946 service = rx_services[i];
947 if (service == (struct rx_service *)0)
949 nProcs += service->minProcs;
950 diff = service->maxProcs - service->minProcs;
954 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
955 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
956 for (i = 0; i < nProcs; i++) {
957 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
963 /* This routine is only required on Windows */
965 rx_StartClientThread(void)
967 #ifdef AFS_PTHREAD_ENV
969 pid = pthread_self();
970 #endif /* AFS_PTHREAD_ENV */
972 #endif /* AFS_NT40_ENV */
974 /* This routine must be called if any services are exported. If the
975 * donateMe flag is set, the calling process is donated to the server
978 rx_StartServer(int donateMe)
980 struct rx_service *service;
986 /* Start server processes, if necessary (exact function is dependent
987 * on the implementation environment--kernel or user space). DonateMe
988 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
989 * case, one less new proc will be created rx_StartServerProcs.
991 rxi_StartServerProcs(donateMe);
993 /* count up the # of threads in minProcs, and add set the min deficit to
994 * be that value, too.
996 for (i = 0; i < RX_MAX_SERVICES; i++) {
997 service = rx_services[i];
998 if (service == (struct rx_service *)0)
1000 MUTEX_ENTER(&rx_quota_mutex);
1001 rxi_totalMin += service->minProcs;
1002 /* below works even if a thread is running, since minDeficit would
1003 * still have been decremented and later re-incremented.
1005 rxi_minDeficit += service->minProcs;
1006 MUTEX_EXIT(&rx_quota_mutex);
1009 /* Turn on reaping of idle server connections */
1010 rxi_ReapConnections(NULL, NULL, NULL, 0);
1015 #ifndef AFS_NT40_ENV
1019 #ifdef AFS_PTHREAD_ENV
1021 pid = afs_pointer_to_int(pthread_self());
1022 #else /* AFS_PTHREAD_ENV */
1024 LWP_CurrentProcess(&pid);
1025 #endif /* AFS_PTHREAD_ENV */
1027 sprintf(name, "srv_%d", ++nProcs);
1028 if (registerProgram)
1029 (*registerProgram) (pid, name);
1031 #endif /* AFS_NT40_ENV */
1032 rx_ServerProc(NULL); /* Never returns */
1034 #ifdef RX_ENABLE_TSFPQ
1035 /* no use leaving packets around in this thread's local queue if
1036 * it isn't getting donated to the server thread pool.
1038 rxi_FlushLocalPacketsTSFPQ();
1039 #endif /* RX_ENABLE_TSFPQ */
1043 /* Create a new client connection to the specified service, using the
1044 * specified security object to implement the security model for this
1046 struct rx_connection *
1047 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
1048 struct rx_securityClass *securityObject,
1049 int serviceSecurityIndex)
1052 struct rx_connection *conn;
1058 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
1059 "serviceSecurityIndex %d)\n",
1060 ntohl(shost), ntohs(sport), sservice, securityObject,
1061 serviceSecurityIndex));
1063 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
1064 * the case of kmem_alloc? */
1065 conn = rxi_AllocConnection();
1066 #ifdef RX_ENABLE_LOCKS
1067 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
1068 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
1069 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
1072 MUTEX_ENTER(&rx_connHashTable_lock);
1073 conn->type = RX_CLIENT_CONNECTION;
1074 conn->epoch = rx_epoch;
1075 conn->cid = rx_nextCid;
1077 conn->peer = rxi_FindPeer(shost, sport, 1);
1078 conn->serviceId = sservice;
1079 conn->securityObject = securityObject;
1080 conn->securityData = (void *) 0;
1081 conn->securityIndex = serviceSecurityIndex;
1082 rx_SetConnDeadTime(conn, rx_connDeadTime);
1083 rx_SetConnSecondsUntilNatPing(conn, 0);
1084 conn->ackRate = RX_FAST_ACK_RATE;
1085 conn->nSpecific = 0;
1086 conn->specific = NULL;
1087 conn->challengeEvent = NULL;
1088 conn->delayedAbortEvent = NULL;
1089 conn->abortCount = 0;
1091 for (i = 0; i < RX_MAXCALLS; i++) {
1092 conn->twind[i] = rx_initSendWindow;
1093 conn->rwind[i] = rx_initReceiveWindow;
1094 conn->lastBusy[i] = 0;
1097 code = RXS_NewConnection(securityObject, conn);
1099 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
1101 conn->refCount++; /* no lock required since only this thread knows... */
1102 conn->next = rx_connHashTable[hashindex];
1103 rx_connHashTable[hashindex] = conn;
1104 if (rx_stats_active)
1105 rx_atomic_inc(&rx_stats.nClientConns);
1106 MUTEX_EXIT(&rx_connHashTable_lock);
1109 rxi_ConnectionError(conn, code);
1115 * Ensure a connection's timeout values are valid.
1117 * @param[in] conn The connection to check
1119 * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
1120 * unless idleDeadTime and/or hardDeadTime are not set
1124 rxi_CheckConnTimeouts(struct rx_connection *conn)
1126 /* a connection's timeouts must have the relationship
1127 * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
1128 * total loss of network to a peer may cause an idle timeout instead of a
1129 * dead timeout, simply because the idle timeout gets hit first. Also set
1130 * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
1131 /* this logic is slightly complicated by the fact that
1132 * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
1134 conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
1135 if (conn->idleDeadTime) {
1136 conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
1138 if (conn->hardDeadTime) {
1139 if (conn->idleDeadTime) {
1140 conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
1142 conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
1148 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
1150 /* The idea is to set the dead time to a value that allows several
1151 * keepalives to be dropped without timing out the connection. */
1152 conn->secondsUntilDead = seconds;
1153 rxi_CheckConnTimeouts(conn);
1154 conn->secondsUntilPing = conn->secondsUntilDead / 6;
1158 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
1160 conn->hardDeadTime = seconds;
1161 rxi_CheckConnTimeouts(conn);
1165 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
1167 conn->idleDeadTime = seconds;
1168 rxi_CheckConnTimeouts(conn);
1171 int rxi_lowPeerRefCount = 0;
1172 int rxi_lowConnRefCount = 0;
1175 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
1176 * NOTE: must not be called with rx_connHashTable_lock held.
1179 rxi_CleanupConnection(struct rx_connection *conn)
1181 /* Notify the service exporter, if requested, that this connection
1182 * is being destroyed */
1183 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
1184 (*conn->service->destroyConnProc) (conn);
1186 /* Notify the security module that this connection is being destroyed */
1187 RXS_DestroyConnection(conn->securityObject, conn);
1189 /* If this is the last connection using the rx_peer struct, set its
1190 * idle time to now. rxi_ReapConnections will reap it if it's still
1191 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
1193 MUTEX_ENTER(&rx_peerHashTable_lock);
1194 if (conn->peer->refCount < 2) {
1195 conn->peer->idleWhen = clock_Sec();
1196 if (conn->peer->refCount < 1) {
1197 conn->peer->refCount = 1;
1198 if (rx_stats_active) {
1199 MUTEX_ENTER(&rx_stats_mutex);
1200 rxi_lowPeerRefCount++;
1201 MUTEX_EXIT(&rx_stats_mutex);
1205 conn->peer->refCount--;
1206 MUTEX_EXIT(&rx_peerHashTable_lock);
1208 if (rx_stats_active)
1210 if (conn->type == RX_SERVER_CONNECTION)
1211 rx_atomic_dec(&rx_stats.nServerConns);
1213 rx_atomic_dec(&rx_stats.nClientConns);
1216 if (conn->specific) {
1218 for (i = 0; i < conn->nSpecific; i++) {
1219 if (conn->specific[i] && rxi_keyCreate_destructor[i])
1220 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
1221 conn->specific[i] = NULL;
1223 free(conn->specific);
1225 conn->specific = NULL;
1226 conn->nSpecific = 0;
1227 #endif /* !KERNEL */
1229 MUTEX_DESTROY(&conn->conn_call_lock);
1230 MUTEX_DESTROY(&conn->conn_data_lock);
1231 CV_DESTROY(&conn->conn_call_cv);
1233 rxi_FreeConnection(conn);
1236 /* Destroy the specified connection */
1238 rxi_DestroyConnection(struct rx_connection *conn)
1240 MUTEX_ENTER(&rx_connHashTable_lock);
1241 rxi_DestroyConnectionNoLock(conn);
1242 /* conn should be at the head of the cleanup list */
1243 if (conn == rx_connCleanup_list) {
1244 rx_connCleanup_list = rx_connCleanup_list->next;
1245 MUTEX_EXIT(&rx_connHashTable_lock);
1246 rxi_CleanupConnection(conn);
1248 #ifdef RX_ENABLE_LOCKS
1250 MUTEX_EXIT(&rx_connHashTable_lock);
1252 #endif /* RX_ENABLE_LOCKS */
1256 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1258 struct rx_connection **conn_ptr;
1266 MUTEX_ENTER(&conn->conn_data_lock);
1267 MUTEX_ENTER(&rx_refcnt_mutex);
1268 if (conn->refCount > 0)
1271 #ifdef RX_REFCOUNT_CHECK
1272 osi_Assert(conn->refCount == 0);
1274 if (rx_stats_active) {
1275 MUTEX_ENTER(&rx_stats_mutex);
1276 rxi_lowConnRefCount++;
1277 MUTEX_EXIT(&rx_stats_mutex);
1281 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1282 /* Busy; wait till the last guy before proceeding */
1283 MUTEX_EXIT(&rx_refcnt_mutex);
1284 MUTEX_EXIT(&conn->conn_data_lock);
1289 /* If the client previously called rx_NewCall, but it is still
1290 * waiting, treat this as a running call, and wait to destroy the
1291 * connection later when the call completes. */
1292 if ((conn->type == RX_CLIENT_CONNECTION)
1293 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1294 conn->flags |= RX_CONN_DESTROY_ME;
1295 MUTEX_EXIT(&rx_refcnt_mutex);
1296 MUTEX_EXIT(&conn->conn_data_lock);
1300 MUTEX_EXIT(&rx_refcnt_mutex);
1301 MUTEX_EXIT(&conn->conn_data_lock);
1303 /* Check for extant references to this connection */
1304 MUTEX_ENTER(&conn->conn_call_lock);
1305 for (i = 0; i < RX_MAXCALLS; i++) {
1306 struct rx_call *call = conn->call[i];
1309 if (conn->type == RX_CLIENT_CONNECTION) {
1310 MUTEX_ENTER(&call->lock);
1311 if (call->delayedAckEvent) {
1312 /* Push the final acknowledgment out now--there
1313 * won't be a subsequent call to acknowledge the
1314 * last reply packets */
1315 rxi_CancelDelayedAckEvent(call);
1316 if (call->state == RX_STATE_PRECALL
1317 || call->state == RX_STATE_ACTIVE) {
1318 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1323 MUTEX_EXIT(&call->lock);
1327 MUTEX_EXIT(&conn->conn_call_lock);
1329 #ifdef RX_ENABLE_LOCKS
1331 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1332 MUTEX_EXIT(&conn->conn_data_lock);
1334 /* Someone is accessing a packet right now. */
1338 #endif /* RX_ENABLE_LOCKS */
1341 /* Don't destroy the connection if there are any call
1342 * structures still in use */
1343 MUTEX_ENTER(&conn->conn_data_lock);
1344 conn->flags |= RX_CONN_DESTROY_ME;
1345 MUTEX_EXIT(&conn->conn_data_lock);
1350 /* Remove from connection hash table before proceeding */
1352 &rx_connHashTable[CONN_HASH
1353 (peer->host, peer->port, conn->cid, conn->epoch,
1355 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1356 if (*conn_ptr == conn) {
1357 *conn_ptr = conn->next;
1361 /* if the conn that we are destroying was the last connection, then we
1362 * clear rxLastConn as well */
1363 if (rxLastConn == conn)
1366 /* Make sure the connection is completely reset before deleting it. */
1368 * Pending events hold a refcount, so we can't get here if they are
1370 osi_Assert(conn->challengeEvent == NULL);
1371 osi_Assert(conn->delayedAbortEvent == NULL);
1372 osi_Assert(conn->natKeepAliveEvent == NULL);
1373 osi_Assert(conn->checkReachEvent == NULL);
1375 /* Add the connection to the list of destroyed connections that
1376 * need to be cleaned up. This is necessary to avoid deadlocks
1377 * in the routines we call to inform others that this connection is
1378 * being destroyed. */
1379 conn->next = rx_connCleanup_list;
1380 rx_connCleanup_list = conn;
1383 /* Externally available version */
1385 rx_DestroyConnection(struct rx_connection *conn)
1390 rxi_DestroyConnection(conn);
1395 rx_GetConnection(struct rx_connection *conn)
1400 MUTEX_ENTER(&rx_refcnt_mutex);
1402 MUTEX_EXIT(&rx_refcnt_mutex);
1406 #ifdef RX_ENABLE_LOCKS
1407 /* Wait for the transmit queue to no longer be busy.
1408 * requires the call->lock to be held */
1410 rxi_WaitforTQBusy(struct rx_call *call) {
1411 while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1412 call->flags |= RX_CALL_TQ_WAIT;
1414 MUTEX_ASSERT(&call->lock);
1415 CV_WAIT(&call->cv_tq, &call->lock);
1417 if (call->tqWaiters == 0) {
1418 call->flags &= ~RX_CALL_TQ_WAIT;
1425 rxi_WakeUpTransmitQueue(struct rx_call *call)
1427 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1428 dpf(("call %p has %d waiters and flags %d\n",
1429 call, call->tqWaiters, call->flags));
1430 #ifdef RX_ENABLE_LOCKS
1431 MUTEX_ASSERT(&call->lock);
1432 CV_BROADCAST(&call->cv_tq);
1433 #else /* RX_ENABLE_LOCKS */
1434 osi_rxWakeup(&call->tq);
1435 #endif /* RX_ENABLE_LOCKS */
1439 /* Start a new rx remote procedure call, on the specified connection.
1440 * If wait is set to 1, wait for a free call channel; otherwise return
1441 * 0. Maxtime gives the maximum number of seconds this call may take,
1442 * after rx_NewCall returns. After this time interval, a call to any
1443 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1444 * For fine grain locking, we hold the conn_call_lock in order to
1445 * to ensure that we don't get signalle after we found a call in an active
1446 * state and before we go to sleep.
1449 rx_NewCall(struct rx_connection *conn)
1451 int i, wait, ignoreBusy = 1;
1452 struct rx_call *call;
1453 struct clock queueTime;
1454 afs_uint32 leastBusy = 0;
1458 dpf(("rx_NewCall(conn %p)\n", conn));
1461 clock_GetTime(&queueTime);
1463 * Check if there are others waiting for a new call.
1464 * If so, let them go first to avoid starving them.
1465 * This is a fairly simple scheme, and might not be
1466 * a complete solution for large numbers of waiters.
1468 * makeCallWaiters keeps track of the number of
1469 * threads waiting to make calls and the
1470 * RX_CONN_MAKECALL_WAITING flag bit is used to
1471 * indicate that there are indeed calls waiting.
1472 * The flag is set when the waiter is incremented.
1473 * It is only cleared when makeCallWaiters is 0.
1474 * This prevents us from accidently destroying the
1475 * connection while it is potentially about to be used.
1477 MUTEX_ENTER(&conn->conn_call_lock);
1478 MUTEX_ENTER(&conn->conn_data_lock);
1479 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1480 conn->flags |= RX_CONN_MAKECALL_WAITING;
1481 conn->makeCallWaiters++;
1482 MUTEX_EXIT(&conn->conn_data_lock);
1484 #ifdef RX_ENABLE_LOCKS
1485 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1489 MUTEX_ENTER(&conn->conn_data_lock);
1490 conn->makeCallWaiters--;
1491 if (conn->makeCallWaiters == 0)
1492 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1495 /* We are now the active thread in rx_NewCall */
1496 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1497 MUTEX_EXIT(&conn->conn_data_lock);
1502 for (i = 0; i < RX_MAXCALLS; i++) {
1503 call = conn->call[i];
1505 if (!ignoreBusy && conn->lastBusy[i] != leastBusy) {
1506 /* we're not ignoring busy call slots; only look at the
1507 * call slot that is the "least" busy */
1511 if (call->state == RX_STATE_DALLY) {
1512 MUTEX_ENTER(&call->lock);
1513 if (call->state == RX_STATE_DALLY) {
1514 if (ignoreBusy && conn->lastBusy[i]) {
1515 /* if we're ignoring busy call slots, skip any ones that
1516 * have lastBusy set */
1517 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1518 leastBusy = conn->lastBusy[i];
1520 MUTEX_EXIT(&call->lock);
1525 * We are setting the state to RX_STATE_RESET to
1526 * ensure that no one else will attempt to use this
1527 * call once we drop the conn->conn_call_lock and
1528 * call->lock. We must drop the conn->conn_call_lock
1529 * before calling rxi_ResetCall because the process
1530 * of clearing the transmit queue can block for an
1531 * extended period of time. If we block while holding
1532 * the conn->conn_call_lock, then all rx_EndCall
1533 * processing will block as well. This has a detrimental
1534 * effect on overall system performance.
1536 call->state = RX_STATE_RESET;
1537 (*call->callNumber)++;
1538 MUTEX_EXIT(&conn->conn_call_lock);
1539 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1540 rxi_ResetCall(call, 0);
1541 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1545 * If we failed to be able to safely obtain the
1546 * conn->conn_call_lock we will have to drop the
1547 * call->lock to avoid a deadlock. When the call->lock
1548 * is released the state of the call can change. If it
1549 * is no longer RX_STATE_RESET then some other thread is
1552 MUTEX_EXIT(&call->lock);
1553 MUTEX_ENTER(&conn->conn_call_lock);
1554 MUTEX_ENTER(&call->lock);
1556 if (call->state == RX_STATE_RESET)
1560 * If we get here it means that after dropping
1561 * the conn->conn_call_lock and call->lock that
1562 * the call is no longer ours. If we can't find
1563 * a free call in the remaining slots we should
1564 * not go immediately to RX_CONN_MAKECALL_WAITING
1565 * because by dropping the conn->conn_call_lock
1566 * we have given up synchronization with rx_EndCall.
1567 * Instead, cycle through one more time to see if
1568 * we can find a call that can call our own.
1570 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1573 MUTEX_EXIT(&call->lock);
1576 if (ignoreBusy && conn->lastBusy[i]) {
1577 /* if we're ignoring busy call slots, skip any ones that
1578 * have lastBusy set */
1579 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1580 leastBusy = conn->lastBusy[i];
1585 /* rxi_NewCall returns with mutex locked */
1586 call = rxi_NewCall(conn, i);
1587 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1591 if (i < RX_MAXCALLS) {
1592 conn->lastBusy[i] = 0;
1597 if (leastBusy && ignoreBusy) {
1598 /* we didn't find a useable call slot, but we did see at least one
1599 * 'busy' slot; look again and only use a slot with the 'least
1605 MUTEX_ENTER(&conn->conn_data_lock);
1606 conn->flags |= RX_CONN_MAKECALL_WAITING;
1607 conn->makeCallWaiters++;
1608 MUTEX_EXIT(&conn->conn_data_lock);
1610 #ifdef RX_ENABLE_LOCKS
1611 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1615 MUTEX_ENTER(&conn->conn_data_lock);
1616 conn->makeCallWaiters--;
1617 if (conn->makeCallWaiters == 0)
1618 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1619 MUTEX_EXIT(&conn->conn_data_lock);
1621 /* Client is initially in send mode */
1622 call->state = RX_STATE_ACTIVE;
1623 call->error = conn->error;
1625 call->app.mode = RX_MODE_ERROR;
1627 call->app.mode = RX_MODE_SENDING;
1629 #ifdef AFS_RXERRQ_ENV
1630 /* remember how many network errors the peer has when we started, so if
1631 * more errors are encountered after the call starts, we know the other endpoint won't be
1632 * responding to us */
1633 call->neterr_gen = rx_atomic_read(&conn->peer->neterrs);
1636 /* remember start time for call in case we have hard dead time limit */
1637 call->queueTime = queueTime;
1638 clock_GetTime(&call->startTime);
1639 call->app.bytesSent = 0;
1640 call->app.bytesRcvd = 0;
1642 /* Turn on busy protocol. */
1643 rxi_KeepAliveOn(call);
1645 /* Attempt MTU discovery */
1646 rxi_GrowMTUOn(call);
1649 * We are no longer the active thread in rx_NewCall
1651 MUTEX_ENTER(&conn->conn_data_lock);
1652 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1653 MUTEX_EXIT(&conn->conn_data_lock);
1656 * Wake up anyone else who might be giving us a chance to
1657 * run (see code above that avoids resource starvation).
1659 #ifdef RX_ENABLE_LOCKS
1660 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1661 osi_Panic("rx_NewCall call about to be used without an empty tq");
1664 CV_BROADCAST(&conn->conn_call_cv);
1668 MUTEX_EXIT(&conn->conn_call_lock);
1669 MUTEX_EXIT(&call->lock);
1672 dpf(("rx_NewCall(call %p)\n", call));
1677 rxi_HasActiveCalls(struct rx_connection *aconn)
1680 struct rx_call *tcall;
1684 for (i = 0; i < RX_MAXCALLS; i++) {
1685 if ((tcall = aconn->call[i])) {
1686 if ((tcall->state == RX_STATE_ACTIVE)
1687 || (tcall->state == RX_STATE_PRECALL)) {
1698 rxi_GetCallNumberVector(struct rx_connection *aconn,
1699 afs_int32 * aint32s)
1702 struct rx_call *tcall;
1706 MUTEX_ENTER(&aconn->conn_call_lock);
1707 for (i = 0; i < RX_MAXCALLS; i++) {
1708 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1709 aint32s[i] = aconn->callNumber[i] + 1;
1711 aint32s[i] = aconn->callNumber[i];
1713 MUTEX_EXIT(&aconn->conn_call_lock);
1719 rxi_SetCallNumberVector(struct rx_connection *aconn,
1720 afs_int32 * aint32s)
1723 struct rx_call *tcall;
1727 MUTEX_ENTER(&aconn->conn_call_lock);
1728 for (i = 0; i < RX_MAXCALLS; i++) {
1729 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1730 aconn->callNumber[i] = aint32s[i] - 1;
1732 aconn->callNumber[i] = aint32s[i];
1734 MUTEX_EXIT(&aconn->conn_call_lock);
1739 /* Advertise a new service. A service is named locally by a UDP port
1740 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1743 char *serviceName; Name for identification purposes (e.g. the
1744 service name might be used for probing for
1747 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1748 char *serviceName, struct rx_securityClass **securityObjects,
1749 int nSecurityObjects,
1750 afs_int32(*serviceProc) (struct rx_call * acall))
1752 osi_socket socket = OSI_NULLSOCKET;
1753 struct rx_service *tservice;
1759 if (serviceId == 0) {
1761 "rx_NewService: service id for service %s is not non-zero.\n",
1768 "rx_NewService: A non-zero port must be specified on this call if a non-zero port was not provided at Rx initialization (service %s).\n",
1776 tservice = rxi_AllocService();
1779 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1781 for (i = 0; i < RX_MAX_SERVICES; i++) {
1782 struct rx_service *service = rx_services[i];
1784 if (port == service->servicePort && host == service->serviceHost) {
1785 if (service->serviceId == serviceId) {
1786 /* The identical service has already been
1787 * installed; if the caller was intending to
1788 * change the security classes used by this
1789 * service, he/she loses. */
1791 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1792 serviceName, serviceId, service->serviceName);
1794 rxi_FreeService(tservice);
1797 /* Different service, same port: re-use the socket
1798 * which is bound to the same port */
1799 socket = service->socket;
1802 if (socket == OSI_NULLSOCKET) {
1803 /* If we don't already have a socket (from another
1804 * service on same port) get a new one */
1805 socket = rxi_GetHostUDPSocket(host, port);
1806 if (socket == OSI_NULLSOCKET) {
1808 rxi_FreeService(tservice);
1813 service->socket = socket;
1814 service->serviceHost = host;
1815 service->servicePort = port;
1816 service->serviceId = serviceId;
1817 service->serviceName = serviceName;
1818 service->nSecurityObjects = nSecurityObjects;
1819 service->securityObjects = securityObjects;
1820 service->minProcs = 0;
1821 service->maxProcs = 1;
1822 service->idleDeadTime = 60;
1823 service->connDeadTime = rx_connDeadTime;
1824 service->executeRequestProc = serviceProc;
1825 service->checkReach = 0;
1826 service->nSpecific = 0;
1827 service->specific = NULL;
1828 rx_services[i] = service; /* not visible until now */
1834 rxi_FreeService(tservice);
1835 (osi_Msg "rx_NewService: cannot support > %d services\n",
1840 /* Set configuration options for all of a service's security objects */
1843 rx_SetSecurityConfiguration(struct rx_service *service,
1844 rx_securityConfigVariables type,
1849 for (i = 0; i<service->nSecurityObjects; i++) {
1850 if (service->securityObjects[i]) {
1851 code = RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1862 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1863 struct rx_securityClass **securityObjects, int nSecurityObjects,
1864 afs_int32(*serviceProc) (struct rx_call * acall))
1866 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1869 /* Generic request processing loop. This routine should be called
1870 * by the implementation dependent rx_ServerProc. If socketp is
1871 * non-null, it will be set to the file descriptor that this thread
1872 * is now listening on. If socketp is null, this routine will never
1875 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1877 struct rx_call *call;
1879 struct rx_service *tservice = NULL;
1886 call = rx_GetCall(threadID, tservice, socketp);
1887 if (socketp && *socketp != OSI_NULLSOCKET) {
1888 /* We are now a listener thread */
1894 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1895 #ifdef RX_ENABLE_LOCKS
1897 #endif /* RX_ENABLE_LOCKS */
1898 afs_termState = AFSOP_STOP_AFS;
1899 afs_osi_Wakeup(&afs_termState);
1900 #ifdef RX_ENABLE_LOCKS
1902 #endif /* RX_ENABLE_LOCKS */
1907 /* if server is restarting( typically smooth shutdown) then do not
1908 * allow any new calls.
1911 if (rx_tranquil && (call != NULL)) {
1915 MUTEX_ENTER(&call->lock);
1917 rxi_CallError(call, RX_RESTARTING);
1918 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1920 MUTEX_EXIT(&call->lock);
1925 tservice = call->conn->service;
1927 if (tservice->beforeProc)
1928 (*tservice->beforeProc) (call);
1930 code = tservice->executeRequestProc(call);
1932 if (tservice->afterProc)
1933 (*tservice->afterProc) (call, code);
1935 rx_EndCall(call, code);
1937 if (tservice->postProc)
1938 (*tservice->postProc) (code);
1940 if (rx_stats_active) {
1941 MUTEX_ENTER(&rx_stats_mutex);
1943 MUTEX_EXIT(&rx_stats_mutex);
1950 rx_WakeupServerProcs(void)
1952 struct rx_serverQueueEntry *np;
1953 struct opr_queue *cursor;
1957 MUTEX_ENTER(&rx_serverPool_lock);
1959 #ifdef RX_ENABLE_LOCKS
1960 if (rx_waitForPacket)
1961 CV_BROADCAST(&rx_waitForPacket->cv);
1962 #else /* RX_ENABLE_LOCKS */
1963 if (rx_waitForPacket)
1964 osi_rxWakeup(rx_waitForPacket);
1965 #endif /* RX_ENABLE_LOCKS */
1966 MUTEX_ENTER(&freeSQEList_lock);
1967 for (opr_queue_Scan(&rx_freeServerQueue, cursor)) {
1968 np = opr_queue_Entry(cursor, struct rx_serverQueueEntry, entry);
1969 #ifdef RX_ENABLE_LOCKS
1970 CV_BROADCAST(&np->cv);
1971 #else /* RX_ENABLE_LOCKS */
1973 #endif /* RX_ENABLE_LOCKS */
1975 MUTEX_EXIT(&freeSQEList_lock);
1976 for (opr_queue_Scan(&rx_idleServerQueue, cursor)) {
1977 np = opr_queue_Entry(cursor, struct rx_serverQueueEntry, entry);
1978 #ifdef RX_ENABLE_LOCKS
1979 CV_BROADCAST(&np->cv);
1980 #else /* RX_ENABLE_LOCKS */
1982 #endif /* RX_ENABLE_LOCKS */
1984 MUTEX_EXIT(&rx_serverPool_lock);
1989 * One thing that seems to happen is that all the server threads get
1990 * tied up on some empty or slow call, and then a whole bunch of calls
1991 * arrive at once, using up the packet pool, so now there are more
1992 * empty calls. The most critical resources here are server threads
1993 * and the free packet pool. The "doreclaim" code seems to help in
1994 * general. I think that eventually we arrive in this state: there
1995 * are lots of pending calls which do have all their packets present,
1996 * so they won't be reclaimed, are multi-packet calls, so they won't
1997 * be scheduled until later, and thus are tying up most of the free
1998 * packet pool for a very long time.
2000 * 1. schedule multi-packet calls if all the packets are present.
2001 * Probably CPU-bound operation, useful to return packets to pool.
2002 * Do what if there is a full window, but the last packet isn't here?
2003 * 3. preserve one thread which *only* runs "best" calls, otherwise
2004 * it sleeps and waits for that type of call.
2005 * 4. Don't necessarily reserve a whole window for each thread. In fact,
2006 * the current dataquota business is badly broken. The quota isn't adjusted
2007 * to reflect how many packets are presently queued for a running call.
2008 * So, when we schedule a queued call with a full window of packets queued
2009 * up for it, that *should* free up a window full of packets for other 2d-class
2010 * calls to be able to use from the packet pool. But it doesn't.
2012 * NB. Most of the time, this code doesn't run -- since idle server threads
2013 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
2014 * as a new call arrives.
2016 /* Sleep until a call arrives. Returns a pointer to the call, ready
2017 * for an rx_Read. */
2018 #ifdef RX_ENABLE_LOCKS
2020 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2022 struct rx_serverQueueEntry *sq;
2023 struct rx_call *call = (struct rx_call *)0;
2024 struct rx_service *service = NULL;
2026 MUTEX_ENTER(&freeSQEList_lock);
2028 if (!opr_queue_IsEmpty(&rx_freeServerQueue)) {
2029 sq = opr_queue_First(&rx_freeServerQueue, struct rx_serverQueueEntry,
2031 opr_queue_Remove(&sq->entry);
2032 MUTEX_EXIT(&freeSQEList_lock);
2033 } else { /* otherwise allocate a new one and return that */
2034 MUTEX_EXIT(&freeSQEList_lock);
2035 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2036 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2037 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2040 MUTEX_ENTER(&rx_serverPool_lock);
2041 if (cur_service != NULL) {
2042 ReturnToServerPool(cur_service);
2045 if (!opr_queue_IsEmpty(&rx_incomingCallQueue)) {
2046 struct rx_call *tcall, *choice2 = NULL;
2047 struct opr_queue *cursor;
2049 /* Scan for eligible incoming calls. A call is not eligible
2050 * if the maximum number of calls for its service type are
2051 * already executing */
2052 /* One thread will process calls FCFS (to prevent starvation),
2053 * while the other threads may run ahead looking for calls which
2054 * have all their input data available immediately. This helps
2055 * keep threads from blocking, waiting for data from the client. */
2056 for (opr_queue_Scan(&rx_incomingCallQueue, cursor)) {
2057 tcall = opr_queue_Entry(cursor, struct rx_call, entry);
2059 service = tcall->conn->service;
2060 if (!QuotaOK(service)) {
2063 MUTEX_ENTER(&rx_pthread_mutex);
2064 if (tno == rxi_fcfs_thread_num
2065 || opr_queue_IsEnd(&rx_incomingCallQueue, cursor)) {
2066 MUTEX_EXIT(&rx_pthread_mutex);
2067 /* If we're the fcfs thread , then we'll just use
2068 * this call. If we haven't been able to find an optimal
2069 * choice, and we're at the end of the list, then use a
2070 * 2d choice if one has been identified. Otherwise... */
2071 call = (choice2 ? choice2 : tcall);
2072 service = call->conn->service;
2074 MUTEX_EXIT(&rx_pthread_mutex);
2075 if (!opr_queue_IsEmpty(&tcall->rq)) {
2076 struct rx_packet *rp;
2077 rp = opr_queue_First(&tcall->rq, struct rx_packet,
2079 if (rp->header.seq == 1) {
2081 || (rp->header.flags & RX_LAST_PACKET)) {
2083 } else if (rxi_2dchoice && !choice2
2084 && !(tcall->flags & RX_CALL_CLEARED)
2085 && (tcall->rprev > rxi_HardAckRate)) {
2095 ReturnToServerPool(service);
2101 opr_queue_Remove(&call->entry);
2102 MUTEX_EXIT(&rx_serverPool_lock);
2103 MUTEX_ENTER(&call->lock);
2104 CLEAR_CALL_QUEUE_LOCK(call);
2106 if (call->flags & RX_CALL_WAIT_PROC) {
2107 call->flags &= ~RX_CALL_WAIT_PROC;
2108 rx_atomic_dec(&rx_nWaiting);
2111 if (call->state != RX_STATE_PRECALL || call->error) {
2112 MUTEX_EXIT(&call->lock);
2113 MUTEX_ENTER(&rx_serverPool_lock);
2114 ReturnToServerPool(service);
2119 if (opr_queue_IsEmpty(&call->rq)
2120 || opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq != 1)
2121 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2125 /* If there are no eligible incoming calls, add this process
2126 * to the idle server queue, to wait for one */
2130 *socketp = OSI_NULLSOCKET;
2132 sq->socketp = socketp;
2133 opr_queue_Append(&rx_idleServerQueue, &sq->entry);
2134 #ifndef AFS_AIX41_ENV
2135 rx_waitForPacket = sq;
2136 #endif /* AFS_AIX41_ENV */
2138 CV_WAIT(&sq->cv, &rx_serverPool_lock);
2140 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2144 } while (!(call = sq->newcall)
2145 && !(socketp && *socketp != OSI_NULLSOCKET));
2146 if (opr_queue_IsOnQueue(&sq->entry)) {
2147 opr_queue_Remove(&sq->entry);
2149 MUTEX_EXIT(&rx_serverPool_lock);
2151 MUTEX_ENTER(&call->lock);
2157 MUTEX_ENTER(&freeSQEList_lock);
2158 opr_queue_Prepend(&rx_freeServerQueue, &sq->entry);
2159 MUTEX_EXIT(&freeSQEList_lock);
2162 clock_GetTime(&call->startTime);
2163 call->state = RX_STATE_ACTIVE;
2164 call->app.mode = RX_MODE_RECEIVING;
2165 #ifdef RX_KERNEL_TRACE
2166 if (ICL_SETACTIVE(afs_iclSetp)) {
2167 int glockOwner = ISAFS_GLOCK();
2170 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2171 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2178 rxi_calltrace(RX_CALL_START, call);
2179 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2180 call->conn->service->servicePort, call->conn->service->serviceId,
2183 MUTEX_EXIT(&call->lock);
2184 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
2186 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2191 #else /* RX_ENABLE_LOCKS */
2193 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2195 struct rx_serverQueueEntry *sq;
2196 struct rx_call *call = (struct rx_call *)0, *choice2;
2197 struct rx_service *service = NULL;
2201 MUTEX_ENTER(&freeSQEList_lock);
2203 if (!opr_queue_IsEmpty(&rx_freeServerQueue)) {
2204 sq = opr_queue_First(&rx_freeServerQueue, struct rx_serverQueueEntry,
2206 opr_queue_Remove(&sq->entry);
2207 MUTEX_EXIT(&freeSQEList_lock);
2208 } else { /* otherwise allocate a new one and return that */
2209 MUTEX_EXIT(&freeSQEList_lock);
2210 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2211 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2212 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2214 MUTEX_ENTER(&sq->lock);
2216 if (cur_service != NULL) {
2217 cur_service->nRequestsRunning--;
2218 MUTEX_ENTER(&rx_quota_mutex);
2219 if (cur_service->nRequestsRunning < cur_service->minProcs)
2222 MUTEX_EXIT(&rx_quota_mutex);
2224 if (!opr_queue_IsEmpty(&rx_incomingCallQueue)) {
2225 struct rx_call *tcall;
2226 struct opr_queue *cursor;
2227 /* Scan for eligible incoming calls. A call is not eligible
2228 * if the maximum number of calls for its service type are
2229 * already executing */
2230 /* One thread will process calls FCFS (to prevent starvation),
2231 * while the other threads may run ahead looking for calls which
2232 * have all their input data available immediately. This helps
2233 * keep threads from blocking, waiting for data from the client. */
2234 choice2 = (struct rx_call *)0;
2235 for (opr_queue_Scan(&rx_incomingCallQueue, cursor)) {
2236 tcall = opr_queue_Entry(cursor, struct rx_call, entry);
2237 service = tcall->conn->service;
2238 if (QuotaOK(service)) {
2239 MUTEX_ENTER(&rx_pthread_mutex);
2240 /* XXX - If tcall->entry.next is NULL, then we're no longer
2241 * on a queue at all. This shouldn't happen. */
2242 if (tno == rxi_fcfs_thread_num || !tcall->entry.next) {
2243 MUTEX_EXIT(&rx_pthread_mutex);
2244 /* If we're the fcfs thread, then we'll just use
2245 * this call. If we haven't been able to find an optimal
2246 * choice, and we're at the end of the list, then use a
2247 * 2d choice if one has been identified. Otherwise... */
2248 call = (choice2 ? choice2 : tcall);
2249 service = call->conn->service;
2251 MUTEX_EXIT(&rx_pthread_mutex);
2252 if (!opr_queue_IsEmpty(&tcall->rq)) {
2253 struct rx_packet *rp;
2254 rp = opr_queue_First(&tcall->rq, struct rx_packet,
2256 if (rp->header.seq == 1
2258 || (rp->header.flags & RX_LAST_PACKET))) {
2260 } else if (rxi_2dchoice && !choice2
2261 && !(tcall->flags & RX_CALL_CLEARED)
2262 && (tcall->rprev > rxi_HardAckRate)) {
2275 opr_queue_Remove(&call->entry);
2276 CLEAR_CALL_QUEUE_LOCK(call);
2277 /* we can't schedule a call if there's no data!!! */
2278 /* send an ack if there's no data, if we're missing the
2279 * first packet, or we're missing something between first
2280 * and last -- there's a "hole" in the incoming data. */
2281 if (opr_queue_IsEmpty(&call->rq)
2282 || opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq != 1
2283 || call->rprev != opr_queue_Last(&call->rq, struct rx_packet, entry)->header.seq)
2284 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2286 call->flags &= (~RX_CALL_WAIT_PROC);
2287 service->nRequestsRunning++;
2288 /* just started call in minProcs pool, need fewer to maintain
2290 MUTEX_ENTER(&rx_quota_mutex);
2291 if (service->nRequestsRunning <= service->minProcs)
2294 MUTEX_EXIT(&rx_quota_mutex);
2295 rx_atomic_dec(&rx_nWaiting);
2296 /* MUTEX_EXIT(&call->lock); */
2298 /* If there are no eligible incoming calls, add this process
2299 * to the idle server queue, to wait for one */
2302 *socketp = OSI_NULLSOCKET;
2304 sq->socketp = socketp;
2305 opr_queue_Append(&rx_idleServerQueue, &sq->entry);
2309 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2311 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2312 return (struct rx_call *)0;
2315 } while (!(call = sq->newcall)
2316 && !(socketp && *socketp != OSI_NULLSOCKET));
2318 MUTEX_EXIT(&sq->lock);
2320 MUTEX_ENTER(&freeSQEList_lock);
2321 opr_queue_Prepend(&rx_freeServerQueue, &sq->entry);
2322 MUTEX_EXIT(&freeSQEList_lock);
2325 clock_GetTime(&call->startTime);
2326 call->state = RX_STATE_ACTIVE;
2327 call->app.mode = RX_MODE_RECEIVING;
2328 #ifdef RX_KERNEL_TRACE
2329 if (ICL_SETACTIVE(afs_iclSetp)) {
2330 int glockOwner = ISAFS_GLOCK();
2333 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2334 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2341 rxi_calltrace(RX_CALL_START, call);
2342 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2343 call->conn->service->servicePort, call->conn->service->serviceId,
2346 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2353 #endif /* RX_ENABLE_LOCKS */
2357 /* Establish a procedure to be called when a packet arrives for a
2358 * call. This routine will be called at most once after each call,
2359 * and will also be called if there is an error condition on the or
2360 * the call is complete. Used by multi rx to build a selection
2361 * function which determines which of several calls is likely to be a
2362 * good one to read from.
2363 * NOTE: the way this is currently implemented it is probably only a
2364 * good idea to (1) use it immediately after a newcall (clients only)
2365 * and (2) only use it once. Other uses currently void your warranty
2368 rx_SetArrivalProc(struct rx_call *call,
2369 void (*proc) (struct rx_call * call,
2372 void * handle, int arg)
2374 call->arrivalProc = proc;
2375 call->arrivalProcHandle = handle;
2376 call->arrivalProcArg = arg;
2379 /* Call is finished (possibly prematurely). Return rc to the peer, if
2380 * appropriate, and return the final error code from the conversation
2384 rx_EndCall(struct rx_call *call, afs_int32 rc)
2386 struct rx_connection *conn = call->conn;
2390 dpf(("rx_EndCall(call %p rc %d error %d abortCode %d)\n",
2391 call, rc, call->error, call->abortCode));
2394 MUTEX_ENTER(&call->lock);
2396 if (rc == 0 && call->error == 0) {
2397 call->abortCode = 0;
2398 call->abortCount = 0;
2401 call->arrivalProc = NULL;
2402 if (rc && call->error == 0) {
2403 rxi_CallError(call, rc);
2404 call->app.mode = RX_MODE_ERROR;
2405 /* Send an abort message to the peer if this error code has
2406 * only just been set. If it was set previously, assume the
2407 * peer has already been sent the error code or will request it
2409 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2411 if (conn->type == RX_SERVER_CONNECTION) {
2412 /* Make sure reply or at least dummy reply is sent */
2413 if (call->app.mode == RX_MODE_RECEIVING) {
2414 MUTEX_EXIT(&call->lock);
2415 rxi_WriteProc(call, 0, 0);
2416 MUTEX_ENTER(&call->lock);
2418 if (call->app.mode == RX_MODE_SENDING) {
2419 rxi_FlushWriteLocked(call);
2421 rxi_calltrace(RX_CALL_END, call);
2422 /* Call goes to hold state until reply packets are acknowledged */
2423 if (call->tfirst + call->nSoftAcked < call->tnext) {
2424 call->state = RX_STATE_HOLD;
2426 call->state = RX_STATE_DALLY;
2427 rxi_ClearTransmitQueue(call, 0);
2428 rxi_rto_cancel(call);
2429 rxi_CancelKeepAliveEvent(call);
2431 } else { /* Client connection */
2433 /* Make sure server receives input packets, in the case where
2434 * no reply arguments are expected */
2436 if ((call->app.mode == RX_MODE_SENDING)
2437 || (call->app.mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2438 MUTEX_EXIT(&call->lock);
2439 (void)rxi_ReadProc(call, &dummy, 1);
2440 MUTEX_ENTER(&call->lock);
2443 /* If we had an outstanding delayed ack, be nice to the server
2444 * and force-send it now.
2446 if (call->delayedAckEvent) {
2447 rxi_CancelDelayedAckEvent(call);
2448 rxi_SendDelayedAck(NULL, call, NULL, 0);
2451 /* We need to release the call lock since it's lower than the
2452 * conn_call_lock and we don't want to hold the conn_call_lock
2453 * over the rx_ReadProc call. The conn_call_lock needs to be held
2454 * here for the case where rx_NewCall is perusing the calls on
2455 * the connection structure. We don't want to signal until
2456 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2457 * have checked this call, found it active and by the time it
2458 * goes to sleep, will have missed the signal.
2460 MUTEX_EXIT(&call->lock);
2461 MUTEX_ENTER(&conn->conn_call_lock);
2462 MUTEX_ENTER(&call->lock);
2465 /* While there are some circumstances where a call with an error is
2466 * obviously not on a "busy" channel, be conservative (clearing
2467 * lastBusy is just best-effort to possibly speed up rx_NewCall).
2468 * The call channel is definitely not busy if we just successfully
2469 * completed a call on it. */
2470 conn->lastBusy[call->channel] = 0;
2472 } else if (call->error == RX_CALL_TIMEOUT) {
2473 /* The call is still probably running on the server side, so try to
2474 * avoid this call channel in the future. */
2475 conn->lastBusy[call->channel] = clock_Sec();
2478 MUTEX_ENTER(&conn->conn_data_lock);
2479 conn->flags |= RX_CONN_BUSY;
2480 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2481 MUTEX_EXIT(&conn->conn_data_lock);
2482 #ifdef RX_ENABLE_LOCKS
2483 CV_BROADCAST(&conn->conn_call_cv);
2488 #ifdef RX_ENABLE_LOCKS
2490 MUTEX_EXIT(&conn->conn_data_lock);
2492 #endif /* RX_ENABLE_LOCKS */
2493 call->state = RX_STATE_DALLY;
2495 error = call->error;
2497 /* currentPacket, nLeft, and NFree must be zeroed here, because
2498 * ResetCall cannot: ResetCall may be called at splnet(), in the
2499 * kernel version, and may interrupt the macros rx_Read or
2500 * rx_Write, which run at normal priority for efficiency. */
2501 if (call->app.currentPacket) {
2502 #ifdef RX_TRACK_PACKETS
2503 call->app.currentPacket->flags &= ~RX_PKTFLAG_CP;
2505 rxi_FreePacket(call->app.currentPacket);
2506 call->app.currentPacket = (struct rx_packet *)0;
2509 call->app.nLeft = call->app.nFree = call->app.curlen = 0;
2511 /* Free any packets from the last call to ReadvProc/WritevProc */
2512 #ifdef RXDEBUG_PACKET
2514 #endif /* RXDEBUG_PACKET */
2515 rxi_FreePackets(0, &call->app.iovq);
2516 MUTEX_EXIT(&call->lock);
2518 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2519 if (conn->type == RX_CLIENT_CONNECTION) {
2520 MUTEX_ENTER(&conn->conn_data_lock);
2521 conn->flags &= ~RX_CONN_BUSY;
2522 MUTEX_EXIT(&conn->conn_data_lock);
2523 MUTEX_EXIT(&conn->conn_call_lock);
2527 * Map errors to the local host's errno.h format.
2529 error = ntoh_syserr_conv(error);
2531 /* If the caller said the call failed with some error, we had better
2532 * return an error code. */
2533 osi_Assert(!rc || error);
2537 #if !defined(KERNEL)
2539 /* Call this routine when shutting down a server or client (especially
2540 * clients). This will allow Rx to gracefully garbage collect server
2541 * connections, and reduce the number of retries that a server might
2542 * make to a dead client.
2543 * This is not quite right, since some calls may still be ongoing and
2544 * we can't lock them to destroy them. */
2550 if (!rxi_IsRunning()) {
2552 return; /* Already shutdown. */
2554 rxi_Finalize_locked();
2559 rxi_Finalize_locked(void)
2561 struct rx_connection **conn_ptr, **conn_end;
2562 rx_atomic_set(&rxi_running, 0);
2563 rxi_DeleteCachedConnections();
2564 if (rx_connHashTable) {
2565 MUTEX_ENTER(&rx_connHashTable_lock);
2566 for (conn_ptr = &rx_connHashTable[0], conn_end =
2567 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2569 struct rx_connection *conn, *next;
2570 for (conn = *conn_ptr; conn; conn = next) {
2572 if (conn->type == RX_CLIENT_CONNECTION) {
2573 rx_GetConnection(conn);
2574 #ifdef RX_ENABLE_LOCKS
2575 rxi_DestroyConnectionNoLock(conn);
2576 #else /* RX_ENABLE_LOCKS */
2577 rxi_DestroyConnection(conn);
2578 #endif /* RX_ENABLE_LOCKS */
2582 #ifdef RX_ENABLE_LOCKS
2583 while (rx_connCleanup_list) {
2584 struct rx_connection *conn;
2585 conn = rx_connCleanup_list;
2586 rx_connCleanup_list = rx_connCleanup_list->next;
2587 MUTEX_EXIT(&rx_connHashTable_lock);
2588 rxi_CleanupConnection(conn);
2589 MUTEX_ENTER(&rx_connHashTable_lock);
2591 MUTEX_EXIT(&rx_connHashTable_lock);
2592 #endif /* RX_ENABLE_LOCKS */
2597 afs_winsockCleanup();
2602 /* if we wakeup packet waiter too often, can get in loop with two
2603 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2605 rxi_PacketsUnWait(void)
2607 if (!rx_waitingForPackets) {
2611 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2612 return; /* still over quota */
2615 rx_waitingForPackets = 0;
2616 #ifdef RX_ENABLE_LOCKS
2617 CV_BROADCAST(&rx_waitingForPackets_cv);
2619 osi_rxWakeup(&rx_waitingForPackets);
2625 /* ------------------Internal interfaces------------------------- */
2627 /* Return this process's service structure for the
2628 * specified socket and service */
2629 static struct rx_service *
2630 rxi_FindService(osi_socket socket, u_short serviceId)
2632 struct rx_service **sp;
2633 for (sp = &rx_services[0]; *sp; sp++) {
2634 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2640 #ifdef RXDEBUG_PACKET
2641 #ifdef KDUMP_RX_LOCK
2642 static struct rx_call_rx_lock *rx_allCallsp = 0;
2644 static struct rx_call *rx_allCallsp = 0;
2646 #endif /* RXDEBUG_PACKET */
2648 /* Allocate a call structure, for the indicated channel of the
2649 * supplied connection. The mode and state of the call must be set by
2650 * the caller. Returns the call with mutex locked. */
2651 static struct rx_call *
2652 rxi_NewCall(struct rx_connection *conn, int channel)
2654 struct rx_call *call;
2655 #ifdef RX_ENABLE_LOCKS
2656 struct rx_call *cp; /* Call pointer temp */
2657 struct opr_queue *cursor;
2660 dpf(("rxi_NewCall(conn %p, channel %d)\n", conn, channel));
2662 /* Grab an existing call structure, or allocate a new one.
2663 * Existing call structures are assumed to have been left reset by
2665 MUTEX_ENTER(&rx_freeCallQueue_lock);
2667 #ifdef RX_ENABLE_LOCKS
2669 * EXCEPT that the TQ might not yet be cleared out.
2670 * Skip over those with in-use TQs.
2673 for (opr_queue_Scan(&rx_freeCallQueue, cursor)) {
2674 cp = opr_queue_Entry(cursor, struct rx_call, entry);
2675 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2681 #else /* RX_ENABLE_LOCKS */
2682 if (!opr_queue_IsEmpty(&rx_freeCallQueue)) {
2683 call = opr_queue_First(&rx_freeCallQueue, struct rx_call, entry);
2684 #endif /* RX_ENABLE_LOCKS */
2685 opr_queue_Remove(&call->entry);
2686 if (rx_stats_active)
2687 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2688 MUTEX_EXIT(&rx_freeCallQueue_lock);
2689 MUTEX_ENTER(&call->lock);
2690 CLEAR_CALL_QUEUE_LOCK(call);
2691 #ifdef RX_ENABLE_LOCKS
2692 /* Now, if TQ wasn't cleared earlier, do it now. */
2693 rxi_WaitforTQBusy(call);
2694 if (call->flags & RX_CALL_TQ_CLEARME) {
2695 rxi_ClearTransmitQueue(call, 1);
2696 /*queue_Init(&call->tq);*/
2698 #endif /* RX_ENABLE_LOCKS */
2699 /* Bind the call to its connection structure */
2701 rxi_ResetCall(call, 1);
2704 call = rxi_Alloc(sizeof(struct rx_call));
2705 #ifdef RXDEBUG_PACKET
2706 call->allNextp = rx_allCallsp;
2707 rx_allCallsp = call;
2709 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2710 #else /* RXDEBUG_PACKET */
2711 rx_atomic_inc(&rx_stats.nCallStructs);
2712 #endif /* RXDEBUG_PACKET */
2714 MUTEX_EXIT(&rx_freeCallQueue_lock);
2715 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2716 MUTEX_ENTER(&call->lock);
2717 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2718 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2719 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2721 /* Initialize once-only items */
2722 opr_queue_Init(&call->tq);
2723 opr_queue_Init(&call->rq);
2724 opr_queue_Init(&call->app.iovq);
2725 #ifdef RXDEBUG_PACKET
2726 call->rqc = call->tqc = call->iovqc = 0;
2727 #endif /* RXDEBUG_PACKET */
2728 /* Bind the call to its connection structure (prereq for reset) */
2730 rxi_ResetCall(call, 1);
2732 call->channel = channel;
2733 call->callNumber = &conn->callNumber[channel];
2734 call->rwind = conn->rwind[channel];
2735 call->twind = conn->twind[channel];
2736 /* Note that the next expected call number is retained (in
2737 * conn->callNumber[i]), even if we reallocate the call structure
2739 conn->call[channel] = call;
2740 /* if the channel's never been used (== 0), we should start at 1, otherwise
2741 * the call number is valid from the last time this channel was used */
2742 if (*call->callNumber == 0)
2743 *call->callNumber = 1;
2748 /* A call has been inactive long enough that so we can throw away
2749 * state, including the call structure, which is placed on the call
2752 * call->lock amd rx_refcnt_mutex are held upon entry.
2753 * haveCTLock is set when called from rxi_ReapConnections.
2755 * return 1 if the call is freed, 0 if not.
2758 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2760 int channel = call->channel;
2761 struct rx_connection *conn = call->conn;
2762 u_char state = call->state;
2765 * We are setting the state to RX_STATE_RESET to
2766 * ensure that no one else will attempt to use this
2767 * call once we drop the refcnt lock. We must drop
2768 * the refcnt lock before calling rxi_ResetCall
2769 * because it cannot be held across acquiring the
2770 * freepktQ lock. NewCall does the same.
2772 call->state = RX_STATE_RESET;
2773 MUTEX_EXIT(&rx_refcnt_mutex);
2774 rxi_ResetCall(call, 0);
2776 if (MUTEX_TRYENTER(&conn->conn_call_lock))
2778 if (state == RX_STATE_DALLY || state == RX_STATE_HOLD)
2779 (*call->callNumber)++;
2781 if (call->conn->call[channel] == call)
2782 call->conn->call[channel] = 0;
2783 MUTEX_EXIT(&conn->conn_call_lock);
2786 * We couldn't obtain the conn_call_lock so we can't
2787 * disconnect the call from the connection. Set the
2788 * call state to dally so that the call can be reused.
2790 MUTEX_ENTER(&rx_refcnt_mutex);
2791 call->state = RX_STATE_DALLY;
2795 MUTEX_ENTER(&rx_freeCallQueue_lock);
2796 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2797 #ifdef RX_ENABLE_LOCKS
2798 /* A call may be free even though its transmit queue is still in use.
2799 * Since we search the call list from head to tail, put busy calls at
2800 * the head of the list, and idle calls at the tail.
2802 if (call->flags & RX_CALL_TQ_BUSY)
2803 opr_queue_Prepend(&rx_freeCallQueue, &call->entry);
2805 opr_queue_Append(&rx_freeCallQueue, &call->entry);
2806 #else /* RX_ENABLE_LOCKS */
2807 opr_queue_Append(&rx_freeCallQueue, &call->entry);
2808 #endif /* RX_ENABLE_LOCKS */
2809 if (rx_stats_active)
2810 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2811 MUTEX_EXIT(&rx_freeCallQueue_lock);
2813 /* Destroy the connection if it was previously slated for
2814 * destruction, i.e. the Rx client code previously called
2815 * rx_DestroyConnection (client connections), or
2816 * rxi_ReapConnections called the same routine (server
2817 * connections). Only do this, however, if there are no
2818 * outstanding calls. Note that for fine grain locking, there appears
2819 * to be a deadlock in that rxi_FreeCall has a call locked and
2820 * DestroyConnectionNoLock locks each call in the conn. But note a
2821 * few lines up where we have removed this call from the conn.
2822 * If someone else destroys a connection, they either have no
2823 * call lock held or are going through this section of code.
2825 MUTEX_ENTER(&conn->conn_data_lock);
2826 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2827 rx_GetConnection(conn);
2828 MUTEX_EXIT(&conn->conn_data_lock);
2829 #ifdef RX_ENABLE_LOCKS
2831 rxi_DestroyConnectionNoLock(conn);
2833 rxi_DestroyConnection(conn);
2834 #else /* RX_ENABLE_LOCKS */
2835 rxi_DestroyConnection(conn);
2836 #endif /* RX_ENABLE_LOCKS */
2838 MUTEX_EXIT(&conn->conn_data_lock);
2840 MUTEX_ENTER(&rx_refcnt_mutex);
2844 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2845 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2848 rxi_Alloc(size_t size)
2852 if (rx_stats_active) {
2853 rx_atomic_add(&rxi_Allocsize, (int) size);
2854 rx_atomic_inc(&rxi_Alloccnt);
2858 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2859 afs_osi_Alloc_NoSleep(size);
2864 osi_Panic("rxi_Alloc error");
2870 rxi_Free(void *addr, size_t size)
2875 if (rx_stats_active) {
2876 rx_atomic_sub(&rxi_Allocsize, (int) size);
2877 rx_atomic_dec(&rxi_Alloccnt);
2879 osi_Free(addr, size);
2883 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2885 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2886 struct rx_peer *next = NULL;
2890 MUTEX_ENTER(&rx_peerHashTable_lock);
2892 peer_ptr = &rx_peerHashTable[0];
2893 peer_end = &rx_peerHashTable[rx_hashTableSize];
2896 for ( ; peer_ptr < peer_end; peer_ptr++) {
2899 for ( ; peer; peer = next) {
2901 if (host == peer->host)
2906 hashIndex = PEER_HASH(host, port);
2907 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2908 if ((peer->host == host) && (peer->port == port))
2913 MUTEX_ENTER(&rx_peerHashTable_lock);
2918 MUTEX_EXIT(&rx_peerHashTable_lock);
2920 MUTEX_ENTER(&peer->peer_lock);
2921 /* We don't handle dropping below min, so don't */
2922 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2923 peer->ifMTU=MIN(mtu, peer->ifMTU);
2924 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2925 /* if we tweaked this down, need to tune our peer MTU too */
2926 peer->MTU = MIN(peer->MTU, peer->natMTU);
2927 /* if we discovered a sub-1500 mtu, degrade */
2928 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2929 peer->maxDgramPackets = 1;
2930 /* We no longer have valid peer packet information */
2931 if (peer->maxPacketSize + RX_HEADER_SIZE > peer->ifMTU)
2932 peer->maxPacketSize = 0;
2933 MUTEX_EXIT(&peer->peer_lock);
2935 MUTEX_ENTER(&rx_peerHashTable_lock);
2937 if (host && !port) {
2939 /* pick up where we left off */
2943 MUTEX_EXIT(&rx_peerHashTable_lock);
2946 #ifdef AFS_RXERRQ_ENV
2948 rxi_SetPeerDead(struct sock_extended_err *err, afs_uint32 host, afs_uint16 port)
2950 int hashIndex = PEER_HASH(host, port);
2951 struct rx_peer *peer;
2953 MUTEX_ENTER(&rx_peerHashTable_lock);
2955 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2956 if (peer->host == host && peer->port == port) {
2962 MUTEX_EXIT(&rx_peerHashTable_lock);
2965 rx_atomic_inc(&peer->neterrs);
2966 MUTEX_ENTER(&peer->peer_lock);
2967 peer->last_err_origin = RX_NETWORK_ERROR_ORIGIN_ICMP;
2968 peer->last_err_type = err->ee_type;
2969 peer->last_err_code = err->ee_code;
2970 MUTEX_EXIT(&peer->peer_lock);
2972 MUTEX_ENTER(&rx_peerHashTable_lock);
2974 MUTEX_EXIT(&rx_peerHashTable_lock);
2979 rxi_ProcessNetError(struct sock_extended_err *err, afs_uint32 addr, afs_uint16 port)
2981 # ifdef AFS_ADAPT_PMTU
2982 if (err->ee_errno == EMSGSIZE && err->ee_info >= 68) {
2983 rxi_SetPeerMtu(NULL, addr, port, err->ee_info - RX_IPUDP_SIZE);
2987 if (err->ee_origin == SO_EE_ORIGIN_ICMP && err->ee_type == ICMP_DEST_UNREACH) {
2988 switch (err->ee_code) {
2989 case ICMP_NET_UNREACH:
2990 case ICMP_HOST_UNREACH:
2991 case ICMP_PORT_UNREACH:
2994 rxi_SetPeerDead(err, addr, port);
3001 rxi_TranslateICMP(int type, int code)
3004 case ICMP_DEST_UNREACH:
3006 case ICMP_NET_UNREACH:
3007 return "Destination Net Unreachable";
3008 case ICMP_HOST_UNREACH:
3009 return "Destination Host Unreachable";
3010 case ICMP_PROT_UNREACH:
3011 return "Destination Protocol Unreachable";
3012 case ICMP_PORT_UNREACH:
3013 return "Destination Port Unreachable";
3015 return "Destination Net Prohibited";
3017 return "Destination Host Prohibited";
3023 #endif /* AFS_RXERRQ_ENV */
3026 * Get the last network error for a connection
3028 * A "network error" here means an error retrieved from ICMP, or some other
3029 * mechanism outside of Rx that informs us of errors in network reachability.
3031 * If a peer associated with the given Rx connection has received a network
3032 * error recently, this function allows the caller to know what error
3033 * specifically occurred. This can be useful to know, since e.g. ICMP errors
3034 * can cause calls to that peer to be quickly aborted. So, this function can
3035 * help see why a call was aborted due to network errors.
3037 * If we have received traffic from a peer since the last network error, we
3038 * treat that peer as if we had not received an network error for it.
3040 * @param[in] conn The Rx connection to examine
3041 * @param[out] err_origin The origin of the last network error (e.g. ICMP);
3042 * one of the RX_NETWORK_ERROR_ORIGIN_* constants
3043 * @param[out] err_type The type of the last error
3044 * @param[out] err_code The code of the last error
3045 * @param[out] msg Human-readable error message, if applicable; NULL otherwise
3047 * @return If we have an error
3048 * @retval -1 No error to get; 'out' params are undefined
3049 * @retval 0 We have an error; 'out' params contain the last error
3052 rx_GetNetworkError(struct rx_connection *conn, int *err_origin, int *err_type,
3053 int *err_code, const char **msg)
3055 #ifdef AFS_RXERRQ_ENV
3056 struct rx_peer *peer = conn->peer;
3057 if (rx_atomic_read(&peer->neterrs)) {
3058 MUTEX_ENTER(&peer->peer_lock);
3059 *err_origin = peer->last_err_origin;
3060 *err_type = peer->last_err_type;
3061 *err_code = peer->last_err_code;
3062 MUTEX_EXIT(&peer->peer_lock);
3065 if (*err_origin == RX_NETWORK_ERROR_ORIGIN_ICMP) {
3066 *msg = rxi_TranslateICMP(*err_type, *err_code);
3075 /* Find the peer process represented by the supplied (host,port)
3076 * combination. If there is no appropriate active peer structure, a
3077 * new one will be allocated and initialized
3080 rxi_FindPeer(afs_uint32 host, u_short port, int create)
3084 hashIndex = PEER_HASH(host, port);
3085 MUTEX_ENTER(&rx_peerHashTable_lock);
3086 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
3087 if ((pp->host == host) && (pp->port == port))
3092 pp = rxi_AllocPeer(); /* This bzero's *pp */
3093 pp->host = host; /* set here or in InitPeerParams is zero */
3095 #ifdef AFS_RXERRQ_ENV
3096 rx_atomic_set(&pp->neterrs, 0);
3098 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
3099 opr_queue_Init(&pp->rpcStats);
3100 pp->next = rx_peerHashTable[hashIndex];
3101 rx_peerHashTable[hashIndex] = pp;
3102 rxi_InitPeerParams(pp);
3103 if (rx_stats_active)
3104 rx_atomic_inc(&rx_stats.nPeerStructs);
3110 MUTEX_EXIT(&rx_peerHashTable_lock);
3115 /* Find the connection at (host, port) started at epoch, and with the
3116 * given connection id. Creates the server connection if necessary.
3117 * The type specifies whether a client connection or a server
3118 * connection is desired. In both cases, (host, port) specify the
3119 * peer's (host, pair) pair. Client connections are not made
3120 * automatically by this routine. The parameter socket gives the
3121 * socket descriptor on which the packet was received. This is used,
3122 * in the case of server connections, to check that *new* connections
3123 * come via a valid (port, serviceId). Finally, the securityIndex
3124 * parameter must match the existing index for the connection. If a
3125 * server connection is created, it will be created using the supplied
3126 * index, if the index is valid for this service */
3127 static struct rx_connection *
3128 rxi_FindConnection(osi_socket socket, afs_uint32 host,
3129 u_short port, u_short serviceId, afs_uint32 cid,
3130 afs_uint32 epoch, int type, u_int securityIndex,
3131 int *unknownService)
3133 int hashindex, flag, i;
3135 struct rx_connection *conn;
3136 *unknownService = 0;
3137 hashindex = CONN_HASH(host, port, cid, epoch, type);
3138 MUTEX_ENTER(&rx_connHashTable_lock);
3139 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
3140 rx_connHashTable[hashindex],
3143 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
3144 && (epoch == conn->epoch)) {
3145 struct rx_peer *pp = conn->peer;
3146 if (securityIndex != conn->securityIndex) {
3147 /* this isn't supposed to happen, but someone could forge a packet
3148 * like this, and there seems to be some CM bug that makes this
3149 * happen from time to time -- in which case, the fileserver
3151 MUTEX_EXIT(&rx_connHashTable_lock);
3152 return (struct rx_connection *)0;
3154 if (pp->host == host && pp->port == port)
3156 if (type == RX_CLIENT_CONNECTION && pp->port == port)
3158 /* So what happens when it's a callback connection? */
3159 if ( /*type == RX_CLIENT_CONNECTION && */
3160 (conn->epoch & 0x80000000))
3164 /* the connection rxLastConn that was used the last time is not the
3165 ** one we are looking for now. Hence, start searching in the hash */
3167 conn = rx_connHashTable[hashindex];
3172 struct rx_service *service;
3173 if (type == RX_CLIENT_CONNECTION) {
3174 MUTEX_EXIT(&rx_connHashTable_lock);
3175 return (struct rx_connection *)0;
3177 service = rxi_FindService(socket, serviceId);
3178 if (!service || (securityIndex >= service->nSecurityObjects)
3179 || (service->securityObjects[securityIndex] == 0)) {
3180 MUTEX_EXIT(&rx_connHashTable_lock);
3181 *unknownService = 1;
3182 return (struct rx_connection *)0;
3184 conn = rxi_AllocConnection(); /* This bzero's the connection */
3185 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
3186 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
3187 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
3188 conn->next = rx_connHashTable[hashindex];
3189 rx_connHashTable[hashindex] = conn;
3190 conn->peer = rxi_FindPeer(host, port, 1);
3191 conn->type = RX_SERVER_CONNECTION;
3192 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
3193 conn->epoch = epoch;
3194 conn->cid = cid & RX_CIDMASK;
3195 conn->ackRate = RX_FAST_ACK_RATE;
3196 conn->service = service;
3197 conn->serviceId = serviceId;
3198 conn->securityIndex = securityIndex;
3199 conn->securityObject = service->securityObjects[securityIndex];
3200 conn->nSpecific = 0;
3201 conn->specific = NULL;
3202 rx_SetConnDeadTime(conn, service->connDeadTime);
3203 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
3204 for (i = 0; i < RX_MAXCALLS; i++) {
3205 conn->twind[i] = rx_initSendWindow;
3206 conn->rwind[i] = rx_initReceiveWindow;
3208 /* Notify security object of the new connection */
3209 code = RXS_NewConnection(conn->securityObject, conn);
3210 /* XXXX Connection timeout? */
3211 if (service->newConnProc)
3212 (*service->newConnProc) (conn);
3213 if (rx_stats_active)
3214 rx_atomic_inc(&rx_stats.nServerConns);
3217 rx_GetConnection(conn);
3219 rxLastConn = conn; /* store this connection as the last conn used */
3220 MUTEX_EXIT(&rx_connHashTable_lock);
3222 rxi_ConnectionError(conn, code);
3228 * Abort the call if the server is over the busy threshold. This
3229 * can be used without requiring a call structure be initialised,
3230 * or connected to a particular channel
3233 rxi_AbortIfServerBusy(osi_socket socket, struct rx_connection *conn,
3234 struct rx_packet *np)
3238 if ((rx_BusyThreshold > 0) &&
3239 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3240 MUTEX_ENTER(&conn->conn_data_lock);
3241 serial = ++conn->serial;
3242 MUTEX_EXIT(&conn->conn_data_lock);
3243 rxi_SendRawAbort(socket, conn->peer->host, conn->peer->port,
3244 serial, rx_BusyError, np, 0);
3245 if (rx_stats_active)
3246 rx_atomic_inc(&rx_stats.nBusies);
3253 static_inline struct rx_call *
3254 rxi_ReceiveClientCall(struct rx_packet *np, struct rx_connection *conn)
3257 struct rx_call *call;
3259 channel = np->header.cid & RX_CHANNELMASK;
3260 MUTEX_ENTER(&conn->conn_call_lock);
3261 call = conn->call[channel];
3262 if (np->header.type == RX_PACKET_TYPE_BUSY) {
3263 conn->lastBusy[channel] = clock_Sec();
3265 if (!call || conn->callNumber[channel] != np->header.callNumber) {
3266 MUTEX_EXIT(&conn->conn_call_lock);
3267 if (rx_stats_active)
3268 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3272 MUTEX_ENTER(&call->lock);
3273 MUTEX_EXIT(&conn->conn_call_lock);
3275 if ((call->state == RX_STATE_DALLY)
3276 && np->header.type == RX_PACKET_TYPE_ACK) {
3277 if (rx_stats_active)
3278 rx_atomic_inc(&rx_stats.ignorePacketDally);
3279 MUTEX_EXIT(&call->lock);
3286 static_inline struct rx_call *
3287 rxi_ReceiveServerCall(osi_socket socket, struct rx_packet *np,
3288 struct rx_connection *conn)
3291 struct rx_call *call;
3293 channel = np->header.cid & RX_CHANNELMASK;
3294 MUTEX_ENTER(&conn->conn_call_lock);
3295 call = conn->call[channel];
3298 if (rxi_AbortIfServerBusy(socket, conn, np)) {
3299 MUTEX_EXIT(&conn->conn_call_lock);
3303 call = rxi_NewCall(conn, channel); /* returns locked call */
3304 *call->callNumber = np->header.callNumber;
3305 MUTEX_EXIT(&conn->conn_call_lock);
3307 call->state = RX_STATE_PRECALL;
3308 clock_GetTime(&call->queueTime);
3309 call->app.bytesSent = 0;
3310 call->app.bytesRcvd = 0;
3311 rxi_KeepAliveOn(call);
3316 if (np->header.callNumber == conn->callNumber[channel]) {
3317 MUTEX_ENTER(&call->lock);
3318 MUTEX_EXIT(&conn->conn_call_lock);
3322 if (np->header.callNumber < conn->callNumber[channel]) {
3323 MUTEX_EXIT(&conn->conn_call_lock);
3324 if (rx_stats_active)
3325 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3329 MUTEX_ENTER(&call->lock);
3330 MUTEX_EXIT(&conn->conn_call_lock);
3332 /* Wait until the transmit queue is idle before deciding
3333 * whether to reset the current call. Chances are that the
3334 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3337 #ifdef RX_ENABLE_LOCKS
3338 if (call->state == RX_STATE_ACTIVE && !call->error) {
3339 rxi_WaitforTQBusy(call);
3340 /* If we entered error state while waiting,
3341 * must call rxi_CallError to permit rxi_ResetCall
3342 * to processed when the tqWaiter count hits zero.
3345 rxi_CallError(call, call->error);
3346 MUTEX_EXIT(&call->lock);
3350 #endif /* RX_ENABLE_LOCKS */
3351 /* If the new call cannot be taken right now send a busy and set
3352 * the error condition in this call, so that it terminates as
3353 * quickly as possible */
3354 if (call->state == RX_STATE_ACTIVE) {
3355 rxi_CallError(call, RX_CALL_DEAD);
3356 rxi_SendSpecial(call, conn, NULL, RX_PACKET_TYPE_BUSY,
3358 MUTEX_EXIT(&call->lock);
3362 if (rxi_AbortIfServerBusy(socket, conn, np)) {
3363 MUTEX_EXIT(&call->lock);
3367 rxi_ResetCall(call, 0);
3368 /* The conn_call_lock is not held but no one else should be
3369 * using this call channel while we are processing this incoming
3370 * packet. This assignment should be safe.
3372 *call->callNumber = np->header.callNumber;
3373 call->state = RX_STATE_PRECALL;
3374 clock_GetTime(&call->queueTime);
3375 call->app.bytesSent = 0;
3376 call->app.bytesRcvd = 0;
3377 rxi_KeepAliveOn(call);
3383 /* There are two packet tracing routines available for testing and monitoring
3384 * Rx. One is called just after every packet is received and the other is
3385 * called just before every packet is sent. Received packets, have had their
3386 * headers decoded, and packets to be sent have not yet had their headers
3387 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
3388 * containing the network address. Both can be modified. The return value, if
3389 * non-zero, indicates that the packet should be dropped. */
3391 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
3392 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
3394 /* A packet has been received off the interface. Np is the packet, socket is
3395 * the socket number it was received from (useful in determining which service
3396 * this packet corresponds to), and (host, port) reflect the host,port of the
3397 * sender. This call returns the packet to the caller if it is finished with
3398 * it, rather than de-allocating it, just as a small performance hack */
3401 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
3402 afs_uint32 host, u_short port, int *tnop,
3403 struct rx_call **newcallp)
3405 struct rx_call *call;
3406 struct rx_connection *conn;
3408 int unknownService = 0;
3412 struct rx_packet *tnp;
3415 /* We don't print out the packet until now because (1) the time may not be
3416 * accurate enough until now in the lwp implementation (rx_Listener only gets
3417 * the time after the packet is read) and (2) from a protocol point of view,
3418 * this is the first time the packet has been seen */
3419 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
3420 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
3421 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %p\n",
3422 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
3423 np->header.epoch, np->header.cid, np->header.callNumber,
3424 np->header.seq, np->header.flags, np));
3427 /* Account for connectionless packets */
3428 if (rx_stats_active &&
3429 ((np->header.type == RX_PACKET_TYPE_VERSION) ||
3430 (np->header.type == RX_PACKET_TYPE_DEBUG))) {
3431 struct rx_peer *peer;
3433 /* Try to look up the peer structure, but don't create one */
3434 peer = rxi_FindPeer(host, port, 0);
3436 /* Since this may not be associated with a connection, it may have
3437 * no refCount, meaning we could race with ReapConnections
3440 if (peer && (peer->refCount > 0)) {
3441 #ifdef AFS_RXERRQ_ENV
3442 if (rx_atomic_read(&peer->neterrs)) {
3443 rx_atomic_set(&peer->neterrs, 0);
3446 MUTEX_ENTER(&peer->peer_lock);
3447 peer->bytesReceived += np->length;
3448 MUTEX_EXIT(&peer->peer_lock);
3452 if (np->header.type == RX_PACKET_TYPE_VERSION) {
3453 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
3456 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
3457 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
3460 /* If an input tracer function is defined, call it with the packet and
3461 * network address. Note this function may modify its arguments. */
3462 if (rx_justReceived) {
3463 struct sockaddr_in addr;
3465 addr.sin_family = AF_INET;
3466 addr.sin_port = port;
3467 addr.sin_addr.s_addr = host;
3468 memset(&addr.sin_zero, 0, sizeof(addr.sin_zero));
3469 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
3470 addr.sin_len = sizeof(addr);
3472 drop = (*rx_justReceived) (np, &addr);
3473 /* drop packet if return value is non-zero */
3476 port = addr.sin_port; /* in case fcn changed addr */
3477 host = addr.sin_addr.s_addr;
3481 /* If packet was not sent by the client, then *we* must be the client */
3482 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
3483 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
3485 /* Find the connection (or fabricate one, if we're the server & if
3486 * necessary) associated with this packet */
3488 rxi_FindConnection(socket, host, port, np->header.serviceId,
3489 np->header.cid, np->header.epoch, type,
3490 np->header.securityIndex, &unknownService);
3492 /* To avoid having 2 connections just abort at each other,
3493 don't abort an abort. */
3495 if (unknownService && (np->header.type != RX_PACKET_TYPE_ABORT))
3496 rxi_SendRawAbort(socket, host, port, 0, RX_INVALID_OPERATION,
3501 #ifdef AFS_RXERRQ_ENV
3502 if (rx_atomic_read(&conn->peer->neterrs)) {
3503 rx_atomic_set(&conn->peer->neterrs, 0);
3507 /* If we're doing statistics, then account for the incoming packet */
3508 if (rx_stats_active) {
3509 MUTEX_ENTER(&conn->peer->peer_lock);
3510 conn->peer->bytesReceived += np->length;
3511 MUTEX_EXIT(&conn->peer->peer_lock);
3514 /* If the connection is in an error state, send an abort packet and ignore
3515 * the incoming packet */
3517 /* Don't respond to an abort packet--we don't want loops! */
3518 MUTEX_ENTER(&conn->conn_data_lock);
3519 if (np->header.type != RX_PACKET_TYPE_ABORT)
3520 np = rxi_SendConnectionAbort(conn, np, 1, 0);
3521 putConnection(conn);
3522 MUTEX_EXIT(&conn->conn_data_lock);
3526 /* Check for connection-only requests (i.e. not call specific). */
3527 if (np->header.callNumber == 0) {
3528 switch (np->header.type) {
3529 case RX_PACKET_TYPE_ABORT: {
3530 /* What if the supplied error is zero? */
3531 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
3532 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
3533 rxi_ConnectionError(conn, errcode);
3534 putConnection(conn);
3537 case RX_PACKET_TYPE_CHALLENGE:
3538 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
3539 putConnection(conn);
3541 case RX_PACKET_TYPE_RESPONSE:
3542 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
3543 putConnection(conn);
3545 case RX_PACKET_TYPE_PARAMS:
3546 case RX_PACKET_TYPE_PARAMS + 1:
3547 case RX_PACKET_TYPE_PARAMS + 2:
3548 /* ignore these packet types for now */
3549 putConnection(conn);
3553 /* Should not reach here, unless the peer is broken: send an
3555 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
3556 MUTEX_ENTER(&conn->conn_data_lock);
3557 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
3558 putConnection(conn);
3559 MUTEX_EXIT(&conn->conn_data_lock);
3564 if (type == RX_SERVER_CONNECTION)
3565 call = rxi_ReceiveServerCall(socket, np, conn);
3567 call = rxi_ReceiveClientCall(np, conn);
3570 putConnection(conn);
3574 MUTEX_ASSERT(&call->lock);
3575 /* Set remote user defined status from packet */
3576 call->remoteStatus = np->header.userStatus;
3578 /* Now do packet type-specific processing */
3579 switch (np->header.type) {
3580 case RX_PACKET_TYPE_DATA:
3581 /* If we're a client, and receiving a response, then all the packets
3582 * we transmitted packets are implicitly acknowledged. */
3583 if (type == RX_CLIENT_CONNECTION && !opr_queue_IsEmpty(&call->tq))
3584 rxi_AckAllInTransmitQueue(call);
3586 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3589 case RX_PACKET_TYPE_ACK:
3590 /* Respond immediately to ack packets requesting acknowledgement
3592 if (np->header.flags & RX_REQUEST_ACK) {
3594 (void)rxi_SendCallAbort(call, 0, 1, 0);
3596 (void)rxi_SendAck(call, 0, np->header.serial,
3597 RX_ACK_PING_RESPONSE, 1);
3599 np = rxi_ReceiveAckPacket(call, np, 1);
3601 case RX_PACKET_TYPE_ABORT: {
3602 /* An abort packet: reset the call, passing the error up to the user. */
3603 /* What if error is zero? */
3604 /* What if the error is -1? the application will treat it as a timeout. */
3605 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3606 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3607 rxi_CallError(call, errdata);
3608 MUTEX_EXIT(&call->lock);
3609 putConnection(conn);
3610 return np; /* xmitting; drop packet */
3612 case RX_PACKET_TYPE_BUSY:
3613 /* Mostly ignore BUSY packets. We will update lastReceiveTime below,
3614 * so we don't think the endpoint is completely dead, but otherwise
3615 * just act as if we never saw anything. If all we get are BUSY packets
3616 * back, then we will eventually error out with RX_CALL_TIMEOUT if the
3617 * connection is configured with idle/hard timeouts. */
3620 case RX_PACKET_TYPE_ACKALL:
3621 /* All packets acknowledged, so we can drop all packets previously
3622 * readied for sending */
3623 rxi_AckAllInTransmitQueue(call);
3626 /* Should not reach here, unless the peer is broken: send an abort
3628 rxi_CallError(call, RX_PROTOCOL_ERROR);
3629 np = rxi_SendCallAbort(call, np, 1, 0);
3632 /* Note when this last legitimate packet was received, for keep-alive
3633 * processing. Note, we delay getting the time until now in the hope that
3634 * the packet will be delivered to the user before any get time is required
3635 * (if not, then the time won't actually be re-evaluated here). */
3636 call->lastReceiveTime = clock_Sec();
3637 MUTEX_EXIT(&call->lock);
3638 putConnection(conn);
3642 /* return true if this is an "interesting" connection from the point of view
3643 of someone trying to debug the system */
3645 rxi_IsConnInteresting(struct rx_connection *aconn)
3648 struct rx_call *tcall;
3650 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3653 for (i = 0; i < RX_MAXCALLS; i++) {
3654 tcall = aconn->call[i];
3656 if ((tcall->state == RX_STATE_PRECALL)
3657 || (tcall->state == RX_STATE_ACTIVE))
3659 if ((tcall->app.mode == RX_MODE_SENDING)
3660 || (tcall->app.mode == RX_MODE_RECEIVING))
3668 /* if this is one of the last few packets AND it wouldn't be used by the
3669 receiving call to immediately satisfy a read request, then drop it on
3670 the floor, since accepting it might prevent a lock-holding thread from
3671 making progress in its reading. If a call has been cleared while in
3672 the precall state then ignore all subsequent packets until the call
3673 is assigned to a thread. */
3676 TooLow(struct rx_packet *ap, struct rx_call *acall)
3680 MUTEX_ENTER(&rx_quota_mutex);
3681 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3682 && (acall->state == RX_STATE_PRECALL))
3683 || ((rx_nFreePackets < rxi_dataQuota + 2)
3684 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3685 && (acall->flags & RX_CALL_READER_WAIT)))) {
3688 MUTEX_EXIT(&rx_quota_mutex);
3694 * Clear the attach wait flag on a connection and proceed.
3696 * Any processing waiting for a connection to be attached should be
3697 * unblocked. We clear the flag and do any other needed tasks.
3700 * the conn to unmark waiting for attach
3702 * @pre conn's conn_data_lock must be locked before calling this function
3706 rxi_ConnClearAttachWait(struct rx_connection *conn)
3708 /* Indicate that rxi_CheckReachEvent is no longer running by
3709 * clearing the flag. Must be atomic under conn_data_lock to
3710 * avoid a new call slipping by: rxi_CheckConnReach holds
3711 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3713 conn->flags &= ~RX_CONN_ATTACHWAIT;
3714 if (conn->flags & RX_CONN_NAT_PING) {
3715 conn->flags &= ~RX_CONN_NAT_PING;
3716 rxi_ScheduleNatKeepAliveEvent(conn);
3721 * Event handler function for connection-specific events for checking
3722 * reachability. Also called directly from main code with |event| == NULL
3723 * in order to trigger the initial reachability check.
3725 * When |event| == NULL, must be called with the connection data lock held,
3726 * but returns with the lock unlocked.
3729 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2, int dummy)
3731 struct rx_connection *conn = arg1;
3732 struct rx_call *acall = arg2;
3733 struct rx_call *call = acall;
3734 struct clock when, now;
3738 MUTEX_ENTER(&conn->conn_data_lock);
3740 MUTEX_ASSERT(&conn->conn_data_lock);
3742 if (event != NULL && event == conn->checkReachEvent)
3743 rxevent_Put(&conn->checkReachEvent);
3744 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3745 MUTEX_EXIT(&conn->conn_data_lock);
3749 MUTEX_ENTER(&conn->conn_call_lock);
3750 MUTEX_ENTER(&conn->conn_data_lock);
3751 for (i = 0; i < RX_MAXCALLS; i++) {
3752 struct rx_call *tc = conn->call[i];
3753 if (tc && tc->state == RX_STATE_PRECALL) {
3759 rxi_ConnClearAttachWait(conn);
3760 MUTEX_EXIT(&conn->conn_data_lock);
3761 MUTEX_EXIT(&conn->conn_call_lock);
3766 MUTEX_ENTER(&call->lock);
3767 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3769 MUTEX_EXIT(&call->lock);
3771 clock_GetTime(&now);
3773 when.sec += RX_CHECKREACH_TIMEOUT;
3774 MUTEX_ENTER(&conn->conn_data_lock);
3775 if (!conn->checkReachEvent) {
3776 rx_GetConnection(conn);
3777 conn->checkReachEvent = rxevent_Post(&when, &now,
3778 rxi_CheckReachEvent, conn,
3781 MUTEX_EXIT(&conn->conn_data_lock);
3784 /* If fired as an event handler, drop our refcount on the connection. */
3786 putConnection(conn);
3790 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3792 struct rx_service *service = conn->service;
3793 struct rx_peer *peer = conn->peer;
3794 afs_uint32 now, lastReach;
3796 if (service->checkReach == 0)
3800 MUTEX_ENTER(&peer->peer_lock);
3801 lastReach = peer->lastReachTime;
3802 MUTEX_EXIT(&peer->peer_lock);
3803 if (now - lastReach < RX_CHECKREACH_TTL)
3806 MUTEX_ENTER(&conn->conn_data_lock);
3807 if (conn->flags & RX_CONN_ATTACHWAIT) {
3808 MUTEX_EXIT(&conn->conn_data_lock);
3811 conn->flags |= RX_CONN_ATTACHWAIT;
3812 if (conn->checkReachEvent == NULL) {
3813 /* rxi_CheckReachEvent(NULL, ...) will drop the lock. */
3814 rxi_CheckReachEvent(NULL, conn, call, 0);
3816 MUTEX_EXIT(&conn->conn_data_lock);
3822 /* try to attach call, if authentication is complete */
3824 TryAttach(struct rx_call *acall, osi_socket socket,
3825 int *tnop, struct rx_call **newcallp,
3826 int reachOverride, int istack)
3828 struct rx_connection *conn = acall->conn;
3830 if (conn->type == RX_SERVER_CONNECTION
3831 && acall->state == RX_STATE_PRECALL) {
3832 /* Don't attach until we have any req'd. authentication. */
3833 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3834 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3835 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3836 /* Note: this does not necessarily succeed; there
3837 * may not any proc available
3841 code = rxi_ChallengeOn(acall->conn);
3844 * Ideally we would rxi_ConnectionError here, but doing that is
3845 * difficult, because some callers may have locked 'call',
3846 * _and_ another call on the same conn. So we cannot
3847 * rxi_ConnectionError, since that needs to lock every call on
3848 * the conn. But we can at least abort the call we have.
3850 rxi_CallError(acall, code);
3851 rxi_SendCallAbort(acall, NULL, istack, 0);
3857 /* A data packet has been received off the interface. This packet is
3858 * appropriate to the call (the call is in the right state, etc.). This
3859 * routine can return a packet to the caller, for re-use */
3861 static struct rx_packet *
3862 rxi_ReceiveDataPacket(struct rx_call *call,
3863 struct rx_packet *np, int istack,
3864 osi_socket socket, afs_uint32 host, u_short port,
3865 int *tnop, struct rx_call **newcallp)
3867 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3872 afs_uint32 serial=0, flags=0;
3874 struct rx_packet *tnp;
3875 if (rx_stats_active)
3876 rx_atomic_inc(&rx_stats.dataPacketsRead);
3879 /* If there are no packet buffers, drop this new packet, unless we can find
3880 * packet buffers from inactive calls */
3882 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3883 MUTEX_ENTER(&rx_freePktQ_lock);
3884 rxi_NeedMorePackets = TRUE;
3885 MUTEX_EXIT(&rx_freePktQ_lock);
3886 if (rx_stats_active)
3887 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3888 rxi_calltrace(RX_TRACE_DROP, call);
3889 dpf(("packet %p dropped on receipt - quota problems\n", np));
3890 /* We used to clear the receive queue here, in an attempt to free
3891 * packets. However this is unsafe if the queue has received a
3892 * soft ACK for the final packet */
3893 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
3899 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3900 * packet is one of several packets transmitted as a single
3901 * datagram. Do not send any soft or hard acks until all packets
3902 * in a jumbogram have been processed. Send negative acks right away.
3904 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3905 /* tnp is non-null when there are more packets in the
3906 * current jumbo gram */
3913 seq = np->header.seq;
3914 serial = np->header.serial;
3915 flags = np->header.flags;
3917 /* If the call is in an error state, send an abort message */
3919 return rxi_SendCallAbort(call, np, istack, 0);
3921 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3922 * AFS 3.5 jumbogram. */
3923 if (flags & RX_JUMBO_PACKET) {
3924 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3929 if (np->header.spare != 0) {
3930 MUTEX_ENTER(&call->conn->conn_data_lock);
3931 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3932 MUTEX_EXIT(&call->conn->conn_data_lock);
3935 /* The usual case is that this is the expected next packet */
3936 if (seq == call->rnext) {
3938 /* Check to make sure it is not a duplicate of one already queued */
3939 if (!opr_queue_IsEmpty(&call->rq)
3940 && opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq == seq) {
3941 if (rx_stats_active)
3942 rx_atomic_inc(&rx_stats.dupPacketsRead);
3943 dpf(("packet %p dropped on receipt - duplicate\n", np));
3944 rxi_CancelDelayedAckEvent(call);
3945 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3951 /* It's the next packet. Stick it on the receive queue
3952 * for this call. Set newPackets to make sure we wake
3953 * the reader once all packets have been processed */
3954 #ifdef RX_TRACK_PACKETS
3955 np->flags |= RX_PKTFLAG_RQ;
3957 opr_queue_Prepend(&call->rq, &np->entry);
3958 #ifdef RXDEBUG_PACKET
3960 #endif /* RXDEBUG_PACKET */
3962 np = NULL; /* We can't use this anymore */
3965 /* If an ack is requested then set a flag to make sure we
3966 * send an acknowledgement for this packet */
3967 if (flags & RX_REQUEST_ACK) {
3968 ackNeeded = RX_ACK_REQUESTED;
3971 /* Keep track of whether we have received the last packet */
3972 if (flags & RX_LAST_PACKET) {
3973 call->flags |= RX_CALL_HAVE_LAST;
3977 /* Check whether we have all of the packets for this call */
3978 if (call->flags & RX_CALL_HAVE_LAST) {
3979 afs_uint32 tseq; /* temporary sequence number */
3980 struct opr_queue *cursor;
3982 for (tseq = seq, opr_queue_Scan(&call->rq, cursor)) {
3983 struct rx_packet *tp;
3985 tp = opr_queue_Entry(cursor, struct rx_packet, entry);
3986 if (tseq != tp->header.seq)
3988 if (tp->header.flags & RX_LAST_PACKET) {
3989 call->flags |= RX_CALL_RECEIVE_DONE;
3996 /* Provide asynchronous notification for those who want it
3997 * (e.g. multi rx) */
3998 if (call->arrivalProc) {
3999 (*call->arrivalProc) (call, call->arrivalProcHandle,
4000 call->arrivalProcArg);
4001 call->arrivalProc = NULL;
4004 /* Update last packet received */
4007 /* If there is no server process serving this call, grab
4008 * one, if available. We only need to do this once. If a
4009 * server thread is available, this thread becomes a server
4010 * thread and the server thread becomes a listener thread. */
4012 TryAttach(call, socket, tnop, newcallp, 0, istack);
4015 /* This is not the expected next packet. */
4017 /* Determine whether this is a new or old packet, and if it's
4018 * a new one, whether it fits into the current receive window.
4019 * Also figure out whether the packet was delivered in sequence.
4020 * We use the prev variable to determine whether the new packet
4021 * is the successor of its immediate predecessor in the
4022 * receive queue, and the missing flag to determine whether
4023 * any of this packets predecessors are missing. */
4025 afs_uint32 prev; /* "Previous packet" sequence number */
4026 struct opr_queue *cursor;
4027 int missing; /* Are any predecessors missing? */
4029 /* If the new packet's sequence number has been sent to the
4030 * application already, then this is a duplicate */
4031 if (seq < call->rnext) {
4032 if (rx_stats_active)
4033 rx_atomic_inc(&rx_stats.dupPacketsRead);
4034 rxi_CancelDelayedAckEvent(call);
4035 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
4041 /* If the sequence number is greater than what can be
4042 * accomodated by the current window, then send a negative
4043 * acknowledge and drop the packet */
4044 if ((call->rnext + call->rwind) <= seq) {
4045 rxi_CancelDelayedAckEvent(call);
4046 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
4053 /* Look for the packet in the queue of old received packets */
4054 prev = call->rnext - 1;
4056 for (opr_queue_Scan(&call->rq, cursor)) {
4057 struct rx_packet *tp
4058 = opr_queue_Entry(cursor, struct rx_packet, entry);
4060 /*Check for duplicate packet */
4061 if (seq == tp->header.seq) {
4062 if (rx_stats_active)
4063 rx_atomic_inc(&rx_stats.dupPacketsRead);
4064 rxi_CancelDelayedAckEvent(call);
4065 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
4071 /* If we find a higher sequence packet, break out and
4072 * insert the new packet here. */
4073 if (seq < tp->header.seq)
4075 /* Check for missing packet */
4076 if (tp->header.seq != prev + 1) {
4080 prev = tp->header.seq;
4083 /* Keep track of whether we have received the last packet. */
4084 if (flags & RX_LAST_PACKET) {
4085 call->flags |= RX_CALL_HAVE_LAST;
4088 /* It's within the window: add it to the the receive queue.
4089 * tp is left by the previous loop either pointing at the
4090 * packet before which to insert the new packet, or at the
4091 * queue head if the queue is empty or the packet should be
4093 #ifdef RX_TRACK_PACKETS
4094 np->flags |= RX_PKTFLAG_RQ;
4096 #ifdef RXDEBUG_PACKET
4098 #endif /* RXDEBUG_PACKET */
4099 opr_queue_InsertBefore(cursor, &np->entry);
4103 /* Check whether we have all of the packets for this call */
4104 if ((call->flags & RX_CALL_HAVE_LAST)
4105 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
4106 afs_uint32 tseq; /* temporary sequence number */
4109 for (opr_queue_Scan(&call->rq, cursor)) {
4110 struct rx_packet *tp
4111 = opr_queue_Entry(cursor, struct rx_packet, entry);
4112 if (tseq != tp->header.seq)
4114 if (tp->header.flags & RX_LAST_PACKET) {
4115 call->flags |= RX_CALL_RECEIVE_DONE;
4122 /* We need to send an ack of the packet is out of sequence,
4123 * or if an ack was requested by the peer. */
4124 if (seq != prev + 1 || missing) {
4125 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
4126 } else if (flags & RX_REQUEST_ACK) {
4127 ackNeeded = RX_ACK_REQUESTED;
4130 /* Acknowledge the last packet for each call */
4131 if (flags & RX_LAST_PACKET) {
4142 * If the receiver is waiting for an iovec, fill the iovec
4143 * using the data from the receive queue */
4144 if (call->flags & RX_CALL_IOVEC_WAIT) {
4145 didHardAck = rxi_FillReadVec(call, serial);
4146 /* the call may have been aborted */
4155 /* Wakeup the reader if any */
4156 if ((call->flags & RX_CALL_READER_WAIT)
4157 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
4158 || (call->iovNext >= call->iovMax)
4159 || (call->flags & RX_CALL_RECEIVE_DONE))) {
4160 call->flags &= ~RX_CALL_READER_WAIT;
4161 #ifdef RX_ENABLE_LOCKS
4162 CV_BROADCAST(&call->cv_rq);
4164 osi_rxWakeup(&call->rq);
4170 * Send an ack when requested by the peer, or once every
4171 * rxi_SoftAckRate packets until the last packet has been
4172 * received. Always send a soft ack for the last packet in
4173 * the server's reply. */
4175 rxi_CancelDelayedAckEvent(call);
4176 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
4177 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
4178 rxi_CancelDelayedAckEvent(call);
4179 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
4180 } else if (call->nSoftAcks) {
4181 if (haveLast && !(flags & RX_CLIENT_INITIATED))
4182 rxi_PostDelayedAckEvent(call, &rx_lastAckDelay);
4184 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
4185 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
4186 rxi_CancelDelayedAckEvent(call);
4193 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall,
4196 struct rx_peer *peer = conn->peer;
4198 MUTEX_ENTER(&peer->peer_lock);
4199 peer->lastReachTime = clock_Sec();
4200 MUTEX_EXIT(&peer->peer_lock);
4202 MUTEX_ENTER(&conn->conn_data_lock);
4203 if (conn->flags & RX_CONN_ATTACHWAIT) {
4206 rxi_ConnClearAttachWait(conn);
4207 MUTEX_EXIT(&conn->conn_data_lock);
4209 for (i = 0; i < RX_MAXCALLS; i++) {
4210 struct rx_call *call = conn->call[i];
4213 MUTEX_ENTER(&call->lock);
4214 /* tnop can be null if newcallp is null */
4215 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1, istack);
4217 MUTEX_EXIT(&call->lock);
4221 MUTEX_EXIT(&conn->conn_data_lock);
4224 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
4226 rx_ack_reason(int reason)
4229 case RX_ACK_REQUESTED:
4231 case RX_ACK_DUPLICATE:
4233 case RX_ACK_OUT_OF_SEQUENCE:
4235 case RX_ACK_EXCEEDS_WINDOW:
4237 case RX_ACK_NOSPACE:
4241 case RX_ACK_PING_RESPONSE:
4254 /* The real smarts of the whole thing. */
4255 static struct rx_packet *
4256 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
4259 struct rx_ackPacket *ap;
4261 struct rx_packet *tp;
4262 struct rx_connection *conn = call->conn;
4263 struct rx_peer *peer = conn->peer;
4264 struct opr_queue *cursor;
4265 struct clock now; /* Current time, for RTT calculations */
4273 int newAckCount = 0;
4274 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
4275 int pktsize = 0; /* Set if we need to update the peer mtu */
4276 int conn_data_locked = 0;
4278 if (rx_stats_active)
4279 rx_atomic_inc(&rx_stats.ackPacketsRead);
4280 ap = (struct rx_ackPacket *)rx_DataOf(np);
4281 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
4283 return np; /* truncated ack packet */
4285 /* depends on ack packet struct */
4286 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
4287 first = ntohl(ap->firstPacket);
4288 prev = ntohl(ap->previousPacket);
4289 serial = ntohl(ap->serial);
4292 * Ignore ack packets received out of order while protecting
4293 * against peers that set the previousPacket field to a packet
4294 * serial number instead of a sequence number.
4296 if (first < call->tfirst ||
4297 (first == call->tfirst && prev < call->tprev && prev < call->tfirst
4304 if (np->header.flags & RX_SLOW_START_OK) {
4305 call->flags |= RX_CALL_SLOW_START_OK;
4308 if (ap->reason == RX_ACK_PING_RESPONSE)
4309 rxi_UpdatePeerReach(conn, call, istack);
4311 if (conn->lastPacketSizeSeq) {
4312 MUTEX_ENTER(&conn->conn_data_lock);
4313 conn_data_locked = 1;
4314 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
4315 pktsize = conn->lastPacketSize;
4316 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
4319 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
4320 if (!conn_data_locked) {
4321 MUTEX_ENTER(&conn->conn_data_lock);
4322 conn_data_locked = 1;
4324 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
4325 /* process mtu ping ack */
4326 pktsize = conn->lastPingSize;
4327 conn->lastPingSizeSer = conn->lastPingSize = 0;
4331 if (conn_data_locked) {
4332 MUTEX_EXIT(&conn->conn_data_lock);
4333 conn_data_locked = 0;
4337 if (rxdebug_active) {
4341 len = _snprintf(msg, sizeof(msg),
4342 "tid[%d] RACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
4343 GetCurrentThreadId(), rx_ack_reason(ap->reason),
4344 ntohl(ap->serial), ntohl(ap->previousPacket),
4345 (unsigned int)np->header.seq, ntohl(ap->firstPacket),
4346 ap->nAcks, ntohs(ap->bufferSpace) );
4350 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
4351 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4355 OutputDebugString(msg);
4357 #else /* AFS_NT40_ENV */
4360 "RACK: reason %x previous %u seq %u serial %u first %u",
4361 ap->reason, ntohl(ap->previousPacket),
4362 (unsigned int)np->header.seq, (unsigned int)serial,
4363 ntohl(ap->firstPacket));
4366 for (offset = 0; offset < nAcks; offset++)
4367 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4372 #endif /* AFS_NT40_ENV */
4375 MUTEX_ENTER(&peer->peer_lock);
4378 * Start somewhere. Can't assume we can send what we can receive,
4379 * but we are clearly receiving.
4381 if (!peer->maxPacketSize)
4382 peer->maxPacketSize = RX_MIN_PACKET_SIZE - RX_HEADER_SIZE;
4384 if (pktsize > peer->maxPacketSize) {
4385 peer->maxPacketSize = pktsize;
4386 if ((pktsize + RX_HEADER_SIZE > peer->ifMTU)) {
4387 peer->ifMTU = pktsize + RX_HEADER_SIZE;
4388 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4389 rxi_ScheduleGrowMTUEvent(call, 1);
4394 clock_GetTime(&now);
4396 /* The transmit queue splits into 4 sections.
4398 * The first section is packets which have now been acknowledged
4399 * by a window size change in the ack. These have reached the
4400 * application layer, and may be discarded. These are packets
4401 * with sequence numbers < ap->firstPacket.
4403 * The second section is packets which have sequence numbers in
4404 * the range ap->firstPacket to ap->firstPacket + ap->nAcks. The
4405 * contents of the packet's ack array determines whether these
4406 * packets are acknowledged or not.
4408 * The third section is packets which fall above the range
4409 * addressed in the ack packet. These have not yet been received
4412 * The four section is packets which have not yet been transmitted.
4413 * These packets will have a header.serial of 0.
4416 /* First section - implicitly acknowledged packets that can be
4420 tp = opr_queue_First(&call->tq, struct rx_packet, entry);
4421 while(!opr_queue_IsEnd(&call->tq, &tp->entry) && tp->header.seq < first) {
4422 struct rx_packet *next;
4424 next = opr_queue_Next(&tp->entry, struct rx_packet, entry);
4425 call->tfirst = tp->header.seq + 1;
4427 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4429 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4432 #ifdef RX_ENABLE_LOCKS
4433 /* XXX Hack. Because we have to release the global call lock when sending
4434 * packets (rxi_NetSend) we drop all acks while we're traversing the tq
4435 * in rxi_Start sending packets out because packets may move to the
4436 * freePacketQueue as result of being here! So we drop these packets until
4437 * we're safely out of the traversing. Really ugly!
4438 * To make it even uglier, if we're using fine grain locking, we can
4439 * set the ack bits in the packets and have rxi_Start remove the packets
4440 * when it's done transmitting.
4442 if (call->flags & RX_CALL_TQ_BUSY) {
4443 tp->flags |= RX_PKTFLAG_ACKED;
4444 call->flags |= RX_CALL_TQ_SOME_ACKED;
4446 #endif /* RX_ENABLE_LOCKS */
4448 opr_queue_Remove(&tp->entry);
4449 #ifdef RX_TRACK_PACKETS
4450 tp->flags &= ~RX_PKTFLAG_TQ;
4452 #ifdef RXDEBUG_PACKET
4454 #endif /* RXDEBUG_PACKET */
4455 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4460 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
4462 /* Second section of the queue - packets for which we are receiving
4465 * Go through the explicit acks/nacks and record the results in
4466 * the waiting packets. These are packets that can't be released
4467 * yet, even with a positive acknowledge. This positive
4468 * acknowledge only means the packet has been received by the
4469 * peer, not that it will be retained long enough to be sent to
4470 * the peer's upper level. In addition, reset the transmit timers
4471 * of any missing packets (those packets that must be missing
4472 * because this packet was out of sequence) */
4474 call->nSoftAcked = 0;
4476 while (!opr_queue_IsEnd(&call->tq, &tp->entry)
4477 && tp->header.seq < first + nAcks) {
4478 /* Set the acknowledge flag per packet based on the
4479 * information in the ack packet. An acknowlegded packet can
4480 * be downgraded when the server has discarded a packet it
4481 * soacked previously, or when an ack packet is received
4482 * out of sequence. */
4483 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4484 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4486 tp->flags |= RX_PKTFLAG_ACKED;
4487 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4494 } else /* RX_ACK_TYPE_NACK */ {
4495 tp->flags &= ~RX_PKTFLAG_ACKED;
4499 tp = opr_queue_Next(&tp->entry, struct rx_packet, entry);
4502 /* We don't need to take any action with the 3rd or 4th section in the
4503 * queue - they're not addressed by the contents of this ACK packet.
4506 /* if the ack packet has a receivelen field hanging off it,
4507 * update our state */
4508 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4511 /* If the ack packet has a "recommended" size that is less than
4512 * what I am using now, reduce my size to match */
4513 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4514 (int)sizeof(afs_int32), &tSize);
4515 tSize = (afs_uint32) ntohl(tSize);
4516 if (tSize > RX_MAX_PACKET_SIZE)
4517 tSize = RX_MAX_PACKET_SIZE;
4518 if (tSize < RX_MIN_PACKET_SIZE)
4519 tSize = RX_MIN_PACKET_SIZE;
4520 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4522 /* Get the maximum packet size to send to this peer */
4523 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4525 tSize = (afs_uint32) ntohl(tSize);
4526 if (tSize > RX_MAX_PACKET_SIZE)
4527 tSize = RX_MAX_PACKET_SIZE;
4528 if (tSize < RX_MIN_PACKET_SIZE)
4529 tSize = RX_MIN_PACKET_SIZE;
4530 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4531 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4533 /* sanity check - peer might have restarted with different params.
4534 * If peer says "send less", dammit, send less... Peer should never
4535 * be unable to accept packets of the size that prior AFS versions would
4536 * send without asking. */
4537 if (peer->maxMTU != tSize) {
4538 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4540 peer->maxMTU = tSize;
4541 peer->MTU = MIN(tSize, peer->MTU);
4542 call->MTU = MIN(call->MTU, tSize);
4545 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4548 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4549 (int)sizeof(afs_int32), &tSize);
4550 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4553 if (tSize >= rx_maxSendWindow)
4554 tSize = rx_maxSendWindow;
4555 if (tSize < call->twind) { /* smaller than our send */
4556 call->twind = tSize; /* window, we must send less... */
4557 call->ssthresh = MIN(call->twind, call->ssthresh);
4558 call->conn->twind[call->channel] = call->twind;
4561 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4562 * network MTU confused with the loopback MTU. Calculate the
4563 * maximum MTU here for use in the slow start code below.
4565 /* Did peer restart with older RX version? */
4566 if (peer->maxDgramPackets > 1) {
4567 peer->maxDgramPackets = 1;
4569 } else if (np->length >=
4570 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4573 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4574 sizeof(afs_int32), &tSize);
4575 tSize = (afs_uint32) ntohl(tSize);
4578 if (tSize >= rx_maxSendWindow)
4579 tSize = rx_maxSendWindow;
4581 * As of AFS 3.5 we set the send window to match the receive window.
4583 if (tSize < call->twind) {
4584 call->twind = tSize;
4585 call->conn->twind[call->channel] = call->twind;
4586 call->ssthresh = MIN(call->twind, call->ssthresh);
4587 } else if (tSize > call->twind) {
4588 call->twind = tSize;
4589 call->conn->twind[call->channel] = call->twind;
4593 * As of AFS 3.5, a jumbogram is more than one fixed size
4594 * packet transmitted in a single UDP datagram. If the remote
4595 * MTU is smaller than our local MTU then never send a datagram
4596 * larger than the natural MTU.
4599 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4600 (int)sizeof(afs_int32), &tSize);
4601 maxDgramPackets = (afs_uint32) ntohl(tSize);
4602 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4604 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4605 if (maxDgramPackets > 1) {
4606 peer->maxDgramPackets = maxDgramPackets;
4607 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4609 peer->maxDgramPackets = 1;
4610 call->MTU = peer->natMTU;
4612 } else if (peer->maxDgramPackets > 1) {
4613 /* Restarted with lower version of RX */
4614 peer->maxDgramPackets = 1;
4616 } else if (peer->maxDgramPackets > 1
4617 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4618 /* Restarted with lower version of RX */
4619 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4620 peer->natMTU = OLD_MAX_PACKET_SIZE;
4621 peer->MTU = OLD_MAX_PACKET_SIZE;
4622 peer->maxDgramPackets = 1;
4623 peer->nDgramPackets = 1;
4625 call->MTU = OLD_MAX_PACKET_SIZE;
4628 /* If the window has been extended by this acknowledge packet,
4629 * then wakeup a sender waiting in alloc for window space, or try
4630 * sending packets now, if he's been sitting on packets due to
4631 * lack of window space */
4632 if (call->tnext < (call->tfirst + call->twind)) {
4633 #ifdef RX_ENABLE_LOCKS
4634 CV_SIGNAL(&call->cv_twind);
4636 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4637 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4638 osi_rxWakeup(&call->twind);
4641 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4642 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4648 * Calculate how many datagrams were successfully received after
4649 * the first missing packet and adjust the negative ack counter
4654 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4655 if (call->nNacks < nNacked) {
4656 call->nNacks = nNacked;
4659 call->nAcks += newAckCount;
4663 /* If the packet contained new acknowledgements, rather than just
4664 * being a duplicate of one we have previously seen, then we can restart
4667 if (newAckCount > 0)
4668 rxi_rto_packet_acked(call, istack);
4670 if (call->flags & RX_CALL_FAST_RECOVER) {
4671 if (newAckCount == 0) {
4672 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4674 call->flags &= ~RX_CALL_FAST_RECOVER;
4675 call->cwind = call->nextCwind;
4676 call->nextCwind = 0;
4679 call->nCwindAcks = 0;
4680 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4681 /* Three negative acks in a row trigger congestion recovery */
4682 call->flags |= RX_CALL_FAST_RECOVER;
4683 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4685 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4686 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4687 call->nextCwind = call->ssthresh;
4690 peer->MTU = call->MTU;
4691 peer->cwind = call->nextCwind;
4692 peer->nDgramPackets = call->nDgramPackets;
4694 call->congestSeq = peer->congestSeq;
4696 /* Reset the resend times on the packets that were nacked
4697 * so we will retransmit as soon as the window permits
4701 for (opr_queue_ScanBackwards(&call->tq, cursor)) {
4702 struct rx_packet *tp =
4703 opr_queue_Entry(cursor, struct rx_packet, entry);
4705 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4706 tp->flags &= ~RX_PKTFLAG_SENT;
4708 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4713 /* If cwind is smaller than ssthresh, then increase
4714 * the window one packet for each ack we receive (exponential
4716 * If cwind is greater than or equal to ssthresh then increase
4717 * the congestion window by one packet for each cwind acks we
4718 * receive (linear growth). */
4719 if (call->cwind < call->ssthresh) {
4721 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4722 call->nCwindAcks = 0;
4724 call->nCwindAcks += newAckCount;
4725 if (call->nCwindAcks >= call->cwind) {
4726 call->nCwindAcks = 0;
4727 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4731 * If we have received several acknowledgements in a row then
4732 * it is time to increase the size of our datagrams
4734 if ((int)call->nAcks > rx_nDgramThreshold) {
4735 if (peer->maxDgramPackets > 1) {
4736 if (call->nDgramPackets < peer->maxDgramPackets) {
4737 call->nDgramPackets++;
4739 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4740 } else if (call->MTU < peer->maxMTU) {
4741 /* don't upgrade if we can't handle it */
4742 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4743 call->MTU = peer->ifMTU;
4745 call->MTU += peer->natMTU;
4746 call->MTU = MIN(call->MTU, peer->maxMTU);
4753 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4755 /* Servers need to hold the call until all response packets have
4756 * been acknowledged. Soft acks are good enough since clients
4757 * are not allowed to clear their receive queues. */
4758 if (call->state == RX_STATE_HOLD
4759 && call->tfirst + call->nSoftAcked >= call->tnext) {
4760 call->state = RX_STATE_DALLY;
4761 rxi_ClearTransmitQueue(call, 0);
4762 rxi_CancelKeepAliveEvent(call);
4763 } else if (!opr_queue_IsEmpty(&call->tq)) {
4764 rxi_Start(call, istack);
4770 * Schedule a connection abort to be sent after some delay.
4772 * @param[in] conn The connection to send the abort on.
4773 * @param[in] msec The number of milliseconds to wait before sending.
4775 * @pre conn_data_lock must be held
4778 rxi_SendConnectionAbortLater(struct rx_connection *conn, int msec)
4780 struct clock when, now;
4782 MUTEX_ASSERT(&conn->conn_data_lock);
4786 if (!conn->delayedAbortEvent) {
4787 clock_GetTime(&now);
4789 clock_Addmsec(&when, msec);
4790 rx_GetConnection(conn);
4791 conn->delayedAbortEvent =
4792 rxevent_Post(&when, &now, rxi_SendDelayedConnAbort, conn, NULL, 0);
4796 /* Received a response to a challenge packet */
4797 static struct rx_packet *
4798 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4799 struct rx_packet *np, int istack)
4803 /* Ignore the packet if we're the client */
4804 if (conn->type == RX_CLIENT_CONNECTION)
4807 /* If already authenticated, ignore the packet (it's probably a retry) */
4808 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4811 if (!conn->securityChallengeSent) {
4812 /* We've never sent out a challenge for this connection, so this
4813 * response cannot possibly be correct; ignore it. This can happen
4814 * if we sent a challenge to the client, then we were restarted, and
4815 * then the client sent us a response. If we ignore the response, the
4816 * client will eventually resend a data packet, causing us to send a
4817 * new challenge and the client to send a new response. */
4821 /* Otherwise, have the security object evaluate the response packet */
4822 error = RXS_CheckResponse(conn->securityObject, conn, np);
4824 /* If the response is invalid, reset the connection, sending
4825 * an abort to the peer. Send the abort with a 1 second delay,
4826 * to avoid a peer hammering us by constantly recreating a
4827 * connection with bad credentials. */
4828 rxi_ConnectionError(conn, error);
4829 MUTEX_ENTER(&conn->conn_data_lock);
4830 rxi_SendConnectionAbortLater(conn, 1000);
4831 MUTEX_EXIT(&conn->conn_data_lock);
4834 /* If the response is valid, any calls waiting to attach
4835 * servers can now do so */
4838 for (i = 0; i < RX_MAXCALLS; i++) {
4839 struct rx_call *call = conn->call[i];
4841 MUTEX_ENTER(&call->lock);
4842 if (call->state == RX_STATE_PRECALL)
4843 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4844 /* tnop can be null if newcallp is null */
4845 MUTEX_EXIT(&call->lock);
4849 /* Update the peer reachability information, just in case
4850 * some calls went into attach-wait while we were waiting
4851 * for authentication..
4853 rxi_UpdatePeerReach(conn, NULL, istack);
4858 /* A client has received an authentication challenge: the security
4859 * object is asked to cough up a respectable response packet to send
4860 * back to the server. The server is responsible for retrying the
4861 * challenge if it fails to get a response. */
4863 static struct rx_packet *
4864 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4865 struct rx_packet *np, int istack)
4869 /* Ignore the challenge if we're the server */
4870 if (conn->type == RX_SERVER_CONNECTION)
4873 /* Ignore the challenge if the connection is otherwise idle; someone's
4874 * trying to use us as an oracle. */
4875 if (!rxi_HasActiveCalls(conn))
4878 /* Send the security object the challenge packet. It is expected to fill
4879 * in the response. */
4880 error = RXS_GetResponse(conn->securityObject, conn, np);
4882 /* If the security object is unable to return a valid response, reset the
4883 * connection and send an abort to the peer. Otherwise send the response
4884 * packet to the peer connection. */
4886 rxi_ConnectionError(conn, error);
4887 MUTEX_ENTER(&conn->conn_data_lock);
4888 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4889 MUTEX_EXIT(&conn->conn_data_lock);
4891 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4892 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4898 /* Find an available server process to service the current request in
4899 * the given call structure. If one isn't available, queue up this
4900 * call so it eventually gets one */
4902 rxi_AttachServerProc(struct rx_call *call,
4903 osi_socket socket, int *tnop,
4904 struct rx_call **newcallp)
4906 struct rx_serverQueueEntry *sq;
4907 struct rx_service *service = call->conn->service;
4910 /* May already be attached */
4911 if (call->state == RX_STATE_ACTIVE)
4914 MUTEX_ENTER(&rx_serverPool_lock);
4916 haveQuota = QuotaOK(service);
4917 if ((!haveQuota) || opr_queue_IsEmpty(&rx_idleServerQueue)) {
4918 /* If there are no processes available to service this call,
4919 * put the call on the incoming call queue (unless it's
4920 * already on the queue).
4922 #ifdef RX_ENABLE_LOCKS
4924 ReturnToServerPool(service);
4925 #endif /* RX_ENABLE_LOCKS */
4927 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4928 call->flags |= RX_CALL_WAIT_PROC;
4929 rx_atomic_inc(&rx_nWaiting);
4930 rx_atomic_inc(&rx_nWaited);
4931 rxi_calltrace(RX_CALL_ARRIVAL, call);
4932 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4933 opr_queue_Append(&rx_incomingCallQueue, &call->entry);
4936 sq = opr_queue_Last(&rx_idleServerQueue,
4937 struct rx_serverQueueEntry, entry);
4939 /* If hot threads are enabled, and both newcallp and sq->socketp
4940 * are non-null, then this thread will process the call, and the
4941 * idle server thread will start listening on this threads socket.
4943 opr_queue_Remove(&sq->entry);
4945 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4948 *sq->socketp = socket;
4949 clock_GetTime(&call->startTime);
4950 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4954 if (call->flags & RX_CALL_WAIT_PROC) {
4955 /* Conservative: I don't think this should happen */
4956 call->flags &= ~RX_CALL_WAIT_PROC;
4957 rx_atomic_dec(&rx_nWaiting);
4958 if (opr_queue_IsOnQueue(&call->entry)) {
4959 opr_queue_Remove(&call->entry);
4961 CLEAR_CALL_QUEUE_LOCK(call);
4963 call->state = RX_STATE_ACTIVE;
4964 call->app.mode = RX_MODE_RECEIVING;
4965 #ifdef RX_KERNEL_TRACE
4967 int glockOwner = ISAFS_GLOCK();
4970 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4971 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4977 if (call->flags & RX_CALL_CLEARED) {
4978 /* send an ack now to start the packet flow up again */
4979 call->flags &= ~RX_CALL_CLEARED;
4980 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4982 #ifdef RX_ENABLE_LOCKS
4985 service->nRequestsRunning++;
4986 MUTEX_ENTER(&rx_quota_mutex);
4987 if (service->nRequestsRunning <= service->minProcs)
4990 MUTEX_EXIT(&rx_quota_mutex);
4994 MUTEX_EXIT(&rx_serverPool_lock);
4997 /* Delay the sending of an acknowledge event for a short while, while
4998 * a new call is being prepared (in the case of a client) or a reply
4999 * is being prepared (in the case of a server). Rather than sending
5000 * an ack packet, an ACKALL packet is sent. */
5002 rxi_AckAll(struct rx_call *call)
5004 rxi_SendSpecial(call, call->conn, NULL, RX_PACKET_TYPE_ACKALL,
5006 call->flags |= RX_CALL_ACKALL_SENT;
5010 * Event handler for per-call delayed acks.
5011 * Also called synchronously, with |event| == NULL, to send a "delayed" ack
5015 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused1,
5018 struct rx_call *call = arg1;
5019 #ifdef RX_ENABLE_LOCKS
5021 MUTEX_ENTER(&call->lock);
5022 if (event == call->delayedAckEvent)
5023 rxevent_Put(&call->delayedAckEvent);
5025 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
5027 MUTEX_EXIT(&call->lock);
5028 #else /* RX_ENABLE_LOCKS */
5030 rxevent_Put(&call->delayedAckEvent);
5031 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
5032 #endif /* RX_ENABLE_LOCKS */
5033 /* Release the call reference for the event that fired. */
5035 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
5038 #ifdef RX_ENABLE_LOCKS
5039 /* Set ack in all packets in transmit queue. rxi_Start will deal with
5040 * clearing them out.
5043 rxi_SetAcksInTransmitQueue(struct rx_call *call)
5045 struct opr_queue *cursor;
5048 for (opr_queue_Scan(&call->tq, cursor)) {
5050 = opr_queue_Entry(cursor, struct rx_packet, entry);
5052 p->flags |= RX_PKTFLAG_ACKED;
5057 call->flags |= RX_CALL_TQ_CLEARME;
5058 call->flags |= RX_CALL_TQ_SOME_ACKED;
5061 rxi_rto_cancel(call);
5063 call->tfirst = call->tnext;
5064 call->nSoftAcked = 0;
5066 if (call->flags & RX_CALL_FAST_RECOVER) {
5067 call->flags &= ~RX_CALL_FAST_RECOVER;
5068 call->cwind = call->nextCwind;
5069 call->nextCwind = 0;
5072 CV_SIGNAL(&call->cv_twind);
5074 #endif /* RX_ENABLE_LOCKS */
5077 * Acknowledge the whole transmit queue.
5079 * If we're running without locks, or the transmit queue isn't busy, then
5080 * we can just clear the queue now. Otherwise, we have to mark all of the
5081 * packets as acknowledged, and let rxi_Start clear it later on
5084 rxi_AckAllInTransmitQueue(struct rx_call *call)
5086 #ifdef RX_ENABLE_LOCKS
5087 if (call->flags & RX_CALL_TQ_BUSY) {
5088 rxi_SetAcksInTransmitQueue(call);
5092 rxi_ClearTransmitQueue(call, 0);
5094 /* Clear out the transmit queue for the current call (all packets have
5095 * been received by peer) */
5097 rxi_ClearTransmitQueue(struct rx_call *call, int force)
5099 #ifdef RX_ENABLE_LOCKS
5100 struct opr_queue *cursor;
5101 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
5103 for (opr_queue_Scan(&call->tq, cursor)) {
5105 = opr_queue_Entry(cursor, struct rx_packet, entry);
5107 p->flags |= RX_PKTFLAG_ACKED;
5111 call->flags |= RX_CALL_TQ_CLEARME;
5112 call->flags |= RX_CALL_TQ_SOME_ACKED;
5115 #endif /* RX_ENABLE_LOCKS */
5116 #ifdef RXDEBUG_PACKET
5118 #endif /* RXDEBUG_PACKET */
5119 rxi_FreePackets(0, &call->tq);
5120 rxi_WakeUpTransmitQueue(call);
5121 #ifdef RX_ENABLE_LOCKS
5122 call->flags &= ~RX_CALL_TQ_CLEARME;
5126 rxi_rto_cancel(call);
5127 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
5128 call->nSoftAcked = 0;
5130 if (call->flags & RX_CALL_FAST_RECOVER) {
5131 call->flags &= ~RX_CALL_FAST_RECOVER;
5132 call->cwind = call->nextCwind;
5134 #ifdef RX_ENABLE_LOCKS
5135 CV_SIGNAL(&call->cv_twind);
5137 osi_rxWakeup(&call->twind);
5142 rxi_ClearReceiveQueue(struct rx_call *call)
5144 if (!opr_queue_IsEmpty(&call->rq)) {
5147 count = rxi_FreePackets(0, &call->rq);
5148 rx_packetReclaims += count;
5149 #ifdef RXDEBUG_PACKET
5151 if ( call->rqc != 0 )
5152 dpf(("rxi_ClearReceiveQueue call %p rqc %u != 0\n", call, call->rqc));
5154 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
5156 if (call->state == RX_STATE_PRECALL) {
5157 call->flags |= RX_CALL_CLEARED;
5161 /* Send an abort packet for the specified call */
5162 static struct rx_packet *
5163 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
5164 int istack, int force)
5167 struct clock when, now;
5172 /* Clients should never delay abort messages */
5173 if (rx_IsClientConn(call->conn))
5177 * An opcode that has been deprecated or has yet to be implemented is not
5178 * a misbehavior of the client. Do not punish the client by introducing
5181 if (call->error == RXGEN_OPCODE) {
5183 } else if (call->abortCode != call->error) {
5184 call->abortCode = call->error;
5185 call->abortCount = 0;
5188 if (force || rxi_callAbortThreshhold == 0
5189 || call->abortCount < rxi_callAbortThreshhold) {
5190 rxi_CancelDelayedAbortEvent(call);
5191 error = htonl(call->error);
5195 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5196 (char *)&error, sizeof(error), istack);
5197 } else if (!call->delayedAbortEvent) {
5198 clock_GetTime(&now);
5200 clock_Addmsec(&when, rxi_callAbortDelay);
5201 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
5202 call->delayedAbortEvent =
5203 rxevent_Post(&when, &now, rxi_SendDelayedCallAbort, call, 0, 0);
5209 rxi_CancelDelayedAbortEvent(struct rx_call *call)
5211 MUTEX_ASSERT(&call->lock);
5212 if (rxevent_Cancel(&call->delayedAbortEvent))
5213 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
5216 /* Send an abort packet for the specified connection. Packet is an
5217 * optional pointer to a packet that can be used to send the abort.
5218 * Once the number of abort messages reaches the threshhold, an
5219 * event is scheduled to send the abort. Setting the force flag
5220 * overrides sending delayed abort messages.
5222 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
5223 * to send the abort packet.
5226 rxi_SendConnectionAbort(struct rx_connection *conn,
5227 struct rx_packet *packet, int istack, int force)
5234 /* Clients should never delay abort messages */
5235 if (rx_IsClientConn(conn))
5238 if (force || rxi_connAbortThreshhold == 0
5239 || conn->abortCount < rxi_connAbortThreshhold) {
5241 if (rxevent_Cancel(&conn->delayedAbortEvent))
5242 putConnection(conn);
5243 error = htonl(conn->error);
5245 MUTEX_EXIT(&conn->conn_data_lock);
5247 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5248 RX_PACKET_TYPE_ABORT, (char *)&error,
5249 sizeof(error), istack);
5250 MUTEX_ENTER(&conn->conn_data_lock);
5252 rxi_SendConnectionAbortLater(conn, rxi_connAbortDelay);
5257 /* Associate an error all of the calls owned by a connection. Called
5258 * with error non-zero. This is only for really fatal things, like
5259 * bad authentication responses. The connection itself is set in
5260 * error at this point, so that future packets received will be
5263 rxi_ConnectionError(struct rx_connection *conn,
5269 dpf(("rxi_ConnectionError conn %p error %d\n", conn, error));
5271 MUTEX_ENTER(&conn->conn_data_lock);
5272 if (rxevent_Cancel(&conn->challengeEvent))
5273 putConnection(conn);
5274 if (rxevent_Cancel(&conn->natKeepAliveEvent))
5275 putConnection(conn);
5276 if (rxevent_Cancel(&conn->checkReachEvent)) {
5277 conn->flags &= ~(RX_CONN_ATTACHWAIT|RX_CONN_NAT_PING);
5278 putConnection(conn);
5280 MUTEX_EXIT(&conn->conn_data_lock);
5281 for (i = 0; i < RX_MAXCALLS; i++) {
5282 struct rx_call *call = conn->call[i];
5284 MUTEX_ENTER(&call->lock);
5285 rxi_CallError(call, error);
5286 MUTEX_EXIT(&call->lock);
5289 conn->error = error;
5290 if (rx_stats_active)
5291 rx_atomic_inc(&rx_stats.fatalErrors);
5296 * Interrupt an in-progress call with the specified error and wakeup waiters.
5298 * @param[in] call The call to interrupt
5299 * @param[in] error The error code to send to the peer
5302 rx_InterruptCall(struct rx_call *call, afs_int32 error)
5304 MUTEX_ENTER(&call->lock);
5305 rxi_CallError(call, error);
5306 rxi_SendCallAbort(call, NULL, 0, 1);
5307 MUTEX_EXIT(&call->lock);
5311 rxi_CallError(struct rx_call *call, afs_int32 error)
5313 MUTEX_ASSERT(&call->lock);
5314 dpf(("rxi_CallError call %p error %d call->error %d\n", call, error, call->error));
5316 error = call->error;
5318 #ifdef RX_ENABLE_LOCKS
5319 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
5320 rxi_ResetCall(call, 0);
5323 rxi_ResetCall(call, 0);
5325 call->error = error;
5328 /* Reset various fields in a call structure, and wakeup waiting
5329 * processes. Some fields aren't changed: state & mode are not
5330 * touched (these must be set by the caller), and bufptr, nLeft, and
5331 * nFree are not reset, since these fields are manipulated by
5332 * unprotected macros, and may only be reset by non-interrupting code.
5336 rxi_ResetCall(struct rx_call *call, int newcall)
5339 struct rx_peer *peer;
5340 struct rx_packet *packet;
5342 MUTEX_ASSERT(&call->lock);
5343 dpf(("rxi_ResetCall(call %p, newcall %d)\n", call, newcall));
5345 /* Notify anyone who is waiting for asynchronous packet arrival */
5346 if (call->arrivalProc) {
5347 (*call->arrivalProc) (call, call->arrivalProcHandle,
5348 call->arrivalProcArg);
5349 call->arrivalProc = NULL;
5353 rxi_CancelGrowMTUEvent(call);
5355 if (call->delayedAbortEvent) {
5356 rxi_CancelDelayedAbortEvent(call);
5357 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5359 rxi_SendCallAbort(call, packet, 0, 1);
5360 rxi_FreePacket(packet);
5365 * Update the peer with the congestion information in this call
5366 * so other calls on this connection can pick up where this call
5367 * left off. If the congestion sequence numbers don't match then
5368 * another call experienced a retransmission.
5370 peer = call->conn->peer;
5371 MUTEX_ENTER(&peer->peer_lock);
5373 if (call->congestSeq == peer->congestSeq) {
5374 peer->cwind = MAX(peer->cwind, call->cwind);
5375 peer->MTU = MAX(peer->MTU, call->MTU);
5376 peer->nDgramPackets =
5377 MAX(peer->nDgramPackets, call->nDgramPackets);
5380 call->abortCode = 0;
5381 call->abortCount = 0;
5383 if (peer->maxDgramPackets > 1) {
5384 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
5386 call->MTU = peer->MTU;
5388 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
5389 call->ssthresh = rx_maxSendWindow;
5390 call->nDgramPackets = peer->nDgramPackets;
5391 call->congestSeq = peer->congestSeq;
5392 call->rtt = peer->rtt;
5393 call->rtt_dev = peer->rtt_dev;
5394 clock_Zero(&call->rto);
5395 clock_Addmsec(&call->rto,
5396 MAX(((call->rtt >> 3) + call->rtt_dev), rx_minPeerTimeout) + 200);
5397 MUTEX_EXIT(&peer->peer_lock);
5399 flags = call->flags;
5400 rxi_WaitforTQBusy(call);
5402 rxi_ClearTransmitQueue(call, 1);
5403 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
5404 dpf(("rcall %p has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5408 rxi_ClearReceiveQueue(call);
5409 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
5413 call->twind = call->conn->twind[call->channel];
5414 call->rwind = call->conn->rwind[call->channel];
5415 call->nSoftAcked = 0;
5416 call->nextCwind = 0;
5419 call->nCwindAcks = 0;
5420 call->nSoftAcks = 0;
5421 call->nHardAcks = 0;
5423 call->tfirst = call->rnext = call->tnext = 1;
5426 call->lastAcked = 0;
5427 call->localStatus = call->remoteStatus = 0;
5429 if (flags & RX_CALL_READER_WAIT) {
5430 #ifdef RX_ENABLE_LOCKS
5431 CV_BROADCAST(&call->cv_rq);
5433 osi_rxWakeup(&call->rq);
5436 if (flags & RX_CALL_WAIT_PACKETS) {
5437 MUTEX_ENTER(&rx_freePktQ_lock);
5438 rxi_PacketsUnWait(); /* XXX */
5439 MUTEX_EXIT(&rx_freePktQ_lock);
5441 #ifdef RX_ENABLE_LOCKS
5442 CV_SIGNAL(&call->cv_twind);
5444 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5445 osi_rxWakeup(&call->twind);
5448 if (flags & RX_CALL_WAIT_PROC) {
5449 rx_atomic_dec(&rx_nWaiting);
5451 #ifdef RX_ENABLE_LOCKS
5452 /* The following ensures that we don't mess with any queue while some
5453 * other thread might also be doing so. The call_queue_lock field is
5454 * is only modified under the call lock. If the call is in the process
5455 * of being removed from a queue, the call is not locked until the
5456 * the queue lock is dropped and only then is the call_queue_lock field
5457 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5458 * Note that any other routine which removes a call from a queue has to
5459 * obtain the queue lock before examing the queue and removing the call.
5461 if (call->call_queue_lock) {
5462 MUTEX_ENTER(call->call_queue_lock);
5463 if (opr_queue_IsOnQueue(&call->entry)) {
5464 opr_queue_Remove(&call->entry);
5466 MUTEX_EXIT(call->call_queue_lock);
5467 CLEAR_CALL_QUEUE_LOCK(call);
5469 #else /* RX_ENABLE_LOCKS */
5470 if (opr_queue_IsOnQueue(&call->entry)) {
5471 opr_queue_Remove(&call->entry);
5473 #endif /* RX_ENABLE_LOCKS */
5475 rxi_CancelKeepAliveEvent(call);
5476 rxi_CancelDelayedAckEvent(call);
5479 /* Send an acknowledge for the indicated packet (seq,serial) of the
5480 * indicated call, for the indicated reason (reason). This
5481 * acknowledge will specifically acknowledge receiving the packet, and
5482 * will also specify which other packets for this call have been
5483 * received. This routine returns the packet that was used to the
5484 * caller. The caller is responsible for freeing it or re-using it.
5485 * This acknowledgement also returns the highest sequence number
5486 * actually read out by the higher level to the sender; the sender
5487 * promises to keep around packets that have not been read by the
5488 * higher level yet (unless, of course, the sender decides to abort
5489 * the call altogether). Any of p, seq, serial, pflags, or reason may
5490 * be set to zero without ill effect. That is, if they are zero, they
5491 * will not convey any information.
5492 * NOW there is a trailer field, after the ack where it will safely be
5493 * ignored by mundanes, which indicates the maximum size packet this
5494 * host can swallow. */
5496 struct rx_packet *optionalPacket; use to send ack (or null)
5497 int seq; Sequence number of the packet we are acking
5498 int serial; Serial number of the packet
5499 int pflags; Flags field from packet header
5500 int reason; Reason an acknowledge was prompted
5503 #define RX_ZEROS 1024
5504 static char rx_zeros[RX_ZEROS];
5507 rxi_SendAck(struct rx_call *call,
5508 struct rx_packet *optionalPacket, int serial, int reason,
5511 struct rx_ackPacket *ap;
5512 struct rx_packet *p;
5513 struct opr_queue *cursor;
5516 afs_uint32 padbytes = 0;
5517 #ifdef RX_ENABLE_TSFPQ
5518 struct rx_ts_info_t * rx_ts_info;
5522 * Open the receive window once a thread starts reading packets
5524 if (call->rnext > 1) {
5525 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5528 /* Don't attempt to grow MTU if this is a critical ping */
5529 if (reason == RX_ACK_MTU) {
5530 /* keep track of per-call attempts, if we're over max, do in small
5531 * otherwise in larger? set a size to increment by, decrease
5534 if (call->conn->peer->maxPacketSize &&
5535 (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5537 padbytes = call->conn->peer->maxPacketSize+16;
5539 padbytes = call->conn->peer->maxMTU + 128;
5541 /* do always try a minimum size ping */
5542 padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5544 /* subtract the ack payload */
5545 padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5546 reason = RX_ACK_PING;
5549 call->nHardAcks = 0;
5550 call->nSoftAcks = 0;
5551 if (call->rnext > call->lastAcked)
5552 call->lastAcked = call->rnext;
5556 rx_computelen(p, p->length); /* reset length, you never know */
5557 } /* where that's been... */
5558 #ifdef RX_ENABLE_TSFPQ
5560 RX_TS_INFO_GET(rx_ts_info);
5561 if ((p = rx_ts_info->local_special_packet)) {
5562 rx_computelen(p, p->length);
5563 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5564 rx_ts_info->local_special_packet = p;
5565 } else { /* We won't send the ack, but don't panic. */
5566 return optionalPacket;
5570 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5571 /* We won't send the ack, but don't panic. */
5572 return optionalPacket;
5577 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5580 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5581 #ifndef RX_ENABLE_TSFPQ
5582 if (!optionalPacket)
5585 return optionalPacket;
5587 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5588 if (rx_Contiguous(p) < templ) {
5589 #ifndef RX_ENABLE_TSFPQ
5590 if (!optionalPacket)
5593 return optionalPacket;
5598 /* MTUXXX failing to send an ack is very serious. We should */
5599 /* try as hard as possible to send even a partial ack; it's */
5600 /* better than nothing. */
5601 ap = (struct rx_ackPacket *)rx_DataOf(p);
5602 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5603 ap->reason = reason;
5605 /* The skew computation used to be bogus, I think it's better now. */
5606 /* We should start paying attention to skew. XXX */
5607 ap->serial = htonl(serial);
5608 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
5611 * First packet not yet forwarded to reader. When ACKALL has been
5612 * sent the peer has been told that all received packets will be
5613 * delivered to the reader. The value 'rnext' is used internally
5614 * to refer to the next packet in the receive queue that must be
5615 * delivered to the reader. From the perspective of the peer it
5616 * already has so report the last sequence number plus one if there
5617 * are packets in the receive queue awaiting processing.
5619 if ((call->flags & RX_CALL_ACKALL_SENT) &&
5620 !opr_queue_IsEmpty(&call->rq)) {
5621 ap->firstPacket = htonl(opr_queue_Last(&call->rq, struct rx_packet, entry)->header.seq + 1);
5623 ap->firstPacket = htonl(call->rnext);
5625 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
5627 /* No fear of running out of ack packet here because there can only
5628 * be at most one window full of unacknowledged packets. The window
5629 * size must be constrained to be less than the maximum ack size,
5630 * of course. Also, an ack should always fit into a single packet
5631 * -- it should not ever be fragmented. */
5633 for (opr_queue_Scan(&call->rq, cursor)) {
5634 struct rx_packet *rqp
5635 = opr_queue_Entry(cursor, struct rx_packet, entry);
5637 if (!rqp || !call->rq.next
5638 || (rqp->header.seq > (call->rnext + call->rwind))) {
5639 #ifndef RX_ENABLE_TSFPQ
5640 if (!optionalPacket)
5643 rxi_CallError(call, RX_CALL_DEAD);
5644 return optionalPacket;
5647 while (rqp->header.seq > call->rnext + offset)
5648 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5649 ap->acks[offset++] = RX_ACK_TYPE_ACK;
5651 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5652 #ifndef RX_ENABLE_TSFPQ
5653 if (!optionalPacket)
5656 rxi_CallError(call, RX_CALL_DEAD);
5657 return optionalPacket;
5663 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5665 /* Must zero the 3 octets that rx_AckDataSize skips at the end of the
5668 rx_packetwrite(p, rx_AckDataSize(offset) - 3, 3, rx_zeros);
5670 /* these are new for AFS 3.3 */
5671 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5672 templ = htonl(templ);
5673 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5674 templ = htonl(call->conn->peer->ifMTU);
5675 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5676 sizeof(afs_int32), &templ);
5678 /* new for AFS 3.4 */
5679 templ = htonl(call->rwind);
5680 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5681 sizeof(afs_int32), &templ);
5683 /* new for AFS 3.5 */
5684 templ = htonl(call->conn->peer->ifDgramPackets);
5685 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5686 sizeof(afs_int32), &templ);
5688 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5690 p->header.serviceId = call->conn->serviceId;
5691 p->header.cid = (call->conn->cid | call->channel);
5692 p->header.callNumber = *call->callNumber;
5694 p->header.securityIndex = call->conn->securityIndex;
5695 p->header.epoch = call->conn->epoch;
5696 p->header.type = RX_PACKET_TYPE_ACK;
5697 p->header.flags = RX_SLOW_START_OK;
5698 if (reason == RX_ACK_PING)
5699 p->header.flags |= RX_REQUEST_ACK;
5701 while (padbytes > 0) {
5702 if (padbytes > RX_ZEROS) {
5703 rx_packetwrite(p, p->length, RX_ZEROS, rx_zeros);
5704 p->length += RX_ZEROS;
5705 padbytes -= RX_ZEROS;
5707 rx_packetwrite(p, p->length, padbytes, rx_zeros);
5708 p->length += padbytes;
5713 if (call->conn->type == RX_CLIENT_CONNECTION)
5714 p->header.flags |= RX_CLIENT_INITIATED;
5718 if (rxdebug_active) {
5722 len = _snprintf(msg, sizeof(msg),
5723 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5724 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5725 ntohl(ap->serial), ntohl(ap->previousPacket),
5726 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5727 ap->nAcks, ntohs(ap->bufferSpace) );
5731 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5732 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5736 OutputDebugString(msg);
5738 #else /* AFS_NT40_ENV */
5740 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5741 ap->reason, ntohl(ap->previousPacket),
5742 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5744 for (offset = 0; offset < ap->nAcks; offset++)
5745 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5750 #endif /* AFS_NT40_ENV */
5753 int i, nbytes = p->length;
5755 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5756 if (nbytes <= p->wirevec[i].iov_len) {
5759 savelen = p->wirevec[i].iov_len;
5761 p->wirevec[i].iov_len = nbytes;
5763 rxi_Send(call, p, istack);
5764 p->wirevec[i].iov_len = savelen;
5768 nbytes -= p->wirevec[i].iov_len;
5771 if (rx_stats_active)
5772 rx_atomic_inc(&rx_stats.ackPacketsSent);
5773 #ifndef RX_ENABLE_TSFPQ
5774 if (!optionalPacket)
5777 return optionalPacket; /* Return packet for re-use by caller */
5781 struct rx_packet **list;
5786 /* Send all of the packets in the list in single datagram */
5788 rxi_SendList(struct rx_call *call, struct xmitlist *xmit,
5789 int istack, int moreFlag)
5795 struct rx_connection *conn = call->conn;
5796 struct rx_peer *peer = conn->peer;
5798 MUTEX_ENTER(&peer->peer_lock);
5799 peer->nSent += xmit->len;
5800 if (xmit->resending)
5801 peer->reSends += xmit->len;
5802 MUTEX_EXIT(&peer->peer_lock);
5804 if (rx_stats_active) {
5805 if (xmit->resending)
5806 rx_atomic_add(&rx_stats.dataPacketsReSent, xmit->len);
5808 rx_atomic_add(&rx_stats.dataPacketsSent, xmit->len);
5811 clock_GetTime(&now);
5813 if (xmit->list[xmit->len - 1]->header.flags & RX_LAST_PACKET) {
5817 /* Set the packet flags and schedule the resend events */
5818 /* Only request an ack for the last packet in the list */
5819 for (i = 0; i < xmit->len; i++) {
5820 struct rx_packet *packet = xmit->list[i];
5822 /* Record the time sent */
5823 packet->timeSent = now;
5824 packet->flags |= RX_PKTFLAG_SENT;
5826 /* Ask for an ack on retransmitted packets, on every other packet
5827 * if the peer doesn't support slow start. Ask for an ack on every
5828 * packet until the congestion window reaches the ack rate. */
5829 if (packet->header.serial) {
5832 packet->firstSent = now;
5833 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5834 || (!(call->flags & RX_CALL_SLOW_START_OK)
5835 && (packet->header.seq & 1)))) {
5840 /* Tag this packet as not being the last in this group,
5841 * for the receiver's benefit */
5842 if (i < xmit->len - 1 || moreFlag) {
5843 packet->header.flags |= RX_MORE_PACKETS;
5848 xmit->list[xmit->len - 1]->header.flags |= RX_REQUEST_ACK;
5851 /* Since we're about to send a data packet to the peer, it's
5852 * safe to nuke any scheduled end-of-packets ack */
5853 rxi_CancelDelayedAckEvent(call);
5855 MUTEX_EXIT(&call->lock);
5856 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5857 if (xmit->len > 1) {
5858 rxi_SendPacketList(call, conn, xmit->list, xmit->len, istack);
5860 rxi_SendPacket(call, conn, xmit->list[0], istack);
5862 MUTEX_ENTER(&call->lock);
5863 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5865 /* Tell the RTO calculation engine that we have sent a packet, and
5866 * if it was the last one */
5867 rxi_rto_packet_sent(call, lastPacket, istack);
5869 /* Update last send time for this call (for keep-alive
5870 * processing), and for the connection (so that we can discover
5871 * idle connections) */
5872 conn->lastSendTime = call->lastSendTime = clock_Sec();
5875 /* When sending packets we need to follow these rules:
5876 * 1. Never send more than maxDgramPackets in a jumbogram.
5877 * 2. Never send a packet with more than two iovecs in a jumbogram.
5878 * 3. Never send a retransmitted packet in a jumbogram.
5879 * 4. Never send more than cwind/4 packets in a jumbogram
5880 * We always keep the last list we should have sent so we
5881 * can set the RX_MORE_PACKETS flags correctly.
5885 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5890 struct xmitlist working;
5891 struct xmitlist last;
5893 struct rx_peer *peer = call->conn->peer;
5894 int morePackets = 0;
5896 memset(&last, 0, sizeof(struct xmitlist));
5897 working.list = &list[0];
5899 working.resending = 0;
5901 recovery = call->flags & RX_CALL_FAST_RECOVER;
5903 for (i = 0; i < len; i++) {
5904 /* Does the current packet force us to flush the current list? */
5906 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5907 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5909 /* This sends the 'last' list and then rolls the current working
5910 * set into the 'last' one, and resets the working set */
5913 rxi_SendList(call, &last, istack, 1);
5914 /* If the call enters an error state stop sending, or if
5915 * we entered congestion recovery mode, stop sending */
5917 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5922 working.resending = 0;
5923 working.list = &list[i];
5925 /* Add the current packet to the list if it hasn't been acked.
5926 * Otherwise adjust the list pointer to skip the current packet. */
5927 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5930 if (list[i]->header.serial)
5931 working.resending = 1;
5933 /* Do we need to flush the list? */
5934 if (working.len >= (int)peer->maxDgramPackets
5935 || working.len >= (int)call->nDgramPackets
5936 || working.len >= (int)call->cwind
5937 || list[i]->header.serial
5938 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5940 rxi_SendList(call, &last, istack, 1);
5941 /* If the call enters an error state stop sending, or if
5942 * we entered congestion recovery mode, stop sending */
5944 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5949 working.resending = 0;
5950 working.list = &list[i + 1];
5953 if (working.len != 0) {
5954 osi_Panic("rxi_SendList error");
5956 working.list = &list[i + 1];
5960 /* Send the whole list when the call is in receive mode, when
5961 * the call is in eof mode, when we are in fast recovery mode,
5962 * and when we have the last packet */
5963 /* XXX - The accesses to app.mode aren't safe, as this may be called by
5964 * the listener or event threads
5966 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5967 || (call->flags & RX_CALL_FLUSH)
5968 || (call->flags & RX_CALL_FAST_RECOVER)) {
5969 /* Check for the case where the current list contains
5970 * an acked packet. Since we always send retransmissions
5971 * in a separate packet, we only need to check the first
5972 * packet in the list */
5973 if (working.len > 0 && !(working.list[0]->flags & RX_PKTFLAG_ACKED)) {
5977 rxi_SendList(call, &last, istack, morePackets);
5978 /* If the call enters an error state stop sending, or if
5979 * we entered congestion recovery mode, stop sending */
5981 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5985 rxi_SendList(call, &working, istack, 0);
5987 } else if (last.len > 0) {
5988 rxi_SendList(call, &last, istack, 0);
5989 /* Packets which are in 'working' are not sent by this call */
5994 * Check if the peer for the given call is known to be dead
5996 * If the call's peer appears dead (it has encountered fatal network errors
5997 * since the call started) the call is killed with RX_CALL_DEAD if the call
5998 * is active. Otherwise, we do nothing.
6000 * @param[in] call The call to check
6003 * @retval 0 The call is fine, and we haven't done anything to the call
6004 * @retval nonzero The call's peer appears dead, and the call has been
6005 * terminated if it was active
6007 * @pre call->lock must be locked
6010 rxi_CheckPeerDead(struct rx_call *call)
6012 #ifdef AFS_RXERRQ_ENV
6015 if (call->state == RX_STATE_DALLY) {
6019 peererrs = rx_atomic_read(&call->conn->peer->neterrs);
6020 if (call->neterr_gen < peererrs) {
6021 /* we have received network errors since this call started; kill
6023 if (call->state == RX_STATE_ACTIVE) {
6024 rxi_CallError(call, RX_CALL_DEAD);
6028 if (call->neterr_gen > peererrs) {
6029 /* someone has reset the number of peer errors; set the call error gen
6030 * so we can detect if more errors are encountered */
6031 call->neterr_gen = peererrs;
6038 rxi_Resend(struct rxevent *event, void *arg0, void *arg1, int istack)
6040 struct rx_call *call = arg0;
6041 struct rx_peer *peer;
6042 struct opr_queue *cursor;
6043 struct clock maxTimeout = { 60, 0 };
6045 MUTEX_ENTER(&call->lock);
6047 peer = call->conn->peer;
6049 /* Make sure that the event pointer is removed from the call
6050 * structure, since there is no longer a per-call retransmission
6052 if (event == call->resendEvent)
6053 rxevent_Put(&call->resendEvent);
6055 rxi_CheckPeerDead(call);
6057 if (opr_queue_IsEmpty(&call->tq)) {
6058 /* Nothing to do. This means that we've been raced, and that an
6059 * ACK has come in between when we were triggered, and when we
6060 * actually got to run. */
6064 /* We're in loss recovery */
6065 call->flags |= RX_CALL_FAST_RECOVER;
6067 /* Mark all of the pending packets in the queue as being lost */
6068 for (opr_queue_Scan(&call->tq, cursor)) {
6069 struct rx_packet *p = opr_queue_Entry(cursor, struct rx_packet, entry);
6070 if (!(p->flags & RX_PKTFLAG_ACKED))
6071 p->flags &= ~RX_PKTFLAG_SENT;
6074 /* We're resending, so we double the timeout of the call. This will be
6075 * dropped back down by the first successful ACK that we receive.
6077 * We apply a maximum value here of 60 seconds
6079 clock_Add(&call->rto, &call->rto);
6080 if (clock_Gt(&call->rto, &maxTimeout))
6081 call->rto = maxTimeout;
6083 /* Packet loss is most likely due to congestion, so drop our window size
6084 * and start again from the beginning */
6085 if (peer->maxDgramPackets >1) {
6086 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
6087 call->MTU = MIN(peer->natMTU, peer->maxMTU);
6089 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
6090 call->nDgramPackets = 1;
6092 call->nextCwind = 1;
6095 MUTEX_ENTER(&peer->peer_lock);
6096 peer->MTU = call->MTU;
6097 peer->cwind = call->cwind;
6098 peer->nDgramPackets = 1;
6100 call->congestSeq = peer->congestSeq;
6101 MUTEX_EXIT(&peer->peer_lock);
6103 rxi_Start(call, istack);
6106 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
6107 MUTEX_EXIT(&call->lock);
6110 /* This routine is called when new packets are readied for
6111 * transmission and when retransmission may be necessary, or when the
6112 * transmission window or burst count are favourable. This should be
6113 * better optimized for new packets, the usual case, now that we've
6114 * got rid of queues of send packets. XXXXXXXXXXX */
6116 rxi_Start(struct rx_call *call, int istack)
6118 struct opr_queue *cursor;
6119 #ifdef RX_ENABLE_LOCKS
6120 struct opr_queue *store;
6126 #ifdef RX_ENABLE_LOCKS
6127 if (rx_stats_active)
6128 rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
6133 if (!opr_queue_IsEmpty(&call->tq)) { /* If we have anything to send */
6134 /* Send (or resend) any packets that need it, subject to
6135 * window restrictions and congestion burst control
6136 * restrictions. Ask for an ack on the last packet sent in
6137 * this burst. For now, we're relying upon the window being
6138 * considerably bigger than the largest number of packets that
6139 * are typically sent at once by one initial call to
6140 * rxi_Start. This is probably bogus (perhaps we should ask
6141 * for an ack when we're half way through the current
6142 * window?). Also, for non file transfer applications, this
6143 * may end up asking for an ack for every packet. Bogus. XXXX
6146 * But check whether we're here recursively, and let the other guy
6149 #ifdef RX_ENABLE_LOCKS
6150 if (!(call->flags & RX_CALL_TQ_BUSY)) {
6151 call->flags |= RX_CALL_TQ_BUSY;
6153 #endif /* RX_ENABLE_LOCKS */
6155 #ifdef RX_ENABLE_LOCKS
6156 call->flags &= ~RX_CALL_NEED_START;
6157 #endif /* RX_ENABLE_LOCKS */
6159 maxXmitPackets = MIN(call->twind, call->cwind);
6160 for (opr_queue_Scan(&call->tq, cursor)) {
6162 = opr_queue_Entry(cursor, struct rx_packet, entry);
6164 if (p->flags & RX_PKTFLAG_ACKED) {
6165 /* Since we may block, don't trust this */
6166 if (rx_stats_active)
6167 rx_atomic_inc(&rx_stats.ignoreAckedPacket);
6168 continue; /* Ignore this packet if it has been acknowledged */
6171 /* Turn off all flags except these ones, which are the same
6172 * on each transmission */
6173 p->header.flags &= RX_PRESET_FLAGS;
6175 if (p->header.seq >=
6176 call->tfirst + MIN((int)call->twind,
6177 (int)(call->nSoftAcked +
6179 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
6180 /* Note: if we're waiting for more window space, we can
6181 * still send retransmits; hence we don't return here, but
6182 * break out to schedule a retransmit event */
6183 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
6184 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
6189 /* Transmit the packet if it needs to be sent. */
6190 if (!(p->flags & RX_PKTFLAG_SENT)) {
6191 if (nXmitPackets == maxXmitPackets) {
6192 rxi_SendXmitList(call, call->xmitList,
6193 nXmitPackets, istack);
6196 dpf(("call %d xmit packet %p\n",
6197 *(call->callNumber), p));
6198 call->xmitList[nXmitPackets++] = p;
6200 } /* end of the queue_Scan */
6202 /* xmitList now hold pointers to all of the packets that are
6203 * ready to send. Now we loop to send the packets */
6204 if (nXmitPackets > 0) {
6205 rxi_SendXmitList(call, call->xmitList, nXmitPackets,
6209 #ifdef RX_ENABLE_LOCKS
6211 /* We went into the error state while sending packets. Now is
6212 * the time to reset the call. This will also inform the using
6213 * process that the call is in an error state.
6215 if (rx_stats_active)
6216 rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
6217 call->flags &= ~RX_CALL_TQ_BUSY;
6218 rxi_WakeUpTransmitQueue(call);
6219 rxi_CallError(call, call->error);
6223 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
6225 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
6226 /* Some packets have received acks. If they all have, we can clear
6227 * the transmit queue.
6230 for (opr_queue_ScanSafe(&call->tq, cursor, store)) {
6232 = opr_queue_Entry(cursor, struct rx_packet, entry);
6234 if (p->header.seq < call->tfirst
6235 && (p->flags & RX_PKTFLAG_ACKED)) {
6236 opr_queue_Remove(&p->entry);
6237 #ifdef RX_TRACK_PACKETS
6238 p->flags &= ~RX_PKTFLAG_TQ;
6240 #ifdef RXDEBUG_PACKET
6248 call->flags |= RX_CALL_TQ_CLEARME;
6250 if (call->flags & RX_CALL_TQ_CLEARME)
6251 rxi_ClearTransmitQueue(call, 1);
6252 } while (call->flags & RX_CALL_NEED_START);
6254 * TQ references no longer protected by this flag; they must remain
6255 * protected by the call lock.
6257 call->flags &= ~RX_CALL_TQ_BUSY;
6258 rxi_WakeUpTransmitQueue(call);
6260 call->flags |= RX_CALL_NEED_START;
6262 #endif /* RX_ENABLE_LOCKS */
6264 rxi_rto_cancel(call);
6268 /* Also adjusts the keep alive parameters for the call, to reflect
6269 * that we have just sent a packet (so keep alives aren't sent
6272 rxi_Send(struct rx_call *call, struct rx_packet *p,
6276 struct rx_connection *conn = call->conn;
6278 /* Stamp each packet with the user supplied status */
6279 p->header.userStatus = call->localStatus;
6281 /* Allow the security object controlling this call's security to
6282 * make any last-minute changes to the packet */
6283 code = RXS_SendPacket(conn->securityObject, call, p);
6285 MUTEX_EXIT(&call->lock);
6286 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6287 rxi_ConnectionError(conn, code);
6288 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6289 MUTEX_ENTER(&call->lock);
6293 /* Since we're about to send SOME sort of packet to the peer, it's
6294 * safe to nuke any scheduled end-of-packets ack */
6295 rxi_CancelDelayedAckEvent(call);
6297 /* Actually send the packet, filling in more connection-specific fields */
6298 MUTEX_EXIT(&call->lock);
6299 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6300 rxi_SendPacket(call, conn, p, istack);
6301 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6302 MUTEX_ENTER(&call->lock);
6304 /* Update last send time for this call (for keep-alive
6305 * processing), and for the connection (so that we can discover
6306 * idle connections) */
6307 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6308 (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
6309 (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
6311 conn->lastSendTime = call->lastSendTime = clock_Sec();
6315 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
6316 * that things are fine. Also called periodically to guarantee that nothing
6317 * falls through the cracks (e.g. (error + dally) connections have keepalive
6318 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
6320 * haveCTLock Set if calling from rxi_ReapConnections
6323 rxi_CheckCall(struct rx_call *call, int haveCTLock)
6325 struct rx_connection *conn = call->conn;
6327 afs_uint32 deadTime, idleDeadTime = 0, hardDeadTime = 0;
6328 afs_uint32 fudgeFactor;
6331 int idle_timeout = 0;
6332 afs_int32 clock_diff = 0;
6334 if (rxi_CheckPeerDead(call)) {
6340 /* Large swings in the clock can have a significant impact on
6341 * the performance of RX call processing. Forward clock shifts
6342 * will result in premature event triggering or timeouts.
6343 * Backward shifts can result in calls not completing until
6344 * the clock catches up with the original start clock value.
6346 * If a backward clock shift of more than five minutes is noticed,
6347 * just fail the call.
6349 if (now < call->lastSendTime)
6350 clock_diff = call->lastSendTime - now;
6351 if (now < call->startWait)
6352 clock_diff = MAX(clock_diff, call->startWait - now);
6353 if (now < call->lastReceiveTime)
6354 clock_diff = MAX(clock_diff, call->lastReceiveTime - now);
6355 if (clock_diff > 5 * 60)
6357 if (call->state == RX_STATE_ACTIVE)
6358 rxi_CallError(call, RX_CALL_TIMEOUT);
6362 #ifdef RX_ENABLE_LOCKS
6363 if (call->flags & RX_CALL_TQ_BUSY) {
6364 /* Call is active and will be reset by rxi_Start if it's
6365 * in an error state.
6370 /* RTT + 8*MDEV, rounded up to the next second. */
6371 fudgeFactor = (((afs_uint32) call->rtt >> 3) +
6372 ((afs_uint32) call->rtt_dev << 1) + 1023) >> 10;
6374 deadTime = conn->secondsUntilDead + fudgeFactor;
6375 /* These are computed to the second (+- 1 second). But that's
6376 * good enough for these values, which should be a significant
6377 * number of seconds. */
6378 if (now > (call->lastReceiveTime + deadTime)) {
6379 if (call->state == RX_STATE_ACTIVE) {
6380 cerror = RX_CALL_DEAD;
6383 #ifdef RX_ENABLE_LOCKS
6384 /* Cancel pending events */
6385 rxi_CancelDelayedAckEvent(call);
6386 rxi_rto_cancel(call);
6387 rxi_CancelKeepAliveEvent(call);
6388 rxi_CancelGrowMTUEvent(call);
6389 MUTEX_ENTER(&rx_refcnt_mutex);
6390 /* if rxi_FreeCall returns 1 it has freed the call */
6391 if (call->refCount == 0 &&
6392 rxi_FreeCall(call, haveCTLock))
6394 MUTEX_EXIT(&rx_refcnt_mutex);
6397 MUTEX_EXIT(&rx_refcnt_mutex);
6399 #else /* RX_ENABLE_LOCKS */
6400 rxi_FreeCall(call, 0);
6402 #endif /* RX_ENABLE_LOCKS */
6404 /* Non-active calls are destroyed if they are not responding
6405 * to pings; active calls are simply flagged in error, so the
6406 * attached process can die reasonably gracefully. */
6409 if (conn->idleDeadTime) {
6410 idleDeadTime = conn->idleDeadTime + fudgeFactor;
6414 /* see if we have a non-activity timeout */
6415 if (call->startWait && ((call->startWait + idleDeadTime) < now)) {
6416 if (call->state == RX_STATE_ACTIVE) {
6417 cerror = RX_CALL_TIMEOUT;
6423 if (conn->hardDeadTime) {
6424 hardDeadTime = conn->hardDeadTime + fudgeFactor;
6427 /* see if we have a hard timeout */
6429 && (now > (hardDeadTime + call->startTime.sec))) {
6430 if (call->state == RX_STATE_ACTIVE)
6431 rxi_CallError(call, RX_CALL_TIMEOUT);
6436 if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT && !idle_timeout &&
6437 call->lastReceiveTime) {
6438 int oldMTU = conn->peer->ifMTU;
6440 /* If we thought we could send more, perhaps things got worse.
6441 * Shrink by 128 bytes and try again. */
6442 if (conn->peer->maxPacketSize < conn->lastPacketSize)
6443 /* maxPacketSize will be cleared in rxi_SetPeerMtu */
6444 newmtu = MAX(conn->peer->maxPacketSize + RX_HEADER_SIZE,
6445 conn->lastPacketSize - 128 + RX_HEADER_SIZE);
6447 newmtu = conn->lastPacketSize - 128 + RX_HEADER_SIZE;
6449 /* minimum capped in SetPeerMtu */
6450 rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6453 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
6455 /* needed so ResetCall doesn't clobber us. */
6456 call->MTU = conn->peer->ifMTU;
6458 /* if we never succeeded, let the error pass out as-is */
6459 if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6460 cerror = conn->msgsizeRetryErr;
6463 rxi_CallError(call, cerror);
6468 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1,
6469 void *dummy, int dummy2)
6471 struct rx_connection *conn = arg1;
6472 struct rx_header theader;
6473 char tbuffer[1 + sizeof(struct rx_header)];
6474 struct sockaddr_in taddr;
6478 struct iovec tmpiov[2];
6481 RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6484 tp = &tbuffer[sizeof(struct rx_header)];
6485 taddr.sin_family = AF_INET;
6486 taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6487 taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6488 memset(&taddr.sin_zero, 0, sizeof(taddr.sin_zero));
6489 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6490 taddr.sin_len = sizeof(struct sockaddr_in);
6492 memset(&theader, 0, sizeof(theader));
6493 theader.epoch = htonl(999);
6495 theader.callNumber = 0;
6498 theader.type = RX_PACKET_TYPE_VERSION;
6499 theader.flags = RX_LAST_PACKET;
6500 theader.serviceId = 0;
6502 memcpy(tbuffer, &theader, sizeof(theader));
6503 memcpy(tp, &a, sizeof(a));
6504 tmpiov[0].iov_base = tbuffer;
6505 tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6507 rxi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6509 MUTEX_ENTER(&conn->conn_data_lock);
6510 /* We ran, so the handle is no longer needed to try to cancel ourselves. */
6511 if (event == conn->natKeepAliveEvent)
6512 rxevent_Put(&conn->natKeepAliveEvent);
6513 MUTEX_ENTER(&rx_refcnt_mutex);
6514 /* Only reschedule ourselves if the connection would not be destroyed */
6515 if (conn->refCount > 1)
6517 if (conn->refCount <= 0) {
6518 #ifdef RX_REFCOUNT_CHECK
6519 osi_Assert(conn->refCount == 0);
6521 if (rx_stats_active) {
6522 MUTEX_ENTER(&rx_stats_mutex);
6523 rxi_lowConnRefCount++;
6524 MUTEX_EXIT(&rx_stats_mutex);
6527 MUTEX_EXIT(&rx_refcnt_mutex);
6529 rxi_ScheduleNatKeepAliveEvent(conn);
6530 MUTEX_EXIT(&conn->conn_data_lock);
6531 putConnection(conn);
6535 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6537 MUTEX_ASSERT(&conn->conn_data_lock);
6538 if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6539 struct clock when, now;
6540 clock_GetTime(&now);
6542 when.sec += conn->secondsUntilNatPing;
6543 rx_GetConnection(conn);
6544 conn->natKeepAliveEvent =
6545 rxevent_Post(&when, &now, rxi_NatKeepAliveEvent, conn, NULL, 0);
6550 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6552 MUTEX_ENTER(&conn->conn_data_lock);
6553 conn->secondsUntilNatPing = seconds;
6555 if (!(conn->flags & RX_CONN_ATTACHWAIT))
6556 rxi_ScheduleNatKeepAliveEvent(conn);
6558 conn->flags |= RX_CONN_NAT_PING;
6560 MUTEX_EXIT(&conn->conn_data_lock);
6563 /* When a call is in progress, this routine is called occasionally to
6564 * make sure that some traffic has arrived (or been sent to) the peer.
6565 * If nothing has arrived in a reasonable amount of time, the call is
6566 * declared dead; if nothing has been sent for a while, we send a
6567 * keep-alive packet (if we're actually trying to keep the call alive)
6570 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy,
6573 struct rx_call *call = arg1;
6574 struct rx_connection *conn;
6577 MUTEX_ENTER(&call->lock);
6579 if (event == call->keepAliveEvent)
6580 rxevent_Put(&call->keepAliveEvent);
6584 if (rxi_CheckCall(call, 0)) {
6585 MUTEX_EXIT(&call->lock);
6586 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6590 /* Don't try to keep alive dallying calls */
6591 if (call->state == RX_STATE_DALLY) {
6592 MUTEX_EXIT(&call->lock);
6593 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6598 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6599 /* Don't try to send keepalives if there is unacknowledged data */
6600 /* the rexmit code should be good enough, this little hack
6601 * doesn't quite work XXX */
6602 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6604 rxi_ScheduleKeepAliveEvent(call);
6605 MUTEX_EXIT(&call->lock);
6606 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6609 /* Does what's on the nameplate. */
6611 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy, int dummy2)
6613 struct rx_call *call = arg1;
6614 struct rx_connection *conn;
6616 MUTEX_ENTER(&call->lock);
6618 if (event == call->growMTUEvent)
6619 rxevent_Put(&call->growMTUEvent);
6621 if (rxi_CheckCall(call, 0))
6624 /* Don't bother with dallying calls */
6625 if (call->state == RX_STATE_DALLY)
6631 * keep being scheduled, just don't do anything if we're at peak,
6632 * or we're not set up to be properly handled (idle timeout required)
6634 if ((conn->peer->maxPacketSize != 0) &&
6635 (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6637 (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6638 rxi_ScheduleGrowMTUEvent(call, 0);
6640 MUTEX_EXIT(&call->lock);
6641 CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6645 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6647 MUTEX_ASSERT(&call->lock);
6648 if (!call->keepAliveEvent) {
6649 struct clock when, now;
6650 clock_GetTime(&now);
6652 when.sec += call->conn->secondsUntilPing;
6653 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6654 call->keepAliveEvent =
6655 rxevent_Post(&when, &now, rxi_KeepAliveEvent, call, NULL, 0);
6660 rxi_CancelKeepAliveEvent(struct rx_call *call) {
6661 MUTEX_ASSERT(&call->lock);
6662 if (rxevent_Cancel(&call->keepAliveEvent))
6663 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6667 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6669 MUTEX_ASSERT(&call->lock);
6670 if (!call->growMTUEvent) {
6671 struct clock when, now;
6673 clock_GetTime(&now);
6676 if (call->conn->secondsUntilPing)
6677 secs = (6*call->conn->secondsUntilPing)-1;
6679 if (call->conn->secondsUntilDead)
6680 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6684 CALL_HOLD(call, RX_CALL_REFCOUNT_MTU);
6685 call->growMTUEvent =
6686 rxevent_Post(&when, &now, rxi_GrowMTUEvent, call, NULL, 0);
6691 rxi_CancelGrowMTUEvent(struct rx_call *call)
6693 MUTEX_ASSERT(&call->lock);
6694 if (rxevent_Cancel(&call->growMTUEvent))
6695 CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6699 * Increment the counter for the next connection ID, handling overflow.
6702 update_nextCid(void)
6704 /* Overflow is technically undefined behavior; avoid it. */
6705 if (rx_nextCid > MAX_AFS_INT32 - (1 << RX_CIDSHIFT))
6706 rx_nextCid = -1 * ((MAX_AFS_INT32 / RX_CIDSHIFT) * RX_CIDSHIFT);
6708 rx_nextCid += 1 << RX_CIDSHIFT;
6712 rxi_KeepAliveOn(struct rx_call *call)
6714 /* Pretend last packet received was received now--i.e. if another
6715 * packet isn't received within the keep alive time, then the call
6716 * will die; Initialize last send time to the current time--even
6717 * if a packet hasn't been sent yet. This will guarantee that a
6718 * keep-alive is sent within the ping time */
6719 call->lastReceiveTime = call->lastSendTime = clock_Sec();
6720 rxi_ScheduleKeepAliveEvent(call);
6724 rxi_GrowMTUOn(struct rx_call *call)
6726 struct rx_connection *conn = call->conn;
6727 MUTEX_ENTER(&conn->conn_data_lock);
6728 conn->lastPingSizeSer = conn->lastPingSize = 0;
6729 MUTEX_EXIT(&conn->conn_data_lock);
6730 rxi_ScheduleGrowMTUEvent(call, 1);
6733 /* This routine is called to send connection abort messages
6734 * that have been delayed to throttle looping clients. */
6736 rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1, void *unused,
6739 struct rx_connection *conn = arg1;
6742 struct rx_packet *packet;
6744 MUTEX_ENTER(&conn->conn_data_lock);
6745 if (event == conn->delayedAbortEvent)
6746 rxevent_Put(&conn->delayedAbortEvent);
6747 error = htonl(conn->error);
6749 MUTEX_EXIT(&conn->conn_data_lock);
6750 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6753 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6754 RX_PACKET_TYPE_ABORT, (char *)&error,
6756 rxi_FreePacket(packet);
6758 putConnection(conn);
6761 /* This routine is called to send call abort messages
6762 * that have been delayed to throttle looping clients. */
6764 rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1, void *dummy,
6767 struct rx_call *call = arg1;
6770 struct rx_packet *packet;
6772 MUTEX_ENTER(&call->lock);
6773 if (event == call->delayedAbortEvent)
6774 rxevent_Put(&call->delayedAbortEvent);
6775 error = htonl(call->error);
6777 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6780 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6781 (char *)&error, sizeof(error), 0);
6782 rxi_FreePacket(packet);
6784 MUTEX_EXIT(&call->lock);
6785 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6789 * This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6790 * seconds) to ask the client to authenticate itself. The routine
6791 * issues a challenge to the client, which is obtained from the
6792 * security object associated with the connection
6794 * This routine is both an event handler and a function called directly;
6795 * when called directly the passed |event| is NULL and the
6796 * conn->conn->data>lock must must not be held. Also, when called as an
6797 * an event handler, we must putConnection before we exit; but when called
6798 * directly (the first challenge), we must NOT putConnection.
6801 rxi_ChallengeEvent(struct rxevent *event,
6802 void *arg0, void *arg1, int tries)
6804 struct rx_connection *conn = arg0;
6805 int event_raised = 0; /* assume we were called directly */
6807 MUTEX_ENTER(&conn->conn_data_lock);
6808 if (event != NULL && event == conn->challengeEvent) {
6809 event_raised = 1; /* called as an event */
6810 rxevent_Put(&conn->challengeEvent);
6812 MUTEX_EXIT(&conn->conn_data_lock);
6814 /* If there are no active calls it is not worth re-issuing the
6815 * challenge. If the client issues another call on this connection
6816 * the challenge can be requested at that time.
6818 if (!rxi_HasActiveCalls(conn))
6821 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6822 struct rx_packet *packet;
6823 struct clock when, now;
6826 /* We've failed to authenticate for too long.
6827 * Reset any calls waiting for authentication;
6828 * they are all in RX_STATE_PRECALL.
6832 MUTEX_ENTER(&conn->conn_call_lock);
6833 for (i = 0; i < RX_MAXCALLS; i++) {
6834 struct rx_call *call = conn->call[i];
6836 MUTEX_ENTER(&call->lock);
6837 if (call->state == RX_STATE_PRECALL) {
6838 rxi_CallError(call, RX_CALL_DEAD);
6839 rxi_SendCallAbort(call, NULL, 0, 0);
6841 MUTEX_EXIT(&call->lock);
6844 MUTEX_EXIT(&conn->conn_call_lock);
6848 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6851 code = RXS_GetChallenge(conn->securityObject, conn, packet);
6852 if (code && event_raised) {
6854 * We can only rxi_ConnectionError the connection if we are
6855 * running as an event. Otherwise, the caller may have our call
6856 * locked, and so we cannot call rxi_ConnectionError (since it
6857 * tries to lock each call in the conn).
6859 rxi_FreePacket(packet);
6860 rxi_ConnectionError(conn, code);
6864 /* Only send a challenge packet if we were able to allocate a
6865 * packet, and the security layer successfully populated the
6867 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6868 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6869 conn->securityChallengeSent = 1;
6871 rxi_FreePacket(packet);
6873 clock_GetTime(&now);
6875 when.sec += RX_CHALLENGE_TIMEOUT;
6876 MUTEX_ENTER(&conn->conn_data_lock);
6877 /* Only reschedule ourselves if not already pending. */
6878 if (conn->challengeEvent == NULL) {
6879 rx_GetConnection(conn);
6880 conn->challengeEvent =
6881 rxevent_Post(&when, &now, rxi_ChallengeEvent, conn, 0,
6884 MUTEX_EXIT(&conn->conn_data_lock);
6888 putConnection(conn);
6891 /* Call this routine to start requesting the client to authenticate
6892 * itself. This will continue until authentication is established,
6893 * the call times out, or an invalid response is returned. The
6894 * security object associated with the connection is asked to create
6895 * the challenge at this time. */
6897 rxi_ChallengeOn(struct rx_connection *conn)
6900 MUTEX_ENTER(&conn->conn_data_lock);
6901 if (!conn->challengeEvent)
6903 MUTEX_EXIT(&conn->conn_data_lock);
6906 code = RXS_CreateChallenge(conn->securityObject, conn);
6910 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
6916 /* rxi_ComputeRoundTripTime is called with peer locked. */
6917 /* peer may be null */
6919 rxi_ComputeRoundTripTime(struct rx_packet *p,
6920 struct rx_ackPacket *ack,
6921 struct rx_call *call,
6922 struct rx_peer *peer,
6925 struct clock thisRtt, *sentp;
6929 /* If the ACK is delayed, then do nothing */
6930 if (ack->reason == RX_ACK_DELAY)
6933 /* On the wire, jumbograms are a single UDP packet. We shouldn't count
6934 * their RTT multiple times, so only include the RTT of the last packet
6936 if (p->flags & RX_JUMBO_PACKET)
6939 /* Use the serial number to determine which transmission the ACK is for,
6940 * and set the sent time to match this. If we have no serial number, then
6941 * only use the ACK for RTT calculations if the packet has not been
6945 serial = ntohl(ack->serial);
6947 if (serial == p->header.serial) {
6948 sentp = &p->timeSent;
6949 } else if (serial == p->firstSerial) {
6950 sentp = &p->firstSent;
6951 } else if (clock_Eq(&p->timeSent, &p->firstSent)) {
6952 sentp = &p->firstSent;
6956 if (clock_Eq(&p->timeSent, &p->firstSent)) {
6957 sentp = &p->firstSent;
6964 if (clock_Lt(&thisRtt, sentp))
6965 return; /* somebody set the clock back, don't count this time. */
6967 clock_Sub(&thisRtt, sentp);
6968 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%p rttp=%d.%06d sec)\n",
6969 p->header.callNumber, p, thisRtt.sec, thisRtt.usec));
6971 if (clock_IsZero(&thisRtt)) {
6973 * The actual round trip time is shorter than the
6974 * clock_GetTime resolution. It is most likely 1ms or 100ns.
6975 * Since we can't tell which at the moment we will assume 1ms.
6977 thisRtt.usec = 1000;
6980 if (rx_stats_active) {
6981 MUTEX_ENTER(&rx_stats_mutex);
6982 if (clock_Lt(&thisRtt, &rx_stats.minRtt))
6983 rx_stats.minRtt = thisRtt;
6984 if (clock_Gt(&thisRtt, &rx_stats.maxRtt)) {
6985 if (thisRtt.sec > 60) {
6986 MUTEX_EXIT(&rx_stats_mutex);
6987 return; /* somebody set the clock ahead */
6989 rx_stats.maxRtt = thisRtt;
6991 clock_Add(&rx_stats.totalRtt, &thisRtt);
6992 rx_atomic_inc(&rx_stats.nRttSamples);
6993 MUTEX_EXIT(&rx_stats_mutex);
6996 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6998 /* Apply VanJacobson round-trip estimations */
7003 * srtt (call->rtt) is in units of one-eighth-milliseconds.
7004 * srtt is stored as fixed point with 3 bits after the binary
7005 * point (i.e., scaled by 8). The following magic is
7006 * equivalent to the smoothing algorithm in rfc793 with an
7007 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
7008 * srtt'*8 = rtt + srtt*7
7009 * srtt'*8 = srtt*8 + rtt - srtt
7010 * srtt' = srtt + rtt/8 - srtt/8
7011 * srtt' = srtt + (rtt - srtt)/8
7014 delta = _8THMSEC(&thisRtt) - call->rtt;
7015 call->rtt += (delta >> 3);
7018 * We accumulate a smoothed rtt variance (actually, a smoothed
7019 * mean difference), then set the retransmit timer to smoothed
7020 * rtt + 4 times the smoothed variance (was 2x in van's original
7021 * paper, but 4x works better for me, and apparently for him as
7023 * rttvar is stored as
7024 * fixed point with 2 bits after the binary point (scaled by
7025 * 4). The following is equivalent to rfc793 smoothing with
7026 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
7027 * rttvar'*4 = rttvar*3 + |delta|
7028 * rttvar'*4 = rttvar*4 + |delta| - rttvar
7029 * rttvar' = rttvar + |delta|/4 - rttvar/4
7030 * rttvar' = rttvar + (|delta| - rttvar)/4
7031 * This replaces rfc793's wired-in beta.
7032 * dev*4 = dev*4 + (|actual - expected| - dev)
7038 delta -= (call->rtt_dev << 1);
7039 call->rtt_dev += (delta >> 3);
7041 /* I don't have a stored RTT so I start with this value. Since I'm
7042 * probably just starting a call, and will be pushing more data down
7043 * this, I expect congestion to increase rapidly. So I fudge a
7044 * little, and I set deviance to half the rtt. In practice,
7045 * deviance tends to approach something a little less than
7046 * half the smoothed rtt. */
7047 call->rtt = _8THMSEC(&thisRtt) + 8;
7048 call->rtt_dev = call->rtt >> 2; /* rtt/2: they're scaled differently */
7050 /* the smoothed RTT time is RTT + 4*MDEV
7052 * We allow a user specified minimum to be set for this, to allow clamping
7053 * at a minimum value in the same way as TCP. In addition, we have to allow
7054 * for the possibility that this packet is answered by a delayed ACK, so we
7055 * add on a fixed 200ms to account for that timer expiring.
7058 rtt_timeout = MAX(((call->rtt >> 3) + call->rtt_dev),
7059 rx_minPeerTimeout) + 200;
7060 clock_Zero(&call->rto);
7061 clock_Addmsec(&call->rto, rtt_timeout);
7063 /* Update the peer, so any new calls start with our values */
7064 peer->rtt_dev = call->rtt_dev;
7065 peer->rtt = call->rtt;
7067 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%p rtt=%d ms, srtt=%d ms, "
7068 "rtt_dev=%d ms, timeout=%d.%06d sec)\n",
7069 p->header.callNumber, p, MSEC(&thisRtt), call->rtt >> 3,
7070 call->rtt_dev >> 2, (call->rto.sec), (call->rto.usec)));
7074 /* Find all server connections that have not been active for a long time, and
7077 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2,
7080 struct clock now, when;
7081 struct rxevent *event;
7082 clock_GetTime(&now);
7084 /* Find server connection structures that haven't been used for
7085 * greater than rx_idleConnectionTime */
7087 struct rx_connection **conn_ptr, **conn_end;
7088 int i, havecalls = 0;
7089 MUTEX_ENTER(&rx_connHashTable_lock);
7090 for (conn_ptr = &rx_connHashTable[0], conn_end =
7091 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
7093 struct rx_connection *conn, *next;
7094 struct rx_call *call;
7098 for (conn = *conn_ptr; conn; conn = next) {
7099 /* XXX -- Shouldn't the connection be locked? */
7102 for (i = 0; i < RX_MAXCALLS; i++) {
7103 call = conn->call[i];
7107 code = MUTEX_TRYENTER(&call->lock);
7110 result = rxi_CheckCall(call, 1);
7111 MUTEX_EXIT(&call->lock);
7113 /* If CheckCall freed the call, it might
7114 * have destroyed the connection as well,
7115 * which screws up the linked lists.
7121 if (conn->type == RX_SERVER_CONNECTION) {
7122 /* This only actually destroys the connection if
7123 * there are no outstanding calls */
7124 MUTEX_ENTER(&conn->conn_data_lock);
7125 MUTEX_ENTER(&rx_refcnt_mutex);
7126 if (!havecalls && !conn->refCount
7127 && ((conn->lastSendTime + rx_idleConnectionTime) <
7129 conn->refCount++; /* it will be decr in rx_DestroyConn */
7130 MUTEX_EXIT(&rx_refcnt_mutex);
7131 MUTEX_EXIT(&conn->conn_data_lock);
7132 #ifdef RX_ENABLE_LOCKS
7133 rxi_DestroyConnectionNoLock(conn);
7134 #else /* RX_ENABLE_LOCKS */
7135 rxi_DestroyConnection(conn);
7136 #endif /* RX_ENABLE_LOCKS */
7138 #ifdef RX_ENABLE_LOCKS
7140 MUTEX_EXIT(&rx_refcnt_mutex);
7141 MUTEX_EXIT(&conn->conn_data_lock);
7143 #endif /* RX_ENABLE_LOCKS */
7147 #ifdef RX_ENABLE_LOCKS
7148 while (rx_connCleanup_list) {
7149 struct rx_connection *conn;
7150 conn = rx_connCleanup_list;
7151 rx_connCleanup_list = rx_connCleanup_list->next;
7152 MUTEX_EXIT(&rx_connHashTable_lock);
7153 rxi_CleanupConnection(conn);
7154 MUTEX_ENTER(&rx_connHashTable_lock);
7156 MUTEX_EXIT(&rx_connHashTable_lock);
7157 #endif /* RX_ENABLE_LOCKS */
7160 /* Find any peer structures that haven't been used (haven't had an
7161 * associated connection) for greater than rx_idlePeerTime */
7163 struct rx_peer **peer_ptr, **peer_end;
7167 * Why do we need to hold the rx_peerHashTable_lock across
7168 * the incrementing of peer_ptr since the rx_peerHashTable
7169 * array is not changing? We don't.
7171 * By dropping the lock periodically we can permit other
7172 * activities to be performed while a rxi_ReapConnections
7173 * call is in progress. The goal of reap connections
7174 * is to clean up quickly without causing large amounts
7175 * of contention. Therefore, it is important that global
7176 * mutexes not be held for extended periods of time.
7178 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7179 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7181 struct rx_peer *peer, *next, *prev;
7183 MUTEX_ENTER(&rx_peerHashTable_lock);
7184 for (prev = peer = *peer_ptr; peer; peer = next) {
7186 code = MUTEX_TRYENTER(&peer->peer_lock);
7187 if ((code) && (peer->refCount == 0)
7188 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
7189 struct opr_queue *cursor, *store;
7193 * now know that this peer object is one to be
7194 * removed from the hash table. Once it is removed
7195 * it can't be referenced by other threads.
7196 * Lets remove it first and decrement the struct
7197 * nPeerStructs count.
7199 if (peer == *peer_ptr) {
7205 if (rx_stats_active)
7206 rx_atomic_dec(&rx_stats.nPeerStructs);
7209 * Now if we hold references on 'prev' and 'next'
7210 * we can safely drop the rx_peerHashTable_lock
7211 * while we destroy this 'peer' object.
7217 MUTEX_EXIT(&rx_peerHashTable_lock);
7219 MUTEX_EXIT(&peer->peer_lock);
7220 MUTEX_DESTROY(&peer->peer_lock);
7222 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
7223 unsigned int num_funcs;
7224 struct rx_interface_stat *rpc_stat
7225 = opr_queue_Entry(cursor, struct rx_interface_stat,
7230 opr_queue_Remove(&rpc_stat->entry);
7231 opr_queue_Remove(&rpc_stat->entryPeers);
7233 num_funcs = rpc_stat->stats[0].func_total;
7235 sizeof(rx_interface_stat_t) +
7236 rpc_stat->stats[0].func_total *
7237 sizeof(rx_function_entry_v1_t);
7239 rxi_Free(rpc_stat, space);
7241 MUTEX_ENTER(&rx_rpc_stats);
7242 rxi_rpc_peer_stat_cnt -= num_funcs;
7243 MUTEX_EXIT(&rx_rpc_stats);
7248 * Regain the rx_peerHashTable_lock and
7249 * decrement the reference count on 'prev'
7252 MUTEX_ENTER(&rx_peerHashTable_lock);
7259 MUTEX_EXIT(&peer->peer_lock);
7264 MUTEX_EXIT(&rx_peerHashTable_lock);
7268 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
7269 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
7270 * GC, just below. Really, we shouldn't have to keep moving packets from
7271 * one place to another, but instead ought to always know if we can
7272 * afford to hold onto a packet in its particular use. */
7273 MUTEX_ENTER(&rx_freePktQ_lock);
7274 if (rx_waitingForPackets) {
7275 rx_waitingForPackets = 0;
7276 #ifdef RX_ENABLE_LOCKS
7277 CV_BROADCAST(&rx_waitingForPackets_cv);
7279 osi_rxWakeup(&rx_waitingForPackets);
7282 MUTEX_EXIT(&rx_freePktQ_lock);
7285 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
7286 event = rxevent_Post(&when, &now, rxi_ReapConnections, 0, NULL, 0);
7287 rxevent_Put(&event);
7291 /* rxs_Release - This isn't strictly necessary but, since the macro name from
7292 * rx.h is sort of strange this is better. This is called with a security
7293 * object before it is discarded. Each connection using a security object has
7294 * its own refcount to the object so it won't actually be freed until the last
7295 * connection is destroyed.
7297 * This is the only rxs module call. A hold could also be written but no one
7301 rxs_Release(struct rx_securityClass *aobj)
7303 return RXS_Close(aobj);
7311 #define TRACE_OPTION_RX_DEBUG 16
7319 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
7320 0, KEY_QUERY_VALUE, &parmKey);
7321 if (code != ERROR_SUCCESS)
7324 dummyLen = sizeof(TraceOption);
7325 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
7326 (BYTE *) &TraceOption, &dummyLen);
7327 if (code == ERROR_SUCCESS) {
7328 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
7330 RegCloseKey (parmKey);
7331 #endif /* AFS_NT40_ENV */
7336 rx_DebugOnOff(int on)
7340 rxdebug_active = on;
7346 rx_StatsOnOff(int on)
7348 rx_stats_active = on;
7352 /* Don't call this debugging routine directly; use dpf */
7354 rxi_DebugPrint(char *format, ...)
7363 va_start(ap, format);
7365 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7368 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7370 OutputDebugString(msg);
7376 va_start(ap, format);
7378 clock_GetTime(&now);
7379 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7380 (unsigned int)now.usec);
7381 vfprintf(rx_Log, format, ap);
7389 * This function is used to process the rx_stats structure that is local
7390 * to a process as well as an rx_stats structure received from a remote
7391 * process (via rxdebug). Therefore, it needs to do minimal version
7395 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7396 afs_int32 freePackets, char version)
7400 if (size != sizeof(struct rx_statistics)) {
7402 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7403 size, sizeof(struct rx_statistics));
7406 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7409 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7410 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7411 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7412 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7413 s->specialPktAllocFailures);
7415 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7416 s->receivePktAllocFailures, s->sendPktAllocFailures,
7417 s->specialPktAllocFailures);
7421 " greedy %u, " "bogusReads %u (last from host %x), "
7422 "noPackets %u, " "noBuffers %u, " "selects %u, "
7423 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7424 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7425 s->selects, s->sendSelects);
7427 fprintf(file, " packets read: ");
7428 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7429 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7431 fprintf(file, "\n");
7434 " other read counters: data %u, " "ack %u, " "dup %u "
7435 "spurious %u " "dally %u\n", s->dataPacketsRead,
7436 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7437 s->ignorePacketDally);
7439 fprintf(file, " packets sent: ");
7440 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7441 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7443 fprintf(file, "\n");
7446 " other send counters: ack %u, " "data %u (not resends), "
7447 "resends %u, " "pushed %u, " "acked&ignored %u\n",
7448 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7449 s->dataPacketsPushed, s->ignoreAckedPacket);
7452 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7453 s->netSendFailures, (int)s->fatalErrors);
7455 if (s->nRttSamples) {
7456 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
7457 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7459 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
7460 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7464 " %d server connections, " "%d client connections, "
7465 "%d peer structs, " "%d call structs, " "%d free call structs\n",
7466 s->nServerConns, s->nClientConns, s->nPeerStructs,
7467 s->nCallStructs, s->nFreeCallStructs);
7469 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7470 fprintf(file, " %d clock updates\n", clock_nUpdates);
7474 /* for backward compatibility */
7476 rx_PrintStats(FILE * file)
7478 MUTEX_ENTER(&rx_stats_mutex);
7479 rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7480 sizeof(rx_stats), rx_nFreePackets,
7482 MUTEX_EXIT(&rx_stats_mutex);
7486 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7488 fprintf(file, "Peer %x.%d.\n",
7489 ntohl(peer->host), (int)ntohs(peer->port));
7492 " Rtt %d, " "total sent %d, " "resent %d\n",
7493 peer->rtt, peer->nSent, peer->reSends);
7495 fprintf(file, " Packet size %d\n", peer->ifMTU);
7499 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7501 * This mutex protects the following static variables:
7505 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7506 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7508 #define LOCK_RX_DEBUG
7509 #define UNLOCK_RX_DEBUG
7510 #endif /* AFS_PTHREAD_ENV */
7512 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7514 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7515 u_char type, void *inputData, size_t inputLength,
7516 void *outputData, size_t outputLength)
7518 static afs_int32 counter = 100;
7519 time_t waitTime, waitCount;
7520 struct rx_header theader;
7523 struct timeval tv_now, tv_wake, tv_delta;
7524 struct sockaddr_in taddr, faddr;
7538 tp = &tbuffer[sizeof(struct rx_header)];
7539 taddr.sin_family = AF_INET;
7540 taddr.sin_port = remotePort;
7541 taddr.sin_addr.s_addr = remoteAddr;
7542 memset(&taddr.sin_zero, 0, sizeof(taddr.sin_zero));
7543 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7544 taddr.sin_len = sizeof(struct sockaddr_in);
7547 memset(&theader, 0, sizeof(theader));
7548 theader.epoch = htonl(999);
7550 theader.callNumber = htonl(counter);
7553 theader.type = type;
7554 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7555 theader.serviceId = 0;
7557 memcpy(tbuffer, &theader, sizeof(theader));
7558 memcpy(tp, inputData, inputLength);
7560 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7561 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7563 /* see if there's a packet available */
7564 gettimeofday(&tv_wake, NULL);
7565 tv_wake.tv_sec += waitTime;
7568 FD_SET(socket, &imask);
7569 tv_delta.tv_sec = tv_wake.tv_sec;
7570 tv_delta.tv_usec = tv_wake.tv_usec;
7571 gettimeofday(&tv_now, NULL);
7573 if (tv_delta.tv_usec < tv_now.tv_usec) {
7575 tv_delta.tv_usec += 1000000;
7578 tv_delta.tv_usec -= tv_now.tv_usec;
7580 if (tv_delta.tv_sec < tv_now.tv_sec) {
7584 tv_delta.tv_sec -= tv_now.tv_sec;
7587 code = select(0, &imask, 0, 0, &tv_delta);
7588 #else /* AFS_NT40_ENV */
7589 code = select(socket + 1, &imask, 0, 0, &tv_delta);
7590 #endif /* AFS_NT40_ENV */
7591 if (code == 1 && FD_ISSET(socket, &imask)) {
7592 /* now receive a packet */
7593 faddrLen = sizeof(struct sockaddr_in);
7595 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7596 (struct sockaddr *)&faddr, &faddrLen);
7599 memcpy(&theader, tbuffer, sizeof(struct rx_header));
7600 if (counter == ntohl(theader.callNumber))
7608 /* see if we've timed out */
7616 code -= sizeof(struct rx_header);
7617 if (code > outputLength)
7618 code = outputLength;
7619 memcpy(outputData, tp, code);
7622 #endif /* RXDEBUG */
7625 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7626 afs_uint16 remotePort, struct rx_debugStats * stat,
7627 afs_uint32 * supportedValues)
7629 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7631 struct rx_debugIn in;
7633 *supportedValues = 0;
7634 in.type = htonl(RX_DEBUGI_GETSTATS);
7637 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7638 &in, sizeof(in), stat, sizeof(*stat));
7641 * If the call was successful, fixup the version and indicate
7642 * what contents of the stat structure are valid.
7643 * Also do net to host conversion of fields here.
7647 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7648 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7650 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7651 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7653 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7654 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7656 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7657 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7659 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7660 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7662 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7663 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7665 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7666 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7668 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7669 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7671 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7672 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7674 stat->nFreePackets = ntohl(stat->nFreePackets);
7675 stat->packetReclaims = ntohl(stat->packetReclaims);
7676 stat->callsExecuted = ntohl(stat->callsExecuted);
7677 stat->nWaiting = ntohl(stat->nWaiting);
7678 stat->idleThreads = ntohl(stat->idleThreads);
7679 stat->nWaited = ntohl(stat->nWaited);
7680 stat->nPackets = ntohl(stat->nPackets);
7689 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7690 afs_uint16 remotePort, struct rx_statistics * stat,
7691 afs_uint32 * supportedValues)
7693 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7695 struct rx_debugIn in;
7696 afs_int32 *lp = (afs_int32 *) stat;
7700 * supportedValues is currently unused, but added to allow future
7701 * versioning of this function.
7704 *supportedValues = 0;
7705 in.type = htonl(RX_DEBUGI_RXSTATS);
7707 memset(stat, 0, sizeof(*stat));
7709 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7710 &in, sizeof(in), stat, sizeof(*stat));
7715 * Do net to host conversion here
7718 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7729 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7730 afs_uint16 remotePort, size_t version_length,
7733 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7735 return MakeDebugCall(socket, remoteAddr, remotePort,
7736 RX_PACKET_TYPE_VERSION, a, 1, version,
7744 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7745 afs_uint16 remotePort, afs_int32 * nextConnection,
7746 int allConnections, afs_uint32 debugSupportedValues,
7747 struct rx_debugConn * conn,
7748 afs_uint32 * supportedValues)
7750 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7752 struct rx_debugIn in;
7756 * supportedValues is currently unused, but added to allow future
7757 * versioning of this function.
7760 *supportedValues = 0;
7761 if (allConnections) {
7762 in.type = htonl(RX_DEBUGI_GETALLCONN);
7764 in.type = htonl(RX_DEBUGI_GETCONN);
7766 in.index = htonl(*nextConnection);
7767 memset(conn, 0, sizeof(*conn));
7769 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7770 &in, sizeof(in), conn, sizeof(*conn));
7773 *nextConnection += 1;
7776 * Convert old connection format to new structure.
7779 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7780 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7781 #define MOVEvL(a) (conn->a = vL->a)
7783 /* any old or unrecognized version... */
7784 for (i = 0; i < RX_MAXCALLS; i++) {
7785 MOVEvL(callState[i]);
7786 MOVEvL(callMode[i]);
7787 MOVEvL(callFlags[i]);
7788 MOVEvL(callOther[i]);
7790 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7791 MOVEvL(secStats.type);
7792 MOVEvL(secStats.level);
7793 MOVEvL(secStats.flags);
7794 MOVEvL(secStats.expires);
7795 MOVEvL(secStats.packetsReceived);
7796 MOVEvL(secStats.packetsSent);
7797 MOVEvL(secStats.bytesReceived);
7798 MOVEvL(secStats.bytesSent);
7803 * Do net to host conversion here
7805 * I don't convert host or port since we are most likely
7806 * going to want these in NBO.
7808 conn->cid = ntohl(conn->cid);
7809 conn->serial = ntohl(conn->serial);
7810 for (i = 0; i < RX_MAXCALLS; i++) {
7811 conn->callNumber[i] = ntohl(conn->callNumber[i]);
7813 conn->error = ntohl(conn->error);
7814 conn->secStats.flags = ntohl(conn->secStats.flags);
7815 conn->secStats.expires = ntohl(conn->secStats.expires);
7816 conn->secStats.packetsReceived =
7817 ntohl(conn->secStats.packetsReceived);
7818 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7819 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7820 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7821 conn->epoch = ntohl(conn->epoch);
7822 conn->natMTU = ntohl(conn->natMTU);
7831 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7832 afs_uint16 remotePort, afs_int32 * nextPeer,
7833 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7834 afs_uint32 * supportedValues)
7836 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7838 struct rx_debugIn in;
7841 * supportedValues is currently unused, but added to allow future
7842 * versioning of this function.
7845 *supportedValues = 0;
7846 in.type = htonl(RX_DEBUGI_GETPEER);
7847 in.index = htonl(*nextPeer);
7848 memset(peer, 0, sizeof(*peer));
7850 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7851 &in, sizeof(in), peer, sizeof(*peer));
7857 * Do net to host conversion here
7859 * I don't convert host or port since we are most likely
7860 * going to want these in NBO.
7862 peer->ifMTU = ntohs(peer->ifMTU);
7863 peer->idleWhen = ntohl(peer->idleWhen);
7864 peer->refCount = ntohs(peer->refCount);
7865 peer->rtt = ntohl(peer->rtt);
7866 peer->rtt_dev = ntohl(peer->rtt_dev);
7867 peer->timeout.sec = 0;
7868 peer->timeout.usec = 0;
7869 peer->nSent = ntohl(peer->nSent);
7870 peer->reSends = ntohl(peer->reSends);
7871 peer->natMTU = ntohs(peer->natMTU);
7872 peer->maxMTU = ntohs(peer->maxMTU);
7873 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7874 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7875 peer->MTU = ntohs(peer->MTU);
7876 peer->cwind = ntohs(peer->cwind);
7877 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7878 peer->congestSeq = ntohs(peer->congestSeq);
7879 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7880 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7881 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7882 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7891 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7892 struct rx_debugPeer * peerStats)
7895 afs_int32 error = 1; /* default to "did not succeed" */
7896 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7898 MUTEX_ENTER(&rx_peerHashTable_lock);
7899 for(tp = rx_peerHashTable[hashValue];
7900 tp != NULL; tp = tp->next) {
7901 if (tp->host == peerHost)
7907 MUTEX_EXIT(&rx_peerHashTable_lock);
7911 MUTEX_ENTER(&tp->peer_lock);
7912 peerStats->host = tp->host;
7913 peerStats->port = tp->port;
7914 peerStats->ifMTU = tp->ifMTU;
7915 peerStats->idleWhen = tp->idleWhen;
7916 peerStats->refCount = tp->refCount;
7917 peerStats->burstSize = 0;
7918 peerStats->burst = 0;
7919 peerStats->burstWait.sec = 0;
7920 peerStats->burstWait.usec = 0;
7921 peerStats->rtt = tp->rtt;
7922 peerStats->rtt_dev = tp->rtt_dev;
7923 peerStats->timeout.sec = 0;
7924 peerStats->timeout.usec = 0;
7925 peerStats->nSent = tp->nSent;
7926 peerStats->reSends = tp->reSends;
7927 peerStats->natMTU = tp->natMTU;
7928 peerStats->maxMTU = tp->maxMTU;
7929 peerStats->maxDgramPackets = tp->maxDgramPackets;
7930 peerStats->ifDgramPackets = tp->ifDgramPackets;
7931 peerStats->MTU = tp->MTU;
7932 peerStats->cwind = tp->cwind;
7933 peerStats->nDgramPackets = tp->nDgramPackets;
7934 peerStats->congestSeq = tp->congestSeq;
7935 peerStats->bytesSent.high = tp->bytesSent >> 32;
7936 peerStats->bytesSent.low = tp->bytesSent & MAX_AFS_UINT32;
7937 peerStats->bytesReceived.high = tp->bytesReceived >> 32;
7938 peerStats->bytesReceived.low
7939 = tp->bytesReceived & MAX_AFS_UINT32;
7940 MUTEX_EXIT(&tp->peer_lock);
7942 MUTEX_ENTER(&rx_peerHashTable_lock);
7945 MUTEX_EXIT(&rx_peerHashTable_lock);
7953 struct rx_serverQueueEntry *np;
7956 struct rx_call *call;
7957 struct rx_serverQueueEntry *sq;
7961 if (!rxi_IsRunning()) {
7963 return; /* Already shutdown. */
7965 rx_atomic_set(&rxi_running, 0);
7968 #ifndef AFS_PTHREAD_ENV
7969 FD_ZERO(&rx_selectMask);
7970 #endif /* AFS_PTHREAD_ENV */
7971 rxi_dataQuota = RX_MAX_QUOTA;
7972 #ifndef AFS_PTHREAD_ENV
7974 #endif /* AFS_PTHREAD_ENV */
7977 #ifndef AFS_PTHREAD_ENV
7978 #ifndef AFS_USE_GETTIMEOFDAY
7980 #endif /* AFS_USE_GETTIMEOFDAY */
7981 #endif /* AFS_PTHREAD_ENV */
7983 while (!opr_queue_IsEmpty(&rx_freeCallQueue)) {
7984 call = opr_queue_First(&rx_freeCallQueue, struct rx_call, entry);
7985 opr_queue_Remove(&call->entry);
7986 rxi_Free(call, sizeof(struct rx_call));
7989 while (!opr_queue_IsEmpty(&rx_idleServerQueue)) {
7990 sq = opr_queue_First(&rx_idleServerQueue, struct rx_serverQueueEntry,
7992 opr_queue_Remove(&sq->entry);
7997 struct rx_peer **peer_ptr, **peer_end;
7998 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7999 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
8001 struct rx_peer *peer, *next;
8003 MUTEX_ENTER(&rx_peerHashTable_lock);
8004 for (peer = *peer_ptr; peer; peer = next) {
8005 struct opr_queue *cursor, *store;
8008 MUTEX_ENTER(&rx_rpc_stats);
8009 MUTEX_ENTER(&peer->peer_lock);
8010 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
8011 unsigned int num_funcs;
8012 struct rx_interface_stat *rpc_stat
8013 = opr_queue_Entry(cursor, struct rx_interface_stat,
8017 opr_queue_Remove(&rpc_stat->entry);
8018 opr_queue_Remove(&rpc_stat->entryPeers);
8019 num_funcs = rpc_stat->stats[0].func_total;
8021 sizeof(rx_interface_stat_t) +
8022 rpc_stat->stats[0].func_total *
8023 sizeof(rx_function_entry_v1_t);
8025 rxi_Free(rpc_stat, space);
8027 /* rx_rpc_stats must be held */
8028 rxi_rpc_peer_stat_cnt -= num_funcs;
8030 MUTEX_EXIT(&peer->peer_lock);
8031 MUTEX_EXIT(&rx_rpc_stats);
8035 if (rx_stats_active)
8036 rx_atomic_dec(&rx_stats.nPeerStructs);
8038 MUTEX_EXIT(&rx_peerHashTable_lock);
8041 for (i = 0; i < RX_MAX_SERVICES; i++) {
8043 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
8045 for (i = 0; i < rx_hashTableSize; i++) {
8046 struct rx_connection *tc, *ntc;
8047 MUTEX_ENTER(&rx_connHashTable_lock);
8048 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
8050 for (j = 0; j < RX_MAXCALLS; j++) {
8052 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
8055 rxi_Free(tc, sizeof(*tc));
8057 MUTEX_EXIT(&rx_connHashTable_lock);
8060 MUTEX_ENTER(&freeSQEList_lock);
8062 while (!opr_queue_IsEmpty(&rx_freeServerQueue)) {
8063 np = opr_queue_First(&rx_freeServerQueue, struct rx_serverQueueEntry,
8065 opr_queue_Remove(&np->entry);
8066 MUTEX_DESTROY(&np->lock);
8067 rxi_Free(np, sizeof(*np));
8070 MUTEX_EXIT(&freeSQEList_lock);
8071 MUTEX_DESTROY(&freeSQEList_lock);
8072 MUTEX_DESTROY(&rx_freeCallQueue_lock);
8073 MUTEX_DESTROY(&rx_connHashTable_lock);
8074 MUTEX_DESTROY(&rx_peerHashTable_lock);
8075 MUTEX_DESTROY(&rx_serverPool_lock);
8077 osi_Free(rx_connHashTable,
8078 rx_hashTableSize * sizeof(struct rx_connection *));
8079 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
8081 UNPIN(rx_connHashTable,
8082 rx_hashTableSize * sizeof(struct rx_connection *));
8083 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
8085 MUTEX_ENTER(&rx_quota_mutex);
8086 rxi_dataQuota = RX_MAX_QUOTA;
8087 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
8088 MUTEX_EXIT(&rx_quota_mutex);
8095 * Routines to implement connection specific data.
8099 rx_KeyCreate(rx_destructor_t rtn)
8102 MUTEX_ENTER(&rxi_keyCreate_lock);
8103 key = rxi_keyCreate_counter++;
8104 rxi_keyCreate_destructor = (rx_destructor_t *)
8105 realloc((void *)rxi_keyCreate_destructor,
8106 (key + 1) * sizeof(rx_destructor_t));
8107 rxi_keyCreate_destructor[key] = rtn;
8108 MUTEX_EXIT(&rxi_keyCreate_lock);
8113 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
8116 MUTEX_ENTER(&conn->conn_data_lock);
8117 if (!conn->specific) {
8118 conn->specific = malloc((key + 1) * sizeof(void *));
8119 for (i = 0; i < key; i++)
8120 conn->specific[i] = NULL;
8121 conn->nSpecific = key + 1;
8122 conn->specific[key] = ptr;
8123 } else if (key >= conn->nSpecific) {
8124 conn->specific = (void **)
8125 realloc(conn->specific, (key + 1) * sizeof(void *));
8126 for (i = conn->nSpecific; i < key; i++)
8127 conn->specific[i] = NULL;
8128 conn->nSpecific = key + 1;
8129 conn->specific[key] = ptr;
8131 if (conn->specific[key] && rxi_keyCreate_destructor[key])
8132 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
8133 conn->specific[key] = ptr;
8135 MUTEX_EXIT(&conn->conn_data_lock);
8139 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
8142 MUTEX_ENTER(&svc->svc_data_lock);
8143 if (!svc->specific) {
8144 svc->specific = malloc((key + 1) * sizeof(void *));
8145 for (i = 0; i < key; i++)
8146 svc->specific[i] = NULL;
8147 svc->nSpecific = key + 1;
8148 svc->specific[key] = ptr;
8149 } else if (key >= svc->nSpecific) {
8150 svc->specific = (void **)
8151 realloc(svc->specific, (key + 1) * sizeof(void *));
8152 for (i = svc->nSpecific; i < key; i++)
8153 svc->specific[i] = NULL;
8154 svc->nSpecific = key + 1;
8155 svc->specific[key] = ptr;
8157 if (svc->specific[key] && rxi_keyCreate_destructor[key])
8158 (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
8159 svc->specific[key] = ptr;
8161 MUTEX_EXIT(&svc->svc_data_lock);
8165 rx_GetSpecific(struct rx_connection *conn, int key)
8168 MUTEX_ENTER(&conn->conn_data_lock);
8169 if (key >= conn->nSpecific)
8172 ptr = conn->specific[key];
8173 MUTEX_EXIT(&conn->conn_data_lock);
8178 rx_GetServiceSpecific(struct rx_service *svc, int key)
8181 MUTEX_ENTER(&svc->svc_data_lock);
8182 if (key >= svc->nSpecific)
8185 ptr = svc->specific[key];
8186 MUTEX_EXIT(&svc->svc_data_lock);
8191 #endif /* !KERNEL */
8194 * processStats is a queue used to store the statistics for the local
8195 * process. Its contents are similar to the contents of the rpcStats
8196 * queue on a rx_peer structure, but the actual data stored within
8197 * this queue contains totals across the lifetime of the process (assuming
8198 * the stats have not been reset) - unlike the per peer structures
8199 * which can come and go based upon the peer lifetime.
8202 static struct opr_queue processStats = { &processStats, &processStats };
8205 * peerStats is a queue used to store the statistics for all peer structs.
8206 * Its contents are the union of all the peer rpcStats queues.
8209 static struct opr_queue peerStats = { &peerStats, &peerStats };
8212 * rxi_monitor_processStats is used to turn process wide stat collection
8216 static int rxi_monitor_processStats = 0;
8219 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
8222 static int rxi_monitor_peerStats = 0;
8226 rxi_ClearRPCOpStat(rx_function_entry_v1_p rpc_stat)
8228 rpc_stat->invocations = 0;
8229 rpc_stat->bytes_sent = 0;
8230 rpc_stat->bytes_rcvd = 0;
8231 rpc_stat->queue_time_sum.sec = 0;
8232 rpc_stat->queue_time_sum.usec = 0;
8233 rpc_stat->queue_time_sum_sqr.sec = 0;
8234 rpc_stat->queue_time_sum_sqr.usec = 0;
8235 rpc_stat->queue_time_min.sec = 9999999;
8236 rpc_stat->queue_time_min.usec = 9999999;
8237 rpc_stat->queue_time_max.sec = 0;
8238 rpc_stat->queue_time_max.usec = 0;
8239 rpc_stat->execution_time_sum.sec = 0;
8240 rpc_stat->execution_time_sum.usec = 0;
8241 rpc_stat->execution_time_sum_sqr.sec = 0;
8242 rpc_stat->execution_time_sum_sqr.usec = 0;
8243 rpc_stat->execution_time_min.sec = 9999999;
8244 rpc_stat->execution_time_min.usec = 9999999;
8245 rpc_stat->execution_time_max.sec = 0;
8246 rpc_stat->execution_time_max.usec = 0;
8250 * Given all of the information for a particular rpc
8251 * call, find or create (if requested) the stat structure for the rpc.
8254 * the queue of stats that will be updated with the new value
8256 * @param rxInterface
8257 * a unique number that identifies the rpc interface
8260 * the total number of functions in this interface. this is only
8261 * required if create is true
8264 * if true, this invocation was made to a server
8267 * the ip address of the remote host. this is only required if create
8268 * and addToPeerList are true
8271 * the port of the remote host. this is only required if create
8272 * and addToPeerList are true
8274 * @param addToPeerList
8275 * if != 0, add newly created stat to the global peer list
8278 * if a new stats structure is allocated, the counter will
8279 * be updated with the new number of allocated stat structures.
8280 * only required if create is true
8283 * if no stats structure exists, allocate one
8287 static rx_interface_stat_p
8288 rxi_FindRpcStat(struct opr_queue *stats, afs_uint32 rxInterface,
8289 afs_uint32 totalFunc, int isServer, afs_uint32 remoteHost,
8290 afs_uint32 remotePort, int addToPeerList,
8291 unsigned int *counter, int create)
8293 rx_interface_stat_p rpc_stat = NULL;
8294 struct opr_queue *cursor;
8297 * See if there's already a structure for this interface
8300 for (opr_queue_Scan(stats, cursor)) {
8301 rpc_stat = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8303 if ((rpc_stat->stats[0].interfaceId == rxInterface)
8304 && (rpc_stat->stats[0].remote_is_server == isServer))
8308 /* if they didn't ask us to create, we're done */
8310 if (opr_queue_IsEnd(stats, cursor))
8316 /* can't proceed without these */
8317 if (!totalFunc || !counter)
8321 * Didn't find a match so allocate a new structure and add it to the
8325 if (opr_queue_IsEnd(stats, cursor) || (rpc_stat == NULL)
8326 || (rpc_stat->stats[0].interfaceId != rxInterface)
8327 || (rpc_stat->stats[0].remote_is_server != isServer)) {
8332 sizeof(rx_interface_stat_t) +
8333 totalFunc * sizeof(rx_function_entry_v1_t);
8335 rpc_stat = rxi_Alloc(space);
8336 if (rpc_stat == NULL)
8339 *counter += totalFunc;
8340 for (i = 0; i < totalFunc; i++) {
8341 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8342 rpc_stat->stats[i].remote_peer = remoteHost;
8343 rpc_stat->stats[i].remote_port = remotePort;
8344 rpc_stat->stats[i].remote_is_server = isServer;
8345 rpc_stat->stats[i].interfaceId = rxInterface;
8346 rpc_stat->stats[i].func_total = totalFunc;
8347 rpc_stat->stats[i].func_index = i;
8349 opr_queue_Prepend(stats, &rpc_stat->entry);
8350 if (addToPeerList) {
8351 opr_queue_Prepend(&peerStats, &rpc_stat->entryPeers);
8358 rx_ClearProcessRPCStats(afs_int32 rxInterface)
8360 rx_interface_stat_p rpc_stat;
8363 if (rxInterface == -1)
8366 MUTEX_ENTER(&rx_rpc_stats);
8367 rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8370 totalFunc = rpc_stat->stats[0].func_total;
8371 for (i = 0; i < totalFunc; i++)
8372 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8374 MUTEX_EXIT(&rx_rpc_stats);
8379 rx_ClearPeerRPCStats(afs_int32 rxInterface, afs_uint32 peerHost, afs_uint16 peerPort)
8381 rx_interface_stat_p rpc_stat;
8383 struct rx_peer * peer;
8385 if (rxInterface == -1)
8388 peer = rxi_FindPeer(peerHost, peerPort, 0);
8392 MUTEX_ENTER(&rx_rpc_stats);
8393 rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8396 totalFunc = rpc_stat->stats[0].func_total;
8397 for (i = 0; i < totalFunc; i++)
8398 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8400 MUTEX_EXIT(&rx_rpc_stats);
8405 rx_CopyProcessRPCStats(afs_uint64 op)
8407 rx_interface_stat_p rpc_stat;
8408 rx_function_entry_v1_p rpcop_stat =
8409 rxi_Alloc(sizeof(rx_function_entry_v1_t));
8410 int currentFunc = (op & MAX_AFS_UINT32);
8411 afs_int32 rxInterface = (op >> 32);
8413 if (!rxi_monitor_processStats)
8416 if (rxInterface == -1)
8419 if (rpcop_stat == NULL)
8422 MUTEX_ENTER(&rx_rpc_stats);
8423 rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8426 memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8427 sizeof(rx_function_entry_v1_t));
8428 MUTEX_EXIT(&rx_rpc_stats);
8430 rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8437 rx_CopyPeerRPCStats(afs_uint64 op, afs_uint32 peerHost, afs_uint16 peerPort)
8439 rx_interface_stat_p rpc_stat;
8440 rx_function_entry_v1_p rpcop_stat =
8441 rxi_Alloc(sizeof(rx_function_entry_v1_t));
8442 int currentFunc = (op & MAX_AFS_UINT32);
8443 afs_int32 rxInterface = (op >> 32);
8444 struct rx_peer *peer;
8446 if (!rxi_monitor_peerStats)
8449 if (rxInterface == -1)
8452 if (rpcop_stat == NULL)
8455 peer = rxi_FindPeer(peerHost, peerPort, 0);
8459 MUTEX_ENTER(&rx_rpc_stats);
8460 rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8463 memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8464 sizeof(rx_function_entry_v1_t));
8465 MUTEX_EXIT(&rx_rpc_stats);
8467 rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8474 rx_ReleaseRPCStats(void *stats)
8477 rxi_Free(stats, sizeof(rx_function_entry_v1_t));
8481 * Given all of the information for a particular rpc
8482 * call, create (if needed) and update the stat totals for the rpc.
8485 * the queue of stats that will be updated with the new value
8487 * @param rxInterface
8488 * a unique number that identifies the rpc interface
8490 * @param currentFunc
8491 * the index of the function being invoked
8494 * the total number of functions in this interface
8497 * the amount of time this function waited for a thread
8500 * the amount of time this function invocation took to execute
8503 * the number bytes sent by this invocation
8506 * the number bytes received by this invocation
8509 * if true, this invocation was made to a server
8512 * the ip address of the remote host
8515 * the port of the remote host
8517 * @param addToPeerList
8518 * if != 0, add newly created stat to the global peer list
8521 * if a new stats structure is allocated, the counter will
8522 * be updated with the new number of allocated stat structures
8527 rxi_AddRpcStat(struct opr_queue *stats, afs_uint32 rxInterface,
8528 afs_uint32 currentFunc, afs_uint32 totalFunc,
8529 struct clock *queueTime, struct clock *execTime,
8530 afs_uint64 bytesSent, afs_uint64 bytesRcvd, int isServer,
8531 afs_uint32 remoteHost, afs_uint32 remotePort,
8532 int addToPeerList, unsigned int *counter)
8535 rx_interface_stat_p rpc_stat;
8537 rpc_stat = rxi_FindRpcStat(stats, rxInterface, totalFunc, isServer,
8538 remoteHost, remotePort, addToPeerList, counter,
8546 * Increment the stats for this function
8549 rpc_stat->stats[currentFunc].invocations++;
8550 rpc_stat->stats[currentFunc].bytes_sent += bytesSent;
8551 rpc_stat->stats[currentFunc].bytes_rcvd += bytesRcvd;
8552 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8553 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8554 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8555 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8557 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8558 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8560 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8561 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8563 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8564 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8566 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8567 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8575 rxi_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8576 afs_uint32 currentFunc, afs_uint32 totalFunc,
8577 struct clock *queueTime, struct clock *execTime,
8578 afs_uint64 bytesSent, afs_uint64 bytesRcvd,
8582 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8585 MUTEX_ENTER(&rx_rpc_stats);
8587 if (rxi_monitor_peerStats) {
8588 MUTEX_ENTER(&peer->peer_lock);
8589 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8590 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8591 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8592 MUTEX_EXIT(&peer->peer_lock);
8595 if (rxi_monitor_processStats) {
8596 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8597 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8598 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8601 MUTEX_EXIT(&rx_rpc_stats);
8605 * Increment the times and count for a particular rpc function.
8607 * Traditionally this call was invoked from rxgen stubs. Modern stubs
8608 * call rx_RecordCallStatistics instead, so the public version of this
8609 * function is left purely for legacy callers.
8612 * The peer who invoked the rpc
8614 * @param rxInterface
8615 * A unique number that identifies the rpc interface
8617 * @param currentFunc
8618 * The index of the function being invoked
8621 * The total number of functions in this interface
8624 * The amount of time this function waited for a thread
8627 * The amount of time this function invocation took to execute
8630 * The number bytes sent by this invocation
8633 * The number bytes received by this invocation
8636 * If true, this invocation was made to a server
8640 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8641 afs_uint32 currentFunc, afs_uint32 totalFunc,
8642 struct clock *queueTime, struct clock *execTime,
8643 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8649 sent64 = ((afs_uint64)bytesSent->high << 32) + bytesSent->low;
8650 rcvd64 = ((afs_uint64)bytesRcvd->high << 32) + bytesRcvd->low;
8652 rxi_IncrementTimeAndCount(peer, rxInterface, currentFunc, totalFunc,
8653 queueTime, execTime, sent64, rcvd64,
8660 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8664 * IN callerVersion - the rpc stat version of the caller.
8666 * IN count - the number of entries to marshall.
8668 * IN stats - pointer to stats to be marshalled.
8670 * OUT ptr - Where to store the marshalled data.
8677 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8678 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8684 * We only support the first version
8686 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8687 *(ptr++) = stats->remote_peer;
8688 *(ptr++) = stats->remote_port;
8689 *(ptr++) = stats->remote_is_server;
8690 *(ptr++) = stats->interfaceId;
8691 *(ptr++) = stats->func_total;
8692 *(ptr++) = stats->func_index;
8693 *(ptr++) = stats->invocations >> 32;
8694 *(ptr++) = stats->invocations & MAX_AFS_UINT32;
8695 *(ptr++) = stats->bytes_sent >> 32;
8696 *(ptr++) = stats->bytes_sent & MAX_AFS_UINT32;
8697 *(ptr++) = stats->bytes_rcvd >> 32;
8698 *(ptr++) = stats->bytes_rcvd & MAX_AFS_UINT32;
8699 *(ptr++) = stats->queue_time_sum.sec;
8700 *(ptr++) = stats->queue_time_sum.usec;
8701 *(ptr++) = stats->queue_time_sum_sqr.sec;
8702 *(ptr++) = stats->queue_time_sum_sqr.usec;
8703 *(ptr++) = stats->queue_time_min.sec;
8704 *(ptr++) = stats->queue_time_min.usec;
8705 *(ptr++) = stats->queue_time_max.sec;
8706 *(ptr++) = stats->queue_time_max.usec;
8707 *(ptr++) = stats->execution_time_sum.sec;
8708 *(ptr++) = stats->execution_time_sum.usec;
8709 *(ptr++) = stats->execution_time_sum_sqr.sec;
8710 *(ptr++) = stats->execution_time_sum_sqr.usec;
8711 *(ptr++) = stats->execution_time_min.sec;
8712 *(ptr++) = stats->execution_time_min.usec;
8713 *(ptr++) = stats->execution_time_max.sec;
8714 *(ptr++) = stats->execution_time_max.usec;
8720 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8725 * IN callerVersion - the rpc stat version of the caller
8727 * OUT myVersion - the rpc stat version of this function
8729 * OUT clock_sec - local time seconds
8731 * OUT clock_usec - local time microseconds
8733 * OUT allocSize - the number of bytes allocated to contain stats
8735 * OUT statCount - the number stats retrieved from this process.
8737 * OUT stats - the actual stats retrieved from this process.
8741 * Returns void. If successful, stats will != NULL.
8745 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8746 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8747 size_t * allocSize, afs_uint32 * statCount,
8748 afs_uint32 ** stats)
8758 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8761 * Check to see if stats are enabled
8764 MUTEX_ENTER(&rx_rpc_stats);
8765 if (!rxi_monitor_processStats) {
8766 MUTEX_EXIT(&rx_rpc_stats);
8770 clock_GetTime(&now);
8771 *clock_sec = now.sec;
8772 *clock_usec = now.usec;
8775 * Allocate the space based upon the caller version
8777 * If the client is at an older version than we are,
8778 * we return the statistic data in the older data format, but
8779 * we still return our version number so the client knows we
8780 * are maintaining more data than it can retrieve.
8783 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8784 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8785 *statCount = rxi_rpc_process_stat_cnt;
8788 * This can't happen yet, but in the future version changes
8789 * can be handled by adding additional code here
8793 if (space > (size_t) 0) {
8795 ptr = *stats = rxi_Alloc(space);
8798 struct opr_queue *cursor;
8800 for (opr_queue_Scan(&processStats, cursor)) {
8801 struct rx_interface_stat *rpc_stat =
8802 opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8804 * Copy the data based upon the caller version
8806 rx_MarshallProcessRPCStats(callerVersion,
8807 rpc_stat->stats[0].func_total,
8808 rpc_stat->stats, &ptr);
8814 MUTEX_EXIT(&rx_rpc_stats);
8819 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8823 * IN callerVersion - the rpc stat version of the caller
8825 * OUT myVersion - the rpc stat version of this function
8827 * OUT clock_sec - local time seconds
8829 * OUT clock_usec - local time microseconds
8831 * OUT allocSize - the number of bytes allocated to contain stats
8833 * OUT statCount - the number of stats retrieved from the individual
8836 * OUT stats - the actual stats retrieved from the individual peer structures.
8840 * Returns void. If successful, stats will != NULL.
8844 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8845 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8846 size_t * allocSize, afs_uint32 * statCount,
8847 afs_uint32 ** stats)
8857 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8860 * Check to see if stats are enabled
8863 MUTEX_ENTER(&rx_rpc_stats);
8864 if (!rxi_monitor_peerStats) {
8865 MUTEX_EXIT(&rx_rpc_stats);
8869 clock_GetTime(&now);
8870 *clock_sec = now.sec;
8871 *clock_usec = now.usec;
8874 * Allocate the space based upon the caller version
8876 * If the client is at an older version than we are,
8877 * we return the statistic data in the older data format, but
8878 * we still return our version number so the client knows we
8879 * are maintaining more data than it can retrieve.
8882 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8883 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8884 *statCount = rxi_rpc_peer_stat_cnt;
8887 * This can't happen yet, but in the future version changes
8888 * can be handled by adding additional code here
8892 if (space > (size_t) 0) {
8894 ptr = *stats = rxi_Alloc(space);
8897 struct opr_queue *cursor;
8899 for (opr_queue_Scan(&peerStats, cursor)) {
8900 struct rx_interface_stat *rpc_stat
8901 = opr_queue_Entry(cursor, struct rx_interface_stat,
8905 * Copy the data based upon the caller version
8907 rx_MarshallProcessRPCStats(callerVersion,
8908 rpc_stat->stats[0].func_total,
8909 rpc_stat->stats, &ptr);
8915 MUTEX_EXIT(&rx_rpc_stats);
8920 * rx_FreeRPCStats - free memory allocated by
8921 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
8925 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
8926 * rx_RetrievePeerRPCStats
8928 * IN allocSize - the number of bytes in stats.
8936 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
8938 rxi_Free(stats, allocSize);
8942 * rx_queryProcessRPCStats - see if process rpc stat collection is
8943 * currently enabled.
8949 * Returns 0 if stats are not enabled != 0 otherwise
8953 rx_queryProcessRPCStats(void)
8956 MUTEX_ENTER(&rx_rpc_stats);
8957 rc = rxi_monitor_processStats;
8958 MUTEX_EXIT(&rx_rpc_stats);
8963 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
8969 * Returns 0 if stats are not enabled != 0 otherwise
8973 rx_queryPeerRPCStats(void)
8976 MUTEX_ENTER(&rx_rpc_stats);
8977 rc = rxi_monitor_peerStats;
8978 MUTEX_EXIT(&rx_rpc_stats);
8983 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
8993 rx_enableProcessRPCStats(void)
8995 MUTEX_ENTER(&rx_rpc_stats);
8996 rx_enable_stats = 1;
8997 rxi_monitor_processStats = 1;
8998 MUTEX_EXIT(&rx_rpc_stats);
9002 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
9012 rx_enablePeerRPCStats(void)
9014 MUTEX_ENTER(&rx_rpc_stats);
9015 rx_enable_stats = 1;
9016 rxi_monitor_peerStats = 1;
9017 MUTEX_EXIT(&rx_rpc_stats);
9021 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
9031 rx_disableProcessRPCStats(void)
9033 struct opr_queue *cursor, *store;
9036 MUTEX_ENTER(&rx_rpc_stats);
9039 * Turn off process statistics and if peer stats is also off, turn
9043 rxi_monitor_processStats = 0;
9044 if (rxi_monitor_peerStats == 0) {
9045 rx_enable_stats = 0;
9048 for (opr_queue_ScanSafe(&processStats, cursor, store)) {
9049 unsigned int num_funcs = 0;
9050 struct rx_interface_stat *rpc_stat
9051 = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
9053 opr_queue_Remove(&rpc_stat->entry);
9055 num_funcs = rpc_stat->stats[0].func_total;
9057 sizeof(rx_interface_stat_t) +
9058 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
9060 rxi_Free(rpc_stat, space);
9061 rxi_rpc_process_stat_cnt -= num_funcs;
9063 MUTEX_EXIT(&rx_rpc_stats);
9067 * rx_disablePeerRPCStats - stop rpc stat collection for peers
9077 rx_disablePeerRPCStats(void)
9079 struct rx_peer **peer_ptr, **peer_end;
9083 * Turn off peer statistics and if process stats is also off, turn
9087 rxi_monitor_peerStats = 0;
9088 if (rxi_monitor_processStats == 0) {
9089 rx_enable_stats = 0;
9092 for (peer_ptr = &rx_peerHashTable[0], peer_end =
9093 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
9095 struct rx_peer *peer, *next, *prev;
9097 MUTEX_ENTER(&rx_peerHashTable_lock);
9098 MUTEX_ENTER(&rx_rpc_stats);
9099 for (prev = peer = *peer_ptr; peer; peer = next) {
9101 code = MUTEX_TRYENTER(&peer->peer_lock);
9104 struct opr_queue *cursor, *store;
9106 if (prev == *peer_ptr) {
9117 MUTEX_EXIT(&rx_peerHashTable_lock);
9119 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
9120 unsigned int num_funcs = 0;
9121 struct rx_interface_stat *rpc_stat
9122 = opr_queue_Entry(cursor, struct rx_interface_stat,
9125 opr_queue_Remove(&rpc_stat->entry);
9126 opr_queue_Remove(&rpc_stat->entryPeers);
9127 num_funcs = rpc_stat->stats[0].func_total;
9129 sizeof(rx_interface_stat_t) +
9130 rpc_stat->stats[0].func_total *
9131 sizeof(rx_function_entry_v1_t);
9133 rxi_Free(rpc_stat, space);
9134 rxi_rpc_peer_stat_cnt -= num_funcs;
9136 MUTEX_EXIT(&peer->peer_lock);
9138 MUTEX_ENTER(&rx_peerHashTable_lock);
9148 MUTEX_EXIT(&rx_rpc_stats);
9149 MUTEX_EXIT(&rx_peerHashTable_lock);
9154 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
9159 * IN clearFlag - flag indicating which stats to clear
9167 rx_clearProcessRPCStats(afs_uint32 clearFlag)
9169 struct opr_queue *cursor;
9171 MUTEX_ENTER(&rx_rpc_stats);
9173 for (opr_queue_Scan(&processStats, cursor)) {
9174 unsigned int num_funcs = 0, i;
9175 struct rx_interface_stat *rpc_stat
9176 = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
9178 num_funcs = rpc_stat->stats[0].func_total;
9179 for (i = 0; i < num_funcs; i++) {
9180 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9181 rpc_stat->stats[i].invocations = 0;
9183 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9184 rpc_stat->stats[i].bytes_sent = 0;
9186 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9187 rpc_stat->stats[i].bytes_rcvd = 0;
9189 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9190 rpc_stat->stats[i].queue_time_sum.sec = 0;
9191 rpc_stat->stats[i].queue_time_sum.usec = 0;
9193 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9194 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9195 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9197 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9198 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9199 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9201 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9202 rpc_stat->stats[i].queue_time_max.sec = 0;
9203 rpc_stat->stats[i].queue_time_max.usec = 0;
9205 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9206 rpc_stat->stats[i].execution_time_sum.sec = 0;
9207 rpc_stat->stats[i].execution_time_sum.usec = 0;
9209 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9210 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9211 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9213 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9214 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9215 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9217 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9218 rpc_stat->stats[i].execution_time_max.sec = 0;
9219 rpc_stat->stats[i].execution_time_max.usec = 0;
9224 MUTEX_EXIT(&rx_rpc_stats);
9228 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
9233 * IN clearFlag - flag indicating which stats to clear
9241 rx_clearPeerRPCStats(afs_uint32 clearFlag)
9243 struct opr_queue *cursor;
9245 MUTEX_ENTER(&rx_rpc_stats);
9247 for (opr_queue_Scan(&peerStats, cursor)) {
9248 unsigned int num_funcs, i;
9249 struct rx_interface_stat *rpc_stat
9250 = opr_queue_Entry(cursor, struct rx_interface_stat, entryPeers);
9252 num_funcs = rpc_stat->stats[0].func_total;
9253 for (i = 0; i < num_funcs; i++) {
9254 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9255 rpc_stat->stats[i].invocations = 0;
9257 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9258 rpc_stat->stats[i].bytes_sent = 0;
9260 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9261 rpc_stat->stats[i].bytes_rcvd = 0;
9263 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9264 rpc_stat->stats[i].queue_time_sum.sec = 0;
9265 rpc_stat->stats[i].queue_time_sum.usec = 0;
9267 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9268 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9269 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9271 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9272 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9273 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9275 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9276 rpc_stat->stats[i].queue_time_max.sec = 0;
9277 rpc_stat->stats[i].queue_time_max.usec = 0;
9279 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9280 rpc_stat->stats[i].execution_time_sum.sec = 0;
9281 rpc_stat->stats[i].execution_time_sum.usec = 0;
9283 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9284 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9285 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9287 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9288 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9289 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9291 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9292 rpc_stat->stats[i].execution_time_max.sec = 0;
9293 rpc_stat->stats[i].execution_time_max.usec = 0;
9298 MUTEX_EXIT(&rx_rpc_stats);
9302 * rxi_rxstat_userok points to a routine that returns 1 if the caller
9303 * is authorized to enable/disable/clear RX statistics.
9305 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
9308 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
9310 rxi_rxstat_userok = proc;
9314 rx_RxStatUserOk(struct rx_call *call)
9316 if (!rxi_rxstat_userok)
9318 return rxi_rxstat_userok(call);
9323 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
9324 * function in the MSVC runtime DLL (msvcrt.dll).
9326 * Note: the system serializes calls to this function.
9329 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
9330 DWORD reason, /* reason function is being called */
9331 LPVOID reserved) /* reserved for future use */
9334 case DLL_PROCESS_ATTACH:
9335 /* library is being attached to a process */
9339 case DLL_PROCESS_DETACH:
9346 #endif /* AFS_NT40_ENV */
9349 int rx_DumpCalls(FILE *outputFile, char *cookie)
9351 #ifdef RXDEBUG_PACKET
9352 #ifdef KDUMP_RX_LOCK
9353 struct rx_call_rx_lock *c;
9360 #define RXDPRINTF sprintf
9361 #define RXDPRINTOUT output
9363 #define RXDPRINTF fprintf
9364 #define RXDPRINTOUT outputFile
9367 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
9369 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9372 for (c = rx_allCallsp; c; c = c->allNextp) {
9373 u_short rqc, tqc, iovqc;
9375 MUTEX_ENTER(&c->lock);
9376 rqc = opr_queue_Count(&c->rq);
9377 tqc = opr_queue_Count(&c->tq);
9378 iovqc = opr_queue_Count(&c->app.iovq);
9380 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, "
9381 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
9382 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
9383 "resendEvent=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
9384 "lastSendTime=%u, lastRecvTime=%u"
9385 #ifdef RX_ENABLE_LOCKS
9388 #ifdef RX_REFCOUNT_CHECK
9389 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
9390 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
9393 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,
9394 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
9395 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
9396 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
9397 c->resendEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
9398 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime
9399 #ifdef RX_ENABLE_LOCKS
9400 , (afs_uint32)c->refCount
9402 #ifdef RX_REFCOUNT_CHECK
9403 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
9406 MUTEX_EXIT(&c->lock);
9409 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9412 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
9414 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9416 #endif /* RXDEBUG_PACKET */
9422 rxi_NetSend(osi_socket socket, void *addr, struct iovec *dvec,
9423 int nvecs, int length, int istack)
9425 return osi_NetSend(socket, addr, dvec, nvecs, length, istack);