2 * Copyright 2000, International Business Machines Corporation and others.
5 * This software has been released under the terms of the IBM Public
6 * License. For details, see the LICENSE file in the top-level source
7 * directory or online at http://www.openafs.org/dl/license10.html
10 /* RX: Extended Remote Procedure Call */
12 #include <afsconfig.h>
13 #include <afs/param.h>
16 # include "afs/sysincludes.h"
17 # include "afsincludes.h"
22 # ifdef AFS_LINUX20_ENV
23 # include "h/socket.h"
25 # include "netinet/in.h"
27 # include "netinet/ip6.h"
28 # include "inet/common.h"
30 # include "inet/ip_ire.h"
32 # include "afs/afs_args.h"
33 # include "afs/afs_osi.h"
34 # ifdef RX_KERNEL_TRACE
35 # include "rx_kcommon.h"
37 # if defined(AFS_AIX_ENV)
41 # undef RXDEBUG /* turn off debugging */
43 # if defined(AFS_SGI_ENV)
44 # include "sys/debug.h"
47 # include "afs/sysincludes.h"
48 # include "afsincludes.h"
49 # endif /* !UKERNEL */
50 # include "afs/lock.h"
51 # include "rx_kmutex.h"
52 # include "rx_kernel.h"
53 # define AFSOP_STOP_RXCALLBACK 210 /* Stop CALLBACK process */
54 # define AFSOP_STOP_AFS 211 /* Stop AFS process */
55 # define AFSOP_STOP_BKG 212 /* Stop BKG process */
56 extern afs_int32 afs_termState;
58 # include "sys/lockl.h"
59 # include "sys/lock_def.h"
60 # endif /* AFS_AIX41_ENV */
61 # include "afs/rxgen_consts.h"
66 # include <afs/afsutil.h>
67 # include <WINNT\afsreg.h>
75 #include <opr/queue.h>
76 #include <hcrypto/rand.h>
80 #include "rx_atomic.h"
81 #include "rx_globals.h"
83 #include "rx_internal.h"
90 #include "rx_packet.h"
91 #include "rx_server.h"
93 #include <afs/rxgen_consts.h>
96 #ifdef AFS_PTHREAD_ENV
98 int (*registerProgram) (pid_t, char *) = 0;
99 int (*swapNameProgram) (pid_t, const char *, char *) = 0;
102 int (*registerProgram) (PROCESS, char *) = 0;
103 int (*swapNameProgram) (PROCESS, const char *, char *) = 0;
107 /* Local static routines */
108 static void rxi_DestroyConnectionNoLock(struct rx_connection *conn);
109 static void rxi_ComputeRoundTripTime(struct rx_packet *, struct rx_ackPacket *,
110 struct rx_call *, struct rx_peer *,
112 static void rxi_Resend(struct rxevent *event, void *arg0, void *arg1,
114 static void rxi_SendDelayedAck(struct rxevent *event, void *call,
115 void *dummy, int dummy2);
116 static void rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1,
117 void *dummy, int dummy2);
118 static void rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1,
119 void *unused, int unused2);
120 static void rxi_ReapConnections(struct rxevent *unused, void *unused1,
121 void *unused2, int unused3);
122 static struct rx_packet *rxi_SendCallAbort(struct rx_call *call,
123 struct rx_packet *packet,
124 int istack, int force);
125 static void rxi_AckAll(struct rx_call *call);
126 static struct rx_connection
127 *rxi_FindConnection(osi_socket socket, afs_uint32 host, u_short port,
128 u_short serviceId, afs_uint32 cid,
129 afs_uint32 epoch, int type, u_int securityIndex,
130 int *unknownService);
131 static struct rx_packet
132 *rxi_ReceiveDataPacket(struct rx_call *call, struct rx_packet *np,
133 int istack, osi_socket socket,
134 afs_uint32 host, u_short port, int *tnop,
135 struct rx_call **newcallp);
136 static struct rx_packet
137 *rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
139 static struct rx_packet
140 *rxi_ReceiveResponsePacket(struct rx_connection *conn,
141 struct rx_packet *np, int istack);
142 static struct rx_packet
143 *rxi_ReceiveChallengePacket(struct rx_connection *conn,
144 struct rx_packet *np, int istack);
145 static void rxi_AttachServerProc(struct rx_call *call, osi_socket socket,
146 int *tnop, struct rx_call **newcallp);
147 static void rxi_ClearTransmitQueue(struct rx_call *call, int force);
148 static void rxi_ClearReceiveQueue(struct rx_call *call);
149 static void rxi_ResetCall(struct rx_call *call, int newcall);
150 static void rxi_ScheduleKeepAliveEvent(struct rx_call *call);
151 static void rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn);
152 static void rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs);
153 static void rxi_KeepAliveOn(struct rx_call *call);
154 static void rxi_GrowMTUOn(struct rx_call *call);
155 static void rxi_ChallengeOn(struct rx_connection *conn);
156 static int rxi_CheckCall(struct rx_call *call, int haveCTLock);
157 static void rxi_AckAllInTransmitQueue(struct rx_call *call);
158 static void rxi_CancelKeepAliveEvent(struct rx_call *call);
159 static void rxi_CancelDelayedAbortEvent(struct rx_call *call);
160 static void rxi_CancelGrowMTUEvent(struct rx_call *call);
161 static void update_nextCid(void);
164 static void rxi_Finalize_locked(void);
165 #elif defined(UKERNEL)
166 # define rxi_Finalize_locked() do { } while (0)
169 #ifdef RX_ENABLE_LOCKS
171 rx_atomic_t rxi_start_aborted; /* rxi_start awoke after rxi_Send in error.*/
172 rx_atomic_t rxi_start_in_error;
174 #endif /* RX_ENABLE_LOCKS */
176 /* Constant delay time before sending an acknowledge of the last packet
177 * received. This is to avoid sending an extra acknowledge when the
178 * client is about to make another call, anyway, or the server is
181 * The lastAckDelay may not exceeed 400ms without causing peers to
182 * unecessarily timeout.
184 struct clock rx_lastAckDelay = {0, 400000};
186 /* Constant delay time before sending a soft ack when none was requested.
187 * This is to make sure we send soft acks before the sender times out,
188 * Normally we wait and send a hard ack when the receiver consumes the packet
190 * This value has been 100ms in all shipping versions of OpenAFS. Changing it
191 * will require changes to the peer's RTT calculations.
193 struct clock rx_softAckDelay = {0, 100000};
196 * rxi_rpc_peer_stat_cnt counts the total number of peer stat structures
197 * currently allocated within rx. This number is used to allocate the
198 * memory required to return the statistics when queried.
199 * Protected by the rx_rpc_stats mutex.
202 static unsigned int rxi_rpc_peer_stat_cnt;
205 * rxi_rpc_process_stat_cnt counts the total number of local process stat
206 * structures currently allocated within rx. The number is used to allocate
207 * the memory required to return the statistics when queried.
208 * Protected by the rx_rpc_stats mutex.
211 static unsigned int rxi_rpc_process_stat_cnt;
213 rx_atomic_t rx_nWaiting = RX_ATOMIC_INIT(0);
214 rx_atomic_t rx_nWaited = RX_ATOMIC_INIT(0);
216 /* Incoming calls wait on this queue when there are no available
217 * server processes */
218 struct opr_queue rx_incomingCallQueue;
220 /* Server processes wait on this queue when there are no appropriate
221 * calls to process */
222 struct opr_queue rx_idleServerQueue;
224 #if !defined(offsetof)
225 #include <stddef.h> /* for definition of offsetof() */
228 #ifdef RX_ENABLE_LOCKS
229 afs_kmutex_t rx_atomic_mutex;
232 /* Forward prototypes */
233 static struct rx_call * rxi_NewCall(struct rx_connection *, int);
236 putConnection (struct rx_connection *conn) {
237 MUTEX_ENTER(&rx_refcnt_mutex);
239 MUTEX_EXIT(&rx_refcnt_mutex);
242 #ifdef AFS_PTHREAD_ENV
245 * Use procedural initialization of mutexes/condition variables
249 extern afs_kmutex_t rx_quota_mutex;
250 extern afs_kmutex_t rx_pthread_mutex;
251 extern afs_kmutex_t rx_packets_mutex;
252 extern afs_kmutex_t rx_refcnt_mutex;
253 extern afs_kmutex_t des_init_mutex;
254 extern afs_kmutex_t des_random_mutex;
256 extern afs_kmutex_t rx_clock_mutex;
257 extern afs_kmutex_t rxi_connCacheMutex;
258 extern afs_kmutex_t event_handler_mutex;
259 extern afs_kmutex_t listener_mutex;
260 extern afs_kmutex_t rx_if_init_mutex;
261 extern afs_kmutex_t rx_if_mutex;
263 extern afs_kcondvar_t rx_event_handler_cond;
264 extern afs_kcondvar_t rx_listener_cond;
267 static afs_kmutex_t epoch_mutex;
268 static afs_kmutex_t rx_init_mutex;
269 static afs_kmutex_t rx_debug_mutex;
270 static afs_kmutex_t rx_rpc_stats;
273 rxi_InitPthread(void)
275 MUTEX_INIT(&rx_quota_mutex, "quota", MUTEX_DEFAULT, 0);
276 MUTEX_INIT(&rx_pthread_mutex, "pthread", MUTEX_DEFAULT, 0);
277 MUTEX_INIT(&rx_packets_mutex, "packets", MUTEX_DEFAULT, 0);
278 MUTEX_INIT(&rx_refcnt_mutex, "refcnts", MUTEX_DEFAULT, 0);
280 MUTEX_INIT(&rx_clock_mutex, "clock", MUTEX_DEFAULT, 0);
281 MUTEX_INIT(&rxi_connCacheMutex, "conn cache", MUTEX_DEFAULT, 0);
282 MUTEX_INIT(&event_handler_mutex, "event handler", MUTEX_DEFAULT, 0);
283 MUTEX_INIT(&listener_mutex, "listener", MUTEX_DEFAULT, 0);
284 MUTEX_INIT(&rx_if_init_mutex, "if init", MUTEX_DEFAULT, 0);
285 MUTEX_INIT(&rx_if_mutex, "if", MUTEX_DEFAULT, 0);
287 MUTEX_INIT(&rx_stats_mutex, "stats", MUTEX_DEFAULT, 0);
288 MUTEX_INIT(&rx_atomic_mutex, "atomic", MUTEX_DEFAULT, 0);
289 MUTEX_INIT(&epoch_mutex, "epoch", MUTEX_DEFAULT, 0);
290 MUTEX_INIT(&rx_init_mutex, "init", MUTEX_DEFAULT, 0);
291 MUTEX_INIT(&rx_debug_mutex, "debug", MUTEX_DEFAULT, 0);
294 CV_INIT(&rx_event_handler_cond, "evhand", CV_DEFAULT, 0);
295 CV_INIT(&rx_listener_cond, "rxlisten", CV_DEFAULT, 0);
298 osi_Assert(pthread_key_create(&rx_thread_id_key, NULL) == 0);
299 osi_Assert(pthread_key_create(&rx_ts_info_key, NULL) == 0);
301 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
302 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
303 MUTEX_INIT(&rx_mallocedPktQ_lock, "rx_mallocedPktQ_lock", MUTEX_DEFAULT,
306 #ifdef RX_ENABLE_LOCKS
309 #endif /* RX_LOCKS_DB */
310 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
311 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
313 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
315 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
317 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
319 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
321 MUTEX_INIT(&rxi_keyCreate_lock, "rxi_keyCreate_lock", MUTEX_DEFAULT, 0);
323 #endif /* RX_ENABLE_LOCKS */
326 pthread_once_t rx_once_init = PTHREAD_ONCE_INIT;
327 #define INIT_PTHREAD_LOCKS osi_Assert(pthread_once(&rx_once_init, rxi_InitPthread)==0)
329 * The rx_stats_mutex mutex protects the following global variables:
330 * rxi_lowConnRefCount
331 * rxi_lowPeerRefCount
340 * The rx_quota_mutex mutex protects the following global variables:
348 * The rx_freePktQ_lock protects the following global variables:
353 * The rx_packets_mutex mutex protects the following global variables:
361 * The rx_pthread_mutex mutex protects the following global variables:
362 * rxi_fcfs_thread_num
365 #define INIT_PTHREAD_LOCKS
369 /* Variables for handling the minProcs implementation. availProcs gives the
370 * number of threads available in the pool at this moment (not counting dudes
371 * executing right now). totalMin gives the total number of procs required
372 * for handling all minProcs requests. minDeficit is a dynamic variable
373 * tracking the # of procs required to satisfy all of the remaining minProcs
375 * For fine grain locking to work, the quota check and the reservation of
376 * a server thread has to come while rxi_availProcs and rxi_minDeficit
377 * are locked. To this end, the code has been modified under #ifdef
378 * RX_ENABLE_LOCKS so that quota checks and reservation occur at the
379 * same time. A new function, ReturnToServerPool() returns the allocation.
381 * A call can be on several queue's (but only one at a time). When
382 * rxi_ResetCall wants to remove the call from a queue, it has to ensure
383 * that no one else is touching the queue. To this end, we store the address
384 * of the queue lock in the call structure (under the call lock) when we
385 * put the call on a queue, and we clear the call_queue_lock when the
386 * call is removed from a queue (once the call lock has been obtained).
387 * This allows rxi_ResetCall to safely synchronize with others wishing
388 * to manipulate the queue.
391 #if defined(RX_ENABLE_LOCKS)
392 static afs_kmutex_t rx_rpc_stats;
395 /* We keep a "last conn pointer" in rxi_FindConnection. The odds are
396 ** pretty good that the next packet coming in is from the same connection
397 ** as the last packet, since we're send multiple packets in a transmit window.
399 struct rx_connection *rxLastConn = 0;
401 #ifdef RX_ENABLE_LOCKS
402 /* The locking hierarchy for rx fine grain locking is composed of these
405 * rx_connHashTable_lock - synchronizes conn creation, rx_connHashTable access
406 * also protects updates to rx_nextCid
407 * conn_call_lock - used to synchonize rx_EndCall and rx_NewCall
408 * call->lock - locks call data fields.
409 * These are independent of each other:
410 * rx_freeCallQueue_lock
415 * serverQueueEntry->lock
416 * rx_peerHashTable_lock - locked under rx_connHashTable_lock
418 * peer->lock - locks peer data fields.
419 * conn_data_lock - that more than one thread is not updating a conn data
420 * field at the same time.
431 * Do we need a lock to protect the peer field in the conn structure?
432 * conn->peer was previously a constant for all intents and so has no
433 * lock protecting this field. The multihomed client delta introduced
434 * a RX code change : change the peer field in the connection structure
435 * to that remote interface from which the last packet for this
436 * connection was sent out. This may become an issue if further changes
439 #define SET_CALL_QUEUE_LOCK(C, L) (C)->call_queue_lock = (L)
440 #define CLEAR_CALL_QUEUE_LOCK(C) (C)->call_queue_lock = NULL
442 /* rxdb_fileID is used to identify the lock location, along with line#. */
443 static int rxdb_fileID = RXDB_FILE_RX;
444 #endif /* RX_LOCKS_DB */
445 #else /* RX_ENABLE_LOCKS */
446 #define SET_CALL_QUEUE_LOCK(C, L)
447 #define CLEAR_CALL_QUEUE_LOCK(C)
448 #endif /* RX_ENABLE_LOCKS */
449 struct rx_serverQueueEntry *rx_waitForPacket = 0;
452 * This mutex serializes calls to our initialization and shutdown routines
453 * (rx_InitHost, rx_Finalize and shutdown_rx). Only one thread can be running
454 * these at any time; all other threads must wait for it to finish running, and
455 * then examine the value of rxi_running afterwards.
457 #ifdef AFS_PTHREAD_ENV
458 # define LOCK_RX_INIT MUTEX_ENTER(&rx_init_mutex)
459 # define UNLOCK_RX_INIT MUTEX_EXIT(&rx_init_mutex)
461 # define LOCK_RX_INIT
462 # define UNLOCK_RX_INIT
465 /* ------------Exported Interfaces------------- */
467 static rx_atomic_t rxi_running = RX_ATOMIC_INIT(0);
471 return rx_atomic_read(&rxi_running);
474 /* Initialize rx. A port number may be mentioned, in which case this
475 * becomes the default port number for any service installed later.
476 * If 0 is provided for the port number, a random port will be chosen
477 * by the kernel. Whether this will ever overlap anything in
478 * /etc/services is anybody's guess... Returns 0 on success, -1 on
481 rx_InitHost(u_int host, u_int port)
488 char *htable, *ptable;
494 if (rxi_IsRunning()) {
496 return 0; /* already started */
502 if (afs_winsockInit() < 0)
508 * Initialize anything necessary to provide a non-premptive threading
511 rxi_InitializeThreadSupport();
514 /* Allocate and initialize a socket for client and perhaps server
517 rx_socket = rxi_GetHostUDPSocket(host, (u_short) port);
518 if (rx_socket == OSI_NULLSOCKET) {
521 #if defined(RX_ENABLE_LOCKS) && defined(KERNEL)
524 #endif /* RX_LOCKS_DB */
525 MUTEX_INIT(&rx_stats_mutex, "rx_stats_mutex", MUTEX_DEFAULT, 0);
526 MUTEX_INIT(&rx_quota_mutex, "rx_quota_mutex", MUTEX_DEFAULT, 0);
527 MUTEX_INIT(&rx_atomic_mutex, "rx_atomic_mutex", MUTEX_DEFAULT, 0);
528 MUTEX_INIT(&rx_pthread_mutex, "rx_pthread_mutex", MUTEX_DEFAULT, 0);
529 MUTEX_INIT(&rx_packets_mutex, "rx_packets_mutex", MUTEX_DEFAULT, 0);
530 MUTEX_INIT(&rx_refcnt_mutex, "rx_refcnt_mutex", MUTEX_DEFAULT, 0);
531 MUTEX_INIT(&rx_rpc_stats, "rx_rpc_stats", MUTEX_DEFAULT, 0);
532 MUTEX_INIT(&rx_freePktQ_lock, "rx_freePktQ_lock", MUTEX_DEFAULT, 0);
533 MUTEX_INIT(&freeSQEList_lock, "freeSQEList lock", MUTEX_DEFAULT, 0);
534 MUTEX_INIT(&rx_freeCallQueue_lock, "rx_freeCallQueue_lock", MUTEX_DEFAULT,
536 CV_INIT(&rx_waitingForPackets_cv, "rx_waitingForPackets_cv", CV_DEFAULT,
538 MUTEX_INIT(&rx_peerHashTable_lock, "rx_peerHashTable_lock", MUTEX_DEFAULT,
540 MUTEX_INIT(&rx_connHashTable_lock, "rx_connHashTable_lock", MUTEX_DEFAULT,
542 MUTEX_INIT(&rx_serverPool_lock, "rx_serverPool_lock", MUTEX_DEFAULT, 0);
543 MUTEX_INIT(&rx_mallocedPktQ_lock, "rx_mallocedPktQ_lock", MUTEX_DEFAULT,
546 #if defined(AFS_HPUX110_ENV)
548 rx_sleepLock = alloc_spinlock(LAST_HELD_ORDER - 10, "rx_sleepLock");
549 #endif /* AFS_HPUX110_ENV */
550 #endif /* RX_ENABLE_LOCKS && KERNEL */
553 rx_connDeadTime = 12;
554 rx_tranquil = 0; /* reset flag */
555 rxi_ResetStatistics();
556 htable = osi_Alloc(rx_hashTableSize * sizeof(struct rx_connection *));
557 PIN(htable, rx_hashTableSize * sizeof(struct rx_connection *)); /* XXXXX */
558 memset(htable, 0, rx_hashTableSize * sizeof(struct rx_connection *));
559 ptable = osi_Alloc(rx_hashTableSize * sizeof(struct rx_peer *));
560 PIN(ptable, rx_hashTableSize * sizeof(struct rx_peer *)); /* XXXXX */
561 memset(ptable, 0, rx_hashTableSize * sizeof(struct rx_peer *));
563 /* Malloc up a bunch of packets & buffers */
565 opr_queue_Init(&rx_freePacketQueue);
566 rxi_NeedMorePackets = FALSE;
567 rx_nPackets = 0; /* rx_nPackets is managed by rxi_MorePackets* */
568 opr_queue_Init(&rx_mallocedPacketQueue);
570 /* enforce a minimum number of allocated packets */
571 if (rx_extraPackets < rxi_nSendFrags * rx_maxSendWindow)
572 rx_extraPackets = rxi_nSendFrags * rx_maxSendWindow;
574 /* allocate the initial free packet pool */
575 #ifdef RX_ENABLE_TSFPQ
576 rxi_MorePacketsTSFPQ(rx_extraPackets + RX_MAX_QUOTA + 2, RX_TS_FPQ_FLUSH_GLOBAL, 0);
577 #else /* RX_ENABLE_TSFPQ */
578 rxi_MorePackets(rx_extraPackets + RX_MAX_QUOTA + 2); /* fudge */
579 #endif /* RX_ENABLE_TSFPQ */
586 #if defined(AFS_NT40_ENV) && !defined(AFS_PTHREAD_ENV)
587 tv.tv_sec = clock_now.sec;
588 tv.tv_usec = clock_now.usec;
589 srand((unsigned int)tv.tv_usec);
596 #if defined(KERNEL) && !defined(UKERNEL)
597 /* Really, this should never happen in a real kernel */
600 struct sockaddr_in addr;
602 int addrlen = sizeof(addr);
604 socklen_t addrlen = sizeof(addr);
606 if (getsockname((intptr_t)rx_socket, (struct sockaddr *)&addr, &addrlen)) {
607 rxi_Finalize_locked();
608 osi_Free(htable, rx_hashTableSize * sizeof(struct rx_connection *));
611 rx_port = addr.sin_port;
614 rx_stats.minRtt.sec = 9999999;
615 if (RAND_bytes(&rx_epoch, sizeof(rx_epoch)) != 1)
617 rx_epoch = (rx_epoch & ~0x40000000) | 0x80000000;
618 if (RAND_bytes(&rx_nextCid, sizeof(rx_nextCid)) != 1)
620 rx_nextCid &= RX_CIDMASK;
621 MUTEX_ENTER(&rx_quota_mutex);
622 rxi_dataQuota += rx_extraQuota; /* + extra pkts caller asked to rsrv */
623 MUTEX_EXIT(&rx_quota_mutex);
624 /* *Slightly* random start time for the cid. This is just to help
625 * out with the hashing function at the peer */
626 rx_nextCid = ((tv.tv_sec ^ tv.tv_usec) << RX_CIDSHIFT);
627 rx_connHashTable = (struct rx_connection **)htable;
628 rx_peerHashTable = (struct rx_peer **)ptable;
630 rx_hardAckDelay.sec = 0;
631 rx_hardAckDelay.usec = 100000; /* 100 milliseconds */
633 rxevent_Init(20, rxi_ReScheduleEvents);
635 /* Initialize various global queues */
636 opr_queue_Init(&rx_idleServerQueue);
637 opr_queue_Init(&rx_incomingCallQueue);
638 opr_queue_Init(&rx_freeCallQueue);
640 #if defined(AFS_NT40_ENV) && !defined(KERNEL)
641 /* Initialize our list of usable IP addresses. */
645 /* Start listener process (exact function is dependent on the
646 * implementation environment--kernel or user space) */
651 rx_atomic_set(&rxi_running, 1);
668 return rx_InitHost(htonl(INADDR_ANY), port);
674 * The rxi_rto functions implement a TCP (RFC2988) style algorithm for
675 * maintaing the round trip timer.
680 * Start a new RTT timer for a given call and packet.
682 * There must be no resendEvent already listed for this call, otherwise this
683 * will leak events - intended for internal use within the RTO code only
686 * the RX call to start the timer for
687 * @param[in] lastPacket
688 * a flag indicating whether the last packet has been sent or not
690 * @pre call must be locked before calling this function
694 rxi_rto_startTimer(struct rx_call *call, int lastPacket, int istack)
696 struct clock now, retryTime;
698 MUTEX_ASSERT(&call->lock);
702 clock_Add(&retryTime, &call->rto);
704 /* If we're sending the last packet, and we're the client, then the server
705 * may wait for an additional 400ms before returning the ACK, wait for it
706 * rather than hitting a timeout */
707 if (lastPacket && call->conn->type == RX_CLIENT_CONNECTION)
708 clock_Addmsec(&retryTime, 400);
710 CALL_HOLD(call, RX_CALL_REFCOUNT_RESEND);
711 call->resendEvent = rxevent_Post(&retryTime, &now, rxi_Resend,
716 * Cancel an RTT timer for a given call.
720 * the RX call to cancel the timer for
722 * @pre call must be locked before calling this function
727 rxi_rto_cancel(struct rx_call *call)
729 MUTEX_ASSERT(&call->lock);
730 if (rxevent_Cancel(&call->resendEvent))
731 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
735 * Tell the RTO timer that we have sent a packet.
737 * If the timer isn't already running, then start it. If the timer is running,
741 * the RX call that the packet has been sent on
742 * @param[in] lastPacket
743 * A flag which is true if this is the last packet for the call
745 * @pre The call must be locked before calling this function
750 rxi_rto_packet_sent(struct rx_call *call, int lastPacket, int istack)
752 if (call->resendEvent)
755 rxi_rto_startTimer(call, lastPacket, istack);
759 * Tell the RTO timer that we have received an new ACK message
761 * This function should be called whenever a call receives an ACK that
762 * acknowledges new packets. Whatever happens, we stop the current timer.
763 * If there are unacked packets in the queue which have been sent, then
764 * we restart the timer from now. Otherwise, we leave it stopped.
767 * the RX call that the ACK has been received on
771 rxi_rto_packet_acked(struct rx_call *call, int istack)
773 struct opr_queue *cursor;
775 rxi_rto_cancel(call);
777 if (opr_queue_IsEmpty(&call->tq))
780 for (opr_queue_Scan(&call->tq, cursor)) {
781 struct rx_packet *p = opr_queue_Entry(cursor, struct rx_packet, entry);
782 if (p->header.seq > call->tfirst + call->twind)
785 if (!(p->flags & RX_PKTFLAG_ACKED) && p->flags & RX_PKTFLAG_SENT) {
786 rxi_rto_startTimer(call, p->header.flags & RX_LAST_PACKET, istack);
794 * Set an initial round trip timeout for a peer connection
796 * @param[in] secs The timeout to set in seconds
800 rx_rto_setPeerTimeoutSecs(struct rx_peer *peer, int secs) {
801 peer->rtt = secs * 8000;
805 * Set a delayed ack event on the specified call for the given time
807 * @param[in] call - the call on which to set the event
808 * @param[in] offset - the delay from now after which the event fires
811 rxi_PostDelayedAckEvent(struct rx_call *call, struct clock *offset)
813 struct clock now, when;
815 MUTEX_ASSERT(&call->lock);
818 clock_Add(&when, offset);
820 if (clock_Gt(&call->delayedAckTime, &when) &&
821 rxevent_Cancel(&call->delayedAckEvent)) {
822 /* We successfully cancelled an event too far in the future to install
823 * our new one; we can reuse the reference on the call. */
824 call->delayedAckEvent = rxevent_Post(&when, &now, rxi_SendDelayedAck,
827 call->delayedAckTime = when;
828 } else if (call->delayedAckEvent == NULL) {
829 CALL_HOLD(call, RX_CALL_REFCOUNT_DELAY);
830 call->delayedAckEvent = rxevent_Post(&when, &now,
833 call->delayedAckTime = when;
838 rxi_CancelDelayedAckEvent(struct rx_call *call)
840 MUTEX_ASSERT(&call->lock);
841 /* Only drop the ref if we cancelled it before it could run. */
842 if (rxevent_Cancel(&call->delayedAckEvent))
843 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
846 /* called with unincremented nRequestsRunning to see if it is OK to start
847 * a new thread in this service. Could be "no" for two reasons: over the
848 * max quota, or would prevent others from reaching their min quota.
850 #ifdef RX_ENABLE_LOCKS
851 /* This verion of QuotaOK reserves quota if it's ok while the
852 * rx_serverPool_lock is held. Return quota using ReturnToServerPool().
855 QuotaOK(struct rx_service *aservice)
857 /* check if over max quota */
858 if (aservice->nRequestsRunning >= aservice->maxProcs) {
862 /* under min quota, we're OK */
863 /* otherwise, can use only if there are enough to allow everyone
864 * to go to their min quota after this guy starts.
867 MUTEX_ENTER(&rx_quota_mutex);
868 if ((aservice->nRequestsRunning < aservice->minProcs)
869 || (rxi_availProcs > rxi_minDeficit)) {
870 aservice->nRequestsRunning++;
871 /* just started call in minProcs pool, need fewer to maintain
873 if (aservice->nRequestsRunning <= aservice->minProcs)
876 MUTEX_EXIT(&rx_quota_mutex);
879 MUTEX_EXIT(&rx_quota_mutex);
885 ReturnToServerPool(struct rx_service *aservice)
887 aservice->nRequestsRunning--;
888 MUTEX_ENTER(&rx_quota_mutex);
889 if (aservice->nRequestsRunning < aservice->minProcs)
892 MUTEX_EXIT(&rx_quota_mutex);
895 #else /* RX_ENABLE_LOCKS */
897 QuotaOK(struct rx_service *aservice)
900 /* under min quota, we're OK */
901 if (aservice->nRequestsRunning < aservice->minProcs)
904 /* check if over max quota */
905 if (aservice->nRequestsRunning >= aservice->maxProcs)
908 /* otherwise, can use only if there are enough to allow everyone
909 * to go to their min quota after this guy starts.
911 MUTEX_ENTER(&rx_quota_mutex);
912 if (rxi_availProcs > rxi_minDeficit)
914 MUTEX_EXIT(&rx_quota_mutex);
917 #endif /* RX_ENABLE_LOCKS */
920 /* Called by rx_StartServer to start up lwp's to service calls.
921 NExistingProcs gives the number of procs already existing, and which
922 therefore needn't be created. */
924 rxi_StartServerProcs(int nExistingProcs)
926 struct rx_service *service;
931 /* For each service, reserve N processes, where N is the "minimum"
932 * number of processes that MUST be able to execute a request in parallel,
933 * at any time, for that process. Also compute the maximum difference
934 * between any service's maximum number of processes that can run
935 * (i.e. the maximum number that ever will be run, and a guarantee
936 * that this number will run if other services aren't running), and its
937 * minimum number. The result is the extra number of processes that
938 * we need in order to provide the latter guarantee */
939 for (i = 0; i < RX_MAX_SERVICES; i++) {
941 service = rx_services[i];
942 if (service == (struct rx_service *)0)
944 nProcs += service->minProcs;
945 diff = service->maxProcs - service->minProcs;
949 nProcs += maxdiff; /* Extra processes needed to allow max number requested to run in any given service, under good conditions */
950 nProcs -= nExistingProcs; /* Subtract the number of procs that were previously created for use as server procs */
951 for (i = 0; i < nProcs; i++) {
952 rxi_StartServerProc(rx_ServerProc, rx_stackSize);
958 /* This routine is only required on Windows */
960 rx_StartClientThread(void)
962 #ifdef AFS_PTHREAD_ENV
964 pid = pthread_self();
965 #endif /* AFS_PTHREAD_ENV */
967 #endif /* AFS_NT40_ENV */
969 /* This routine must be called if any services are exported. If the
970 * donateMe flag is set, the calling process is donated to the server
973 rx_StartServer(int donateMe)
975 struct rx_service *service;
981 /* Start server processes, if necessary (exact function is dependent
982 * on the implementation environment--kernel or user space). DonateMe
983 * will be 1 if there is 1 pre-existing proc, i.e. this one. In this
984 * case, one less new proc will be created rx_StartServerProcs.
986 rxi_StartServerProcs(donateMe);
988 /* count up the # of threads in minProcs, and add set the min deficit to
989 * be that value, too.
991 for (i = 0; i < RX_MAX_SERVICES; i++) {
992 service = rx_services[i];
993 if (service == (struct rx_service *)0)
995 MUTEX_ENTER(&rx_quota_mutex);
996 rxi_totalMin += service->minProcs;
997 /* below works even if a thread is running, since minDeficit would
998 * still have been decremented and later re-incremented.
1000 rxi_minDeficit += service->minProcs;
1001 MUTEX_EXIT(&rx_quota_mutex);
1004 /* Turn on reaping of idle server connections */
1005 rxi_ReapConnections(NULL, NULL, NULL, 0);
1010 #ifndef AFS_NT40_ENV
1014 #ifdef AFS_PTHREAD_ENV
1016 pid = afs_pointer_to_int(pthread_self());
1017 #else /* AFS_PTHREAD_ENV */
1019 LWP_CurrentProcess(&pid);
1020 #endif /* AFS_PTHREAD_ENV */
1022 sprintf(name, "srv_%d", ++nProcs);
1023 if (registerProgram)
1024 (*registerProgram) (pid, name);
1026 #endif /* AFS_NT40_ENV */
1027 rx_ServerProc(NULL); /* Never returns */
1029 #ifdef RX_ENABLE_TSFPQ
1030 /* no use leaving packets around in this thread's local queue if
1031 * it isn't getting donated to the server thread pool.
1033 rxi_FlushLocalPacketsTSFPQ();
1034 #endif /* RX_ENABLE_TSFPQ */
1038 /* Create a new client connection to the specified service, using the
1039 * specified security object to implement the security model for this
1041 struct rx_connection *
1042 rx_NewConnection(afs_uint32 shost, u_short sport, u_short sservice,
1043 struct rx_securityClass *securityObject,
1044 int serviceSecurityIndex)
1047 struct rx_connection *conn;
1052 dpf(("rx_NewConnection(host %x, port %u, service %u, securityObject %p, "
1053 "serviceSecurityIndex %d)\n",
1054 ntohl(shost), ntohs(sport), sservice, securityObject,
1055 serviceSecurityIndex));
1057 /* Vasilsi said: "NETPRI protects Cid and Alloc", but can this be true in
1058 * the case of kmem_alloc? */
1059 conn = rxi_AllocConnection();
1060 #ifdef RX_ENABLE_LOCKS
1061 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
1062 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
1063 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
1066 MUTEX_ENTER(&rx_connHashTable_lock);
1067 conn->type = RX_CLIENT_CONNECTION;
1068 conn->epoch = rx_epoch;
1069 conn->cid = rx_nextCid;
1071 conn->peer = rxi_FindPeer(shost, sport, 1);
1072 conn->serviceId = sservice;
1073 conn->securityObject = securityObject;
1074 conn->securityData = (void *) 0;
1075 conn->securityIndex = serviceSecurityIndex;
1076 rx_SetConnDeadTime(conn, rx_connDeadTime);
1077 rx_SetConnSecondsUntilNatPing(conn, 0);
1078 conn->ackRate = RX_FAST_ACK_RATE;
1079 conn->nSpecific = 0;
1080 conn->specific = NULL;
1081 conn->challengeEvent = NULL;
1082 conn->delayedAbortEvent = NULL;
1083 conn->abortCount = 0;
1085 for (i = 0; i < RX_MAXCALLS; i++) {
1086 conn->twind[i] = rx_initSendWindow;
1087 conn->rwind[i] = rx_initReceiveWindow;
1088 conn->lastBusy[i] = 0;
1091 RXS_NewConnection(securityObject, conn);
1093 CONN_HASH(shost, sport, conn->cid, conn->epoch, RX_CLIENT_CONNECTION);
1095 conn->refCount++; /* no lock required since only this thread knows... */
1096 conn->next = rx_connHashTable[hashindex];
1097 rx_connHashTable[hashindex] = conn;
1098 if (rx_stats_active)
1099 rx_atomic_inc(&rx_stats.nClientConns);
1100 MUTEX_EXIT(&rx_connHashTable_lock);
1106 * Ensure a connection's timeout values are valid.
1108 * @param[in] conn The connection to check
1110 * @post conn->secondUntilDead <= conn->idleDeadTime <= conn->hardDeadTime,
1111 * unless idleDeadTime and/or hardDeadTime are not set
1115 rxi_CheckConnTimeouts(struct rx_connection *conn)
1117 /* a connection's timeouts must have the relationship
1118 * deadTime <= idleDeadTime <= hardDeadTime. Otherwise, for example, a
1119 * total loss of network to a peer may cause an idle timeout instead of a
1120 * dead timeout, simply because the idle timeout gets hit first. Also set
1121 * a minimum deadTime of 6, just to ensure it doesn't get set too low. */
1122 /* this logic is slightly complicated by the fact that
1123 * idleDeadTime/hardDeadTime may not be set at all, but it's not too bad.
1125 conn->secondsUntilDead = MAX(conn->secondsUntilDead, 6);
1126 if (conn->idleDeadTime) {
1127 conn->idleDeadTime = MAX(conn->idleDeadTime, conn->secondsUntilDead);
1129 if (conn->hardDeadTime) {
1130 if (conn->idleDeadTime) {
1131 conn->hardDeadTime = MAX(conn->idleDeadTime, conn->hardDeadTime);
1133 conn->hardDeadTime = MAX(conn->secondsUntilDead, conn->hardDeadTime);
1139 rx_SetConnDeadTime(struct rx_connection *conn, int seconds)
1141 /* The idea is to set the dead time to a value that allows several
1142 * keepalives to be dropped without timing out the connection. */
1143 conn->secondsUntilDead = seconds;
1144 rxi_CheckConnTimeouts(conn);
1145 conn->secondsUntilPing = conn->secondsUntilDead / 6;
1149 rx_SetConnHardDeadTime(struct rx_connection *conn, int seconds)
1151 conn->hardDeadTime = seconds;
1152 rxi_CheckConnTimeouts(conn);
1156 rx_SetConnIdleDeadTime(struct rx_connection *conn, int seconds)
1158 conn->idleDeadTime = seconds;
1159 rxi_CheckConnTimeouts(conn);
1162 int rxi_lowPeerRefCount = 0;
1163 int rxi_lowConnRefCount = 0;
1166 * Cleanup a connection that was destroyed in rxi_DestroyConnectioNoLock.
1167 * NOTE: must not be called with rx_connHashTable_lock held.
1170 rxi_CleanupConnection(struct rx_connection *conn)
1172 /* Notify the service exporter, if requested, that this connection
1173 * is being destroyed */
1174 if (conn->type == RX_SERVER_CONNECTION && conn->service->destroyConnProc)
1175 (*conn->service->destroyConnProc) (conn);
1177 /* Notify the security module that this connection is being destroyed */
1178 RXS_DestroyConnection(conn->securityObject, conn);
1180 /* If this is the last connection using the rx_peer struct, set its
1181 * idle time to now. rxi_ReapConnections will reap it if it's still
1182 * idle (refCount == 0) after rx_idlePeerTime (60 seconds) have passed.
1184 MUTEX_ENTER(&rx_peerHashTable_lock);
1185 if (conn->peer->refCount < 2) {
1186 conn->peer->idleWhen = clock_Sec();
1187 if (conn->peer->refCount < 1) {
1188 conn->peer->refCount = 1;
1189 if (rx_stats_active) {
1190 MUTEX_ENTER(&rx_stats_mutex);
1191 rxi_lowPeerRefCount++;
1192 MUTEX_EXIT(&rx_stats_mutex);
1196 conn->peer->refCount--;
1197 MUTEX_EXIT(&rx_peerHashTable_lock);
1199 if (rx_stats_active)
1201 if (conn->type == RX_SERVER_CONNECTION)
1202 rx_atomic_dec(&rx_stats.nServerConns);
1204 rx_atomic_dec(&rx_stats.nClientConns);
1207 if (conn->specific) {
1209 for (i = 0; i < conn->nSpecific; i++) {
1210 if (conn->specific[i] && rxi_keyCreate_destructor[i])
1211 (*rxi_keyCreate_destructor[i]) (conn->specific[i]);
1212 conn->specific[i] = NULL;
1214 free(conn->specific);
1216 conn->specific = NULL;
1217 conn->nSpecific = 0;
1218 #endif /* !KERNEL */
1220 MUTEX_DESTROY(&conn->conn_call_lock);
1221 MUTEX_DESTROY(&conn->conn_data_lock);
1222 CV_DESTROY(&conn->conn_call_cv);
1224 rxi_FreeConnection(conn);
1227 /* Destroy the specified connection */
1229 rxi_DestroyConnection(struct rx_connection *conn)
1231 MUTEX_ENTER(&rx_connHashTable_lock);
1232 rxi_DestroyConnectionNoLock(conn);
1233 /* conn should be at the head of the cleanup list */
1234 if (conn == rx_connCleanup_list) {
1235 rx_connCleanup_list = rx_connCleanup_list->next;
1236 MUTEX_EXIT(&rx_connHashTable_lock);
1237 rxi_CleanupConnection(conn);
1239 #ifdef RX_ENABLE_LOCKS
1241 MUTEX_EXIT(&rx_connHashTable_lock);
1243 #endif /* RX_ENABLE_LOCKS */
1247 rxi_DestroyConnectionNoLock(struct rx_connection *conn)
1249 struct rx_connection **conn_ptr;
1257 MUTEX_ENTER(&conn->conn_data_lock);
1258 MUTEX_ENTER(&rx_refcnt_mutex);
1259 if (conn->refCount > 0)
1262 #ifdef RX_REFCOUNT_CHECK
1263 osi_Assert(conn->refCount == 0);
1265 if (rx_stats_active) {
1266 MUTEX_ENTER(&rx_stats_mutex);
1267 rxi_lowConnRefCount++;
1268 MUTEX_EXIT(&rx_stats_mutex);
1272 if ((conn->refCount > 0) || (conn->flags & RX_CONN_BUSY)) {
1273 /* Busy; wait till the last guy before proceeding */
1274 MUTEX_EXIT(&rx_refcnt_mutex);
1275 MUTEX_EXIT(&conn->conn_data_lock);
1280 /* If the client previously called rx_NewCall, but it is still
1281 * waiting, treat this as a running call, and wait to destroy the
1282 * connection later when the call completes. */
1283 if ((conn->type == RX_CLIENT_CONNECTION)
1284 && (conn->flags & (RX_CONN_MAKECALL_WAITING|RX_CONN_MAKECALL_ACTIVE))) {
1285 conn->flags |= RX_CONN_DESTROY_ME;
1286 MUTEX_EXIT(&rx_refcnt_mutex);
1287 MUTEX_EXIT(&conn->conn_data_lock);
1291 MUTEX_EXIT(&rx_refcnt_mutex);
1292 MUTEX_EXIT(&conn->conn_data_lock);
1294 /* Check for extant references to this connection */
1295 MUTEX_ENTER(&conn->conn_call_lock);
1296 for (i = 0; i < RX_MAXCALLS; i++) {
1297 struct rx_call *call = conn->call[i];
1300 if (conn->type == RX_CLIENT_CONNECTION) {
1301 MUTEX_ENTER(&call->lock);
1302 if (call->delayedAckEvent) {
1303 /* Push the final acknowledgment out now--there
1304 * won't be a subsequent call to acknowledge the
1305 * last reply packets */
1306 rxi_CancelDelayedAckEvent(call);
1307 if (call->state == RX_STATE_PRECALL
1308 || call->state == RX_STATE_ACTIVE) {
1309 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
1314 MUTEX_EXIT(&call->lock);
1318 MUTEX_EXIT(&conn->conn_call_lock);
1320 #ifdef RX_ENABLE_LOCKS
1322 if (MUTEX_TRYENTER(&conn->conn_data_lock)) {
1323 MUTEX_EXIT(&conn->conn_data_lock);
1325 /* Someone is accessing a packet right now. */
1329 #endif /* RX_ENABLE_LOCKS */
1332 /* Don't destroy the connection if there are any call
1333 * structures still in use */
1334 MUTEX_ENTER(&conn->conn_data_lock);
1335 conn->flags |= RX_CONN_DESTROY_ME;
1336 MUTEX_EXIT(&conn->conn_data_lock);
1341 /* Remove from connection hash table before proceeding */
1343 &rx_connHashTable[CONN_HASH
1344 (peer->host, peer->port, conn->cid, conn->epoch,
1346 for (; *conn_ptr; conn_ptr = &(*conn_ptr)->next) {
1347 if (*conn_ptr == conn) {
1348 *conn_ptr = conn->next;
1352 /* if the conn that we are destroying was the last connection, then we
1353 * clear rxLastConn as well */
1354 if (rxLastConn == conn)
1357 /* Make sure the connection is completely reset before deleting it. */
1359 * Pending events hold a refcount, so we can't get here if they are
1361 osi_Assert(conn->challengeEvent == NULL);
1362 osi_Assert(conn->delayedAbortEvent == NULL);
1363 osi_Assert(conn->natKeepAliveEvent == NULL);
1364 osi_Assert(conn->checkReachEvent == NULL);
1366 /* Add the connection to the list of destroyed connections that
1367 * need to be cleaned up. This is necessary to avoid deadlocks
1368 * in the routines we call to inform others that this connection is
1369 * being destroyed. */
1370 conn->next = rx_connCleanup_list;
1371 rx_connCleanup_list = conn;
1374 /* Externally available version */
1376 rx_DestroyConnection(struct rx_connection *conn)
1381 rxi_DestroyConnection(conn);
1386 rx_GetConnection(struct rx_connection *conn)
1391 MUTEX_ENTER(&rx_refcnt_mutex);
1393 MUTEX_EXIT(&rx_refcnt_mutex);
1397 #ifdef RX_ENABLE_LOCKS
1398 /* Wait for the transmit queue to no longer be busy.
1399 * requires the call->lock to be held */
1401 rxi_WaitforTQBusy(struct rx_call *call) {
1402 while (!call->error && (call->flags & RX_CALL_TQ_BUSY)) {
1403 call->flags |= RX_CALL_TQ_WAIT;
1405 MUTEX_ASSERT(&call->lock);
1406 CV_WAIT(&call->cv_tq, &call->lock);
1408 if (call->tqWaiters == 0) {
1409 call->flags &= ~RX_CALL_TQ_WAIT;
1416 rxi_WakeUpTransmitQueue(struct rx_call *call)
1418 if (call->tqWaiters || (call->flags & RX_CALL_TQ_WAIT)) {
1419 dpf(("call %"AFS_PTR_FMT" has %d waiters and flags %d\n",
1420 call, call->tqWaiters, call->flags));
1421 #ifdef RX_ENABLE_LOCKS
1422 MUTEX_ASSERT(&call->lock);
1423 CV_BROADCAST(&call->cv_tq);
1424 #else /* RX_ENABLE_LOCKS */
1425 osi_rxWakeup(&call->tq);
1426 #endif /* RX_ENABLE_LOCKS */
1430 /* Start a new rx remote procedure call, on the specified connection.
1431 * If wait is set to 1, wait for a free call channel; otherwise return
1432 * 0. Maxtime gives the maximum number of seconds this call may take,
1433 * after rx_NewCall returns. After this time interval, a call to any
1434 * of rx_SendData, rx_ReadData, etc. will fail with RX_CALL_TIMEOUT.
1435 * For fine grain locking, we hold the conn_call_lock in order to
1436 * to ensure that we don't get signalle after we found a call in an active
1437 * state and before we go to sleep.
1440 rx_NewCall(struct rx_connection *conn)
1442 int i, wait, ignoreBusy = 1;
1443 struct rx_call *call;
1444 struct clock queueTime;
1445 afs_uint32 leastBusy = 0;
1449 dpf(("rx_NewCall(conn %"AFS_PTR_FMT")\n", conn));
1452 clock_GetTime(&queueTime);
1454 * Check if there are others waiting for a new call.
1455 * If so, let them go first to avoid starving them.
1456 * This is a fairly simple scheme, and might not be
1457 * a complete solution for large numbers of waiters.
1459 * makeCallWaiters keeps track of the number of
1460 * threads waiting to make calls and the
1461 * RX_CONN_MAKECALL_WAITING flag bit is used to
1462 * indicate that there are indeed calls waiting.
1463 * The flag is set when the waiter is incremented.
1464 * It is only cleared when makeCallWaiters is 0.
1465 * This prevents us from accidently destroying the
1466 * connection while it is potentially about to be used.
1468 MUTEX_ENTER(&conn->conn_call_lock);
1469 MUTEX_ENTER(&conn->conn_data_lock);
1470 while (conn->flags & RX_CONN_MAKECALL_ACTIVE) {
1471 conn->flags |= RX_CONN_MAKECALL_WAITING;
1472 conn->makeCallWaiters++;
1473 MUTEX_EXIT(&conn->conn_data_lock);
1475 #ifdef RX_ENABLE_LOCKS
1476 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1480 MUTEX_ENTER(&conn->conn_data_lock);
1481 conn->makeCallWaiters--;
1482 if (conn->makeCallWaiters == 0)
1483 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1486 /* We are now the active thread in rx_NewCall */
1487 conn->flags |= RX_CONN_MAKECALL_ACTIVE;
1488 MUTEX_EXIT(&conn->conn_data_lock);
1493 for (i = 0; i < RX_MAXCALLS; i++) {
1494 call = conn->call[i];
1496 if (!ignoreBusy && conn->lastBusy[i] != leastBusy) {
1497 /* we're not ignoring busy call slots; only look at the
1498 * call slot that is the "least" busy */
1502 if (call->state == RX_STATE_DALLY) {
1503 MUTEX_ENTER(&call->lock);
1504 if (call->state == RX_STATE_DALLY) {
1505 if (ignoreBusy && conn->lastBusy[i]) {
1506 /* if we're ignoring busy call slots, skip any ones that
1507 * have lastBusy set */
1508 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1509 leastBusy = conn->lastBusy[i];
1511 MUTEX_EXIT(&call->lock);
1516 * We are setting the state to RX_STATE_RESET to
1517 * ensure that no one else will attempt to use this
1518 * call once we drop the conn->conn_call_lock and
1519 * call->lock. We must drop the conn->conn_call_lock
1520 * before calling rxi_ResetCall because the process
1521 * of clearing the transmit queue can block for an
1522 * extended period of time. If we block while holding
1523 * the conn->conn_call_lock, then all rx_EndCall
1524 * processing will block as well. This has a detrimental
1525 * effect on overall system performance.
1527 call->state = RX_STATE_RESET;
1528 (*call->callNumber)++;
1529 MUTEX_EXIT(&conn->conn_call_lock);
1530 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1531 rxi_ResetCall(call, 0);
1532 if (MUTEX_TRYENTER(&conn->conn_call_lock))
1536 * If we failed to be able to safely obtain the
1537 * conn->conn_call_lock we will have to drop the
1538 * call->lock to avoid a deadlock. When the call->lock
1539 * is released the state of the call can change. If it
1540 * is no longer RX_STATE_RESET then some other thread is
1543 MUTEX_EXIT(&call->lock);
1544 MUTEX_ENTER(&conn->conn_call_lock);
1545 MUTEX_ENTER(&call->lock);
1547 if (call->state == RX_STATE_RESET)
1551 * If we get here it means that after dropping
1552 * the conn->conn_call_lock and call->lock that
1553 * the call is no longer ours. If we can't find
1554 * a free call in the remaining slots we should
1555 * not go immediately to RX_CONN_MAKECALL_WAITING
1556 * because by dropping the conn->conn_call_lock
1557 * we have given up synchronization with rx_EndCall.
1558 * Instead, cycle through one more time to see if
1559 * we can find a call that can call our own.
1561 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
1564 MUTEX_EXIT(&call->lock);
1567 if (ignoreBusy && conn->lastBusy[i]) {
1568 /* if we're ignoring busy call slots, skip any ones that
1569 * have lastBusy set */
1570 if (leastBusy == 0 || conn->lastBusy[i] < leastBusy) {
1571 leastBusy = conn->lastBusy[i];
1576 /* rxi_NewCall returns with mutex locked */
1577 call = rxi_NewCall(conn, i);
1578 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
1582 if (i < RX_MAXCALLS) {
1583 conn->lastBusy[i] = 0;
1588 if (leastBusy && ignoreBusy) {
1589 /* we didn't find a useable call slot, but we did see at least one
1590 * 'busy' slot; look again and only use a slot with the 'least
1596 MUTEX_ENTER(&conn->conn_data_lock);
1597 conn->flags |= RX_CONN_MAKECALL_WAITING;
1598 conn->makeCallWaiters++;
1599 MUTEX_EXIT(&conn->conn_data_lock);
1601 #ifdef RX_ENABLE_LOCKS
1602 CV_WAIT(&conn->conn_call_cv, &conn->conn_call_lock);
1606 MUTEX_ENTER(&conn->conn_data_lock);
1607 conn->makeCallWaiters--;
1608 if (conn->makeCallWaiters == 0)
1609 conn->flags &= ~RX_CONN_MAKECALL_WAITING;
1610 MUTEX_EXIT(&conn->conn_data_lock);
1612 /* Client is initially in send mode */
1613 call->state = RX_STATE_ACTIVE;
1614 call->error = conn->error;
1616 call->app.mode = RX_MODE_ERROR;
1618 call->app.mode = RX_MODE_SENDING;
1620 #ifdef AFS_RXERRQ_ENV
1621 /* remember how many network errors the peer has when we started, so if
1622 * more errors are encountered after the call starts, we know the other endpoint won't be
1623 * responding to us */
1624 call->neterr_gen = rx_atomic_read(&conn->peer->neterrs);
1627 /* remember start time for call in case we have hard dead time limit */
1628 call->queueTime = queueTime;
1629 clock_GetTime(&call->startTime);
1630 call->app.bytesSent = 0;
1631 call->app.bytesRcvd = 0;
1633 /* Turn on busy protocol. */
1634 rxi_KeepAliveOn(call);
1636 /* Attempt MTU discovery */
1637 rxi_GrowMTUOn(call);
1640 * We are no longer the active thread in rx_NewCall
1642 MUTEX_ENTER(&conn->conn_data_lock);
1643 conn->flags &= ~RX_CONN_MAKECALL_ACTIVE;
1644 MUTEX_EXIT(&conn->conn_data_lock);
1647 * Wake up anyone else who might be giving us a chance to
1648 * run (see code above that avoids resource starvation).
1650 #ifdef RX_ENABLE_LOCKS
1651 if (call->flags & (RX_CALL_TQ_BUSY | RX_CALL_TQ_CLEARME)) {
1652 osi_Panic("rx_NewCall call about to be used without an empty tq");
1655 CV_BROADCAST(&conn->conn_call_cv);
1659 MUTEX_EXIT(&conn->conn_call_lock);
1660 MUTEX_EXIT(&call->lock);
1663 dpf(("rx_NewCall(call %"AFS_PTR_FMT")\n", call));
1668 rxi_HasActiveCalls(struct rx_connection *aconn)
1671 struct rx_call *tcall;
1675 for (i = 0; i < RX_MAXCALLS; i++) {
1676 if ((tcall = aconn->call[i])) {
1677 if ((tcall->state == RX_STATE_ACTIVE)
1678 || (tcall->state == RX_STATE_PRECALL)) {
1689 rxi_GetCallNumberVector(struct rx_connection *aconn,
1690 afs_int32 * aint32s)
1693 struct rx_call *tcall;
1697 MUTEX_ENTER(&aconn->conn_call_lock);
1698 for (i = 0; i < RX_MAXCALLS; i++) {
1699 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1700 aint32s[i] = aconn->callNumber[i] + 1;
1702 aint32s[i] = aconn->callNumber[i];
1704 MUTEX_EXIT(&aconn->conn_call_lock);
1710 rxi_SetCallNumberVector(struct rx_connection *aconn,
1711 afs_int32 * aint32s)
1714 struct rx_call *tcall;
1718 MUTEX_ENTER(&aconn->conn_call_lock);
1719 for (i = 0; i < RX_MAXCALLS; i++) {
1720 if ((tcall = aconn->call[i]) && (tcall->state == RX_STATE_DALLY))
1721 aconn->callNumber[i] = aint32s[i] - 1;
1723 aconn->callNumber[i] = aint32s[i];
1725 MUTEX_EXIT(&aconn->conn_call_lock);
1730 /* Advertise a new service. A service is named locally by a UDP port
1731 * number plus a 16-bit service id. Returns (struct rx_service *) 0
1734 char *serviceName; Name for identification purposes (e.g. the
1735 service name might be used for probing for
1738 rx_NewServiceHost(afs_uint32 host, u_short port, u_short serviceId,
1739 char *serviceName, struct rx_securityClass **securityObjects,
1740 int nSecurityObjects,
1741 afs_int32(*serviceProc) (struct rx_call * acall))
1743 osi_socket socket = OSI_NULLSOCKET;
1744 struct rx_service *tservice;
1750 if (serviceId == 0) {
1752 "rx_NewService: service id for service %s is not non-zero.\n",
1759 "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",
1767 tservice = rxi_AllocService();
1770 MUTEX_INIT(&tservice->svc_data_lock, "svc data lock", MUTEX_DEFAULT, 0);
1772 for (i = 0; i < RX_MAX_SERVICES; i++) {
1773 struct rx_service *service = rx_services[i];
1775 if (port == service->servicePort && host == service->serviceHost) {
1776 if (service->serviceId == serviceId) {
1777 /* The identical service has already been
1778 * installed; if the caller was intending to
1779 * change the security classes used by this
1780 * service, he/she loses. */
1782 "rx_NewService: tried to install service %s with service id %d, which is already in use for service %s\n",
1783 serviceName, serviceId, service->serviceName);
1785 rxi_FreeService(tservice);
1788 /* Different service, same port: re-use the socket
1789 * which is bound to the same port */
1790 socket = service->socket;
1793 if (socket == OSI_NULLSOCKET) {
1794 /* If we don't already have a socket (from another
1795 * service on same port) get a new one */
1796 socket = rxi_GetHostUDPSocket(host, port);
1797 if (socket == OSI_NULLSOCKET) {
1799 rxi_FreeService(tservice);
1804 service->socket = socket;
1805 service->serviceHost = host;
1806 service->servicePort = port;
1807 service->serviceId = serviceId;
1808 service->serviceName = serviceName;
1809 service->nSecurityObjects = nSecurityObjects;
1810 service->securityObjects = securityObjects;
1811 service->minProcs = 0;
1812 service->maxProcs = 1;
1813 service->idleDeadTime = 60;
1814 service->connDeadTime = rx_connDeadTime;
1815 service->executeRequestProc = serviceProc;
1816 service->checkReach = 0;
1817 service->nSpecific = 0;
1818 service->specific = NULL;
1819 rx_services[i] = service; /* not visible until now */
1825 rxi_FreeService(tservice);
1826 (osi_Msg "rx_NewService: cannot support > %d services\n",
1831 /* Set configuration options for all of a service's security objects */
1834 rx_SetSecurityConfiguration(struct rx_service *service,
1835 rx_securityConfigVariables type,
1839 for (i = 0; i<service->nSecurityObjects; i++) {
1840 if (service->securityObjects[i]) {
1841 RXS_SetConfiguration(service->securityObjects[i], NULL, type,
1849 rx_NewService(u_short port, u_short serviceId, char *serviceName,
1850 struct rx_securityClass **securityObjects, int nSecurityObjects,
1851 afs_int32(*serviceProc) (struct rx_call * acall))
1853 return rx_NewServiceHost(htonl(INADDR_ANY), port, serviceId, serviceName, securityObjects, nSecurityObjects, serviceProc);
1856 /* Generic request processing loop. This routine should be called
1857 * by the implementation dependent rx_ServerProc. If socketp is
1858 * non-null, it will be set to the file descriptor that this thread
1859 * is now listening on. If socketp is null, this routine will never
1862 rxi_ServerProc(int threadID, struct rx_call *newcall, osi_socket * socketp)
1864 struct rx_call *call;
1866 struct rx_service *tservice = NULL;
1873 call = rx_GetCall(threadID, tservice, socketp);
1874 if (socketp && *socketp != OSI_NULLSOCKET) {
1875 /* We are now a listener thread */
1881 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
1882 #ifdef RX_ENABLE_LOCKS
1884 #endif /* RX_ENABLE_LOCKS */
1885 afs_termState = AFSOP_STOP_AFS;
1886 afs_osi_Wakeup(&afs_termState);
1887 #ifdef RX_ENABLE_LOCKS
1889 #endif /* RX_ENABLE_LOCKS */
1894 /* if server is restarting( typically smooth shutdown) then do not
1895 * allow any new calls.
1898 if (rx_tranquil && (call != NULL)) {
1902 MUTEX_ENTER(&call->lock);
1904 rxi_CallError(call, RX_RESTARTING);
1905 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
1907 MUTEX_EXIT(&call->lock);
1912 tservice = call->conn->service;
1914 if (tservice->beforeProc)
1915 (*tservice->beforeProc) (call);
1917 code = tservice->executeRequestProc(call);
1919 if (tservice->afterProc)
1920 (*tservice->afterProc) (call, code);
1922 rx_EndCall(call, code);
1924 if (tservice->postProc)
1925 (*tservice->postProc) (code);
1927 if (rx_stats_active) {
1928 MUTEX_ENTER(&rx_stats_mutex);
1930 MUTEX_EXIT(&rx_stats_mutex);
1937 rx_WakeupServerProcs(void)
1939 struct rx_serverQueueEntry *np, *tqp;
1940 struct opr_queue *cursor;
1944 MUTEX_ENTER(&rx_serverPool_lock);
1946 #ifdef RX_ENABLE_LOCKS
1947 if (rx_waitForPacket)
1948 CV_BROADCAST(&rx_waitForPacket->cv);
1949 #else /* RX_ENABLE_LOCKS */
1950 if (rx_waitForPacket)
1951 osi_rxWakeup(rx_waitForPacket);
1952 #endif /* RX_ENABLE_LOCKS */
1953 MUTEX_ENTER(&freeSQEList_lock);
1954 for (np = rx_FreeSQEList; np; np = tqp) {
1955 tqp = *(struct rx_serverQueueEntry **)np;
1956 #ifdef RX_ENABLE_LOCKS
1957 CV_BROADCAST(&np->cv);
1958 #else /* RX_ENABLE_LOCKS */
1960 #endif /* RX_ENABLE_LOCKS */
1962 MUTEX_EXIT(&freeSQEList_lock);
1963 for (opr_queue_Scan(&rx_idleServerQueue, cursor)) {
1964 np = opr_queue_Entry(cursor, struct rx_serverQueueEntry, entry);
1965 #ifdef RX_ENABLE_LOCKS
1966 CV_BROADCAST(&np->cv);
1967 #else /* RX_ENABLE_LOCKS */
1969 #endif /* RX_ENABLE_LOCKS */
1971 MUTEX_EXIT(&rx_serverPool_lock);
1976 * One thing that seems to happen is that all the server threads get
1977 * tied up on some empty or slow call, and then a whole bunch of calls
1978 * arrive at once, using up the packet pool, so now there are more
1979 * empty calls. The most critical resources here are server threads
1980 * and the free packet pool. The "doreclaim" code seems to help in
1981 * general. I think that eventually we arrive in this state: there
1982 * are lots of pending calls which do have all their packets present,
1983 * so they won't be reclaimed, are multi-packet calls, so they won't
1984 * be scheduled until later, and thus are tying up most of the free
1985 * packet pool for a very long time.
1987 * 1. schedule multi-packet calls if all the packets are present.
1988 * Probably CPU-bound operation, useful to return packets to pool.
1989 * Do what if there is a full window, but the last packet isn't here?
1990 * 3. preserve one thread which *only* runs "best" calls, otherwise
1991 * it sleeps and waits for that type of call.
1992 * 4. Don't necessarily reserve a whole window for each thread. In fact,
1993 * the current dataquota business is badly broken. The quota isn't adjusted
1994 * to reflect how many packets are presently queued for a running call.
1995 * So, when we schedule a queued call with a full window of packets queued
1996 * up for it, that *should* free up a window full of packets for other 2d-class
1997 * calls to be able to use from the packet pool. But it doesn't.
1999 * NB. Most of the time, this code doesn't run -- since idle server threads
2000 * sit on the idle server queue and are assigned by "...ReceivePacket" as soon
2001 * as a new call arrives.
2003 /* Sleep until a call arrives. Returns a pointer to the call, ready
2004 * for an rx_Read. */
2005 #ifdef RX_ENABLE_LOCKS
2007 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2009 struct rx_serverQueueEntry *sq;
2010 struct rx_call *call = (struct rx_call *)0;
2011 struct rx_service *service = NULL;
2013 MUTEX_ENTER(&freeSQEList_lock);
2015 if ((sq = rx_FreeSQEList)) {
2016 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
2017 MUTEX_EXIT(&freeSQEList_lock);
2018 } else { /* otherwise allocate a new one and return that */
2019 MUTEX_EXIT(&freeSQEList_lock);
2020 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2021 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2022 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2025 MUTEX_ENTER(&rx_serverPool_lock);
2026 if (cur_service != NULL) {
2027 ReturnToServerPool(cur_service);
2030 if (!opr_queue_IsEmpty(&rx_incomingCallQueue)) {
2031 struct rx_call *tcall, *choice2 = NULL;
2032 struct opr_queue *cursor;
2034 /* Scan for eligible incoming calls. A call is not eligible
2035 * if the maximum number of calls for its service type are
2036 * already executing */
2037 /* One thread will process calls FCFS (to prevent starvation),
2038 * while the other threads may run ahead looking for calls which
2039 * have all their input data available immediately. This helps
2040 * keep threads from blocking, waiting for data from the client. */
2041 for (opr_queue_Scan(&rx_incomingCallQueue, cursor)) {
2042 tcall = opr_queue_Entry(cursor, struct rx_call, entry);
2044 service = tcall->conn->service;
2045 if (!QuotaOK(service)) {
2048 MUTEX_ENTER(&rx_pthread_mutex);
2049 if (tno == rxi_fcfs_thread_num
2050 || opr_queue_IsEnd(&rx_incomingCallQueue, cursor)) {
2051 MUTEX_EXIT(&rx_pthread_mutex);
2052 /* If we're the fcfs thread , then we'll just use
2053 * this call. If we haven't been able to find an optimal
2054 * choice, and we're at the end of the list, then use a
2055 * 2d choice if one has been identified. Otherwise... */
2056 call = (choice2 ? choice2 : tcall);
2057 service = call->conn->service;
2059 MUTEX_EXIT(&rx_pthread_mutex);
2060 if (!opr_queue_IsEmpty(&tcall->rq)) {
2061 struct rx_packet *rp;
2062 rp = opr_queue_First(&tcall->rq, struct rx_packet,
2064 if (rp->header.seq == 1) {
2066 || (rp->header.flags & RX_LAST_PACKET)) {
2068 } else if (rxi_2dchoice && !choice2
2069 && !(tcall->flags & RX_CALL_CLEARED)
2070 && (tcall->rprev > rxi_HardAckRate)) {
2080 ReturnToServerPool(service);
2086 opr_queue_Remove(&call->entry);
2087 MUTEX_EXIT(&rx_serverPool_lock);
2088 MUTEX_ENTER(&call->lock);
2090 if (call->flags & RX_CALL_WAIT_PROC) {
2091 call->flags &= ~RX_CALL_WAIT_PROC;
2092 rx_atomic_dec(&rx_nWaiting);
2095 if (call->state != RX_STATE_PRECALL || call->error) {
2096 MUTEX_EXIT(&call->lock);
2097 MUTEX_ENTER(&rx_serverPool_lock);
2098 ReturnToServerPool(service);
2103 if (opr_queue_IsEmpty(&call->rq)
2104 || opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq != 1)
2105 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2107 CLEAR_CALL_QUEUE_LOCK(call);
2110 /* If there are no eligible incoming calls, add this process
2111 * to the idle server queue, to wait for one */
2115 *socketp = OSI_NULLSOCKET;
2117 sq->socketp = socketp;
2118 opr_queue_Append(&rx_idleServerQueue, &sq->entry);
2119 #ifndef AFS_AIX41_ENV
2120 rx_waitForPacket = sq;
2121 #endif /* AFS_AIX41_ENV */
2123 CV_WAIT(&sq->cv, &rx_serverPool_lock);
2125 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2126 MUTEX_EXIT(&rx_serverPool_lock);
2127 return (struct rx_call *)0;
2130 } while (!(call = sq->newcall)
2131 && !(socketp && *socketp != OSI_NULLSOCKET));
2132 MUTEX_EXIT(&rx_serverPool_lock);
2134 MUTEX_ENTER(&call->lock);
2140 MUTEX_ENTER(&freeSQEList_lock);
2141 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2142 rx_FreeSQEList = sq;
2143 MUTEX_EXIT(&freeSQEList_lock);
2146 clock_GetTime(&call->startTime);
2147 call->state = RX_STATE_ACTIVE;
2148 call->app.mode = RX_MODE_RECEIVING;
2149 #ifdef RX_KERNEL_TRACE
2150 if (ICL_SETACTIVE(afs_iclSetp)) {
2151 int glockOwner = ISAFS_GLOCK();
2154 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2155 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2162 rxi_calltrace(RX_CALL_START, call);
2163 dpf(("rx_GetCall(port=%d, service=%d) ==> call %"AFS_PTR_FMT"\n",
2164 call->conn->service->servicePort, call->conn->service->serviceId,
2167 MUTEX_EXIT(&call->lock);
2168 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
2170 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2175 #else /* RX_ENABLE_LOCKS */
2177 rx_GetCall(int tno, struct rx_service *cur_service, osi_socket * socketp)
2179 struct rx_serverQueueEntry *sq;
2180 struct rx_call *call = (struct rx_call *)0, *choice2;
2181 struct rx_service *service = NULL;
2185 MUTEX_ENTER(&freeSQEList_lock);
2187 if ((sq = rx_FreeSQEList)) {
2188 rx_FreeSQEList = *(struct rx_serverQueueEntry **)sq;
2189 MUTEX_EXIT(&freeSQEList_lock);
2190 } else { /* otherwise allocate a new one and return that */
2191 MUTEX_EXIT(&freeSQEList_lock);
2192 sq = rxi_Alloc(sizeof(struct rx_serverQueueEntry));
2193 MUTEX_INIT(&sq->lock, "server Queue lock", MUTEX_DEFAULT, 0);
2194 CV_INIT(&sq->cv, "server Queue lock", CV_DEFAULT, 0);
2196 MUTEX_ENTER(&sq->lock);
2198 if (cur_service != NULL) {
2199 cur_service->nRequestsRunning--;
2200 MUTEX_ENTER(&rx_quota_mutex);
2201 if (cur_service->nRequestsRunning < cur_service->minProcs)
2204 MUTEX_EXIT(&rx_quota_mutex);
2206 if (!opr_queue_IsEmpty(&rx_incomingCallQueue)) {
2207 struct rx_call *tcall;
2208 struct opr_queue *cursor;
2209 /* Scan for eligible incoming calls. A call is not eligible
2210 * if the maximum number of calls for its service type are
2211 * already executing */
2212 /* One thread will process calls FCFS (to prevent starvation),
2213 * while the other threads may run ahead looking for calls which
2214 * have all their input data available immediately. This helps
2215 * keep threads from blocking, waiting for data from the client. */
2216 choice2 = (struct rx_call *)0;
2217 for (opr_queue_Scan(&rx_incomingCallQueue, cursor)) {
2218 tcall = opr_queue_Entry(cursor, struct rx_call, entry);
2219 service = tcall->conn->service;
2220 if (QuotaOK(service)) {
2221 MUTEX_ENTER(&rx_pthread_mutex);
2222 /* XXX - If tcall->entry.next is NULL, then we're no longer
2223 * on a queue at all. This shouldn't happen. */
2224 if (tno == rxi_fcfs_thread_num || !tcall->entry.next) {
2225 MUTEX_EXIT(&rx_pthread_mutex);
2226 /* If we're the fcfs thread, then we'll just use
2227 * this call. If we haven't been able to find an optimal
2228 * choice, and we're at the end of the list, then use a
2229 * 2d choice if one has been identified. Otherwise... */
2230 call = (choice2 ? choice2 : tcall);
2231 service = call->conn->service;
2233 MUTEX_EXIT(&rx_pthread_mutex);
2234 if (!opr_queue_IsEmpty(&tcall->rq)) {
2235 struct rx_packet *rp;
2236 rp = opr_queue_First(&tcall->rq, struct rx_packet,
2238 if (rp->header.seq == 1
2240 || (rp->header.flags & RX_LAST_PACKET))) {
2242 } else if (rxi_2dchoice && !choice2
2243 && !(tcall->flags & RX_CALL_CLEARED)
2244 && (tcall->rprev > rxi_HardAckRate)) {
2257 opr_queue_Remove(&call->entry);
2258 /* we can't schedule a call if there's no data!!! */
2259 /* send an ack if there's no data, if we're missing the
2260 * first packet, or we're missing something between first
2261 * and last -- there's a "hole" in the incoming data. */
2262 if (opr_queue_IsEmpty(&call->rq)
2263 || opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq != 1
2264 || call->rprev != opr_queue_Last(&call->rq, struct rx_packet, entry)->header.seq)
2265 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
2267 call->flags &= (~RX_CALL_WAIT_PROC);
2268 service->nRequestsRunning++;
2269 /* just started call in minProcs pool, need fewer to maintain
2271 MUTEX_ENTER(&rx_quota_mutex);
2272 if (service->nRequestsRunning <= service->minProcs)
2275 MUTEX_EXIT(&rx_quota_mutex);
2276 rx_atomic_dec(&rx_nWaiting);
2277 /* MUTEX_EXIT(&call->lock); */
2279 /* If there are no eligible incoming calls, add this process
2280 * to the idle server queue, to wait for one */
2283 *socketp = OSI_NULLSOCKET;
2285 sq->socketp = socketp;
2286 opr_queue_Append(&rx_idleServerQueue, &sq->entry);
2290 if (afs_termState == AFSOP_STOP_RXCALLBACK) {
2292 rxi_Free(sq, sizeof(struct rx_serverQueueEntry));
2293 return (struct rx_call *)0;
2296 } while (!(call = sq->newcall)
2297 && !(socketp && *socketp != OSI_NULLSOCKET));
2299 MUTEX_EXIT(&sq->lock);
2301 MUTEX_ENTER(&freeSQEList_lock);
2302 *(struct rx_serverQueueEntry **)sq = rx_FreeSQEList;
2303 rx_FreeSQEList = sq;
2304 MUTEX_EXIT(&freeSQEList_lock);
2307 clock_GetTime(&call->startTime);
2308 call->state = RX_STATE_ACTIVE;
2309 call->app.mode = RX_MODE_RECEIVING;
2310 #ifdef RX_KERNEL_TRACE
2311 if (ICL_SETACTIVE(afs_iclSetp)) {
2312 int glockOwner = ISAFS_GLOCK();
2315 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
2316 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
2323 rxi_calltrace(RX_CALL_START, call);
2324 dpf(("rx_GetCall(port=%d, service=%d) ==> call %p\n",
2325 call->conn->service->servicePort, call->conn->service->serviceId,
2328 dpf(("rx_GetCall(socketp=%p, *socketp=0x%x)\n", socketp, *socketp));
2335 #endif /* RX_ENABLE_LOCKS */
2339 /* Establish a procedure to be called when a packet arrives for a
2340 * call. This routine will be called at most once after each call,
2341 * and will also be called if there is an error condition on the or
2342 * the call is complete. Used by multi rx to build a selection
2343 * function which determines which of several calls is likely to be a
2344 * good one to read from.
2345 * NOTE: the way this is currently implemented it is probably only a
2346 * good idea to (1) use it immediately after a newcall (clients only)
2347 * and (2) only use it once. Other uses currently void your warranty
2350 rx_SetArrivalProc(struct rx_call *call,
2351 void (*proc) (struct rx_call * call,
2354 void * handle, int arg)
2356 call->arrivalProc = proc;
2357 call->arrivalProcHandle = handle;
2358 call->arrivalProcArg = arg;
2361 /* Call is finished (possibly prematurely). Return rc to the peer, if
2362 * appropriate, and return the final error code from the conversation
2366 rx_EndCall(struct rx_call *call, afs_int32 rc)
2368 struct rx_connection *conn = call->conn;
2372 dpf(("rx_EndCall(call %"AFS_PTR_FMT" rc %d error %d abortCode %d)\n",
2373 call, rc, call->error, call->abortCode));
2376 MUTEX_ENTER(&call->lock);
2378 if (rc == 0 && call->error == 0) {
2379 call->abortCode = 0;
2380 call->abortCount = 0;
2383 call->arrivalProc = NULL;
2384 if (rc && call->error == 0) {
2385 rxi_CallError(call, rc);
2386 call->app.mode = RX_MODE_ERROR;
2387 /* Send an abort message to the peer if this error code has
2388 * only just been set. If it was set previously, assume the
2389 * peer has already been sent the error code or will request it
2391 rxi_SendCallAbort(call, (struct rx_packet *)0, 0, 0);
2393 if (conn->type == RX_SERVER_CONNECTION) {
2394 /* Make sure reply or at least dummy reply is sent */
2395 if (call->app.mode == RX_MODE_RECEIVING) {
2396 MUTEX_EXIT(&call->lock);
2397 rxi_WriteProc(call, 0, 0);
2398 MUTEX_ENTER(&call->lock);
2400 if (call->app.mode == RX_MODE_SENDING) {
2401 rxi_FlushWriteLocked(call);
2403 rxi_calltrace(RX_CALL_END, call);
2404 /* Call goes to hold state until reply packets are acknowledged */
2405 if (call->tfirst + call->nSoftAcked < call->tnext) {
2406 call->state = RX_STATE_HOLD;
2408 call->state = RX_STATE_DALLY;
2409 rxi_ClearTransmitQueue(call, 0);
2410 rxi_rto_cancel(call);
2411 rxi_CancelKeepAliveEvent(call);
2413 } else { /* Client connection */
2415 /* Make sure server receives input packets, in the case where
2416 * no reply arguments are expected */
2418 if ((call->app.mode == RX_MODE_SENDING)
2419 || (call->app.mode == RX_MODE_RECEIVING && call->rnext == 1)) {
2420 MUTEX_EXIT(&call->lock);
2421 (void)rxi_ReadProc(call, &dummy, 1);
2422 MUTEX_ENTER(&call->lock);
2425 /* If we had an outstanding delayed ack, be nice to the server
2426 * and force-send it now.
2428 if (call->delayedAckEvent) {
2429 rxi_CancelDelayedAckEvent(call);
2430 rxi_SendDelayedAck(NULL, call, NULL, 0);
2433 /* We need to release the call lock since it's lower than the
2434 * conn_call_lock and we don't want to hold the conn_call_lock
2435 * over the rx_ReadProc call. The conn_call_lock needs to be held
2436 * here for the case where rx_NewCall is perusing the calls on
2437 * the connection structure. We don't want to signal until
2438 * rx_NewCall is in a stable state. Otherwise, rx_NewCall may
2439 * have checked this call, found it active and by the time it
2440 * goes to sleep, will have missed the signal.
2442 MUTEX_EXIT(&call->lock);
2443 MUTEX_ENTER(&conn->conn_call_lock);
2444 MUTEX_ENTER(&call->lock);
2447 /* While there are some circumstances where a call with an error is
2448 * obviously not on a "busy" channel, be conservative (clearing
2449 * lastBusy is just best-effort to possibly speed up rx_NewCall).
2450 * The call channel is definitely not busy if we just successfully
2451 * completed a call on it. */
2452 conn->lastBusy[call->channel] = 0;
2454 } else if (call->error == RX_CALL_TIMEOUT) {
2455 /* The call is still probably running on the server side, so try to
2456 * avoid this call channel in the future. */
2457 conn->lastBusy[call->channel] = clock_Sec();
2460 MUTEX_ENTER(&conn->conn_data_lock);
2461 conn->flags |= RX_CONN_BUSY;
2462 if (conn->flags & RX_CONN_MAKECALL_WAITING) {
2463 MUTEX_EXIT(&conn->conn_data_lock);
2464 #ifdef RX_ENABLE_LOCKS
2465 CV_BROADCAST(&conn->conn_call_cv);
2470 #ifdef RX_ENABLE_LOCKS
2472 MUTEX_EXIT(&conn->conn_data_lock);
2474 #endif /* RX_ENABLE_LOCKS */
2475 call->state = RX_STATE_DALLY;
2477 error = call->error;
2479 /* currentPacket, nLeft, and NFree must be zeroed here, because
2480 * ResetCall cannot: ResetCall may be called at splnet(), in the
2481 * kernel version, and may interrupt the macros rx_Read or
2482 * rx_Write, which run at normal priority for efficiency. */
2483 if (call->app.currentPacket) {
2484 #ifdef RX_TRACK_PACKETS
2485 call->app.currentPacket->flags &= ~RX_PKTFLAG_CP;
2487 rxi_FreePacket(call->app.currentPacket);
2488 call->app.currentPacket = (struct rx_packet *)0;
2491 call->app.nLeft = call->app.nFree = call->app.curlen = 0;
2493 /* Free any packets from the last call to ReadvProc/WritevProc */
2494 #ifdef RXDEBUG_PACKET
2496 #endif /* RXDEBUG_PACKET */
2497 rxi_FreePackets(0, &call->app.iovq);
2498 MUTEX_EXIT(&call->lock);
2500 CALL_RELE(call, RX_CALL_REFCOUNT_BEGIN);
2501 if (conn->type == RX_CLIENT_CONNECTION) {
2502 MUTEX_ENTER(&conn->conn_data_lock);
2503 conn->flags &= ~RX_CONN_BUSY;
2504 MUTEX_EXIT(&conn->conn_data_lock);
2505 MUTEX_EXIT(&conn->conn_call_lock);
2509 * Map errors to the local host's errno.h format.
2511 error = ntoh_syserr_conv(error);
2513 /* If the caller said the call failed with some error, we had better
2514 * return an error code. */
2515 osi_Assert(!rc || error);
2519 #if !defined(KERNEL)
2521 /* Call this routine when shutting down a server or client (especially
2522 * clients). This will allow Rx to gracefully garbage collect server
2523 * connections, and reduce the number of retries that a server might
2524 * make to a dead client.
2525 * This is not quite right, since some calls may still be ongoing and
2526 * we can't lock them to destroy them. */
2532 if (!rxi_IsRunning()) {
2534 return; /* Already shutdown. */
2536 rxi_Finalize_locked();
2541 rxi_Finalize_locked(void)
2543 struct rx_connection **conn_ptr, **conn_end;
2544 rx_atomic_set(&rxi_running, 0);
2545 rxi_DeleteCachedConnections();
2546 if (rx_connHashTable) {
2547 MUTEX_ENTER(&rx_connHashTable_lock);
2548 for (conn_ptr = &rx_connHashTable[0], conn_end =
2549 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
2551 struct rx_connection *conn, *next;
2552 for (conn = *conn_ptr; conn; conn = next) {
2554 if (conn->type == RX_CLIENT_CONNECTION) {
2555 rx_GetConnection(conn);
2556 #ifdef RX_ENABLE_LOCKS
2557 rxi_DestroyConnectionNoLock(conn);
2558 #else /* RX_ENABLE_LOCKS */
2559 rxi_DestroyConnection(conn);
2560 #endif /* RX_ENABLE_LOCKS */
2564 #ifdef RX_ENABLE_LOCKS
2565 while (rx_connCleanup_list) {
2566 struct rx_connection *conn;
2567 conn = rx_connCleanup_list;
2568 rx_connCleanup_list = rx_connCleanup_list->next;
2569 MUTEX_EXIT(&rx_connHashTable_lock);
2570 rxi_CleanupConnection(conn);
2571 MUTEX_ENTER(&rx_connHashTable_lock);
2573 MUTEX_EXIT(&rx_connHashTable_lock);
2574 #endif /* RX_ENABLE_LOCKS */
2579 afs_winsockCleanup();
2584 /* if we wakeup packet waiter too often, can get in loop with two
2585 AllocSendPackets each waking each other up (from ReclaimPacket calls) */
2587 rxi_PacketsUnWait(void)
2589 if (!rx_waitingForPackets) {
2593 if (rxi_OverQuota(RX_PACKET_CLASS_SEND)) {
2594 return; /* still over quota */
2597 rx_waitingForPackets = 0;
2598 #ifdef RX_ENABLE_LOCKS
2599 CV_BROADCAST(&rx_waitingForPackets_cv);
2601 osi_rxWakeup(&rx_waitingForPackets);
2607 /* ------------------Internal interfaces------------------------- */
2609 /* Return this process's service structure for the
2610 * specified socket and service */
2611 static struct rx_service *
2612 rxi_FindService(osi_socket socket, u_short serviceId)
2614 struct rx_service **sp;
2615 for (sp = &rx_services[0]; *sp; sp++) {
2616 if ((*sp)->serviceId == serviceId && (*sp)->socket == socket)
2622 #ifdef RXDEBUG_PACKET
2623 #ifdef KDUMP_RX_LOCK
2624 static struct rx_call_rx_lock *rx_allCallsp = 0;
2626 static struct rx_call *rx_allCallsp = 0;
2628 #endif /* RXDEBUG_PACKET */
2630 /* Allocate a call structure, for the indicated channel of the
2631 * supplied connection. The mode and state of the call must be set by
2632 * the caller. Returns the call with mutex locked. */
2633 static struct rx_call *
2634 rxi_NewCall(struct rx_connection *conn, int channel)
2636 struct rx_call *call;
2637 #ifdef RX_ENABLE_LOCKS
2638 struct rx_call *cp; /* Call pointer temp */
2639 struct opr_queue *cursor;
2642 dpf(("rxi_NewCall(conn %"AFS_PTR_FMT", channel %d)\n", conn, channel));
2644 /* Grab an existing call structure, or allocate a new one.
2645 * Existing call structures are assumed to have been left reset by
2647 MUTEX_ENTER(&rx_freeCallQueue_lock);
2649 #ifdef RX_ENABLE_LOCKS
2651 * EXCEPT that the TQ might not yet be cleared out.
2652 * Skip over those with in-use TQs.
2655 for (opr_queue_Scan(&rx_freeCallQueue, cursor)) {
2656 cp = opr_queue_Entry(cursor, struct rx_call, entry);
2657 if (!(cp->flags & RX_CALL_TQ_BUSY)) {
2663 #else /* RX_ENABLE_LOCKS */
2664 if (!opr_queue_IsEmpty(&rx_freeCallQueue)) {
2665 call = opr_queue_First(&rx_freeCallQueue, struct rx_call, entry);
2666 #endif /* RX_ENABLE_LOCKS */
2667 opr_queue_Remove(&call->entry);
2668 if (rx_stats_active)
2669 rx_atomic_dec(&rx_stats.nFreeCallStructs);
2670 MUTEX_EXIT(&rx_freeCallQueue_lock);
2671 MUTEX_ENTER(&call->lock);
2672 CLEAR_CALL_QUEUE_LOCK(call);
2673 #ifdef RX_ENABLE_LOCKS
2674 /* Now, if TQ wasn't cleared earlier, do it now. */
2675 rxi_WaitforTQBusy(call);
2676 if (call->flags & RX_CALL_TQ_CLEARME) {
2677 rxi_ClearTransmitQueue(call, 1);
2678 /*queue_Init(&call->tq);*/
2680 #endif /* RX_ENABLE_LOCKS */
2681 /* Bind the call to its connection structure */
2683 rxi_ResetCall(call, 1);
2686 call = rxi_Alloc(sizeof(struct rx_call));
2687 #ifdef RXDEBUG_PACKET
2688 call->allNextp = rx_allCallsp;
2689 rx_allCallsp = call;
2691 rx_atomic_inc_and_read(&rx_stats.nCallStructs);
2692 #else /* RXDEBUG_PACKET */
2693 rx_atomic_inc(&rx_stats.nCallStructs);
2694 #endif /* RXDEBUG_PACKET */
2696 MUTEX_EXIT(&rx_freeCallQueue_lock);
2697 MUTEX_INIT(&call->lock, "call lock", MUTEX_DEFAULT, NULL);
2698 MUTEX_ENTER(&call->lock);
2699 CV_INIT(&call->cv_twind, "call twind", CV_DEFAULT, 0);
2700 CV_INIT(&call->cv_rq, "call rq", CV_DEFAULT, 0);
2701 CV_INIT(&call->cv_tq, "call tq", CV_DEFAULT, 0);
2703 /* Initialize once-only items */
2704 opr_queue_Init(&call->tq);
2705 opr_queue_Init(&call->rq);
2706 opr_queue_Init(&call->app.iovq);
2707 #ifdef RXDEBUG_PACKET
2708 call->rqc = call->tqc = call->iovqc = 0;
2709 #endif /* RXDEBUG_PACKET */
2710 /* Bind the call to its connection structure (prereq for reset) */
2712 rxi_ResetCall(call, 1);
2714 call->channel = channel;
2715 call->callNumber = &conn->callNumber[channel];
2716 call->rwind = conn->rwind[channel];
2717 call->twind = conn->twind[channel];
2718 /* Note that the next expected call number is retained (in
2719 * conn->callNumber[i]), even if we reallocate the call structure
2721 conn->call[channel] = call;
2722 /* if the channel's never been used (== 0), we should start at 1, otherwise
2723 * the call number is valid from the last time this channel was used */
2724 if (*call->callNumber == 0)
2725 *call->callNumber = 1;
2730 /* A call has been inactive long enough that so we can throw away
2731 * state, including the call structure, which is placed on the call
2734 * call->lock amd rx_refcnt_mutex are held upon entry.
2735 * haveCTLock is set when called from rxi_ReapConnections.
2737 * return 1 if the call is freed, 0 if not.
2740 rxi_FreeCall(struct rx_call *call, int haveCTLock)
2742 int channel = call->channel;
2743 struct rx_connection *conn = call->conn;
2744 u_char state = call->state;
2747 * We are setting the state to RX_STATE_RESET to
2748 * ensure that no one else will attempt to use this
2749 * call once we drop the refcnt lock. We must drop
2750 * the refcnt lock before calling rxi_ResetCall
2751 * because it cannot be held across acquiring the
2752 * freepktQ lock. NewCall does the same.
2754 call->state = RX_STATE_RESET;
2755 MUTEX_EXIT(&rx_refcnt_mutex);
2756 rxi_ResetCall(call, 0);
2758 if (MUTEX_TRYENTER(&conn->conn_call_lock))
2760 if (state == RX_STATE_DALLY || state == RX_STATE_HOLD)
2761 (*call->callNumber)++;
2763 if (call->conn->call[channel] == call)
2764 call->conn->call[channel] = 0;
2765 MUTEX_EXIT(&conn->conn_call_lock);
2768 * We couldn't obtain the conn_call_lock so we can't
2769 * disconnect the call from the connection. Set the
2770 * call state to dally so that the call can be reused.
2772 MUTEX_ENTER(&rx_refcnt_mutex);
2773 call->state = RX_STATE_DALLY;
2777 MUTEX_ENTER(&rx_freeCallQueue_lock);
2778 SET_CALL_QUEUE_LOCK(call, &rx_freeCallQueue_lock);
2779 #ifdef RX_ENABLE_LOCKS
2780 /* A call may be free even though its transmit queue is still in use.
2781 * Since we search the call list from head to tail, put busy calls at
2782 * the head of the list, and idle calls at the tail.
2784 if (call->flags & RX_CALL_TQ_BUSY)
2785 opr_queue_Prepend(&rx_freeCallQueue, &call->entry);
2787 opr_queue_Append(&rx_freeCallQueue, &call->entry);
2788 #else /* RX_ENABLE_LOCKS */
2789 opr_queue_Append(&rx_freeCallQueue, &call->entry);
2790 #endif /* RX_ENABLE_LOCKS */
2791 if (rx_stats_active)
2792 rx_atomic_inc(&rx_stats.nFreeCallStructs);
2793 MUTEX_EXIT(&rx_freeCallQueue_lock);
2795 /* Destroy the connection if it was previously slated for
2796 * destruction, i.e. the Rx client code previously called
2797 * rx_DestroyConnection (client connections), or
2798 * rxi_ReapConnections called the same routine (server
2799 * connections). Only do this, however, if there are no
2800 * outstanding calls. Note that for fine grain locking, there appears
2801 * to be a deadlock in that rxi_FreeCall has a call locked and
2802 * DestroyConnectionNoLock locks each call in the conn. But note a
2803 * few lines up where we have removed this call from the conn.
2804 * If someone else destroys a connection, they either have no
2805 * call lock held or are going through this section of code.
2807 MUTEX_ENTER(&conn->conn_data_lock);
2808 if (conn->flags & RX_CONN_DESTROY_ME && !(conn->flags & RX_CONN_MAKECALL_WAITING)) {
2809 rx_GetConnection(conn);
2810 MUTEX_EXIT(&conn->conn_data_lock);
2811 #ifdef RX_ENABLE_LOCKS
2813 rxi_DestroyConnectionNoLock(conn);
2815 rxi_DestroyConnection(conn);
2816 #else /* RX_ENABLE_LOCKS */
2817 rxi_DestroyConnection(conn);
2818 #endif /* RX_ENABLE_LOCKS */
2820 MUTEX_EXIT(&conn->conn_data_lock);
2822 MUTEX_ENTER(&rx_refcnt_mutex);
2826 rx_atomic_t rxi_Allocsize = RX_ATOMIC_INIT(0);
2827 rx_atomic_t rxi_Alloccnt = RX_ATOMIC_INIT(0);
2830 rxi_Alloc(size_t size)
2834 if (rx_stats_active) {
2835 rx_atomic_add(&rxi_Allocsize, (int) size);
2836 rx_atomic_inc(&rxi_Alloccnt);
2840 #if defined(KERNEL) && !defined(UKERNEL) && defined(AFS_FBSD80_ENV)
2841 afs_osi_Alloc_NoSleep(size);
2846 osi_Panic("rxi_Alloc error");
2852 rxi_Free(void *addr, size_t size)
2854 if (rx_stats_active) {
2855 rx_atomic_sub(&rxi_Allocsize, (int) size);
2856 rx_atomic_dec(&rxi_Alloccnt);
2858 osi_Free(addr, size);
2862 rxi_SetPeerMtu(struct rx_peer *peer, afs_uint32 host, afs_uint32 port, int mtu)
2864 struct rx_peer **peer_ptr = NULL, **peer_end = NULL;
2865 struct rx_peer *next = NULL;
2869 MUTEX_ENTER(&rx_peerHashTable_lock);
2871 peer_ptr = &rx_peerHashTable[0];
2872 peer_end = &rx_peerHashTable[rx_hashTableSize];
2875 for ( ; peer_ptr < peer_end; peer_ptr++) {
2878 for ( ; peer; peer = next) {
2880 if (host == peer->host)
2885 hashIndex = PEER_HASH(host, port);
2886 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2887 if ((peer->host == host) && (peer->port == port))
2892 MUTEX_ENTER(&rx_peerHashTable_lock);
2897 MUTEX_EXIT(&rx_peerHashTable_lock);
2899 MUTEX_ENTER(&peer->peer_lock);
2900 /* We don't handle dropping below min, so don't */
2901 mtu = MAX(mtu, RX_MIN_PACKET_SIZE);
2902 peer->ifMTU=MIN(mtu, peer->ifMTU);
2903 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
2904 /* if we tweaked this down, need to tune our peer MTU too */
2905 peer->MTU = MIN(peer->MTU, peer->natMTU);
2906 /* if we discovered a sub-1500 mtu, degrade */
2907 if (peer->ifMTU < OLD_MAX_PACKET_SIZE)
2908 peer->maxDgramPackets = 1;
2909 /* We no longer have valid peer packet information */
2910 if (peer->maxPacketSize + RX_HEADER_SIZE > peer->ifMTU)
2911 peer->maxPacketSize = 0;
2912 MUTEX_EXIT(&peer->peer_lock);
2914 MUTEX_ENTER(&rx_peerHashTable_lock);
2916 if (host && !port) {
2918 /* pick up where we left off */
2922 MUTEX_EXIT(&rx_peerHashTable_lock);
2925 #ifdef AFS_RXERRQ_ENV
2927 rxi_SetPeerDead(struct sock_extended_err *err, afs_uint32 host, afs_uint16 port)
2929 int hashIndex = PEER_HASH(host, port);
2930 struct rx_peer *peer;
2932 MUTEX_ENTER(&rx_peerHashTable_lock);
2934 for (peer = rx_peerHashTable[hashIndex]; peer; peer = peer->next) {
2935 if (peer->host == host && peer->port == port) {
2941 MUTEX_EXIT(&rx_peerHashTable_lock);
2944 rx_atomic_inc(&peer->neterrs);
2945 MUTEX_ENTER(&peer->peer_lock);
2946 peer->last_err_origin = RX_NETWORK_ERROR_ORIGIN_ICMP;
2947 peer->last_err_type = err->ee_type;
2948 peer->last_err_code = err->ee_code;
2949 MUTEX_EXIT(&peer->peer_lock);
2951 MUTEX_ENTER(&rx_peerHashTable_lock);
2953 MUTEX_EXIT(&rx_peerHashTable_lock);
2958 rxi_ProcessNetError(struct sock_extended_err *err, afs_uint32 addr, afs_uint16 port)
2960 # ifdef AFS_ADAPT_PMTU
2961 if (err->ee_errno == EMSGSIZE && err->ee_info >= 68) {
2962 rxi_SetPeerMtu(NULL, addr, port, err->ee_info - RX_IPUDP_SIZE);
2966 if (err->ee_origin == SO_EE_ORIGIN_ICMP && err->ee_type == ICMP_DEST_UNREACH) {
2967 switch (err->ee_code) {
2968 case ICMP_NET_UNREACH:
2969 case ICMP_HOST_UNREACH:
2970 case ICMP_PORT_UNREACH:
2973 rxi_SetPeerDead(err, addr, port);
2980 rxi_TranslateICMP(int type, int code)
2983 case ICMP_DEST_UNREACH:
2985 case ICMP_NET_UNREACH:
2986 return "Destination Net Unreachable";
2987 case ICMP_HOST_UNREACH:
2988 return "Destination Host Unreachable";
2989 case ICMP_PROT_UNREACH:
2990 return "Destination Protocol Unreachable";
2991 case ICMP_PORT_UNREACH:
2992 return "Destination Port Unreachable";
2994 return "Destination Net Prohibited";
2996 return "Destination Host Prohibited";
3002 #endif /* AFS_RXERRQ_ENV */
3005 * Get the last network error for a connection
3007 * A "network error" here means an error retrieved from ICMP, or some other
3008 * mechanism outside of Rx that informs us of errors in network reachability.
3010 * If a peer associated with the given Rx connection has received a network
3011 * error recently, this function allows the caller to know what error
3012 * specifically occurred. This can be useful to know, since e.g. ICMP errors
3013 * can cause calls to that peer to be quickly aborted. So, this function can
3014 * help see why a call was aborted due to network errors.
3016 * If we have received traffic from a peer since the last network error, we
3017 * treat that peer as if we had not received an network error for it.
3019 * @param[in] conn The Rx connection to examine
3020 * @param[out] err_origin The origin of the last network error (e.g. ICMP);
3021 * one of the RX_NETWORK_ERROR_ORIGIN_* constants
3022 * @param[out] err_type The type of the last error
3023 * @param[out] err_code The code of the last error
3024 * @param[out] msg Human-readable error message, if applicable; NULL otherwise
3026 * @return If we have an error
3027 * @retval -1 No error to get; 'out' params are undefined
3028 * @retval 0 We have an error; 'out' params contain the last error
3031 rx_GetNetworkError(struct rx_connection *conn, int *err_origin, int *err_type,
3032 int *err_code, const char **msg)
3034 #ifdef AFS_RXERRQ_ENV
3035 struct rx_peer *peer = conn->peer;
3036 if (rx_atomic_read(&peer->neterrs)) {
3037 MUTEX_ENTER(&peer->peer_lock);
3038 *err_origin = peer->last_err_origin;
3039 *err_type = peer->last_err_type;
3040 *err_code = peer->last_err_code;
3041 MUTEX_EXIT(&peer->peer_lock);
3044 if (*err_origin == RX_NETWORK_ERROR_ORIGIN_ICMP) {
3045 *msg = rxi_TranslateICMP(*err_type, *err_code);
3054 /* Find the peer process represented by the supplied (host,port)
3055 * combination. If there is no appropriate active peer structure, a
3056 * new one will be allocated and initialized
3059 rxi_FindPeer(afs_uint32 host, u_short port, int create)
3063 hashIndex = PEER_HASH(host, port);
3064 MUTEX_ENTER(&rx_peerHashTable_lock);
3065 for (pp = rx_peerHashTable[hashIndex]; pp; pp = pp->next) {
3066 if ((pp->host == host) && (pp->port == port))
3071 pp = rxi_AllocPeer(); /* This bzero's *pp */
3072 pp->host = host; /* set here or in InitPeerParams is zero */
3074 #ifdef AFS_RXERRQ_ENV
3075 rx_atomic_set(&pp->neterrs, 0);
3077 MUTEX_INIT(&pp->peer_lock, "peer_lock", MUTEX_DEFAULT, 0);
3078 opr_queue_Init(&pp->rpcStats);
3079 pp->next = rx_peerHashTable[hashIndex];
3080 rx_peerHashTable[hashIndex] = pp;
3081 rxi_InitPeerParams(pp);
3082 if (rx_stats_active)
3083 rx_atomic_inc(&rx_stats.nPeerStructs);
3089 MUTEX_EXIT(&rx_peerHashTable_lock);
3094 /* Find the connection at (host, port) started at epoch, and with the
3095 * given connection id. Creates the server connection if necessary.
3096 * The type specifies whether a client connection or a server
3097 * connection is desired. In both cases, (host, port) specify the
3098 * peer's (host, pair) pair. Client connections are not made
3099 * automatically by this routine. The parameter socket gives the
3100 * socket descriptor on which the packet was received. This is used,
3101 * in the case of server connections, to check that *new* connections
3102 * come via a valid (port, serviceId). Finally, the securityIndex
3103 * parameter must match the existing index for the connection. If a
3104 * server connection is created, it will be created using the supplied
3105 * index, if the index is valid for this service */
3106 static struct rx_connection *
3107 rxi_FindConnection(osi_socket socket, afs_uint32 host,
3108 u_short port, u_short serviceId, afs_uint32 cid,
3109 afs_uint32 epoch, int type, u_int securityIndex,
3110 int *unknownService)
3112 int hashindex, flag, i;
3113 struct rx_connection *conn;
3114 *unknownService = 0;
3115 hashindex = CONN_HASH(host, port, cid, epoch, type);
3116 MUTEX_ENTER(&rx_connHashTable_lock);
3117 rxLastConn ? (conn = rxLastConn, flag = 0) : (conn =
3118 rx_connHashTable[hashindex],
3121 if ((conn->type == type) && ((cid & RX_CIDMASK) == conn->cid)
3122 && (epoch == conn->epoch)) {
3123 struct rx_peer *pp = conn->peer;
3124 if (securityIndex != conn->securityIndex) {
3125 /* this isn't supposed to happen, but someone could forge a packet
3126 * like this, and there seems to be some CM bug that makes this
3127 * happen from time to time -- in which case, the fileserver
3129 MUTEX_EXIT(&rx_connHashTable_lock);
3130 return (struct rx_connection *)0;
3132 if (pp->host == host && pp->port == port)
3134 if (type == RX_CLIENT_CONNECTION && pp->port == port)
3136 /* So what happens when it's a callback connection? */
3137 if ( /*type == RX_CLIENT_CONNECTION && */
3138 (conn->epoch & 0x80000000))
3142 /* the connection rxLastConn that was used the last time is not the
3143 ** one we are looking for now. Hence, start searching in the hash */
3145 conn = rx_connHashTable[hashindex];
3150 struct rx_service *service;
3151 if (type == RX_CLIENT_CONNECTION) {
3152 MUTEX_EXIT(&rx_connHashTable_lock);
3153 return (struct rx_connection *)0;
3155 service = rxi_FindService(socket, serviceId);
3156 if (!service || (securityIndex >= service->nSecurityObjects)
3157 || (service->securityObjects[securityIndex] == 0)) {
3158 MUTEX_EXIT(&rx_connHashTable_lock);
3159 *unknownService = 1;
3160 return (struct rx_connection *)0;
3162 conn = rxi_AllocConnection(); /* This bzero's the connection */
3163 MUTEX_INIT(&conn->conn_call_lock, "conn call lock", MUTEX_DEFAULT, 0);
3164 MUTEX_INIT(&conn->conn_data_lock, "conn data lock", MUTEX_DEFAULT, 0);
3165 CV_INIT(&conn->conn_call_cv, "conn call cv", CV_DEFAULT, 0);
3166 conn->next = rx_connHashTable[hashindex];
3167 rx_connHashTable[hashindex] = conn;
3168 conn->peer = rxi_FindPeer(host, port, 1);
3169 conn->type = RX_SERVER_CONNECTION;
3170 conn->lastSendTime = clock_Sec(); /* don't GC immediately */
3171 conn->epoch = epoch;
3172 conn->cid = cid & RX_CIDMASK;
3173 conn->ackRate = RX_FAST_ACK_RATE;
3174 conn->service = service;
3175 conn->serviceId = serviceId;
3176 conn->securityIndex = securityIndex;
3177 conn->securityObject = service->securityObjects[securityIndex];
3178 conn->nSpecific = 0;
3179 conn->specific = NULL;
3180 rx_SetConnDeadTime(conn, service->connDeadTime);
3181 rx_SetConnIdleDeadTime(conn, service->idleDeadTime);
3182 for (i = 0; i < RX_MAXCALLS; i++) {
3183 conn->twind[i] = rx_initSendWindow;
3184 conn->rwind[i] = rx_initReceiveWindow;
3186 /* Notify security object of the new connection */
3187 RXS_NewConnection(conn->securityObject, conn);
3188 /* XXXX Connection timeout? */
3189 if (service->newConnProc)
3190 (*service->newConnProc) (conn);
3191 if (rx_stats_active)
3192 rx_atomic_inc(&rx_stats.nServerConns);
3195 rx_GetConnection(conn);
3197 rxLastConn = conn; /* store this connection as the last conn used */
3198 MUTEX_EXIT(&rx_connHashTable_lock);
3203 * Abort the call if the server is over the busy threshold. This
3204 * can be used without requiring a call structure be initialised,
3205 * or connected to a particular channel
3208 rxi_AbortIfServerBusy(osi_socket socket, struct rx_connection *conn,
3209 struct rx_packet *np)
3213 if ((rx_BusyThreshold > 0) &&
3214 (rx_atomic_read(&rx_nWaiting) > rx_BusyThreshold)) {
3215 MUTEX_ENTER(&conn->conn_data_lock);
3216 serial = ++conn->serial;
3217 MUTEX_EXIT(&conn->conn_data_lock);
3218 rxi_SendRawAbort(socket, conn->peer->host, conn->peer->port,
3219 serial, rx_BusyError, np, 0);
3220 if (rx_stats_active)
3221 rx_atomic_inc(&rx_stats.nBusies);
3228 static_inline struct rx_call *
3229 rxi_ReceiveClientCall(struct rx_packet *np, struct rx_connection *conn)
3232 struct rx_call *call;
3234 channel = np->header.cid & RX_CHANNELMASK;
3235 MUTEX_ENTER(&conn->conn_call_lock);
3236 call = conn->call[channel];
3237 if (np->header.type == RX_PACKET_TYPE_BUSY) {
3238 conn->lastBusy[channel] = clock_Sec();
3240 if (!call || conn->callNumber[channel] != np->header.callNumber) {
3241 MUTEX_EXIT(&conn->conn_call_lock);
3242 if (rx_stats_active)
3243 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3247 MUTEX_ENTER(&call->lock);
3248 MUTEX_EXIT(&conn->conn_call_lock);
3250 if ((call->state == RX_STATE_DALLY)
3251 && np->header.type == RX_PACKET_TYPE_ACK) {
3252 if (rx_stats_active)
3253 rx_atomic_inc(&rx_stats.ignorePacketDally);
3254 MUTEX_EXIT(&call->lock);
3261 static_inline struct rx_call *
3262 rxi_ReceiveServerCall(osi_socket socket, struct rx_packet *np,
3263 struct rx_connection *conn)
3266 struct rx_call *call;
3268 channel = np->header.cid & RX_CHANNELMASK;
3269 MUTEX_ENTER(&conn->conn_call_lock);
3270 call = conn->call[channel];
3273 if (rxi_AbortIfServerBusy(socket, conn, np)) {
3274 MUTEX_EXIT(&conn->conn_call_lock);
3278 call = rxi_NewCall(conn, channel); /* returns locked call */
3279 *call->callNumber = np->header.callNumber;
3280 MUTEX_EXIT(&conn->conn_call_lock);
3282 call->state = RX_STATE_PRECALL;
3283 clock_GetTime(&call->queueTime);
3284 call->app.bytesSent = 0;
3285 call->app.bytesRcvd = 0;
3286 rxi_KeepAliveOn(call);
3291 if (np->header.callNumber == conn->callNumber[channel]) {
3292 MUTEX_ENTER(&call->lock);
3293 MUTEX_EXIT(&conn->conn_call_lock);
3297 if (np->header.callNumber < conn->callNumber[channel]) {
3298 MUTEX_EXIT(&conn->conn_call_lock);
3299 if (rx_stats_active)
3300 rx_atomic_inc(&rx_stats.spuriousPacketsRead);
3304 MUTEX_ENTER(&call->lock);
3305 MUTEX_EXIT(&conn->conn_call_lock);
3307 /* Wait until the transmit queue is idle before deciding
3308 * whether to reset the current call. Chances are that the
3309 * call will be in ether DALLY or HOLD state once the TQ_BUSY
3312 #ifdef RX_ENABLE_LOCKS
3313 if (call->state == RX_STATE_ACTIVE && !call->error) {
3314 rxi_WaitforTQBusy(call);
3315 /* If we entered error state while waiting,
3316 * must call rxi_CallError to permit rxi_ResetCall
3317 * to processed when the tqWaiter count hits zero.
3320 rxi_CallError(call, call->error);
3321 MUTEX_EXIT(&call->lock);
3325 #endif /* RX_ENABLE_LOCKS */
3326 /* If the new call cannot be taken right now send a busy and set
3327 * the error condition in this call, so that it terminates as
3328 * quickly as possible */
3329 if (call->state == RX_STATE_ACTIVE) {
3330 rxi_CallError(call, RX_CALL_DEAD);
3331 rxi_SendSpecial(call, conn, NULL, RX_PACKET_TYPE_BUSY,
3333 MUTEX_EXIT(&call->lock);
3337 if (rxi_AbortIfServerBusy(socket, conn, np)) {
3338 MUTEX_EXIT(&call->lock);
3342 rxi_ResetCall(call, 0);
3343 /* The conn_call_lock is not held but no one else should be
3344 * using this call channel while we are processing this incoming
3345 * packet. This assignment should be safe.
3347 *call->callNumber = np->header.callNumber;
3348 call->state = RX_STATE_PRECALL;
3349 clock_GetTime(&call->queueTime);
3350 call->app.bytesSent = 0;
3351 call->app.bytesRcvd = 0;
3352 rxi_KeepAliveOn(call);
3358 /* There are two packet tracing routines available for testing and monitoring
3359 * Rx. One is called just after every packet is received and the other is
3360 * called just before every packet is sent. Received packets, have had their
3361 * headers decoded, and packets to be sent have not yet had their headers
3362 * encoded. Both take two parameters: a pointer to the packet and a sockaddr
3363 * containing the network address. Both can be modified. The return value, if
3364 * non-zero, indicates that the packet should be dropped. */
3366 int (*rx_justReceived) (struct rx_packet *, struct sockaddr_in *) = 0;
3367 int (*rx_almostSent) (struct rx_packet *, struct sockaddr_in *) = 0;
3369 /* A packet has been received off the interface. Np is the packet, socket is
3370 * the socket number it was received from (useful in determining which service
3371 * this packet corresponds to), and (host, port) reflect the host,port of the
3372 * sender. This call returns the packet to the caller if it is finished with
3373 * it, rather than de-allocating it, just as a small performance hack */
3376 rxi_ReceivePacket(struct rx_packet *np, osi_socket socket,
3377 afs_uint32 host, u_short port, int *tnop,
3378 struct rx_call **newcallp)
3380 struct rx_call *call;
3381 struct rx_connection *conn;
3383 int unknownService = 0;
3387 struct rx_packet *tnp;
3390 /* We don't print out the packet until now because (1) the time may not be
3391 * accurate enough until now in the lwp implementation (rx_Listener only gets
3392 * the time after the packet is read) and (2) from a protocol point of view,
3393 * this is the first time the packet has been seen */
3394 packetType = (np->header.type > 0 && np->header.type < RX_N_PACKET_TYPES)
3395 ? rx_packetTypes[np->header.type - 1] : "*UNKNOWN*";
3396 dpf(("R %d %s: %x.%d.%d.%d.%d.%d.%d flags %d, packet %"AFS_PTR_FMT"\n",
3397 np->header.serial, packetType, ntohl(host), ntohs(port), np->header.serviceId,
3398 np->header.epoch, np->header.cid, np->header.callNumber,
3399 np->header.seq, np->header.flags, np));
3402 /* Account for connectionless packets */
3403 if (rx_stats_active &&
3404 ((np->header.type == RX_PACKET_TYPE_VERSION) ||
3405 (np->header.type == RX_PACKET_TYPE_DEBUG))) {
3406 struct rx_peer *peer;
3408 /* Try to look up the peer structure, but don't create one */
3409 peer = rxi_FindPeer(host, port, 0);
3411 /* Since this may not be associated with a connection, it may have
3412 * no refCount, meaning we could race with ReapConnections
3415 if (peer && (peer->refCount > 0)) {
3416 #ifdef AFS_RXERRQ_ENV
3417 if (rx_atomic_read(&peer->neterrs)) {
3418 rx_atomic_set(&peer->neterrs, 0);
3421 MUTEX_ENTER(&peer->peer_lock);
3422 peer->bytesReceived += np->length;
3423 MUTEX_EXIT(&peer->peer_lock);
3427 if (np->header.type == RX_PACKET_TYPE_VERSION) {
3428 return rxi_ReceiveVersionPacket(np, socket, host, port, 1);
3431 if (np->header.type == RX_PACKET_TYPE_DEBUG) {
3432 return rxi_ReceiveDebugPacket(np, socket, host, port, 1);
3435 /* If an input tracer function is defined, call it with the packet and
3436 * network address. Note this function may modify its arguments. */
3437 if (rx_justReceived) {
3438 struct sockaddr_in addr;
3440 addr.sin_family = AF_INET;
3441 addr.sin_port = port;
3442 addr.sin_addr.s_addr = host;
3443 memset(&addr.sin_zero, 0, sizeof(addr.sin_zero));
3444 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
3445 addr.sin_len = sizeof(addr);
3447 drop = (*rx_justReceived) (np, &addr);
3448 /* drop packet if return value is non-zero */
3451 port = addr.sin_port; /* in case fcn changed addr */
3452 host = addr.sin_addr.s_addr;
3456 /* If packet was not sent by the client, then *we* must be the client */
3457 type = ((np->header.flags & RX_CLIENT_INITIATED) != RX_CLIENT_INITIATED)
3458 ? RX_CLIENT_CONNECTION : RX_SERVER_CONNECTION;
3460 /* Find the connection (or fabricate one, if we're the server & if
3461 * necessary) associated with this packet */
3463 rxi_FindConnection(socket, host, port, np->header.serviceId,
3464 np->header.cid, np->header.epoch, type,
3465 np->header.securityIndex, &unknownService);
3467 /* To avoid having 2 connections just abort at each other,
3468 don't abort an abort. */
3470 if (unknownService && (np->header.type != RX_PACKET_TYPE_ABORT))
3471 rxi_SendRawAbort(socket, host, port, 0, RX_INVALID_OPERATION,
3476 #ifdef AFS_RXERRQ_ENV
3477 if (rx_atomic_read(&conn->peer->neterrs)) {
3478 rx_atomic_set(&conn->peer->neterrs, 0);
3482 /* If we're doing statistics, then account for the incoming packet */
3483 if (rx_stats_active) {
3484 MUTEX_ENTER(&conn->peer->peer_lock);
3485 conn->peer->bytesReceived += np->length;
3486 MUTEX_EXIT(&conn->peer->peer_lock);
3489 /* If the connection is in an error state, send an abort packet and ignore
3490 * the incoming packet */
3492 /* Don't respond to an abort packet--we don't want loops! */
3493 MUTEX_ENTER(&conn->conn_data_lock);
3494 if (np->header.type != RX_PACKET_TYPE_ABORT)
3495 np = rxi_SendConnectionAbort(conn, np, 1, 0);
3496 putConnection(conn);
3497 MUTEX_EXIT(&conn->conn_data_lock);
3501 /* Check for connection-only requests (i.e. not call specific). */
3502 if (np->header.callNumber == 0) {
3503 switch (np->header.type) {
3504 case RX_PACKET_TYPE_ABORT: {
3505 /* What if the supplied error is zero? */
3506 afs_int32 errcode = ntohl(rx_GetInt32(np, 0));
3507 dpf(("rxi_ReceivePacket ABORT rx_GetInt32 = %d\n", errcode));
3508 rxi_ConnectionError(conn, errcode);
3509 putConnection(conn);
3512 case RX_PACKET_TYPE_CHALLENGE:
3513 tnp = rxi_ReceiveChallengePacket(conn, np, 1);
3514 putConnection(conn);
3516 case RX_PACKET_TYPE_RESPONSE:
3517 tnp = rxi_ReceiveResponsePacket(conn, np, 1);
3518 putConnection(conn);
3520 case RX_PACKET_TYPE_PARAMS:
3521 case RX_PACKET_TYPE_PARAMS + 1:
3522 case RX_PACKET_TYPE_PARAMS + 2:
3523 /* ignore these packet types for now */
3524 putConnection(conn);
3528 /* Should not reach here, unless the peer is broken: send an
3530 rxi_ConnectionError(conn, RX_PROTOCOL_ERROR);
3531 MUTEX_ENTER(&conn->conn_data_lock);
3532 tnp = rxi_SendConnectionAbort(conn, np, 1, 0);
3533 putConnection(conn);
3534 MUTEX_EXIT(&conn->conn_data_lock);
3539 if (type == RX_SERVER_CONNECTION)
3540 call = rxi_ReceiveServerCall(socket, np, conn);
3542 call = rxi_ReceiveClientCall(np, conn);
3545 putConnection(conn);
3549 MUTEX_ASSERT(&call->lock);
3550 /* Set remote user defined status from packet */
3551 call->remoteStatus = np->header.userStatus;
3553 /* Now do packet type-specific processing */
3554 switch (np->header.type) {
3555 case RX_PACKET_TYPE_DATA:
3556 /* If we're a client, and receiving a response, then all the packets
3557 * we transmitted packets are implicitly acknowledged. */
3558 if (type == RX_CLIENT_CONNECTION && !opr_queue_IsEmpty(&call->tq))
3559 rxi_AckAllInTransmitQueue(call);
3561 np = rxi_ReceiveDataPacket(call, np, 1, socket, host, port, tnop,
3564 case RX_PACKET_TYPE_ACK:
3565 /* Respond immediately to ack packets requesting acknowledgement
3567 if (np->header.flags & RX_REQUEST_ACK) {
3569 (void)rxi_SendCallAbort(call, 0, 1, 0);
3571 (void)rxi_SendAck(call, 0, np->header.serial,
3572 RX_ACK_PING_RESPONSE, 1);
3574 np = rxi_ReceiveAckPacket(call, np, 1);
3576 case RX_PACKET_TYPE_ABORT: {
3577 /* An abort packet: reset the call, passing the error up to the user. */
3578 /* What if error is zero? */
3579 /* What if the error is -1? the application will treat it as a timeout. */
3580 afs_int32 errdata = ntohl(*(afs_int32 *) rx_DataOf(np));
3581 dpf(("rxi_ReceivePacket ABORT rx_DataOf = %d\n", errdata));
3582 rxi_CallError(call, errdata);
3583 MUTEX_EXIT(&call->lock);
3584 putConnection(conn);
3585 return np; /* xmitting; drop packet */
3587 case RX_PACKET_TYPE_BUSY:
3588 /* Mostly ignore BUSY packets. We will update lastReceiveTime below,
3589 * so we don't think the endpoint is completely dead, but otherwise
3590 * just act as if we never saw anything. If all we get are BUSY packets
3591 * back, then we will eventually error out with RX_CALL_TIMEOUT if the
3592 * connection is configured with idle/hard timeouts. */
3595 case RX_PACKET_TYPE_ACKALL:
3596 /* All packets acknowledged, so we can drop all packets previously
3597 * readied for sending */
3598 rxi_AckAllInTransmitQueue(call);
3601 /* Should not reach here, unless the peer is broken: send an abort
3603 rxi_CallError(call, RX_PROTOCOL_ERROR);
3604 np = rxi_SendCallAbort(call, np, 1, 0);
3607 /* Note when this last legitimate packet was received, for keep-alive
3608 * processing. Note, we delay getting the time until now in the hope that
3609 * the packet will be delivered to the user before any get time is required
3610 * (if not, then the time won't actually be re-evaluated here). */
3611 call->lastReceiveTime = clock_Sec();
3612 MUTEX_EXIT(&call->lock);
3613 putConnection(conn);
3617 /* return true if this is an "interesting" connection from the point of view
3618 of someone trying to debug the system */
3620 rxi_IsConnInteresting(struct rx_connection *aconn)
3623 struct rx_call *tcall;
3625 if (aconn->flags & (RX_CONN_MAKECALL_WAITING | RX_CONN_DESTROY_ME))
3628 for (i = 0; i < RX_MAXCALLS; i++) {
3629 tcall = aconn->call[i];
3631 if ((tcall->state == RX_STATE_PRECALL)
3632 || (tcall->state == RX_STATE_ACTIVE))
3634 if ((tcall->app.mode == RX_MODE_SENDING)
3635 || (tcall->app.mode == RX_MODE_RECEIVING))
3643 /* if this is one of the last few packets AND it wouldn't be used by the
3644 receiving call to immediately satisfy a read request, then drop it on
3645 the floor, since accepting it might prevent a lock-holding thread from
3646 making progress in its reading. If a call has been cleared while in
3647 the precall state then ignore all subsequent packets until the call
3648 is assigned to a thread. */
3651 TooLow(struct rx_packet *ap, struct rx_call *acall)
3655 MUTEX_ENTER(&rx_quota_mutex);
3656 if (((ap->header.seq != 1) && (acall->flags & RX_CALL_CLEARED)
3657 && (acall->state == RX_STATE_PRECALL))
3658 || ((rx_nFreePackets < rxi_dataQuota + 2)
3659 && !((ap->header.seq < acall->rnext + rx_initSendWindow)
3660 && (acall->flags & RX_CALL_READER_WAIT)))) {
3663 MUTEX_EXIT(&rx_quota_mutex);
3669 * Clear the attach wait flag on a connection and proceed.
3671 * Any processing waiting for a connection to be attached should be
3672 * unblocked. We clear the flag and do any other needed tasks.
3675 * the conn to unmark waiting for attach
3677 * @pre conn's conn_data_lock must be locked before calling this function
3681 rxi_ConnClearAttachWait(struct rx_connection *conn)
3683 /* Indicate that rxi_CheckReachEvent is no longer running by
3684 * clearing the flag. Must be atomic under conn_data_lock to
3685 * avoid a new call slipping by: rxi_CheckConnReach holds
3686 * conn_data_lock while checking RX_CONN_ATTACHWAIT.
3688 conn->flags &= ~RX_CONN_ATTACHWAIT;
3689 if (conn->flags & RX_CONN_NAT_PING) {
3690 conn->flags &= ~RX_CONN_NAT_PING;
3691 rxi_ScheduleNatKeepAliveEvent(conn);
3696 * Event handler function for connection-specific events for checking
3697 * reachability. Also called directly from main code with |event| == NULL
3698 * in order to trigger the initial reachability check.
3700 * When |event| == NULL, must be called with the connection data lock held,
3701 * but returns with the lock unlocked.
3704 rxi_CheckReachEvent(struct rxevent *event, void *arg1, void *arg2, int dummy)
3706 struct rx_connection *conn = arg1;
3707 struct rx_call *acall = arg2;
3708 struct rx_call *call = acall;
3709 struct clock when, now;
3713 MUTEX_ENTER(&conn->conn_data_lock);
3715 MUTEX_ASSERT(&conn->conn_data_lock);
3717 if (event != NULL && event == conn->checkReachEvent)
3718 rxevent_Put(&conn->checkReachEvent);
3719 waiting = conn->flags & RX_CONN_ATTACHWAIT;
3720 MUTEX_EXIT(&conn->conn_data_lock);
3724 MUTEX_ENTER(&conn->conn_call_lock);
3725 MUTEX_ENTER(&conn->conn_data_lock);
3726 for (i = 0; i < RX_MAXCALLS; i++) {
3727 struct rx_call *tc = conn->call[i];
3728 if (tc && tc->state == RX_STATE_PRECALL) {
3734 rxi_ConnClearAttachWait(conn);
3735 MUTEX_EXIT(&conn->conn_data_lock);
3736 MUTEX_EXIT(&conn->conn_call_lock);
3741 MUTEX_ENTER(&call->lock);
3742 rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
3744 MUTEX_EXIT(&call->lock);
3746 clock_GetTime(&now);
3748 when.sec += RX_CHECKREACH_TIMEOUT;
3749 MUTEX_ENTER(&conn->conn_data_lock);
3750 if (!conn->checkReachEvent) {
3751 rx_GetConnection(conn);
3752 conn->checkReachEvent = rxevent_Post(&when, &now,
3753 rxi_CheckReachEvent, conn,
3756 MUTEX_EXIT(&conn->conn_data_lock);
3759 /* If fired as an event handler, drop our refcount on the connection. */
3761 putConnection(conn);
3765 rxi_CheckConnReach(struct rx_connection *conn, struct rx_call *call)
3767 struct rx_service *service = conn->service;
3768 struct rx_peer *peer = conn->peer;
3769 afs_uint32 now, lastReach;
3771 if (service->checkReach == 0)
3775 MUTEX_ENTER(&peer->peer_lock);
3776 lastReach = peer->lastReachTime;
3777 MUTEX_EXIT(&peer->peer_lock);
3778 if (now - lastReach < RX_CHECKREACH_TTL)
3781 MUTEX_ENTER(&conn->conn_data_lock);
3782 if (conn->flags & RX_CONN_ATTACHWAIT) {
3783 MUTEX_EXIT(&conn->conn_data_lock);
3786 conn->flags |= RX_CONN_ATTACHWAIT;
3787 if (conn->checkReachEvent == NULL) {
3788 /* rxi_CheckReachEvent(NULL, ...) will drop the lock. */
3789 rxi_CheckReachEvent(NULL, conn, call, 0);
3791 MUTEX_EXIT(&conn->conn_data_lock);
3797 /* try to attach call, if authentication is complete */
3799 TryAttach(struct rx_call *acall, osi_socket socket,
3800 int *tnop, struct rx_call **newcallp,
3803 struct rx_connection *conn = acall->conn;
3805 if (conn->type == RX_SERVER_CONNECTION
3806 && acall->state == RX_STATE_PRECALL) {
3807 /* Don't attach until we have any req'd. authentication. */
3808 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0) {
3809 if (reachOverride || rxi_CheckConnReach(conn, acall) == 0)
3810 rxi_AttachServerProc(acall, socket, tnop, newcallp);
3811 /* Note: this does not necessarily succeed; there
3812 * may not any proc available
3815 rxi_ChallengeOn(acall->conn);
3820 /* A data packet has been received off the interface. This packet is
3821 * appropriate to the call (the call is in the right state, etc.). This
3822 * routine can return a packet to the caller, for re-use */
3824 static struct rx_packet *
3825 rxi_ReceiveDataPacket(struct rx_call *call,
3826 struct rx_packet *np, int istack,
3827 osi_socket socket, afs_uint32 host, u_short port,
3828 int *tnop, struct rx_call **newcallp)
3830 int ackNeeded = 0; /* 0 means no, otherwise ack_reason */
3835 afs_uint32 serial=0, flags=0;
3837 struct rx_packet *tnp;
3838 if (rx_stats_active)
3839 rx_atomic_inc(&rx_stats.dataPacketsRead);
3842 /* If there are no packet buffers, drop this new packet, unless we can find
3843 * packet buffers from inactive calls */
3845 && (rxi_OverQuota(RX_PACKET_CLASS_RECEIVE) || TooLow(np, call))) {
3846 MUTEX_ENTER(&rx_freePktQ_lock);
3847 rxi_NeedMorePackets = TRUE;
3848 MUTEX_EXIT(&rx_freePktQ_lock);
3849 if (rx_stats_active)
3850 rx_atomic_inc(&rx_stats.noPacketBuffersOnRead);
3851 rxi_calltrace(RX_TRACE_DROP, call);
3852 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - quota problems\n", np));
3853 /* We used to clear the receive queue here, in an attempt to free
3854 * packets. However this is unsafe if the queue has received a
3855 * soft ACK for the final packet */
3856 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
3862 * New in AFS 3.5, if the RX_JUMBO_PACKET flag is set then this
3863 * packet is one of several packets transmitted as a single
3864 * datagram. Do not send any soft or hard acks until all packets
3865 * in a jumbogram have been processed. Send negative acks right away.
3867 for (isFirst = 1, tnp = NULL; isFirst || tnp; isFirst = 0) {
3868 /* tnp is non-null when there are more packets in the
3869 * current jumbo gram */
3876 seq = np->header.seq;
3877 serial = np->header.serial;
3878 flags = np->header.flags;
3880 /* If the call is in an error state, send an abort message */
3882 return rxi_SendCallAbort(call, np, istack, 0);
3884 /* The RX_JUMBO_PACKET is set in all but the last packet in each
3885 * AFS 3.5 jumbogram. */
3886 if (flags & RX_JUMBO_PACKET) {
3887 tnp = rxi_SplitJumboPacket(np, host, port, isFirst);
3892 if (np->header.spare != 0) {
3893 MUTEX_ENTER(&call->conn->conn_data_lock);
3894 call->conn->flags |= RX_CONN_USING_PACKET_CKSUM;
3895 MUTEX_EXIT(&call->conn->conn_data_lock);
3898 /* The usual case is that this is the expected next packet */
3899 if (seq == call->rnext) {
3901 /* Check to make sure it is not a duplicate of one already queued */
3902 if (!opr_queue_IsEmpty(&call->rq)
3903 && opr_queue_First(&call->rq, struct rx_packet, entry)->header.seq == seq) {
3904 if (rx_stats_active)
3905 rx_atomic_inc(&rx_stats.dupPacketsRead);
3906 dpf(("packet %"AFS_PTR_FMT" dropped on receipt - duplicate\n", np));
3907 rxi_CancelDelayedAckEvent(call);
3908 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
3914 /* It's the next packet. Stick it on the receive queue
3915 * for this call. Set newPackets to make sure we wake
3916 * the reader once all packets have been processed */
3917 #ifdef RX_TRACK_PACKETS
3918 np->flags |= RX_PKTFLAG_RQ;
3920 opr_queue_Prepend(&call->rq, &np->entry);
3921 #ifdef RXDEBUG_PACKET
3923 #endif /* RXDEBUG_PACKET */
3925 np = NULL; /* We can't use this anymore */
3928 /* If an ack is requested then set a flag to make sure we
3929 * send an acknowledgement for this packet */
3930 if (flags & RX_REQUEST_ACK) {
3931 ackNeeded = RX_ACK_REQUESTED;
3934 /* Keep track of whether we have received the last packet */
3935 if (flags & RX_LAST_PACKET) {
3936 call->flags |= RX_CALL_HAVE_LAST;
3940 /* Check whether we have all of the packets for this call */
3941 if (call->flags & RX_CALL_HAVE_LAST) {
3942 afs_uint32 tseq; /* temporary sequence number */
3943 struct opr_queue *cursor;
3945 for (tseq = seq, opr_queue_Scan(&call->rq, cursor)) {
3946 struct rx_packet *tp;
3948 tp = opr_queue_Entry(cursor, struct rx_packet, entry);
3949 if (tseq != tp->header.seq)
3951 if (tp->header.flags & RX_LAST_PACKET) {
3952 call->flags |= RX_CALL_RECEIVE_DONE;
3959 /* Provide asynchronous notification for those who want it
3960 * (e.g. multi rx) */
3961 if (call->arrivalProc) {
3962 (*call->arrivalProc) (call, call->arrivalProcHandle,
3963 call->arrivalProcArg);
3964 call->arrivalProc = NULL;
3967 /* Update last packet received */
3970 /* If there is no server process serving this call, grab
3971 * one, if available. We only need to do this once. If a
3972 * server thread is available, this thread becomes a server
3973 * thread and the server thread becomes a listener thread. */
3975 TryAttach(call, socket, tnop, newcallp, 0);
3978 /* This is not the expected next packet. */
3980 /* Determine whether this is a new or old packet, and if it's
3981 * a new one, whether it fits into the current receive window.
3982 * Also figure out whether the packet was delivered in sequence.
3983 * We use the prev variable to determine whether the new packet
3984 * is the successor of its immediate predecessor in the
3985 * receive queue, and the missing flag to determine whether
3986 * any of this packets predecessors are missing. */
3988 afs_uint32 prev; /* "Previous packet" sequence number */
3989 struct opr_queue *cursor;
3990 int missing; /* Are any predecessors missing? */
3992 /* If the new packet's sequence number has been sent to the
3993 * application already, then this is a duplicate */
3994 if (seq < call->rnext) {
3995 if (rx_stats_active)
3996 rx_atomic_inc(&rx_stats.dupPacketsRead);
3997 rxi_CancelDelayedAckEvent(call);
3998 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE, istack);
4004 /* If the sequence number is greater than what can be
4005 * accomodated by the current window, then send a negative
4006 * acknowledge and drop the packet */
4007 if ((call->rnext + call->rwind) <= seq) {
4008 rxi_CancelDelayedAckEvent(call);
4009 np = rxi_SendAck(call, np, serial, RX_ACK_EXCEEDS_WINDOW,
4016 /* Look for the packet in the queue of old received packets */
4017 prev = call->rnext - 1;
4019 for (opr_queue_Scan(&call->rq, cursor)) {
4020 struct rx_packet *tp
4021 = opr_queue_Entry(cursor, struct rx_packet, entry);
4023 /*Check for duplicate packet */
4024 if (seq == tp->header.seq) {
4025 if (rx_stats_active)
4026 rx_atomic_inc(&rx_stats.dupPacketsRead);
4027 rxi_CancelDelayedAckEvent(call);
4028 np = rxi_SendAck(call, np, serial, RX_ACK_DUPLICATE,
4034 /* If we find a higher sequence packet, break out and
4035 * insert the new packet here. */
4036 if (seq < tp->header.seq)
4038 /* Check for missing packet */
4039 if (tp->header.seq != prev + 1) {
4043 prev = tp->header.seq;
4046 /* Keep track of whether we have received the last packet. */
4047 if (flags & RX_LAST_PACKET) {
4048 call->flags |= RX_CALL_HAVE_LAST;
4051 /* It's within the window: add it to the the receive queue.
4052 * tp is left by the previous loop either pointing at the
4053 * packet before which to insert the new packet, or at the
4054 * queue head if the queue is empty or the packet should be
4056 #ifdef RX_TRACK_PACKETS
4057 np->flags |= RX_PKTFLAG_RQ;
4059 #ifdef RXDEBUG_PACKET
4061 #endif /* RXDEBUG_PACKET */
4062 opr_queue_InsertBefore(cursor, &np->entry);
4066 /* Check whether we have all of the packets for this call */
4067 if ((call->flags & RX_CALL_HAVE_LAST)
4068 && !(call->flags & RX_CALL_RECEIVE_DONE)) {
4069 afs_uint32 tseq; /* temporary sequence number */
4072 for (opr_queue_Scan(&call->rq, cursor)) {
4073 struct rx_packet *tp
4074 = opr_queue_Entry(cursor, struct rx_packet, entry);
4075 if (tseq != tp->header.seq)
4077 if (tp->header.flags & RX_LAST_PACKET) {
4078 call->flags |= RX_CALL_RECEIVE_DONE;
4085 /* We need to send an ack of the packet is out of sequence,
4086 * or if an ack was requested by the peer. */
4087 if (seq != prev + 1 || missing) {
4088 ackNeeded = RX_ACK_OUT_OF_SEQUENCE;
4089 } else if (flags & RX_REQUEST_ACK) {
4090 ackNeeded = RX_ACK_REQUESTED;
4093 /* Acknowledge the last packet for each call */
4094 if (flags & RX_LAST_PACKET) {
4105 * If the receiver is waiting for an iovec, fill the iovec
4106 * using the data from the receive queue */
4107 if (call->flags & RX_CALL_IOVEC_WAIT) {
4108 didHardAck = rxi_FillReadVec(call, serial);
4109 /* the call may have been aborted */
4118 /* Wakeup the reader if any */
4119 if ((call->flags & RX_CALL_READER_WAIT)
4120 && (!(call->flags & RX_CALL_IOVEC_WAIT) || !(call->iovNBytes)
4121 || (call->iovNext >= call->iovMax)
4122 || (call->flags & RX_CALL_RECEIVE_DONE))) {
4123 call->flags &= ~RX_CALL_READER_WAIT;
4124 #ifdef RX_ENABLE_LOCKS
4125 CV_BROADCAST(&call->cv_rq);
4127 osi_rxWakeup(&call->rq);
4133 * Send an ack when requested by the peer, or once every
4134 * rxi_SoftAckRate packets until the last packet has been
4135 * received. Always send a soft ack for the last packet in
4136 * the server's reply. */
4138 rxi_CancelDelayedAckEvent(call);
4139 np = rxi_SendAck(call, np, serial, ackNeeded, istack);
4140 } else if (call->nSoftAcks > (u_short) rxi_SoftAckRate) {
4141 rxi_CancelDelayedAckEvent(call);
4142 np = rxi_SendAck(call, np, serial, RX_ACK_IDLE, istack);
4143 } else if (call->nSoftAcks) {
4144 if (haveLast && !(flags & RX_CLIENT_INITIATED))
4145 rxi_PostDelayedAckEvent(call, &rx_lastAckDelay);
4147 rxi_PostDelayedAckEvent(call, &rx_softAckDelay);
4148 } else if (call->flags & RX_CALL_RECEIVE_DONE) {
4149 rxi_CancelDelayedAckEvent(call);
4156 rxi_UpdatePeerReach(struct rx_connection *conn, struct rx_call *acall)
4158 struct rx_peer *peer = conn->peer;
4160 MUTEX_ENTER(&peer->peer_lock);
4161 peer->lastReachTime = clock_Sec();
4162 MUTEX_EXIT(&peer->peer_lock);
4164 MUTEX_ENTER(&conn->conn_data_lock);
4165 if (conn->flags & RX_CONN_ATTACHWAIT) {
4168 rxi_ConnClearAttachWait(conn);
4169 MUTEX_EXIT(&conn->conn_data_lock);
4171 for (i = 0; i < RX_MAXCALLS; i++) {
4172 struct rx_call *call = conn->call[i];
4175 MUTEX_ENTER(&call->lock);
4176 /* tnop can be null if newcallp is null */
4177 TryAttach(call, (osi_socket) - 1, NULL, NULL, 1);
4179 MUTEX_EXIT(&call->lock);
4183 MUTEX_EXIT(&conn->conn_data_lock);
4186 #if defined(RXDEBUG) && defined(AFS_NT40_ENV)
4188 rx_ack_reason(int reason)
4191 case RX_ACK_REQUESTED:
4193 case RX_ACK_DUPLICATE:
4195 case RX_ACK_OUT_OF_SEQUENCE:
4197 case RX_ACK_EXCEEDS_WINDOW:
4199 case RX_ACK_NOSPACE:
4203 case RX_ACK_PING_RESPONSE:
4216 /* The real smarts of the whole thing. */
4217 static struct rx_packet *
4218 rxi_ReceiveAckPacket(struct rx_call *call, struct rx_packet *np,
4221 struct rx_ackPacket *ap;
4223 struct rx_packet *tp;
4224 struct rx_connection *conn = call->conn;
4225 struct rx_peer *peer = conn->peer;
4226 struct opr_queue *cursor;
4227 struct clock now; /* Current time, for RTT calculations */
4235 int newAckCount = 0;
4236 int maxDgramPackets = 0; /* Set if peer supports AFS 3.5 jumbo datagrams */
4237 int pktsize = 0; /* Set if we need to update the peer mtu */
4238 int conn_data_locked = 0;
4240 if (rx_stats_active)
4241 rx_atomic_inc(&rx_stats.ackPacketsRead);
4242 ap = (struct rx_ackPacket *)rx_DataOf(np);
4243 nbytes = rx_Contiguous(np) - (int)((ap->acks) - (u_char *) ap);
4245 return np; /* truncated ack packet */
4247 /* depends on ack packet struct */
4248 nAcks = MIN((unsigned)nbytes, (unsigned)ap->nAcks);
4249 first = ntohl(ap->firstPacket);
4250 prev = ntohl(ap->previousPacket);
4251 serial = ntohl(ap->serial);
4254 * Ignore ack packets received out of order while protecting
4255 * against peers that set the previousPacket field to a packet
4256 * serial number instead of a sequence number.
4258 if (first < call->tfirst ||
4259 (first == call->tfirst && prev < call->tprev && prev < call->tfirst
4266 if (np->header.flags & RX_SLOW_START_OK) {
4267 call->flags |= RX_CALL_SLOW_START_OK;
4270 if (ap->reason == RX_ACK_PING_RESPONSE)
4271 rxi_UpdatePeerReach(conn, call);
4273 if (conn->lastPacketSizeSeq) {
4274 MUTEX_ENTER(&conn->conn_data_lock);
4275 conn_data_locked = 1;
4276 if ((first > conn->lastPacketSizeSeq) && (conn->lastPacketSize)) {
4277 pktsize = conn->lastPacketSize;
4278 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
4281 if ((ap->reason == RX_ACK_PING_RESPONSE) && (conn->lastPingSizeSer)) {
4282 if (!conn_data_locked) {
4283 MUTEX_ENTER(&conn->conn_data_lock);
4284 conn_data_locked = 1;
4286 if ((conn->lastPingSizeSer == serial) && (conn->lastPingSize)) {
4287 /* process mtu ping ack */
4288 pktsize = conn->lastPingSize;
4289 conn->lastPingSizeSer = conn->lastPingSize = 0;
4293 if (conn_data_locked) {
4294 MUTEX_EXIT(&conn->conn_data_lock);
4295 conn_data_locked = 0;
4299 if (rxdebug_active) {
4303 len = _snprintf(msg, sizeof(msg),
4304 "tid[%d] RACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
4305 GetCurrentThreadId(), rx_ack_reason(ap->reason),
4306 ntohl(ap->serial), ntohl(ap->previousPacket),
4307 (unsigned int)np->header.seq, ntohl(ap->firstPacket),
4308 ap->nAcks, ntohs(ap->bufferSpace) );
4312 for (offset = 0; offset < nAcks && len < sizeof(msg); offset++)
4313 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
4317 OutputDebugString(msg);
4319 #else /* AFS_NT40_ENV */
4322 "RACK: reason %x previous %u seq %u serial %u first %u",
4323 ap->reason, ntohl(ap->previousPacket),
4324 (unsigned int)np->header.seq, (unsigned int)serial,
4325 ntohl(ap->firstPacket));
4328 for (offset = 0; offset < nAcks; offset++)
4329 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
4334 #endif /* AFS_NT40_ENV */
4337 MUTEX_ENTER(&peer->peer_lock);
4340 * Start somewhere. Can't assume we can send what we can receive,
4341 * but we are clearly receiving.
4343 if (!peer->maxPacketSize)
4344 peer->maxPacketSize = RX_MIN_PACKET_SIZE - RX_HEADER_SIZE;
4346 if (pktsize > peer->maxPacketSize) {
4347 peer->maxPacketSize = pktsize;
4348 if ((pktsize + RX_HEADER_SIZE > peer->ifMTU)) {
4349 peer->ifMTU = pktsize + RX_HEADER_SIZE;
4350 peer->natMTU = rxi_AdjustIfMTU(peer->ifMTU);
4351 rxi_ScheduleGrowMTUEvent(call, 1);
4356 clock_GetTime(&now);
4358 /* The transmit queue splits into 4 sections.
4360 * The first section is packets which have now been acknowledged
4361 * by a window size change in the ack. These have reached the
4362 * application layer, and may be discarded. These are packets
4363 * with sequence numbers < ap->firstPacket.
4365 * The second section is packets which have sequence numbers in
4366 * the range ap->firstPacket to ap->firstPacket + ap->nAcks. The
4367 * contents of the packet's ack array determines whether these
4368 * packets are acknowledged or not.
4370 * The third section is packets which fall above the range
4371 * addressed in the ack packet. These have not yet been received
4374 * The four section is packets which have not yet been transmitted.
4375 * These packets will have a header.serial of 0.
4378 /* First section - implicitly acknowledged packets that can be
4382 tp = opr_queue_First(&call->tq, struct rx_packet, entry);
4383 while(!opr_queue_IsEnd(&call->tq, &tp->entry) && tp->header.seq < first) {
4384 struct rx_packet *next;
4386 next = opr_queue_Next(&tp->entry, struct rx_packet, entry);
4387 call->tfirst = tp->header.seq + 1;
4389 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4391 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4394 #ifdef RX_ENABLE_LOCKS
4395 /* XXX Hack. Because we have to release the global call lock when sending
4396 * packets (osi_NetSend) we drop all acks while we're traversing the tq
4397 * in rxi_Start sending packets out because packets may move to the
4398 * freePacketQueue as result of being here! So we drop these packets until
4399 * we're safely out of the traversing. Really ugly!
4400 * To make it even uglier, if we're using fine grain locking, we can
4401 * set the ack bits in the packets and have rxi_Start remove the packets
4402 * when it's done transmitting.
4404 if (call->flags & RX_CALL_TQ_BUSY) {
4405 tp->flags |= RX_PKTFLAG_ACKED;
4406 call->flags |= RX_CALL_TQ_SOME_ACKED;
4408 #endif /* RX_ENABLE_LOCKS */
4410 opr_queue_Remove(&tp->entry);
4411 #ifdef RX_TRACK_PACKETS
4412 tp->flags &= ~RX_PKTFLAG_TQ;
4414 #ifdef RXDEBUG_PACKET
4416 #endif /* RXDEBUG_PACKET */
4417 rxi_FreePacket(tp); /* rxi_FreePacket mustn't wake up anyone, preemptively. */
4422 /* N.B. we don't turn off any timers here. They'll go away by themselves, anyway */
4424 /* Second section of the queue - packets for which we are receiving
4427 * Go through the explicit acks/nacks and record the results in
4428 * the waiting packets. These are packets that can't be released
4429 * yet, even with a positive acknowledge. This positive
4430 * acknowledge only means the packet has been received by the
4431 * peer, not that it will be retained long enough to be sent to
4432 * the peer's upper level. In addition, reset the transmit timers
4433 * of any missing packets (those packets that must be missing
4434 * because this packet was out of sequence) */
4436 call->nSoftAcked = 0;
4438 while (!opr_queue_IsEnd(&call->tq, &tp->entry)
4439 && tp->header.seq < first + nAcks) {
4440 /* Set the acknowledge flag per packet based on the
4441 * information in the ack packet. An acknowlegded packet can
4442 * be downgraded when the server has discarded a packet it
4443 * soacked previously, or when an ack packet is received
4444 * out of sequence. */
4445 if (ap->acks[tp->header.seq - first] == RX_ACK_TYPE_ACK) {
4446 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4448 tp->flags |= RX_PKTFLAG_ACKED;
4449 rxi_ComputeRoundTripTime(tp, ap, call, peer, &now);
4456 } else /* RX_ACK_TYPE_NACK */ {
4457 tp->flags &= ~RX_PKTFLAG_ACKED;
4461 tp = opr_queue_Next(&tp->entry, struct rx_packet, entry);
4464 /* We don't need to take any action with the 3rd or 4th section in the
4465 * queue - they're not addressed by the contents of this ACK packet.
4468 /* if the ack packet has a receivelen field hanging off it,
4469 * update our state */
4470 if (np->length >= rx_AckDataSize(ap->nAcks) + 2 * sizeof(afs_int32)) {
4473 /* If the ack packet has a "recommended" size that is less than
4474 * what I am using now, reduce my size to match */
4475 rx_packetread(np, rx_AckDataSize(ap->nAcks) + (int)sizeof(afs_int32),
4476 (int)sizeof(afs_int32), &tSize);
4477 tSize = (afs_uint32) ntohl(tSize);
4478 if (tSize > RX_MAX_PACKET_SIZE)
4479 tSize = RX_MAX_PACKET_SIZE;
4480 if (tSize < RX_MIN_PACKET_SIZE)
4481 tSize = RX_MIN_PACKET_SIZE;
4482 peer->natMTU = rxi_AdjustIfMTU(MIN(tSize, peer->ifMTU));
4484 /* Get the maximum packet size to send to this peer */
4485 rx_packetread(np, rx_AckDataSize(ap->nAcks), (int)sizeof(afs_int32),
4487 tSize = (afs_uint32) ntohl(tSize);
4488 if (tSize > RX_MAX_PACKET_SIZE)
4489 tSize = RX_MAX_PACKET_SIZE;
4490 if (tSize < RX_MIN_PACKET_SIZE)
4491 tSize = RX_MIN_PACKET_SIZE;
4492 tSize = (afs_uint32) MIN(tSize, rx_MyMaxSendSize);
4493 tSize = rxi_AdjustMaxMTU(peer->natMTU, tSize);
4495 /* sanity check - peer might have restarted with different params.
4496 * If peer says "send less", dammit, send less... Peer should never
4497 * be unable to accept packets of the size that prior AFS versions would
4498 * send without asking. */
4499 if (peer->maxMTU != tSize) {
4500 if (peer->maxMTU > tSize) /* possible cong., maxMTU decreased */
4502 peer->maxMTU = tSize;
4503 peer->MTU = MIN(tSize, peer->MTU);
4504 call->MTU = MIN(call->MTU, tSize);
4507 if (np->length == rx_AckDataSize(ap->nAcks) + 3 * sizeof(afs_int32)) {
4510 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4511 (int)sizeof(afs_int32), &tSize);
4512 tSize = (afs_uint32) ntohl(tSize); /* peer's receive window, if it's */
4515 if (tSize >= rx_maxSendWindow)
4516 tSize = rx_maxSendWindow;
4517 if (tSize < call->twind) { /* smaller than our send */
4518 call->twind = tSize; /* window, we must send less... */
4519 call->ssthresh = MIN(call->twind, call->ssthresh);
4520 call->conn->twind[call->channel] = call->twind;
4523 /* Only send jumbograms to 3.4a fileservers. 3.3a RX gets the
4524 * network MTU confused with the loopback MTU. Calculate the
4525 * maximum MTU here for use in the slow start code below.
4527 /* Did peer restart with older RX version? */
4528 if (peer->maxDgramPackets > 1) {
4529 peer->maxDgramPackets = 1;
4531 } else if (np->length >=
4532 rx_AckDataSize(ap->nAcks) + 4 * sizeof(afs_int32)) {
4535 rx_AckDataSize(ap->nAcks) + 2 * (int)sizeof(afs_int32),
4536 sizeof(afs_int32), &tSize);
4537 tSize = (afs_uint32) ntohl(tSize);
4540 if (tSize >= rx_maxSendWindow)
4541 tSize = rx_maxSendWindow;
4543 * As of AFS 3.5 we set the send window to match the receive window.
4545 if (tSize < call->twind) {
4546 call->twind = tSize;
4547 call->conn->twind[call->channel] = call->twind;
4548 call->ssthresh = MIN(call->twind, call->ssthresh);
4549 } else if (tSize > call->twind) {
4550 call->twind = tSize;
4551 call->conn->twind[call->channel] = call->twind;
4555 * As of AFS 3.5, a jumbogram is more than one fixed size
4556 * packet transmitted in a single UDP datagram. If the remote
4557 * MTU is smaller than our local MTU then never send a datagram
4558 * larger than the natural MTU.
4561 rx_AckDataSize(ap->nAcks) + 3 * (int)sizeof(afs_int32),
4562 (int)sizeof(afs_int32), &tSize);
4563 maxDgramPackets = (afs_uint32) ntohl(tSize);
4564 maxDgramPackets = MIN(maxDgramPackets, rxi_nDgramPackets);
4566 MIN(maxDgramPackets, (int)(peer->ifDgramPackets));
4567 if (maxDgramPackets > 1) {
4568 peer->maxDgramPackets = maxDgramPackets;
4569 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
4571 peer->maxDgramPackets = 1;
4572 call->MTU = peer->natMTU;
4574 } else if (peer->maxDgramPackets > 1) {
4575 /* Restarted with lower version of RX */
4576 peer->maxDgramPackets = 1;
4578 } else if (peer->maxDgramPackets > 1
4579 || peer->maxMTU != OLD_MAX_PACKET_SIZE) {
4580 /* Restarted with lower version of RX */
4581 peer->maxMTU = OLD_MAX_PACKET_SIZE;
4582 peer->natMTU = OLD_MAX_PACKET_SIZE;
4583 peer->MTU = OLD_MAX_PACKET_SIZE;
4584 peer->maxDgramPackets = 1;
4585 peer->nDgramPackets = 1;
4587 call->MTU = OLD_MAX_PACKET_SIZE;
4590 /* If the window has been extended by this acknowledge packet,
4591 * then wakeup a sender waiting in alloc for window space, or try
4592 * sending packets now, if he's been sitting on packets due to
4593 * lack of window space */
4594 if (call->tnext < (call->tfirst + call->twind)) {
4595 #ifdef RX_ENABLE_LOCKS
4596 CV_SIGNAL(&call->cv_twind);
4598 if (call->flags & RX_CALL_WAIT_WINDOW_ALLOC) {
4599 call->flags &= ~RX_CALL_WAIT_WINDOW_ALLOC;
4600 osi_rxWakeup(&call->twind);
4603 if (call->flags & RX_CALL_WAIT_WINDOW_SEND) {
4604 call->flags &= ~RX_CALL_WAIT_WINDOW_SEND;
4610 * Calculate how many datagrams were successfully received after
4611 * the first missing packet and adjust the negative ack counter
4616 nNacked = (nNacked + call->nDgramPackets - 1) / call->nDgramPackets;
4617 if (call->nNacks < nNacked) {
4618 call->nNacks = nNacked;
4621 call->nAcks += newAckCount;
4625 /* If the packet contained new acknowledgements, rather than just
4626 * being a duplicate of one we have previously seen, then we can restart
4629 if (newAckCount > 0)
4630 rxi_rto_packet_acked(call, istack);
4632 if (call->flags & RX_CALL_FAST_RECOVER) {
4633 if (newAckCount == 0) {
4634 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4636 call->flags &= ~RX_CALL_FAST_RECOVER;
4637 call->cwind = call->nextCwind;
4638 call->nextCwind = 0;
4641 call->nCwindAcks = 0;
4642 } else if (nNacked && call->nNacks >= (u_short) rx_nackThreshold) {
4643 /* Three negative acks in a row trigger congestion recovery */
4644 call->flags |= RX_CALL_FAST_RECOVER;
4645 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
4647 MIN((int)(call->ssthresh + rx_nackThreshold), rx_maxSendWindow);
4648 call->nDgramPackets = MAX(2, (int)call->nDgramPackets) >> 1;
4649 call->nextCwind = call->ssthresh;
4652 peer->MTU = call->MTU;
4653 peer->cwind = call->nextCwind;
4654 peer->nDgramPackets = call->nDgramPackets;
4656 call->congestSeq = peer->congestSeq;
4658 /* Reset the resend times on the packets that were nacked
4659 * so we will retransmit as soon as the window permits
4663 for (opr_queue_ScanBackwards(&call->tq, cursor)) {
4664 struct rx_packet *tp =
4665 opr_queue_Entry(cursor, struct rx_packet, entry);
4667 if (!(tp->flags & RX_PKTFLAG_ACKED)) {
4668 tp->flags &= ~RX_PKTFLAG_SENT;
4670 } else if (tp->flags & RX_PKTFLAG_ACKED) {
4675 /* If cwind is smaller than ssthresh, then increase
4676 * the window one packet for each ack we receive (exponential
4678 * If cwind is greater than or equal to ssthresh then increase
4679 * the congestion window by one packet for each cwind acks we
4680 * receive (linear growth). */
4681 if (call->cwind < call->ssthresh) {
4683 MIN((int)call->ssthresh, (int)(call->cwind + newAckCount));
4684 call->nCwindAcks = 0;
4686 call->nCwindAcks += newAckCount;
4687 if (call->nCwindAcks >= call->cwind) {
4688 call->nCwindAcks = 0;
4689 call->cwind = MIN((int)(call->cwind + 1), rx_maxSendWindow);
4693 * If we have received several acknowledgements in a row then
4694 * it is time to increase the size of our datagrams
4696 if ((int)call->nAcks > rx_nDgramThreshold) {
4697 if (peer->maxDgramPackets > 1) {
4698 if (call->nDgramPackets < peer->maxDgramPackets) {
4699 call->nDgramPackets++;
4701 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
4702 } else if (call->MTU < peer->maxMTU) {
4703 /* don't upgrade if we can't handle it */
4704 if ((call->nDgramPackets == 1) && (call->MTU >= peer->ifMTU))
4705 call->MTU = peer->ifMTU;
4707 call->MTU += peer->natMTU;
4708 call->MTU = MIN(call->MTU, peer->maxMTU);
4715 MUTEX_EXIT(&peer->peer_lock); /* rxi_Start will lock peer. */
4717 /* Servers need to hold the call until all response packets have
4718 * been acknowledged. Soft acks are good enough since clients
4719 * are not allowed to clear their receive queues. */
4720 if (call->state == RX_STATE_HOLD
4721 && call->tfirst + call->nSoftAcked >= call->tnext) {
4722 call->state = RX_STATE_DALLY;
4723 rxi_ClearTransmitQueue(call, 0);
4724 rxi_CancelKeepAliveEvent(call);
4725 } else if (!opr_queue_IsEmpty(&call->tq)) {
4726 rxi_Start(call, istack);
4732 * Schedule a connection abort to be sent after some delay.
4734 * @param[in] conn The connection to send the abort on.
4735 * @param[in] msec The number of milliseconds to wait before sending.
4737 * @pre conn_data_lock must be held
4740 rxi_SendConnectionAbortLater(struct rx_connection *conn, int msec)
4742 struct clock when, now;
4744 MUTEX_ASSERT(&conn->conn_data_lock);
4748 if (!conn->delayedAbortEvent) {
4749 clock_GetTime(&now);
4751 clock_Addmsec(&when, msec);
4752 rx_GetConnection(conn);
4753 conn->delayedAbortEvent =
4754 rxevent_Post(&when, &now, rxi_SendDelayedConnAbort, conn, NULL, 0);
4758 /* Received a response to a challenge packet */
4759 static struct rx_packet *
4760 rxi_ReceiveResponsePacket(struct rx_connection *conn,
4761 struct rx_packet *np, int istack)
4765 /* Ignore the packet if we're the client */
4766 if (conn->type == RX_CLIENT_CONNECTION)
4769 /* If already authenticated, ignore the packet (it's probably a retry) */
4770 if (RXS_CheckAuthentication(conn->securityObject, conn) == 0)
4773 if (!conn->securityChallengeSent) {
4774 /* We've never sent out a challenge for this connection, so this
4775 * response cannot possibly be correct; ignore it. This can happen
4776 * if we sent a challenge to the client, then we were restarted, and
4777 * then the client sent us a response. If we ignore the response, the
4778 * client will eventually resend a data packet, causing us to send a
4779 * new challenge and the client to send a new response. */
4783 /* Otherwise, have the security object evaluate the response packet */
4784 error = RXS_CheckResponse(conn->securityObject, conn, np);
4786 /* If the response is invalid, reset the connection, sending
4787 * an abort to the peer. Send the abort with a 1 second delay,
4788 * to avoid a peer hammering us by constantly recreating a
4789 * connection with bad credentials. */
4790 rxi_ConnectionError(conn, error);
4791 MUTEX_ENTER(&conn->conn_data_lock);
4792 rxi_SendConnectionAbortLater(conn, 1000);
4793 MUTEX_EXIT(&conn->conn_data_lock);
4796 /* If the response is valid, any calls waiting to attach
4797 * servers can now do so */
4800 for (i = 0; i < RX_MAXCALLS; i++) {
4801 struct rx_call *call = conn->call[i];
4803 MUTEX_ENTER(&call->lock);
4804 if (call->state == RX_STATE_PRECALL)
4805 rxi_AttachServerProc(call, (osi_socket) - 1, NULL, NULL);
4806 /* tnop can be null if newcallp is null */
4807 MUTEX_EXIT(&call->lock);
4811 /* Update the peer reachability information, just in case
4812 * some calls went into attach-wait while we were waiting
4813 * for authentication..
4815 rxi_UpdatePeerReach(conn, NULL);
4820 /* A client has received an authentication challenge: the security
4821 * object is asked to cough up a respectable response packet to send
4822 * back to the server. The server is responsible for retrying the
4823 * challenge if it fails to get a response. */
4825 static struct rx_packet *
4826 rxi_ReceiveChallengePacket(struct rx_connection *conn,
4827 struct rx_packet *np, int istack)
4831 /* Ignore the challenge if we're the server */
4832 if (conn->type == RX_SERVER_CONNECTION)
4835 /* Ignore the challenge if the connection is otherwise idle; someone's
4836 * trying to use us as an oracle. */
4837 if (!rxi_HasActiveCalls(conn))
4840 /* Send the security object the challenge packet. It is expected to fill
4841 * in the response. */
4842 error = RXS_GetResponse(conn->securityObject, conn, np);
4844 /* If the security object is unable to return a valid response, reset the
4845 * connection and send an abort to the peer. Otherwise send the response
4846 * packet to the peer connection. */
4848 rxi_ConnectionError(conn, error);
4849 MUTEX_ENTER(&conn->conn_data_lock);
4850 np = rxi_SendConnectionAbort(conn, np, istack, 0);
4851 MUTEX_EXIT(&conn->conn_data_lock);
4853 np = rxi_SendSpecial((struct rx_call *)0, conn, np,
4854 RX_PACKET_TYPE_RESPONSE, NULL, -1, istack);
4860 /* Find an available server process to service the current request in
4861 * the given call structure. If one isn't available, queue up this
4862 * call so it eventually gets one */
4864 rxi_AttachServerProc(struct rx_call *call,
4865 osi_socket socket, int *tnop,
4866 struct rx_call **newcallp)
4868 struct rx_serverQueueEntry *sq;
4869 struct rx_service *service = call->conn->service;
4872 /* May already be attached */
4873 if (call->state == RX_STATE_ACTIVE)
4876 MUTEX_ENTER(&rx_serverPool_lock);
4878 haveQuota = QuotaOK(service);
4879 if ((!haveQuota) || opr_queue_IsEmpty(&rx_idleServerQueue)) {
4880 /* If there are no processes available to service this call,
4881 * put the call on the incoming call queue (unless it's
4882 * already on the queue).
4884 #ifdef RX_ENABLE_LOCKS
4886 ReturnToServerPool(service);
4887 #endif /* RX_ENABLE_LOCKS */
4889 if (!(call->flags & RX_CALL_WAIT_PROC)) {
4890 call->flags |= RX_CALL_WAIT_PROC;
4891 rx_atomic_inc(&rx_nWaiting);
4892 rx_atomic_inc(&rx_nWaited);
4893 rxi_calltrace(RX_CALL_ARRIVAL, call);
4894 SET_CALL_QUEUE_LOCK(call, &rx_serverPool_lock);
4895 opr_queue_Append(&rx_incomingCallQueue, &call->entry);
4898 sq = opr_queue_Last(&rx_idleServerQueue,
4899 struct rx_serverQueueEntry, entry);
4901 /* If hot threads are enabled, and both newcallp and sq->socketp
4902 * are non-null, then this thread will process the call, and the
4903 * idle server thread will start listening on this threads socket.
4905 opr_queue_Remove(&sq->entry);
4907 if (rx_enable_hot_thread && newcallp && sq->socketp) {
4910 *sq->socketp = socket;
4911 clock_GetTime(&call->startTime);
4912 CALL_HOLD(call, RX_CALL_REFCOUNT_BEGIN);
4916 if (call->flags & RX_CALL_WAIT_PROC) {
4917 /* Conservative: I don't think this should happen */
4918 call->flags &= ~RX_CALL_WAIT_PROC;
4919 rx_atomic_dec(&rx_nWaiting);
4920 if (opr_queue_IsOnQueue(&call->entry)) {
4921 opr_queue_Remove(&call->entry);
4924 call->state = RX_STATE_ACTIVE;
4925 call->app.mode = RX_MODE_RECEIVING;
4926 #ifdef RX_KERNEL_TRACE
4928 int glockOwner = ISAFS_GLOCK();
4931 afs_Trace3(afs_iclSetp, CM_TRACE_WASHERE, ICL_TYPE_STRING,
4932 __FILE__, ICL_TYPE_INT32, __LINE__, ICL_TYPE_POINTER,
4938 if (call->flags & RX_CALL_CLEARED) {
4939 /* send an ack now to start the packet flow up again */
4940 call->flags &= ~RX_CALL_CLEARED;
4941 rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4943 #ifdef RX_ENABLE_LOCKS
4946 service->nRequestsRunning++;
4947 MUTEX_ENTER(&rx_quota_mutex);
4948 if (service->nRequestsRunning <= service->minProcs)
4951 MUTEX_EXIT(&rx_quota_mutex);
4955 MUTEX_EXIT(&rx_serverPool_lock);
4958 /* Delay the sending of an acknowledge event for a short while, while
4959 * a new call is being prepared (in the case of a client) or a reply
4960 * is being prepared (in the case of a server). Rather than sending
4961 * an ack packet, an ACKALL packet is sent. */
4963 rxi_AckAll(struct rx_call *call)
4965 rxi_SendSpecial(call, call->conn, NULL, RX_PACKET_TYPE_ACKALL,
4967 call->flags |= RX_CALL_ACKALL_SENT;
4971 * Event handler for per-call delayed acks.
4972 * Also called synchronously, with |event| == NULL, to send a "delayed" ack
4976 rxi_SendDelayedAck(struct rxevent *event, void *arg1, void *unused1,
4979 struct rx_call *call = arg1;
4980 #ifdef RX_ENABLE_LOCKS
4982 MUTEX_ENTER(&call->lock);
4983 if (event == call->delayedAckEvent)
4984 rxevent_Put(&call->delayedAckEvent);
4986 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4988 MUTEX_EXIT(&call->lock);
4989 #else /* RX_ENABLE_LOCKS */
4991 rxevent_Put(&call->delayedAckEvent);
4992 (void)rxi_SendAck(call, 0, 0, RX_ACK_DELAY, 0);
4993 #endif /* RX_ENABLE_LOCKS */
4994 /* Release the call reference for the event that fired. */
4996 CALL_RELE(call, RX_CALL_REFCOUNT_DELAY);
4999 #ifdef RX_ENABLE_LOCKS
5000 /* Set ack in all packets in transmit queue. rxi_Start will deal with
5001 * clearing them out.
5004 rxi_SetAcksInTransmitQueue(struct rx_call *call)
5006 struct opr_queue *cursor;
5009 for (opr_queue_Scan(&call->tq, cursor)) {
5011 = opr_queue_Entry(cursor, struct rx_packet, entry);
5013 p->flags |= RX_PKTFLAG_ACKED;
5018 call->flags |= RX_CALL_TQ_CLEARME;
5019 call->flags |= RX_CALL_TQ_SOME_ACKED;
5022 rxi_rto_cancel(call);
5024 call->tfirst = call->tnext;
5025 call->nSoftAcked = 0;
5027 if (call->flags & RX_CALL_FAST_RECOVER) {
5028 call->flags &= ~RX_CALL_FAST_RECOVER;
5029 call->cwind = call->nextCwind;
5030 call->nextCwind = 0;
5033 CV_SIGNAL(&call->cv_twind);
5035 #endif /* RX_ENABLE_LOCKS */
5038 * Acknowledge the whole transmit queue.
5040 * If we're running without locks, or the transmit queue isn't busy, then
5041 * we can just clear the queue now. Otherwise, we have to mark all of the
5042 * packets as acknowledged, and let rxi_Start clear it later on
5045 rxi_AckAllInTransmitQueue(struct rx_call *call)
5047 #ifdef RX_ENABLE_LOCKS
5048 if (call->flags & RX_CALL_TQ_BUSY) {
5049 rxi_SetAcksInTransmitQueue(call);
5053 rxi_ClearTransmitQueue(call, 0);
5055 /* Clear out the transmit queue for the current call (all packets have
5056 * been received by peer) */
5058 rxi_ClearTransmitQueue(struct rx_call *call, int force)
5060 #ifdef RX_ENABLE_LOCKS
5061 struct opr_queue *cursor;
5062 if (!force && (call->flags & RX_CALL_TQ_BUSY)) {
5064 for (opr_queue_Scan(&call->tq, cursor)) {
5066 = opr_queue_Entry(cursor, struct rx_packet, entry);
5068 p->flags |= RX_PKTFLAG_ACKED;
5072 call->flags |= RX_CALL_TQ_CLEARME;
5073 call->flags |= RX_CALL_TQ_SOME_ACKED;
5076 #endif /* RX_ENABLE_LOCKS */
5077 #ifdef RXDEBUG_PACKET
5079 #endif /* RXDEBUG_PACKET */
5080 rxi_FreePackets(0, &call->tq);
5081 rxi_WakeUpTransmitQueue(call);
5082 #ifdef RX_ENABLE_LOCKS
5083 call->flags &= ~RX_CALL_TQ_CLEARME;
5087 rxi_rto_cancel(call);
5088 call->tfirst = call->tnext; /* implicitly acknowledge all data already sent */
5089 call->nSoftAcked = 0;
5091 if (call->flags & RX_CALL_FAST_RECOVER) {
5092 call->flags &= ~RX_CALL_FAST_RECOVER;
5093 call->cwind = call->nextCwind;
5095 #ifdef RX_ENABLE_LOCKS
5096 CV_SIGNAL(&call->cv_twind);
5098 osi_rxWakeup(&call->twind);
5103 rxi_ClearReceiveQueue(struct rx_call *call)
5105 if (!opr_queue_IsEmpty(&call->rq)) {
5108 count = rxi_FreePackets(0, &call->rq);
5109 rx_packetReclaims += count;
5110 #ifdef RXDEBUG_PACKET
5112 if ( call->rqc != 0 )
5113 dpf(("rxi_ClearReceiveQueue call %"AFS_PTR_FMT" rqc %u != 0\n", call, call->rqc));
5115 call->flags &= ~(RX_CALL_RECEIVE_DONE | RX_CALL_HAVE_LAST);
5117 if (call->state == RX_STATE_PRECALL) {
5118 call->flags |= RX_CALL_CLEARED;
5122 /* Send an abort packet for the specified call */
5123 static struct rx_packet *
5124 rxi_SendCallAbort(struct rx_call *call, struct rx_packet *packet,
5125 int istack, int force)
5128 struct clock when, now;
5133 /* Clients should never delay abort messages */
5134 if (rx_IsClientConn(call->conn))
5138 * An opcode that has been deprecated or has yet to be implemented is not
5139 * a misbehavior of the client. Do not punish the client by introducing
5142 if (call->error == RXGEN_OPCODE) {
5144 } else if (call->abortCode != call->error) {
5145 call->abortCode = call->error;
5146 call->abortCount = 0;
5149 if (force || rxi_callAbortThreshhold == 0
5150 || call->abortCount < rxi_callAbortThreshhold) {
5151 rxi_CancelDelayedAbortEvent(call);
5152 error = htonl(call->error);
5156 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
5157 (char *)&error, sizeof(error), istack);
5158 } else if (!call->delayedAbortEvent) {
5159 clock_GetTime(&now);
5161 clock_Addmsec(&when, rxi_callAbortDelay);
5162 CALL_HOLD(call, RX_CALL_REFCOUNT_ABORT);
5163 call->delayedAbortEvent =
5164 rxevent_Post(&when, &now, rxi_SendDelayedCallAbort, call, 0, 0);
5170 rxi_CancelDelayedAbortEvent(struct rx_call *call)
5172 MUTEX_ASSERT(&call->lock);
5173 if (rxevent_Cancel(&call->delayedAbortEvent))
5174 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
5177 /* Send an abort packet for the specified connection. Packet is an
5178 * optional pointer to a packet that can be used to send the abort.
5179 * Once the number of abort messages reaches the threshhold, an
5180 * event is scheduled to send the abort. Setting the force flag
5181 * overrides sending delayed abort messages.
5183 * NOTE: Called with conn_data_lock held. conn_data_lock is dropped
5184 * to send the abort packet.
5187 rxi_SendConnectionAbort(struct rx_connection *conn,
5188 struct rx_packet *packet, int istack, int force)
5195 /* Clients should never delay abort messages */
5196 if (rx_IsClientConn(conn))
5199 if (force || rxi_connAbortThreshhold == 0
5200 || conn->abortCount < rxi_connAbortThreshhold) {
5202 if (rxevent_Cancel(&conn->delayedAbortEvent))
5203 putConnection(conn);
5204 error = htonl(conn->error);
5206 MUTEX_EXIT(&conn->conn_data_lock);
5208 rxi_SendSpecial((struct rx_call *)0, conn, packet,
5209 RX_PACKET_TYPE_ABORT, (char *)&error,
5210 sizeof(error), istack);
5211 MUTEX_ENTER(&conn->conn_data_lock);
5213 rxi_SendConnectionAbortLater(conn, rxi_connAbortDelay);
5218 /* Associate an error all of the calls owned by a connection. Called
5219 * with error non-zero. This is only for really fatal things, like
5220 * bad authentication responses. The connection itself is set in
5221 * error at this point, so that future packets received will be
5224 rxi_ConnectionError(struct rx_connection *conn,
5230 dpf(("rxi_ConnectionError conn %"AFS_PTR_FMT" error %d\n", conn, error));
5232 MUTEX_ENTER(&conn->conn_data_lock);
5233 if (rxevent_Cancel(&conn->challengeEvent))
5234 putConnection(conn);
5235 if (rxevent_Cancel(&conn->natKeepAliveEvent))
5236 putConnection(conn);
5237 if (rxevent_Cancel(&conn->checkReachEvent)) {
5238 conn->flags &= ~(RX_CONN_ATTACHWAIT|RX_CONN_NAT_PING);
5239 putConnection(conn);
5241 MUTEX_EXIT(&conn->conn_data_lock);
5242 for (i = 0; i < RX_MAXCALLS; i++) {
5243 struct rx_call *call = conn->call[i];
5245 MUTEX_ENTER(&call->lock);
5246 rxi_CallError(call, error);
5247 MUTEX_EXIT(&call->lock);
5250 conn->error = error;
5251 if (rx_stats_active)
5252 rx_atomic_inc(&rx_stats.fatalErrors);
5257 * Interrupt an in-progress call with the specified error and wakeup waiters.
5259 * @param[in] call The call to interrupt
5260 * @param[in] error The error code to send to the peer
5263 rx_InterruptCall(struct rx_call *call, afs_int32 error)
5265 MUTEX_ENTER(&call->lock);
5266 rxi_CallError(call, error);
5267 rxi_SendCallAbort(call, NULL, 0, 1);
5268 MUTEX_EXIT(&call->lock);
5272 rxi_CallError(struct rx_call *call, afs_int32 error)
5274 MUTEX_ASSERT(&call->lock);
5275 dpf(("rxi_CallError call %"AFS_PTR_FMT" error %d call->error %d\n", call, error, call->error));
5277 error = call->error;
5279 #ifdef RX_ENABLE_LOCKS
5280 if (!((call->flags & RX_CALL_TQ_BUSY) || (call->tqWaiters > 0))) {
5281 rxi_ResetCall(call, 0);
5284 rxi_ResetCall(call, 0);
5286 call->error = error;
5289 /* Reset various fields in a call structure, and wakeup waiting
5290 * processes. Some fields aren't changed: state & mode are not
5291 * touched (these must be set by the caller), and bufptr, nLeft, and
5292 * nFree are not reset, since these fields are manipulated by
5293 * unprotected macros, and may only be reset by non-interrupting code.
5297 rxi_ResetCall(struct rx_call *call, int newcall)
5300 struct rx_peer *peer;
5301 struct rx_packet *packet;
5303 MUTEX_ASSERT(&call->lock);
5304 dpf(("rxi_ResetCall(call %"AFS_PTR_FMT", newcall %d)\n", call, newcall));
5306 /* Notify anyone who is waiting for asynchronous packet arrival */
5307 if (call->arrivalProc) {
5308 (*call->arrivalProc) (call, call->arrivalProcHandle,
5309 call->arrivalProcArg);
5310 call->arrivalProc = NULL;
5314 rxi_CancelGrowMTUEvent(call);
5316 if (call->delayedAbortEvent) {
5317 rxi_CancelDelayedAbortEvent(call);
5318 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
5320 rxi_SendCallAbort(call, packet, 0, 1);
5321 rxi_FreePacket(packet);
5326 * Update the peer with the congestion information in this call
5327 * so other calls on this connection can pick up where this call
5328 * left off. If the congestion sequence numbers don't match then
5329 * another call experienced a retransmission.
5331 peer = call->conn->peer;
5332 MUTEX_ENTER(&peer->peer_lock);
5334 if (call->congestSeq == peer->congestSeq) {
5335 peer->cwind = MAX(peer->cwind, call->cwind);
5336 peer->MTU = MAX(peer->MTU, call->MTU);
5337 peer->nDgramPackets =
5338 MAX(peer->nDgramPackets, call->nDgramPackets);
5341 call->abortCode = 0;
5342 call->abortCount = 0;
5344 if (peer->maxDgramPackets > 1) {
5345 call->MTU = RX_HEADER_SIZE + RX_JUMBOBUFFERSIZE;
5347 call->MTU = peer->MTU;
5349 call->cwind = MIN((int)peer->cwind, (int)peer->nDgramPackets);
5350 call->ssthresh = rx_maxSendWindow;
5351 call->nDgramPackets = peer->nDgramPackets;
5352 call->congestSeq = peer->congestSeq;
5353 call->rtt = peer->rtt;
5354 call->rtt_dev = peer->rtt_dev;
5355 clock_Zero(&call->rto);
5356 clock_Addmsec(&call->rto,
5357 MAX(((call->rtt >> 3) + call->rtt_dev), rx_minPeerTimeout) + 200);
5358 MUTEX_EXIT(&peer->peer_lock);
5360 flags = call->flags;
5361 rxi_WaitforTQBusy(call);
5363 rxi_ClearTransmitQueue(call, 1);
5364 if (call->tqWaiters || (flags & RX_CALL_TQ_WAIT)) {
5365 dpf(("rcall %"AFS_PTR_FMT" has %d waiters and flags %d\n", call, call->tqWaiters, call->flags));
5369 rxi_ClearReceiveQueue(call);
5370 /* why init the queue if you just emptied it? queue_Init(&call->rq); */
5374 call->twind = call->conn->twind[call->channel];
5375 call->rwind = call->conn->rwind[call->channel];
5376 call->nSoftAcked = 0;
5377 call->nextCwind = 0;
5380 call->nCwindAcks = 0;
5381 call->nSoftAcks = 0;
5382 call->nHardAcks = 0;
5384 call->tfirst = call->rnext = call->tnext = 1;
5387 call->lastAcked = 0;
5388 call->localStatus = call->remoteStatus = 0;
5390 if (flags & RX_CALL_READER_WAIT) {
5391 #ifdef RX_ENABLE_LOCKS
5392 CV_BROADCAST(&call->cv_rq);
5394 osi_rxWakeup(&call->rq);
5397 if (flags & RX_CALL_WAIT_PACKETS) {
5398 MUTEX_ENTER(&rx_freePktQ_lock);
5399 rxi_PacketsUnWait(); /* XXX */
5400 MUTEX_EXIT(&rx_freePktQ_lock);
5402 #ifdef RX_ENABLE_LOCKS
5403 CV_SIGNAL(&call->cv_twind);
5405 if (flags & RX_CALL_WAIT_WINDOW_ALLOC)
5406 osi_rxWakeup(&call->twind);
5409 if (flags & RX_CALL_WAIT_PROC) {
5410 rx_atomic_dec(&rx_nWaiting);
5412 #ifdef RX_ENABLE_LOCKS
5413 /* The following ensures that we don't mess with any queue while some
5414 * other thread might also be doing so. The call_queue_lock field is
5415 * is only modified under the call lock. If the call is in the process
5416 * of being removed from a queue, the call is not locked until the
5417 * the queue lock is dropped and only then is the call_queue_lock field
5418 * zero'd out. So it's safe to lock the queue if call_queue_lock is set.
5419 * Note that any other routine which removes a call from a queue has to
5420 * obtain the queue lock before examing the queue and removing the call.
5422 if (call->call_queue_lock) {
5423 MUTEX_ENTER(call->call_queue_lock);
5424 if (opr_queue_IsOnQueue(&call->entry)) {
5425 opr_queue_Remove(&call->entry);
5427 MUTEX_EXIT(call->call_queue_lock);
5428 CLEAR_CALL_QUEUE_LOCK(call);
5430 #else /* RX_ENABLE_LOCKS */
5431 if (opr_queue_IsOnQueue(&call->entry)) {
5432 opr_queue_Remove(&call->entry);
5434 #endif /* RX_ENABLE_LOCKS */
5436 rxi_CancelKeepAliveEvent(call);
5437 rxi_CancelDelayedAckEvent(call);
5440 /* Send an acknowledge for the indicated packet (seq,serial) of the
5441 * indicated call, for the indicated reason (reason). This
5442 * acknowledge will specifically acknowledge receiving the packet, and
5443 * will also specify which other packets for this call have been
5444 * received. This routine returns the packet that was used to the
5445 * caller. The caller is responsible for freeing it or re-using it.
5446 * This acknowledgement also returns the highest sequence number
5447 * actually read out by the higher level to the sender; the sender
5448 * promises to keep around packets that have not been read by the
5449 * higher level yet (unless, of course, the sender decides to abort
5450 * the call altogether). Any of p, seq, serial, pflags, or reason may
5451 * be set to zero without ill effect. That is, if they are zero, they
5452 * will not convey any information.
5453 * NOW there is a trailer field, after the ack where it will safely be
5454 * ignored by mundanes, which indicates the maximum size packet this
5455 * host can swallow. */
5457 struct rx_packet *optionalPacket; use to send ack (or null)
5458 int seq; Sequence number of the packet we are acking
5459 int serial; Serial number of the packet
5460 int pflags; Flags field from packet header
5461 int reason; Reason an acknowledge was prompted
5464 #define RX_ZEROS 1024
5465 static char rx_zeros[RX_ZEROS];
5468 rxi_SendAck(struct rx_call *call,
5469 struct rx_packet *optionalPacket, int serial, int reason,
5472 struct rx_ackPacket *ap;
5473 struct rx_packet *p;
5474 struct opr_queue *cursor;
5477 afs_uint32 padbytes = 0;
5478 #ifdef RX_ENABLE_TSFPQ
5479 struct rx_ts_info_t * rx_ts_info;
5483 * Open the receive window once a thread starts reading packets
5485 if (call->rnext > 1) {
5486 call->conn->rwind[call->channel] = call->rwind = rx_maxReceiveWindow;
5489 /* Don't attempt to grow MTU if this is a critical ping */
5490 if (reason == RX_ACK_MTU) {
5491 /* keep track of per-call attempts, if we're over max, do in small
5492 * otherwise in larger? set a size to increment by, decrease
5495 if (call->conn->peer->maxPacketSize &&
5496 (call->conn->peer->maxPacketSize < OLD_MAX_PACKET_SIZE
5498 padbytes = call->conn->peer->maxPacketSize+16;
5500 padbytes = call->conn->peer->maxMTU + 128;
5502 /* do always try a minimum size ping */
5503 padbytes = MAX(padbytes, RX_MIN_PACKET_SIZE+RX_IPUDP_SIZE+4);
5505 /* subtract the ack payload */
5506 padbytes -= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32));
5507 reason = RX_ACK_PING;
5510 call->nHardAcks = 0;
5511 call->nSoftAcks = 0;
5512 if (call->rnext > call->lastAcked)
5513 call->lastAcked = call->rnext;
5517 rx_computelen(p, p->length); /* reset length, you never know */
5518 } /* where that's been... */
5519 #ifdef RX_ENABLE_TSFPQ
5521 RX_TS_INFO_GET(rx_ts_info);
5522 if ((p = rx_ts_info->local_special_packet)) {
5523 rx_computelen(p, p->length);
5524 } else if ((p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5525 rx_ts_info->local_special_packet = p;
5526 } else { /* We won't send the ack, but don't panic. */
5527 return optionalPacket;
5531 else if (!(p = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL))) {
5532 /* We won't send the ack, but don't panic. */
5533 return optionalPacket;
5538 rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32) -
5541 if (rxi_AllocDataBuf(p, templ, RX_PACKET_CLASS_SPECIAL) > 0) {
5542 #ifndef RX_ENABLE_TSFPQ
5543 if (!optionalPacket)
5546 return optionalPacket;
5548 templ = rx_AckDataSize(call->rwind) + 2 * sizeof(afs_int32);
5549 if (rx_Contiguous(p) < templ) {
5550 #ifndef RX_ENABLE_TSFPQ
5551 if (!optionalPacket)
5554 return optionalPacket;
5559 /* MTUXXX failing to send an ack is very serious. We should */
5560 /* try as hard as possible to send even a partial ack; it's */
5561 /* better than nothing. */
5562 ap = (struct rx_ackPacket *)rx_DataOf(p);
5563 ap->bufferSpace = htonl(0); /* Something should go here, sometime */
5564 ap->reason = reason;
5566 /* The skew computation used to be bogus, I think it's better now. */
5567 /* We should start paying attention to skew. XXX */
5568 ap->serial = htonl(serial);
5569 ap->maxSkew = 0; /* used to be peer->inPacketSkew */
5572 * First packet not yet forwarded to reader. When ACKALL has been
5573 * sent the peer has been told that all received packets will be
5574 * delivered to the reader. The value 'rnext' is used internally
5575 * to refer to the next packet in the receive queue that must be
5576 * delivered to the reader. From the perspective of the peer it
5577 * already has so report the last sequence number plus one if there
5578 * are packets in the receive queue awaiting processing.
5580 if ((call->flags & RX_CALL_ACKALL_SENT) &&
5581 !opr_queue_IsEmpty(&call->rq)) {
5582 ap->firstPacket = htonl(opr_queue_Last(&call->rq, struct rx_packet, entry)->header.seq + 1);
5584 ap->firstPacket = htonl(call->rnext);
5586 ap->previousPacket = htonl(call->rprev); /* Previous packet received */
5588 /* No fear of running out of ack packet here because there can only
5589 * be at most one window full of unacknowledged packets. The window
5590 * size must be constrained to be less than the maximum ack size,
5591 * of course. Also, an ack should always fit into a single packet
5592 * -- it should not ever be fragmented. */
5594 for (opr_queue_Scan(&call->rq, cursor)) {
5595 struct rx_packet *rqp
5596 = opr_queue_Entry(cursor, struct rx_packet, entry);
5598 if (!rqp || !call->rq.next
5599 || (rqp->header.seq > (call->rnext + call->rwind))) {
5600 #ifndef RX_ENABLE_TSFPQ
5601 if (!optionalPacket)
5604 rxi_CallError(call, RX_CALL_DEAD);
5605 return optionalPacket;
5608 while (rqp->header.seq > call->rnext + offset)
5609 ap->acks[offset++] = RX_ACK_TYPE_NACK;
5610 ap->acks[offset++] = RX_ACK_TYPE_ACK;
5612 if ((offset > (u_char) rx_maxReceiveWindow) || (offset > call->rwind)) {
5613 #ifndef RX_ENABLE_TSFPQ
5614 if (!optionalPacket)
5617 rxi_CallError(call, RX_CALL_DEAD);
5618 return optionalPacket;
5624 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5626 /* Must zero the 3 octets that rx_AckDataSize skips at the end of the
5629 rx_packetwrite(p, rx_AckDataSize(offset) - 3, 3, rx_zeros);
5631 /* these are new for AFS 3.3 */
5632 templ = rxi_AdjustMaxMTU(call->conn->peer->ifMTU, rx_maxReceiveSize);
5633 templ = htonl(templ);
5634 rx_packetwrite(p, rx_AckDataSize(offset), sizeof(afs_int32), &templ);
5635 templ = htonl(call->conn->peer->ifMTU);
5636 rx_packetwrite(p, rx_AckDataSize(offset) + sizeof(afs_int32),
5637 sizeof(afs_int32), &templ);
5639 /* new for AFS 3.4 */
5640 templ = htonl(call->rwind);
5641 rx_packetwrite(p, rx_AckDataSize(offset) + 2 * sizeof(afs_int32),
5642 sizeof(afs_int32), &templ);
5644 /* new for AFS 3.5 */
5645 templ = htonl(call->conn->peer->ifDgramPackets);
5646 rx_packetwrite(p, rx_AckDataSize(offset) + 3 * sizeof(afs_int32),
5647 sizeof(afs_int32), &templ);
5649 p->length = rx_AckDataSize(offset) + 4 * sizeof(afs_int32);
5651 p->header.serviceId = call->conn->serviceId;
5652 p->header.cid = (call->conn->cid | call->channel);
5653 p->header.callNumber = *call->callNumber;
5655 p->header.securityIndex = call->conn->securityIndex;
5656 p->header.epoch = call->conn->epoch;
5657 p->header.type = RX_PACKET_TYPE_ACK;
5658 p->header.flags = RX_SLOW_START_OK;
5659 if (reason == RX_ACK_PING)
5660 p->header.flags |= RX_REQUEST_ACK;
5662 while (padbytes > 0) {
5663 if (padbytes > RX_ZEROS) {
5664 rx_packetwrite(p, p->length, RX_ZEROS, rx_zeros);
5665 p->length += RX_ZEROS;
5666 padbytes -= RX_ZEROS;
5668 rx_packetwrite(p, p->length, padbytes, rx_zeros);
5669 p->length += padbytes;
5674 if (call->conn->type == RX_CLIENT_CONNECTION)
5675 p->header.flags |= RX_CLIENT_INITIATED;
5679 if (rxdebug_active) {
5683 len = _snprintf(msg, sizeof(msg),
5684 "tid[%d] SACK: reason %s serial %u previous %u seq %u first %u acks %u space %u ",
5685 GetCurrentThreadId(), rx_ack_reason(ap->reason),
5686 ntohl(ap->serial), ntohl(ap->previousPacket),
5687 (unsigned int)p->header.seq, ntohl(ap->firstPacket),
5688 ap->nAcks, ntohs(ap->bufferSpace) );
5692 for (offset = 0; offset < ap->nAcks && len < sizeof(msg); offset++)
5693 msg[len++] = (ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*');
5697 OutputDebugString(msg);
5699 #else /* AFS_NT40_ENV */
5701 fprintf(rx_Log, "SACK: reason %x previous %u seq %u first %u ",
5702 ap->reason, ntohl(ap->previousPacket),
5703 (unsigned int)p->header.seq, ntohl(ap->firstPacket));
5705 for (offset = 0; offset < ap->nAcks; offset++)
5706 putc(ap->acks[offset] == RX_ACK_TYPE_NACK ? '-' : '*',
5711 #endif /* AFS_NT40_ENV */
5714 int i, nbytes = p->length;
5716 for (i = 1; i < p->niovecs; i++) { /* vec 0 is ALWAYS header */
5717 if (nbytes <= p->wirevec[i].iov_len) {
5720 savelen = p->wirevec[i].iov_len;
5722 p->wirevec[i].iov_len = nbytes;
5724 rxi_Send(call, p, istack);
5725 p->wirevec[i].iov_len = savelen;
5729 nbytes -= p->wirevec[i].iov_len;
5732 if (rx_stats_active)
5733 rx_atomic_inc(&rx_stats.ackPacketsSent);
5734 #ifndef RX_ENABLE_TSFPQ
5735 if (!optionalPacket)
5738 return optionalPacket; /* Return packet for re-use by caller */
5742 struct rx_packet **list;
5747 /* Send all of the packets in the list in single datagram */
5749 rxi_SendList(struct rx_call *call, struct xmitlist *xmit,
5750 int istack, int moreFlag)
5756 struct rx_connection *conn = call->conn;
5757 struct rx_peer *peer = conn->peer;
5759 MUTEX_ENTER(&peer->peer_lock);
5760 peer->nSent += xmit->len;
5761 if (xmit->resending)
5762 peer->reSends += xmit->len;
5763 MUTEX_EXIT(&peer->peer_lock);
5765 if (rx_stats_active) {
5766 if (xmit->resending)
5767 rx_atomic_add(&rx_stats.dataPacketsReSent, xmit->len);
5769 rx_atomic_add(&rx_stats.dataPacketsSent, xmit->len);
5772 clock_GetTime(&now);
5774 if (xmit->list[xmit->len - 1]->header.flags & RX_LAST_PACKET) {
5778 /* Set the packet flags and schedule the resend events */
5779 /* Only request an ack for the last packet in the list */
5780 for (i = 0; i < xmit->len; i++) {
5781 struct rx_packet *packet = xmit->list[i];
5783 /* Record the time sent */
5784 packet->timeSent = now;
5785 packet->flags |= RX_PKTFLAG_SENT;
5787 /* Ask for an ack on retransmitted packets, on every other packet
5788 * if the peer doesn't support slow start. Ask for an ack on every
5789 * packet until the congestion window reaches the ack rate. */
5790 if (packet->header.serial) {
5793 packet->firstSent = now;
5794 if (!lastPacket && (call->cwind <= (u_short) (conn->ackRate + 1)
5795 || (!(call->flags & RX_CALL_SLOW_START_OK)
5796 && (packet->header.seq & 1)))) {
5801 /* Tag this packet as not being the last in this group,
5802 * for the receiver's benefit */
5803 if (i < xmit->len - 1 || moreFlag) {
5804 packet->header.flags |= RX_MORE_PACKETS;
5809 xmit->list[xmit->len - 1]->header.flags |= RX_REQUEST_ACK;
5812 /* Since we're about to send a data packet to the peer, it's
5813 * safe to nuke any scheduled end-of-packets ack */
5814 rxi_CancelDelayedAckEvent(call);
5816 MUTEX_EXIT(&call->lock);
5817 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
5818 if (xmit->len > 1) {
5819 rxi_SendPacketList(call, conn, xmit->list, xmit->len, istack);
5821 rxi_SendPacket(call, conn, xmit->list[0], istack);
5823 MUTEX_ENTER(&call->lock);
5824 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
5826 /* Tell the RTO calculation engine that we have sent a packet, and
5827 * if it was the last one */
5828 rxi_rto_packet_sent(call, lastPacket, istack);
5830 /* Update last send time for this call (for keep-alive
5831 * processing), and for the connection (so that we can discover
5832 * idle connections) */
5833 conn->lastSendTime = call->lastSendTime = clock_Sec();
5836 /* When sending packets we need to follow these rules:
5837 * 1. Never send more than maxDgramPackets in a jumbogram.
5838 * 2. Never send a packet with more than two iovecs in a jumbogram.
5839 * 3. Never send a retransmitted packet in a jumbogram.
5840 * 4. Never send more than cwind/4 packets in a jumbogram
5841 * We always keep the last list we should have sent so we
5842 * can set the RX_MORE_PACKETS flags correctly.
5846 rxi_SendXmitList(struct rx_call *call, struct rx_packet **list, int len,
5851 struct xmitlist working;
5852 struct xmitlist last;
5854 struct rx_peer *peer = call->conn->peer;
5855 int morePackets = 0;
5857 memset(&last, 0, sizeof(struct xmitlist));
5858 working.list = &list[0];
5860 working.resending = 0;
5862 recovery = call->flags & RX_CALL_FAST_RECOVER;
5864 for (i = 0; i < len; i++) {
5865 /* Does the current packet force us to flush the current list? */
5867 && (list[i]->header.serial || (list[i]->flags & RX_PKTFLAG_ACKED)
5868 || list[i]->length > RX_JUMBOBUFFERSIZE)) {
5870 /* This sends the 'last' list and then rolls the current working
5871 * set into the 'last' one, and resets the working set */
5874 rxi_SendList(call, &last, istack, 1);
5875 /* If the call enters an error state stop sending, or if
5876 * we entered congestion recovery mode, stop sending */
5878 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5883 working.resending = 0;
5884 working.list = &list[i];
5886 /* Add the current packet to the list if it hasn't been acked.
5887 * Otherwise adjust the list pointer to skip the current packet. */
5888 if (!(list[i]->flags & RX_PKTFLAG_ACKED)) {
5891 if (list[i]->header.serial)
5892 working.resending = 1;
5894 /* Do we need to flush the list? */
5895 if (working.len >= (int)peer->maxDgramPackets
5896 || working.len >= (int)call->nDgramPackets
5897 || working.len >= (int)call->cwind
5898 || list[i]->header.serial
5899 || list[i]->length != RX_JUMBOBUFFERSIZE) {
5901 rxi_SendList(call, &last, istack, 1);
5902 /* If the call enters an error state stop sending, or if
5903 * we entered congestion recovery mode, stop sending */
5905 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5910 working.resending = 0;
5911 working.list = &list[i + 1];
5914 if (working.len != 0) {
5915 osi_Panic("rxi_SendList error");
5917 working.list = &list[i + 1];
5921 /* Send the whole list when the call is in receive mode, when
5922 * the call is in eof mode, when we are in fast recovery mode,
5923 * and when we have the last packet */
5924 /* XXX - The accesses to app.mode aren't safe, as this may be called by
5925 * the listener or event threads
5927 if ((list[len - 1]->header.flags & RX_LAST_PACKET)
5928 || (call->flags & RX_CALL_FLUSH)
5929 || (call->flags & RX_CALL_FAST_RECOVER)) {
5930 /* Check for the case where the current list contains
5931 * an acked packet. Since we always send retransmissions
5932 * in a separate packet, we only need to check the first
5933 * packet in the list */
5934 if (working.len > 0 && !(working.list[0]->flags & RX_PKTFLAG_ACKED)) {
5938 rxi_SendList(call, &last, istack, morePackets);
5939 /* If the call enters an error state stop sending, or if
5940 * we entered congestion recovery mode, stop sending */
5942 || (!recovery && (call->flags & RX_CALL_FAST_RECOVER)))
5946 rxi_SendList(call, &working, istack, 0);
5948 } else if (last.len > 0) {
5949 rxi_SendList(call, &last, istack, 0);
5950 /* Packets which are in 'working' are not sent by this call */
5955 * Check if the peer for the given call is known to be dead
5957 * If the call's peer appears dead (it has encountered fatal network errors
5958 * since the call started) the call is killed with RX_CALL_DEAD if the call
5959 * is active. Otherwise, we do nothing.
5961 * @param[in] call The call to check
5964 * @retval 0 The call is fine, and we haven't done anything to the call
5965 * @retval nonzero The call's peer appears dead, and the call has been
5966 * terminated if it was active
5968 * @pre call->lock must be locked
5971 rxi_CheckPeerDead(struct rx_call *call)
5973 #ifdef AFS_RXERRQ_ENV
5976 if (call->state == RX_STATE_DALLY) {
5980 peererrs = rx_atomic_read(&call->conn->peer->neterrs);
5981 if (call->neterr_gen < peererrs) {
5982 /* we have received network errors since this call started; kill
5984 if (call->state == RX_STATE_ACTIVE) {
5985 rxi_CallError(call, RX_CALL_DEAD);
5989 if (call->neterr_gen > peererrs) {
5990 /* someone has reset the number of peer errors; set the call error gen
5991 * so we can detect if more errors are encountered */
5992 call->neterr_gen = peererrs;
5999 rxi_Resend(struct rxevent *event, void *arg0, void *arg1, int istack)
6001 struct rx_call *call = arg0;
6002 struct rx_peer *peer;
6003 struct opr_queue *cursor;
6004 struct clock maxTimeout = { 60, 0 };
6006 MUTEX_ENTER(&call->lock);
6008 peer = call->conn->peer;
6010 /* Make sure that the event pointer is removed from the call
6011 * structure, since there is no longer a per-call retransmission
6013 if (event == call->resendEvent)
6014 rxevent_Put(&call->resendEvent);
6016 rxi_CheckPeerDead(call);
6018 if (opr_queue_IsEmpty(&call->tq)) {
6019 /* Nothing to do. This means that we've been raced, and that an
6020 * ACK has come in between when we were triggered, and when we
6021 * actually got to run. */
6025 /* We're in loss recovery */
6026 call->flags |= RX_CALL_FAST_RECOVER;
6028 /* Mark all of the pending packets in the queue as being lost */
6029 for (opr_queue_Scan(&call->tq, cursor)) {
6030 struct rx_packet *p = opr_queue_Entry(cursor, struct rx_packet, entry);
6031 if (!(p->flags & RX_PKTFLAG_ACKED))
6032 p->flags &= ~RX_PKTFLAG_SENT;
6035 /* We're resending, so we double the timeout of the call. This will be
6036 * dropped back down by the first successful ACK that we receive.
6038 * We apply a maximum value here of 60 seconds
6040 clock_Add(&call->rto, &call->rto);
6041 if (clock_Gt(&call->rto, &maxTimeout))
6042 call->rto = maxTimeout;
6044 /* Packet loss is most likely due to congestion, so drop our window size
6045 * and start again from the beginning */
6046 if (peer->maxDgramPackets >1) {
6047 call->MTU = RX_JUMBOBUFFERSIZE + RX_HEADER_SIZE;
6048 call->MTU = MIN(peer->natMTU, peer->maxMTU);
6050 call->ssthresh = MAX(4, MIN((int)call->cwind, (int)call->twind)) >> 1;
6051 call->nDgramPackets = 1;
6053 call->nextCwind = 1;
6056 MUTEX_ENTER(&peer->peer_lock);
6057 peer->MTU = call->MTU;
6058 peer->cwind = call->cwind;
6059 peer->nDgramPackets = 1;
6061 call->congestSeq = peer->congestSeq;
6062 MUTEX_EXIT(&peer->peer_lock);
6064 rxi_Start(call, istack);
6067 CALL_RELE(call, RX_CALL_REFCOUNT_RESEND);
6068 MUTEX_EXIT(&call->lock);
6071 /* This routine is called when new packets are readied for
6072 * transmission and when retransmission may be necessary, or when the
6073 * transmission window or burst count are favourable. This should be
6074 * better optimized for new packets, the usual case, now that we've
6075 * got rid of queues of send packets. XXXXXXXXXXX */
6077 rxi_Start(struct rx_call *call, int istack)
6079 struct opr_queue *cursor;
6080 #ifdef RX_ENABLE_LOCKS
6081 struct opr_queue *store;
6087 #ifdef RX_ENABLE_LOCKS
6088 if (rx_stats_active)
6089 rx_atomic_inc(&rx_tq_debug.rxi_start_in_error);
6094 if (!opr_queue_IsEmpty(&call->tq)) { /* If we have anything to send */
6095 /* Send (or resend) any packets that need it, subject to
6096 * window restrictions and congestion burst control
6097 * restrictions. Ask for an ack on the last packet sent in
6098 * this burst. For now, we're relying upon the window being
6099 * considerably bigger than the largest number of packets that
6100 * are typically sent at once by one initial call to
6101 * rxi_Start. This is probably bogus (perhaps we should ask
6102 * for an ack when we're half way through the current
6103 * window?). Also, for non file transfer applications, this
6104 * may end up asking for an ack for every packet. Bogus. XXXX
6107 * But check whether we're here recursively, and let the other guy
6110 #ifdef RX_ENABLE_LOCKS
6111 if (!(call->flags & RX_CALL_TQ_BUSY)) {
6112 call->flags |= RX_CALL_TQ_BUSY;
6114 #endif /* RX_ENABLE_LOCKS */
6116 #ifdef RX_ENABLE_LOCKS
6117 call->flags &= ~RX_CALL_NEED_START;
6118 #endif /* RX_ENABLE_LOCKS */
6120 maxXmitPackets = MIN(call->twind, call->cwind);
6121 for (opr_queue_Scan(&call->tq, cursor)) {
6123 = opr_queue_Entry(cursor, struct rx_packet, entry);
6125 if (p->flags & RX_PKTFLAG_ACKED) {
6126 /* Since we may block, don't trust this */
6127 if (rx_stats_active)
6128 rx_atomic_inc(&rx_stats.ignoreAckedPacket);
6129 continue; /* Ignore this packet if it has been acknowledged */
6132 /* Turn off all flags except these ones, which are the same
6133 * on each transmission */
6134 p->header.flags &= RX_PRESET_FLAGS;
6136 if (p->header.seq >=
6137 call->tfirst + MIN((int)call->twind,
6138 (int)(call->nSoftAcked +
6140 call->flags |= RX_CALL_WAIT_WINDOW_SEND; /* Wait for transmit window */
6141 /* Note: if we're waiting for more window space, we can
6142 * still send retransmits; hence we don't return here, but
6143 * break out to schedule a retransmit event */
6144 dpf(("call %d waiting for window (seq %d, twind %d, nSoftAcked %d, cwind %d)\n",
6145 *(call->callNumber), p->header.seq, call->twind, call->nSoftAcked,
6150 /* Transmit the packet if it needs to be sent. */
6151 if (!(p->flags & RX_PKTFLAG_SENT)) {
6152 if (nXmitPackets == maxXmitPackets) {
6153 rxi_SendXmitList(call, call->xmitList,
6154 nXmitPackets, istack);
6157 dpf(("call %d xmit packet %"AFS_PTR_FMT"\n",
6158 *(call->callNumber), p));
6159 call->xmitList[nXmitPackets++] = p;
6161 } /* end of the queue_Scan */
6163 /* xmitList now hold pointers to all of the packets that are
6164 * ready to send. Now we loop to send the packets */
6165 if (nXmitPackets > 0) {
6166 rxi_SendXmitList(call, call->xmitList, nXmitPackets,
6170 #ifdef RX_ENABLE_LOCKS
6172 /* We went into the error state while sending packets. Now is
6173 * the time to reset the call. This will also inform the using
6174 * process that the call is in an error state.
6176 if (rx_stats_active)
6177 rx_atomic_inc(&rx_tq_debug.rxi_start_aborted);
6178 call->flags &= ~RX_CALL_TQ_BUSY;
6179 rxi_WakeUpTransmitQueue(call);
6180 rxi_CallError(call, call->error);
6184 if (call->flags & RX_CALL_TQ_SOME_ACKED) {
6186 call->flags &= ~RX_CALL_TQ_SOME_ACKED;
6187 /* Some packets have received acks. If they all have, we can clear
6188 * the transmit queue.
6191 for (opr_queue_ScanSafe(&call->tq, cursor, store)) {
6193 = opr_queue_Entry(cursor, struct rx_packet, entry);
6195 if (p->header.seq < call->tfirst
6196 && (p->flags & RX_PKTFLAG_ACKED)) {
6197 opr_queue_Remove(&p->entry);
6198 #ifdef RX_TRACK_PACKETS
6199 p->flags &= ~RX_PKTFLAG_TQ;
6201 #ifdef RXDEBUG_PACKET
6209 call->flags |= RX_CALL_TQ_CLEARME;
6211 if (call->flags & RX_CALL_TQ_CLEARME)
6212 rxi_ClearTransmitQueue(call, 1);
6213 } while (call->flags & RX_CALL_NEED_START);
6215 * TQ references no longer protected by this flag; they must remain
6216 * protected by the call lock.
6218 call->flags &= ~RX_CALL_TQ_BUSY;
6219 rxi_WakeUpTransmitQueue(call);
6221 call->flags |= RX_CALL_NEED_START;
6223 #endif /* RX_ENABLE_LOCKS */
6225 rxi_rto_cancel(call);
6229 /* Also adjusts the keep alive parameters for the call, to reflect
6230 * that we have just sent a packet (so keep alives aren't sent
6233 rxi_Send(struct rx_call *call, struct rx_packet *p,
6236 struct rx_connection *conn = call->conn;
6238 /* Stamp each packet with the user supplied status */
6239 p->header.userStatus = call->localStatus;
6241 /* Allow the security object controlling this call's security to
6242 * make any last-minute changes to the packet */
6243 RXS_SendPacket(conn->securityObject, call, p);
6245 /* Since we're about to send SOME sort of packet to the peer, it's
6246 * safe to nuke any scheduled end-of-packets ack */
6247 rxi_CancelDelayedAckEvent(call);
6249 /* Actually send the packet, filling in more connection-specific fields */
6250 MUTEX_EXIT(&call->lock);
6251 CALL_HOLD(call, RX_CALL_REFCOUNT_SEND);
6252 rxi_SendPacket(call, conn, p, istack);
6253 CALL_RELE(call, RX_CALL_REFCOUNT_SEND);
6254 MUTEX_ENTER(&call->lock);
6256 /* Update last send time for this call (for keep-alive
6257 * processing), and for the connection (so that we can discover
6258 * idle connections) */
6259 if ((p->header.type != RX_PACKET_TYPE_ACK) ||
6260 (((struct rx_ackPacket *)rx_DataOf(p))->reason == RX_ACK_PING) ||
6261 (p->length <= (rx_AckDataSize(call->rwind) + 4 * sizeof(afs_int32))))
6263 conn->lastSendTime = call->lastSendTime = clock_Sec();
6267 /* Check if a call needs to be destroyed. Called by keep-alive code to ensure
6268 * that things are fine. Also called periodically to guarantee that nothing
6269 * falls through the cracks (e.g. (error + dally) connections have keepalive
6270 * turned off. Returns 0 if conn is well, -1 otherwise. If otherwise, call
6272 * haveCTLock Set if calling from rxi_ReapConnections
6275 rxi_CheckCall(struct rx_call *call, int haveCTLock)
6277 struct rx_connection *conn = call->conn;
6279 afs_uint32 deadTime, idleDeadTime = 0, hardDeadTime = 0;
6280 afs_uint32 fudgeFactor;
6283 int idle_timeout = 0;
6284 afs_int32 clock_diff = 0;
6286 if (rxi_CheckPeerDead(call)) {
6292 /* Large swings in the clock can have a significant impact on
6293 * the performance of RX call processing. Forward clock shifts
6294 * will result in premature event triggering or timeouts.
6295 * Backward shifts can result in calls not completing until
6296 * the clock catches up with the original start clock value.
6298 * If a backward clock shift of more than five minutes is noticed,
6299 * just fail the call.
6301 if (now < call->lastSendTime)
6302 clock_diff = call->lastSendTime - now;
6303 if (now < call->startWait)
6304 clock_diff = MAX(clock_diff, call->startWait - now);
6305 if (now < call->lastReceiveTime)
6306 clock_diff = MAX(clock_diff, call->lastReceiveTime - now);
6307 if (clock_diff > 5 * 60)
6309 if (call->state == RX_STATE_ACTIVE)
6310 rxi_CallError(call, RX_CALL_TIMEOUT);
6314 #ifdef RX_ENABLE_LOCKS
6315 if (call->flags & RX_CALL_TQ_BUSY) {
6316 /* Call is active and will be reset by rxi_Start if it's
6317 * in an error state.
6322 /* RTT + 8*MDEV, rounded up to the next second. */
6323 fudgeFactor = (((afs_uint32) call->rtt >> 3) +
6324 ((afs_uint32) call->rtt_dev << 1) + 1023) >> 10;
6326 deadTime = conn->secondsUntilDead + fudgeFactor;
6327 /* These are computed to the second (+- 1 second). But that's
6328 * good enough for these values, which should be a significant
6329 * number of seconds. */
6330 if (now > (call->lastReceiveTime + deadTime)) {
6331 if (call->state == RX_STATE_ACTIVE) {
6332 cerror = RX_CALL_DEAD;
6335 #ifdef RX_ENABLE_LOCKS
6336 /* Cancel pending events */
6337 rxi_CancelDelayedAckEvent(call);
6338 rxi_rto_cancel(call);
6339 rxi_CancelKeepAliveEvent(call);
6340 rxi_CancelGrowMTUEvent(call);
6341 MUTEX_ENTER(&rx_refcnt_mutex);
6342 /* if rxi_FreeCall returns 1 it has freed the call */
6343 if (call->refCount == 0 &&
6344 rxi_FreeCall(call, haveCTLock))
6346 MUTEX_EXIT(&rx_refcnt_mutex);
6349 MUTEX_EXIT(&rx_refcnt_mutex);
6351 #else /* RX_ENABLE_LOCKS */
6352 rxi_FreeCall(call, 0);
6354 #endif /* RX_ENABLE_LOCKS */
6356 /* Non-active calls are destroyed if they are not responding
6357 * to pings; active calls are simply flagged in error, so the
6358 * attached process can die reasonably gracefully. */
6361 if (conn->idleDeadTime) {
6362 idleDeadTime = conn->idleDeadTime + fudgeFactor;
6366 /* see if we have a non-activity timeout */
6367 if (call->startWait && ((call->startWait + idleDeadTime) < now)) {
6368 if (call->state == RX_STATE_ACTIVE) {
6369 cerror = RX_CALL_TIMEOUT;
6375 if (conn->hardDeadTime) {
6376 hardDeadTime = conn->hardDeadTime + fudgeFactor;
6379 /* see if we have a hard timeout */
6381 && (now > (hardDeadTime + call->startTime.sec))) {
6382 if (call->state == RX_STATE_ACTIVE)
6383 rxi_CallError(call, RX_CALL_TIMEOUT);
6388 if (conn->msgsizeRetryErr && cerror != RX_CALL_TIMEOUT && !idle_timeout &&
6389 call->lastReceiveTime) {
6390 int oldMTU = conn->peer->ifMTU;
6392 /* If we thought we could send more, perhaps things got worse.
6393 * Shrink by 128 bytes and try again. */
6394 if (conn->peer->maxPacketSize < conn->lastPacketSize)
6395 /* maxPacketSize will be cleared in rxi_SetPeerMtu */
6396 newmtu = MAX(conn->peer->maxPacketSize + RX_HEADER_SIZE,
6397 conn->lastPacketSize - 128 + RX_HEADER_SIZE);
6399 newmtu = conn->lastPacketSize - 128 + RX_HEADER_SIZE;
6401 /* minimum capped in SetPeerMtu */
6402 rxi_SetPeerMtu(conn->peer, 0, 0, newmtu);
6405 conn->lastPacketSize = conn->lastPacketSizeSeq = 0;
6407 /* needed so ResetCall doesn't clobber us. */
6408 call->MTU = conn->peer->ifMTU;
6410 /* if we never succeeded, let the error pass out as-is */
6411 if (conn->peer->maxPacketSize && oldMTU != conn->peer->ifMTU)
6412 cerror = conn->msgsizeRetryErr;
6415 rxi_CallError(call, cerror);
6420 rxi_NatKeepAliveEvent(struct rxevent *event, void *arg1,
6421 void *dummy, int dummy2)
6423 struct rx_connection *conn = arg1;
6424 struct rx_header theader;
6425 char tbuffer[1 + sizeof(struct rx_header)];
6426 struct sockaddr_in taddr;
6430 struct iovec tmpiov[2];
6433 RX_CLIENT_CONNECTION ? rx_socket : conn->service->socket);
6436 tp = &tbuffer[sizeof(struct rx_header)];
6437 taddr.sin_family = AF_INET;
6438 taddr.sin_port = rx_PortOf(rx_PeerOf(conn));
6439 taddr.sin_addr.s_addr = rx_HostOf(rx_PeerOf(conn));
6440 memset(&taddr.sin_zero, 0, sizeof(taddr.sin_zero));
6441 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
6442 taddr.sin_len = sizeof(struct sockaddr_in);
6444 memset(&theader, 0, sizeof(theader));
6445 theader.epoch = htonl(999);
6447 theader.callNumber = 0;
6450 theader.type = RX_PACKET_TYPE_VERSION;
6451 theader.flags = RX_LAST_PACKET;
6452 theader.serviceId = 0;
6454 memcpy(tbuffer, &theader, sizeof(theader));
6455 memcpy(tp, &a, sizeof(a));
6456 tmpiov[0].iov_base = tbuffer;
6457 tmpiov[0].iov_len = 1 + sizeof(struct rx_header);
6459 osi_NetSend(socket, &taddr, tmpiov, 1, 1 + sizeof(struct rx_header), 1);
6461 MUTEX_ENTER(&conn->conn_data_lock);
6462 /* We ran, so the handle is no longer needed to try to cancel ourselves. */
6463 if (event == conn->natKeepAliveEvent)
6464 rxevent_Put(&conn->natKeepAliveEvent);
6465 MUTEX_ENTER(&rx_refcnt_mutex);
6466 /* Only reschedule ourselves if the connection would not be destroyed */
6467 if (conn->refCount > 1)
6469 if (conn->refCount <= 0) {
6470 #ifdef RX_REFCOUNT_CHECK
6471 osi_Assert(conn->refCount == 0);
6473 if (rx_stats_active) {
6474 MUTEX_ENTER(&rx_stats_mutex);
6475 rxi_lowConnRefCount++;
6476 MUTEX_EXIT(&rx_stats_mutex);
6479 MUTEX_EXIT(&rx_refcnt_mutex);
6481 rxi_ScheduleNatKeepAliveEvent(conn);
6482 MUTEX_EXIT(&conn->conn_data_lock);
6483 putConnection(conn);
6487 rxi_ScheduleNatKeepAliveEvent(struct rx_connection *conn)
6489 MUTEX_ASSERT(&conn->conn_data_lock);
6490 if (!conn->natKeepAliveEvent && conn->secondsUntilNatPing) {
6491 struct clock when, now;
6492 clock_GetTime(&now);
6494 when.sec += conn->secondsUntilNatPing;
6495 rx_GetConnection(conn);
6496 conn->natKeepAliveEvent =
6497 rxevent_Post(&when, &now, rxi_NatKeepAliveEvent, conn, NULL, 0);
6502 rx_SetConnSecondsUntilNatPing(struct rx_connection *conn, afs_int32 seconds)
6504 MUTEX_ENTER(&conn->conn_data_lock);
6505 conn->secondsUntilNatPing = seconds;
6507 if (!(conn->flags & RX_CONN_ATTACHWAIT))
6508 rxi_ScheduleNatKeepAliveEvent(conn);
6510 conn->flags |= RX_CONN_NAT_PING;
6512 MUTEX_EXIT(&conn->conn_data_lock);
6515 /* When a call is in progress, this routine is called occasionally to
6516 * make sure that some traffic has arrived (or been sent to) the peer.
6517 * If nothing has arrived in a reasonable amount of time, the call is
6518 * declared dead; if nothing has been sent for a while, we send a
6519 * keep-alive packet (if we're actually trying to keep the call alive)
6522 rxi_KeepAliveEvent(struct rxevent *event, void *arg1, void *dummy,
6525 struct rx_call *call = arg1;
6526 struct rx_connection *conn;
6529 MUTEX_ENTER(&call->lock);
6531 if (event == call->keepAliveEvent)
6532 rxevent_Put(&call->keepAliveEvent);
6536 if (rxi_CheckCall(call, 0)) {
6537 MUTEX_EXIT(&call->lock);
6538 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6542 /* Don't try to keep alive dallying calls */
6543 if (call->state == RX_STATE_DALLY) {
6544 MUTEX_EXIT(&call->lock);
6545 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6550 if ((now - call->lastSendTime) > conn->secondsUntilPing) {
6551 /* Don't try to send keepalives if there is unacknowledged data */
6552 /* the rexmit code should be good enough, this little hack
6553 * doesn't quite work XXX */
6554 (void)rxi_SendAck(call, NULL, 0, RX_ACK_PING, 0);
6556 rxi_ScheduleKeepAliveEvent(call);
6557 MUTEX_EXIT(&call->lock);
6558 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6561 /* Does what's on the nameplate. */
6563 rxi_GrowMTUEvent(struct rxevent *event, void *arg1, void *dummy, int dummy2)
6565 struct rx_call *call = arg1;
6566 struct rx_connection *conn;
6568 MUTEX_ENTER(&call->lock);
6570 if (event == call->growMTUEvent)
6571 rxevent_Put(&call->growMTUEvent);
6573 if (rxi_CheckCall(call, 0))
6576 /* Don't bother with dallying calls */
6577 if (call->state == RX_STATE_DALLY)
6583 * keep being scheduled, just don't do anything if we're at peak,
6584 * or we're not set up to be properly handled (idle timeout required)
6586 if ((conn->peer->maxPacketSize != 0) &&
6587 (conn->peer->natMTU < RX_MAX_PACKET_SIZE) &&
6589 (void)rxi_SendAck(call, NULL, 0, RX_ACK_MTU, 0);
6590 rxi_ScheduleGrowMTUEvent(call, 0);
6592 MUTEX_EXIT(&call->lock);
6593 CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6597 rxi_ScheduleKeepAliveEvent(struct rx_call *call)
6599 MUTEX_ASSERT(&call->lock);
6600 if (!call->keepAliveEvent) {
6601 struct clock when, now;
6602 clock_GetTime(&now);
6604 when.sec += call->conn->secondsUntilPing;
6605 CALL_HOLD(call, RX_CALL_REFCOUNT_ALIVE);
6606 call->keepAliveEvent =
6607 rxevent_Post(&when, &now, rxi_KeepAliveEvent, call, NULL, 0);
6612 rxi_CancelKeepAliveEvent(struct rx_call *call) {
6613 MUTEX_ASSERT(&call->lock);
6614 if (rxevent_Cancel(&call->keepAliveEvent))
6615 CALL_RELE(call, RX_CALL_REFCOUNT_ALIVE);
6619 rxi_ScheduleGrowMTUEvent(struct rx_call *call, int secs)
6621 MUTEX_ASSERT(&call->lock);
6622 if (!call->growMTUEvent) {
6623 struct clock when, now;
6625 clock_GetTime(&now);
6628 if (call->conn->secondsUntilPing)
6629 secs = (6*call->conn->secondsUntilPing)-1;
6631 if (call->conn->secondsUntilDead)
6632 secs = MIN(secs, (call->conn->secondsUntilDead-1));
6636 CALL_HOLD(call, RX_CALL_REFCOUNT_MTU);
6637 call->growMTUEvent =
6638 rxevent_Post(&when, &now, rxi_GrowMTUEvent, call, NULL, 0);
6643 rxi_CancelGrowMTUEvent(struct rx_call *call)
6645 MUTEX_ASSERT(&call->lock);
6646 if (rxevent_Cancel(&call->growMTUEvent))
6647 CALL_RELE(call, RX_CALL_REFCOUNT_MTU);
6651 * Increment the counter for the next connection ID, handling overflow.
6654 update_nextCid(void)
6656 /* Overflow is technically undefined behavior; avoid it. */
6657 if (rx_nextCid > MAX_AFS_INT32 - (1 << RX_CIDSHIFT))
6658 rx_nextCid = -1 * ((MAX_AFS_INT32 / RX_CIDSHIFT) * RX_CIDSHIFT);
6660 rx_nextCid += 1 << RX_CIDSHIFT;
6664 rxi_KeepAliveOn(struct rx_call *call)
6666 /* Pretend last packet received was received now--i.e. if another
6667 * packet isn't received within the keep alive time, then the call
6668 * will die; Initialize last send time to the current time--even
6669 * if a packet hasn't been sent yet. This will guarantee that a
6670 * keep-alive is sent within the ping time */
6671 call->lastReceiveTime = call->lastSendTime = clock_Sec();
6672 rxi_ScheduleKeepAliveEvent(call);
6676 rxi_GrowMTUOn(struct rx_call *call)
6678 struct rx_connection *conn = call->conn;
6679 MUTEX_ENTER(&conn->conn_data_lock);
6680 conn->lastPingSizeSer = conn->lastPingSize = 0;
6681 MUTEX_EXIT(&conn->conn_data_lock);
6682 rxi_ScheduleGrowMTUEvent(call, 1);
6685 /* This routine is called to send connection abort messages
6686 * that have been delayed to throttle looping clients. */
6688 rxi_SendDelayedConnAbort(struct rxevent *event, void *arg1, void *unused,
6691 struct rx_connection *conn = arg1;
6694 struct rx_packet *packet;
6696 MUTEX_ENTER(&conn->conn_data_lock);
6697 if (event == conn->delayedAbortEvent)
6698 rxevent_Put(&conn->delayedAbortEvent);
6699 error = htonl(conn->error);
6701 MUTEX_EXIT(&conn->conn_data_lock);
6702 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6705 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6706 RX_PACKET_TYPE_ABORT, (char *)&error,
6708 rxi_FreePacket(packet);
6710 putConnection(conn);
6713 /* This routine is called to send call abort messages
6714 * that have been delayed to throttle looping clients. */
6716 rxi_SendDelayedCallAbort(struct rxevent *event, void *arg1, void *dummy,
6719 struct rx_call *call = arg1;
6722 struct rx_packet *packet;
6724 MUTEX_ENTER(&call->lock);
6725 if (event == call->delayedAbortEvent)
6726 rxevent_Put(&call->delayedAbortEvent);
6727 error = htonl(call->error);
6729 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6732 rxi_SendSpecial(call, call->conn, packet, RX_PACKET_TYPE_ABORT,
6733 (char *)&error, sizeof(error), 0);
6734 rxi_FreePacket(packet);
6736 MUTEX_EXIT(&call->lock);
6737 CALL_RELE(call, RX_CALL_REFCOUNT_ABORT);
6741 * This routine is called periodically (every RX_AUTH_REQUEST_TIMEOUT
6742 * seconds) to ask the client to authenticate itself. The routine
6743 * issues a challenge to the client, which is obtained from the
6744 * security object associated with the connection
6746 * This routine is both an event handler and a function called directly;
6747 * when called directly the passed |event| is NULL and the
6748 * conn->conn->data>lock must must not be held. Also, when called as an
6749 * an event handler, we must putConnection before we exit; but when called
6750 * directly (the first challenge), we must NOT putConnection.
6753 rxi_ChallengeEvent(struct rxevent *event,
6754 void *arg0, void *arg1, int tries)
6756 struct rx_connection *conn = arg0;
6757 int event_raised = 0; /* assume we were called directly */
6759 MUTEX_ENTER(&conn->conn_data_lock);
6760 if (event != NULL && event == conn->challengeEvent) {
6761 event_raised = 1; /* called as an event */
6762 rxevent_Put(&conn->challengeEvent);
6764 MUTEX_EXIT(&conn->conn_data_lock);
6766 /* If there are no active calls it is not worth re-issuing the
6767 * challenge. If the client issues another call on this connection
6768 * the challenge can be requested at that time.
6770 if (!rxi_HasActiveCalls(conn))
6773 if (RXS_CheckAuthentication(conn->securityObject, conn) != 0) {
6774 struct rx_packet *packet;
6775 struct clock when, now;
6778 /* We've failed to authenticate for too long.
6779 * Reset any calls waiting for authentication;
6780 * they are all in RX_STATE_PRECALL.
6784 MUTEX_ENTER(&conn->conn_call_lock);
6785 for (i = 0; i < RX_MAXCALLS; i++) {
6786 struct rx_call *call = conn->call[i];
6788 MUTEX_ENTER(&call->lock);
6789 if (call->state == RX_STATE_PRECALL) {
6790 rxi_CallError(call, RX_CALL_DEAD);
6791 rxi_SendCallAbort(call, NULL, 0, 0);
6793 MUTEX_EXIT(&call->lock);
6796 MUTEX_EXIT(&conn->conn_call_lock);
6800 packet = rxi_AllocPacket(RX_PACKET_CLASS_SPECIAL);
6802 /* If there's no packet available, do this later. */
6803 RXS_GetChallenge(conn->securityObject, conn, packet);
6804 rxi_SendSpecial((struct rx_call *)0, conn, packet,
6805 RX_PACKET_TYPE_CHALLENGE, NULL, -1, 0);
6806 rxi_FreePacket(packet);
6807 conn->securityChallengeSent = 1;
6809 clock_GetTime(&now);
6811 when.sec += RX_CHALLENGE_TIMEOUT;
6812 MUTEX_ENTER(&conn->conn_data_lock);
6813 /* Only reschedule ourselves if not already pending. */
6814 if (conn->challengeEvent == NULL) {
6815 rx_GetConnection(conn);
6816 conn->challengeEvent =
6817 rxevent_Post(&when, &now, rxi_ChallengeEvent, conn, 0,
6820 MUTEX_EXIT(&conn->conn_data_lock);
6824 putConnection(conn);
6827 /* Call this routine to start requesting the client to authenticate
6828 * itself. This will continue until authentication is established,
6829 * the call times out, or an invalid response is returned. The
6830 * security object associated with the connection is asked to create
6831 * the challenge at this time. */
6833 rxi_ChallengeOn(struct rx_connection *conn)
6836 MUTEX_ENTER(&conn->conn_data_lock);
6837 if (!conn->challengeEvent)
6839 MUTEX_EXIT(&conn->conn_data_lock);
6841 RXS_CreateChallenge(conn->securityObject, conn);
6842 rxi_ChallengeEvent(NULL, conn, 0, RX_CHALLENGE_MAXTRIES);
6847 /* rxi_ComputeRoundTripTime is called with peer locked. */
6848 /* peer may be null */
6850 rxi_ComputeRoundTripTime(struct rx_packet *p,
6851 struct rx_ackPacket *ack,
6852 struct rx_call *call,
6853 struct rx_peer *peer,
6856 struct clock thisRtt, *sentp;
6860 /* If the ACK is delayed, then do nothing */
6861 if (ack->reason == RX_ACK_DELAY)
6864 /* On the wire, jumbograms are a single UDP packet. We shouldn't count
6865 * their RTT multiple times, so only include the RTT of the last packet
6867 if (p->flags & RX_JUMBO_PACKET)
6870 /* Use the serial number to determine which transmission the ACK is for,
6871 * and set the sent time to match this. If we have no serial number, then
6872 * only use the ACK for RTT calculations if the packet has not been
6876 serial = ntohl(ack->serial);
6878 if (serial == p->header.serial) {
6879 sentp = &p->timeSent;
6880 } else if (serial == p->firstSerial) {
6881 sentp = &p->firstSent;
6882 } else if (clock_Eq(&p->timeSent, &p->firstSent)) {
6883 sentp = &p->firstSent;
6887 if (clock_Eq(&p->timeSent, &p->firstSent)) {
6888 sentp = &p->firstSent;
6895 if (clock_Lt(&thisRtt, sentp))
6896 return; /* somebody set the clock back, don't count this time. */
6898 clock_Sub(&thisRtt, sentp);
6899 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rttp=%d.%06d sec)\n",
6900 p->header.callNumber, p, thisRtt.sec, thisRtt.usec));
6902 if (clock_IsZero(&thisRtt)) {
6904 * The actual round trip time is shorter than the
6905 * clock_GetTime resolution. It is most likely 1ms or 100ns.
6906 * Since we can't tell which at the moment we will assume 1ms.
6908 thisRtt.usec = 1000;
6911 if (rx_stats_active) {
6912 MUTEX_ENTER(&rx_stats_mutex);
6913 if (clock_Lt(&thisRtt, &rx_stats.minRtt))
6914 rx_stats.minRtt = thisRtt;
6915 if (clock_Gt(&thisRtt, &rx_stats.maxRtt)) {
6916 if (thisRtt.sec > 60) {
6917 MUTEX_EXIT(&rx_stats_mutex);
6918 return; /* somebody set the clock ahead */
6920 rx_stats.maxRtt = thisRtt;
6922 clock_Add(&rx_stats.totalRtt, &thisRtt);
6923 rx_atomic_inc(&rx_stats.nRttSamples);
6924 MUTEX_EXIT(&rx_stats_mutex);
6927 /* better rtt calculation courtesy of UMich crew (dave,larry,peter,?) */
6929 /* Apply VanJacobson round-trip estimations */
6934 * srtt (call->rtt) is in units of one-eighth-milliseconds.
6935 * srtt is stored as fixed point with 3 bits after the binary
6936 * point (i.e., scaled by 8). The following magic is
6937 * equivalent to the smoothing algorithm in rfc793 with an
6938 * alpha of .875 (srtt' = rtt/8 + srtt*7/8 in fixed point).
6939 * srtt'*8 = rtt + srtt*7
6940 * srtt'*8 = srtt*8 + rtt - srtt
6941 * srtt' = srtt + rtt/8 - srtt/8
6942 * srtt' = srtt + (rtt - srtt)/8
6945 delta = _8THMSEC(&thisRtt) - call->rtt;
6946 call->rtt += (delta >> 3);
6949 * We accumulate a smoothed rtt variance (actually, a smoothed
6950 * mean difference), then set the retransmit timer to smoothed
6951 * rtt + 4 times the smoothed variance (was 2x in van's original
6952 * paper, but 4x works better for me, and apparently for him as
6954 * rttvar is stored as
6955 * fixed point with 2 bits after the binary point (scaled by
6956 * 4). The following is equivalent to rfc793 smoothing with
6957 * an alpha of .75 (rttvar' = rttvar*3/4 + |delta| / 4).
6958 * rttvar'*4 = rttvar*3 + |delta|
6959 * rttvar'*4 = rttvar*4 + |delta| - rttvar
6960 * rttvar' = rttvar + |delta|/4 - rttvar/4
6961 * rttvar' = rttvar + (|delta| - rttvar)/4
6962 * This replaces rfc793's wired-in beta.
6963 * dev*4 = dev*4 + (|actual - expected| - dev)
6969 delta -= (call->rtt_dev << 1);
6970 call->rtt_dev += (delta >> 3);
6972 /* I don't have a stored RTT so I start with this value. Since I'm
6973 * probably just starting a call, and will be pushing more data down
6974 * this, I expect congestion to increase rapidly. So I fudge a
6975 * little, and I set deviance to half the rtt. In practice,
6976 * deviance tends to approach something a little less than
6977 * half the smoothed rtt. */
6978 call->rtt = _8THMSEC(&thisRtt) + 8;
6979 call->rtt_dev = call->rtt >> 2; /* rtt/2: they're scaled differently */
6981 /* the smoothed RTT time is RTT + 4*MDEV
6983 * We allow a user specified minimum to be set for this, to allow clamping
6984 * at a minimum value in the same way as TCP. In addition, we have to allow
6985 * for the possibility that this packet is answered by a delayed ACK, so we
6986 * add on a fixed 200ms to account for that timer expiring.
6989 rtt_timeout = MAX(((call->rtt >> 3) + call->rtt_dev),
6990 rx_minPeerTimeout) + 200;
6991 clock_Zero(&call->rto);
6992 clock_Addmsec(&call->rto, rtt_timeout);
6994 /* Update the peer, so any new calls start with our values */
6995 peer->rtt_dev = call->rtt_dev;
6996 peer->rtt = call->rtt;
6998 dpf(("rxi_ComputeRoundTripTime(call=%d packet=%"AFS_PTR_FMT" rtt=%d ms, srtt=%d ms, rtt_dev=%d ms, timeout=%d.%06d sec)\n",
6999 p->header.callNumber, p, MSEC(&thisRtt), call->rtt >> 3, call->rtt_dev >> 2, (call->rto.sec), (call->rto.usec)));
7003 /* Find all server connections that have not been active for a long time, and
7006 rxi_ReapConnections(struct rxevent *unused, void *unused1, void *unused2,
7009 struct clock now, when;
7010 struct rxevent *event;
7011 clock_GetTime(&now);
7013 /* Find server connection structures that haven't been used for
7014 * greater than rx_idleConnectionTime */
7016 struct rx_connection **conn_ptr, **conn_end;
7017 int i, havecalls = 0;
7018 MUTEX_ENTER(&rx_connHashTable_lock);
7019 for (conn_ptr = &rx_connHashTable[0], conn_end =
7020 &rx_connHashTable[rx_hashTableSize]; conn_ptr < conn_end;
7022 struct rx_connection *conn, *next;
7023 struct rx_call *call;
7027 for (conn = *conn_ptr; conn; conn = next) {
7028 /* XXX -- Shouldn't the connection be locked? */
7031 for (i = 0; i < RX_MAXCALLS; i++) {
7032 call = conn->call[i];
7036 code = MUTEX_TRYENTER(&call->lock);
7039 result = rxi_CheckCall(call, 1);
7040 MUTEX_EXIT(&call->lock);
7042 /* If CheckCall freed the call, it might
7043 * have destroyed the connection as well,
7044 * which screws up the linked lists.
7050 if (conn->type == RX_SERVER_CONNECTION) {
7051 /* This only actually destroys the connection if
7052 * there are no outstanding calls */
7053 MUTEX_ENTER(&conn->conn_data_lock);
7054 MUTEX_ENTER(&rx_refcnt_mutex);
7055 if (!havecalls && !conn->refCount
7056 && ((conn->lastSendTime + rx_idleConnectionTime) <
7058 conn->refCount++; /* it will be decr in rx_DestroyConn */
7059 MUTEX_EXIT(&rx_refcnt_mutex);
7060 MUTEX_EXIT(&conn->conn_data_lock);
7061 #ifdef RX_ENABLE_LOCKS
7062 rxi_DestroyConnectionNoLock(conn);
7063 #else /* RX_ENABLE_LOCKS */
7064 rxi_DestroyConnection(conn);
7065 #endif /* RX_ENABLE_LOCKS */
7067 #ifdef RX_ENABLE_LOCKS
7069 MUTEX_EXIT(&rx_refcnt_mutex);
7070 MUTEX_EXIT(&conn->conn_data_lock);
7072 #endif /* RX_ENABLE_LOCKS */
7076 #ifdef RX_ENABLE_LOCKS
7077 while (rx_connCleanup_list) {
7078 struct rx_connection *conn;
7079 conn = rx_connCleanup_list;
7080 rx_connCleanup_list = rx_connCleanup_list->next;
7081 MUTEX_EXIT(&rx_connHashTable_lock);
7082 rxi_CleanupConnection(conn);
7083 MUTEX_ENTER(&rx_connHashTable_lock);
7085 MUTEX_EXIT(&rx_connHashTable_lock);
7086 #endif /* RX_ENABLE_LOCKS */
7089 /* Find any peer structures that haven't been used (haven't had an
7090 * associated connection) for greater than rx_idlePeerTime */
7092 struct rx_peer **peer_ptr, **peer_end;
7096 * Why do we need to hold the rx_peerHashTable_lock across
7097 * the incrementing of peer_ptr since the rx_peerHashTable
7098 * array is not changing? We don't.
7100 * By dropping the lock periodically we can permit other
7101 * activities to be performed while a rxi_ReapConnections
7102 * call is in progress. The goal of reap connections
7103 * is to clean up quickly without causing large amounts
7104 * of contention. Therefore, it is important that global
7105 * mutexes not be held for extended periods of time.
7107 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7108 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7110 struct rx_peer *peer, *next, *prev;
7112 MUTEX_ENTER(&rx_peerHashTable_lock);
7113 for (prev = peer = *peer_ptr; peer; peer = next) {
7115 code = MUTEX_TRYENTER(&peer->peer_lock);
7116 if ((code) && (peer->refCount == 0)
7117 && ((peer->idleWhen + rx_idlePeerTime) < now.sec)) {
7118 struct opr_queue *cursor, *store;
7122 * now know that this peer object is one to be
7123 * removed from the hash table. Once it is removed
7124 * it can't be referenced by other threads.
7125 * Lets remove it first and decrement the struct
7126 * nPeerStructs count.
7128 if (peer == *peer_ptr) {
7134 if (rx_stats_active)
7135 rx_atomic_dec(&rx_stats.nPeerStructs);
7138 * Now if we hold references on 'prev' and 'next'
7139 * we can safely drop the rx_peerHashTable_lock
7140 * while we destroy this 'peer' object.
7146 MUTEX_EXIT(&rx_peerHashTable_lock);
7148 MUTEX_EXIT(&peer->peer_lock);
7149 MUTEX_DESTROY(&peer->peer_lock);
7151 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
7152 unsigned int num_funcs;
7153 struct rx_interface_stat *rpc_stat
7154 = opr_queue_Entry(cursor, struct rx_interface_stat,
7159 opr_queue_Remove(&rpc_stat->entry);
7160 opr_queue_Remove(&rpc_stat->entryPeers);
7162 num_funcs = rpc_stat->stats[0].func_total;
7164 sizeof(rx_interface_stat_t) +
7165 rpc_stat->stats[0].func_total *
7166 sizeof(rx_function_entry_v1_t);
7168 rxi_Free(rpc_stat, space);
7170 MUTEX_ENTER(&rx_rpc_stats);
7171 rxi_rpc_peer_stat_cnt -= num_funcs;
7172 MUTEX_EXIT(&rx_rpc_stats);
7177 * Regain the rx_peerHashTable_lock and
7178 * decrement the reference count on 'prev'
7181 MUTEX_ENTER(&rx_peerHashTable_lock);
7188 MUTEX_EXIT(&peer->peer_lock);
7193 MUTEX_EXIT(&rx_peerHashTable_lock);
7197 /* THIS HACK IS A TEMPORARY HACK. The idea is that the race condition in
7198 * rxi_AllocSendPacket, if it hits, will be handled at the next conn
7199 * GC, just below. Really, we shouldn't have to keep moving packets from
7200 * one place to another, but instead ought to always know if we can
7201 * afford to hold onto a packet in its particular use. */
7202 MUTEX_ENTER(&rx_freePktQ_lock);
7203 if (rx_waitingForPackets) {
7204 rx_waitingForPackets = 0;
7205 #ifdef RX_ENABLE_LOCKS
7206 CV_BROADCAST(&rx_waitingForPackets_cv);
7208 osi_rxWakeup(&rx_waitingForPackets);
7211 MUTEX_EXIT(&rx_freePktQ_lock);
7214 when.sec += RX_REAP_TIME; /* Check every RX_REAP_TIME seconds */
7215 event = rxevent_Post(&when, &now, rxi_ReapConnections, 0, NULL, 0);
7216 rxevent_Put(&event);
7220 /* rxs_Release - This isn't strictly necessary but, since the macro name from
7221 * rx.h is sort of strange this is better. This is called with a security
7222 * object before it is discarded. Each connection using a security object has
7223 * its own refcount to the object so it won't actually be freed until the last
7224 * connection is destroyed.
7226 * This is the only rxs module call. A hold could also be written but no one
7230 rxs_Release(struct rx_securityClass *aobj)
7232 return RXS_Close(aobj);
7240 #define TRACE_OPTION_RX_DEBUG 16
7248 code = RegOpenKeyEx(HKEY_LOCAL_MACHINE, AFSREG_CLT_SVC_PARAM_SUBKEY,
7249 0, KEY_QUERY_VALUE, &parmKey);
7250 if (code != ERROR_SUCCESS)
7253 dummyLen = sizeof(TraceOption);
7254 code = RegQueryValueEx(parmKey, "TraceOption", NULL, NULL,
7255 (BYTE *) &TraceOption, &dummyLen);
7256 if (code == ERROR_SUCCESS) {
7257 rxdebug_active = (TraceOption & TRACE_OPTION_RX_DEBUG) ? 1 : 0;
7259 RegCloseKey (parmKey);
7260 #endif /* AFS_NT40_ENV */
7265 rx_DebugOnOff(int on)
7269 rxdebug_active = on;
7275 rx_StatsOnOff(int on)
7277 rx_stats_active = on;
7281 /* Don't call this debugging routine directly; use dpf */
7283 rxi_DebugPrint(char *format, ...)
7292 va_start(ap, format);
7294 len = _snprintf(tformat, sizeof(tformat), "tid[%d] %s", GetCurrentThreadId(), format);
7297 len = _vsnprintf(msg, sizeof(msg)-2, tformat, ap);
7299 OutputDebugString(msg);
7305 va_start(ap, format);
7307 clock_GetTime(&now);
7308 fprintf(rx_Log, " %d.%06d:", (unsigned int)now.sec,
7309 (unsigned int)now.usec);
7310 vfprintf(rx_Log, format, ap);
7318 * This function is used to process the rx_stats structure that is local
7319 * to a process as well as an rx_stats structure received from a remote
7320 * process (via rxdebug). Therefore, it needs to do minimal version
7324 rx_PrintTheseStats(FILE * file, struct rx_statistics *s, int size,
7325 afs_int32 freePackets, char version)
7329 if (size != sizeof(struct rx_statistics)) {
7331 "Unexpected size of stats structure: was %d, expected %" AFS_SIZET_FMT "\n",
7332 size, sizeof(struct rx_statistics));
7335 fprintf(file, "rx stats: free packets %d, allocs %d, ", (int)freePackets,
7338 if (version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7339 fprintf(file, "alloc-failures(rcv %u/%u,send %u/%u,ack %u)\n",
7340 s->receivePktAllocFailures, s->receiveCbufPktAllocFailures,
7341 s->sendPktAllocFailures, s->sendCbufPktAllocFailures,
7342 s->specialPktAllocFailures);
7344 fprintf(file, "alloc-failures(rcv %u,send %u,ack %u)\n",
7345 s->receivePktAllocFailures, s->sendPktAllocFailures,
7346 s->specialPktAllocFailures);
7350 " greedy %u, " "bogusReads %u (last from host %x), "
7351 "noPackets %u, " "noBuffers %u, " "selects %u, "
7352 "sendSelects %u\n", s->socketGreedy, s->bogusPacketOnRead,
7353 s->bogusHost, s->noPacketOnRead, s->noPacketBuffersOnRead,
7354 s->selects, s->sendSelects);
7356 fprintf(file, " packets read: ");
7357 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7358 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsRead[i]);
7360 fprintf(file, "\n");
7363 " other read counters: data %u, " "ack %u, " "dup %u "
7364 "spurious %u " "dally %u\n", s->dataPacketsRead,
7365 s->ackPacketsRead, s->dupPacketsRead, s->spuriousPacketsRead,
7366 s->ignorePacketDally);
7368 fprintf(file, " packets sent: ");
7369 for (i = 0; i < RX_N_PACKET_TYPES; i++) {
7370 fprintf(file, "%s %u ", rx_packetTypes[i], s->packetsSent[i]);
7372 fprintf(file, "\n");
7375 " other send counters: ack %u, " "data %u (not resends), "
7376 "resends %u, " "pushed %u, " "acked&ignored %u\n",
7377 s->ackPacketsSent, s->dataPacketsSent, s->dataPacketsReSent,
7378 s->dataPacketsPushed, s->ignoreAckedPacket);
7381 " \t(these should be small) sendFailed %u, " "fatalErrors %u\n",
7382 s->netSendFailures, (int)s->fatalErrors);
7384 if (s->nRttSamples) {
7385 fprintf(file, " Average rtt is %0.3f, with %d samples\n",
7386 clock_Float(&s->totalRtt) / s->nRttSamples, s->nRttSamples);
7388 fprintf(file, " Minimum rtt is %0.3f, maximum is %0.3f\n",
7389 clock_Float(&s->minRtt), clock_Float(&s->maxRtt));
7393 " %d server connections, " "%d client connections, "
7394 "%d peer structs, " "%d call structs, " "%d free call structs\n",
7395 s->nServerConns, s->nClientConns, s->nPeerStructs,
7396 s->nCallStructs, s->nFreeCallStructs);
7398 #if !defined(AFS_PTHREAD_ENV) && !defined(AFS_USE_GETTIMEOFDAY)
7399 fprintf(file, " %d clock updates\n", clock_nUpdates);
7403 /* for backward compatibility */
7405 rx_PrintStats(FILE * file)
7407 MUTEX_ENTER(&rx_stats_mutex);
7408 rx_PrintTheseStats(file, (struct rx_statistics *) &rx_stats,
7409 sizeof(rx_stats), rx_nFreePackets,
7411 MUTEX_EXIT(&rx_stats_mutex);
7415 rx_PrintPeerStats(FILE * file, struct rx_peer *peer)
7417 fprintf(file, "Peer %x.%d.\n",
7418 ntohl(peer->host), (int)ntohs(peer->port));
7421 " Rtt %d, " "total sent %d, " "resent %d\n",
7422 peer->rtt, peer->nSent, peer->reSends);
7424 fprintf(file, " Packet size %d\n", peer->ifMTU);
7428 #if defined(AFS_PTHREAD_ENV) && defined(RXDEBUG)
7430 * This mutex protects the following static variables:
7434 #define LOCK_RX_DEBUG MUTEX_ENTER(&rx_debug_mutex)
7435 #define UNLOCK_RX_DEBUG MUTEX_EXIT(&rx_debug_mutex)
7437 #define LOCK_RX_DEBUG
7438 #define UNLOCK_RX_DEBUG
7439 #endif /* AFS_PTHREAD_ENV */
7441 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7443 MakeDebugCall(osi_socket socket, afs_uint32 remoteAddr, afs_uint16 remotePort,
7444 u_char type, void *inputData, size_t inputLength,
7445 void *outputData, size_t outputLength)
7447 static afs_int32 counter = 100;
7448 time_t waitTime, waitCount;
7449 struct rx_header theader;
7452 struct timeval tv_now, tv_wake, tv_delta;
7453 struct sockaddr_in taddr, faddr;
7467 tp = &tbuffer[sizeof(struct rx_header)];
7468 taddr.sin_family = AF_INET;
7469 taddr.sin_port = remotePort;
7470 taddr.sin_addr.s_addr = remoteAddr;
7471 memset(&taddr.sin_zero, 0, sizeof(taddr.sin_zero));
7472 #ifdef STRUCT_SOCKADDR_HAS_SA_LEN
7473 taddr.sin_len = sizeof(struct sockaddr_in);
7476 memset(&theader, 0, sizeof(theader));
7477 theader.epoch = htonl(999);
7479 theader.callNumber = htonl(counter);
7482 theader.type = type;
7483 theader.flags = RX_CLIENT_INITIATED | RX_LAST_PACKET;
7484 theader.serviceId = 0;
7486 memcpy(tbuffer, &theader, sizeof(theader));
7487 memcpy(tp, inputData, inputLength);
7489 sendto(socket, tbuffer, inputLength + sizeof(struct rx_header), 0,
7490 (struct sockaddr *)&taddr, sizeof(struct sockaddr_in));
7492 /* see if there's a packet available */
7493 gettimeofday(&tv_wake, NULL);
7494 tv_wake.tv_sec += waitTime;
7497 FD_SET(socket, &imask);
7498 tv_delta.tv_sec = tv_wake.tv_sec;
7499 tv_delta.tv_usec = tv_wake.tv_usec;
7500 gettimeofday(&tv_now, NULL);
7502 if (tv_delta.tv_usec < tv_now.tv_usec) {
7504 tv_delta.tv_usec += 1000000;
7507 tv_delta.tv_usec -= tv_now.tv_usec;
7509 if (tv_delta.tv_sec < tv_now.tv_sec) {
7513 tv_delta.tv_sec -= tv_now.tv_sec;
7516 code = select(0, &imask, 0, 0, &tv_delta);
7517 #else /* AFS_NT40_ENV */
7518 code = select(socket + 1, &imask, 0, 0, &tv_delta);
7519 #endif /* AFS_NT40_ENV */
7520 if (code == 1 && FD_ISSET(socket, &imask)) {
7521 /* now receive a packet */
7522 faddrLen = sizeof(struct sockaddr_in);
7524 recvfrom(socket, tbuffer, sizeof(tbuffer), 0,
7525 (struct sockaddr *)&faddr, &faddrLen);
7528 memcpy(&theader, tbuffer, sizeof(struct rx_header));
7529 if (counter == ntohl(theader.callNumber))
7537 /* see if we've timed out */
7545 code -= sizeof(struct rx_header);
7546 if (code > outputLength)
7547 code = outputLength;
7548 memcpy(outputData, tp, code);
7551 #endif /* RXDEBUG */
7554 rx_GetServerDebug(osi_socket socket, afs_uint32 remoteAddr,
7555 afs_uint16 remotePort, struct rx_debugStats * stat,
7556 afs_uint32 * supportedValues)
7558 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7560 struct rx_debugIn in;
7562 *supportedValues = 0;
7563 in.type = htonl(RX_DEBUGI_GETSTATS);
7566 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7567 &in, sizeof(in), stat, sizeof(*stat));
7570 * If the call was successful, fixup the version and indicate
7571 * what contents of the stat structure are valid.
7572 * Also do net to host conversion of fields here.
7576 if (stat->version >= RX_DEBUGI_VERSION_W_SECSTATS) {
7577 *supportedValues |= RX_SERVER_DEBUG_SEC_STATS;
7579 if (stat->version >= RX_DEBUGI_VERSION_W_GETALLCONN) {
7580 *supportedValues |= RX_SERVER_DEBUG_ALL_CONN;
7582 if (stat->version >= RX_DEBUGI_VERSION_W_RXSTATS) {
7583 *supportedValues |= RX_SERVER_DEBUG_RX_STATS;
7585 if (stat->version >= RX_DEBUGI_VERSION_W_WAITERS) {
7586 *supportedValues |= RX_SERVER_DEBUG_WAITER_CNT;
7588 if (stat->version >= RX_DEBUGI_VERSION_W_IDLETHREADS) {
7589 *supportedValues |= RX_SERVER_DEBUG_IDLE_THREADS;
7591 if (stat->version >= RX_DEBUGI_VERSION_W_NEWPACKETTYPES) {
7592 *supportedValues |= RX_SERVER_DEBUG_NEW_PACKETS;
7594 if (stat->version >= RX_DEBUGI_VERSION_W_GETPEER) {
7595 *supportedValues |= RX_SERVER_DEBUG_ALL_PEER;
7597 if (stat->version >= RX_DEBUGI_VERSION_W_WAITED) {
7598 *supportedValues |= RX_SERVER_DEBUG_WAITED_CNT;
7600 if (stat->version >= RX_DEBUGI_VERSION_W_PACKETS) {
7601 *supportedValues |= RX_SERVER_DEBUG_PACKETS_CNT;
7603 stat->nFreePackets = ntohl(stat->nFreePackets);
7604 stat->packetReclaims = ntohl(stat->packetReclaims);
7605 stat->callsExecuted = ntohl(stat->callsExecuted);
7606 stat->nWaiting = ntohl(stat->nWaiting);
7607 stat->idleThreads = ntohl(stat->idleThreads);
7608 stat->nWaited = ntohl(stat->nWaited);
7609 stat->nPackets = ntohl(stat->nPackets);
7618 rx_GetServerStats(osi_socket socket, afs_uint32 remoteAddr,
7619 afs_uint16 remotePort, struct rx_statistics * stat,
7620 afs_uint32 * supportedValues)
7622 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7624 struct rx_debugIn in;
7625 afs_int32 *lp = (afs_int32 *) stat;
7629 * supportedValues is currently unused, but added to allow future
7630 * versioning of this function.
7633 *supportedValues = 0;
7634 in.type = htonl(RX_DEBUGI_RXSTATS);
7636 memset(stat, 0, sizeof(*stat));
7638 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7639 &in, sizeof(in), stat, sizeof(*stat));
7644 * Do net to host conversion here
7647 for (i = 0; i < sizeof(*stat) / sizeof(afs_int32); i++, lp++) {
7658 rx_GetServerVersion(osi_socket socket, afs_uint32 remoteAddr,
7659 afs_uint16 remotePort, size_t version_length,
7662 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7664 return MakeDebugCall(socket, remoteAddr, remotePort,
7665 RX_PACKET_TYPE_VERSION, a, 1, version,
7673 rx_GetServerConnections(osi_socket socket, afs_uint32 remoteAddr,
7674 afs_uint16 remotePort, afs_int32 * nextConnection,
7675 int allConnections, afs_uint32 debugSupportedValues,
7676 struct rx_debugConn * conn,
7677 afs_uint32 * supportedValues)
7679 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7681 struct rx_debugIn in;
7685 * supportedValues is currently unused, but added to allow future
7686 * versioning of this function.
7689 *supportedValues = 0;
7690 if (allConnections) {
7691 in.type = htonl(RX_DEBUGI_GETALLCONN);
7693 in.type = htonl(RX_DEBUGI_GETCONN);
7695 in.index = htonl(*nextConnection);
7696 memset(conn, 0, sizeof(*conn));
7698 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7699 &in, sizeof(in), conn, sizeof(*conn));
7702 *nextConnection += 1;
7705 * Convert old connection format to new structure.
7708 if (debugSupportedValues & RX_SERVER_DEBUG_OLD_CONN) {
7709 struct rx_debugConn_vL *vL = (struct rx_debugConn_vL *)conn;
7710 #define MOVEvL(a) (conn->a = vL->a)
7712 /* any old or unrecognized version... */
7713 for (i = 0; i < RX_MAXCALLS; i++) {
7714 MOVEvL(callState[i]);
7715 MOVEvL(callMode[i]);
7716 MOVEvL(callFlags[i]);
7717 MOVEvL(callOther[i]);
7719 if (debugSupportedValues & RX_SERVER_DEBUG_SEC_STATS) {
7720 MOVEvL(secStats.type);
7721 MOVEvL(secStats.level);
7722 MOVEvL(secStats.flags);
7723 MOVEvL(secStats.expires);
7724 MOVEvL(secStats.packetsReceived);
7725 MOVEvL(secStats.packetsSent);
7726 MOVEvL(secStats.bytesReceived);
7727 MOVEvL(secStats.bytesSent);
7732 * Do net to host conversion here
7734 * I don't convert host or port since we are most likely
7735 * going to want these in NBO.
7737 conn->cid = ntohl(conn->cid);
7738 conn->serial = ntohl(conn->serial);
7739 for (i = 0; i < RX_MAXCALLS; i++) {
7740 conn->callNumber[i] = ntohl(conn->callNumber[i]);
7742 conn->error = ntohl(conn->error);
7743 conn->secStats.flags = ntohl(conn->secStats.flags);
7744 conn->secStats.expires = ntohl(conn->secStats.expires);
7745 conn->secStats.packetsReceived =
7746 ntohl(conn->secStats.packetsReceived);
7747 conn->secStats.packetsSent = ntohl(conn->secStats.packetsSent);
7748 conn->secStats.bytesReceived = ntohl(conn->secStats.bytesReceived);
7749 conn->secStats.bytesSent = ntohl(conn->secStats.bytesSent);
7750 conn->epoch = ntohl(conn->epoch);
7751 conn->natMTU = ntohl(conn->natMTU);
7760 rx_GetServerPeers(osi_socket socket, afs_uint32 remoteAddr,
7761 afs_uint16 remotePort, afs_int32 * nextPeer,
7762 afs_uint32 debugSupportedValues, struct rx_debugPeer * peer,
7763 afs_uint32 * supportedValues)
7765 #if defined(RXDEBUG) || defined(MAKEDEBUGCALL)
7767 struct rx_debugIn in;
7770 * supportedValues is currently unused, but added to allow future
7771 * versioning of this function.
7774 *supportedValues = 0;
7775 in.type = htonl(RX_DEBUGI_GETPEER);
7776 in.index = htonl(*nextPeer);
7777 memset(peer, 0, sizeof(*peer));
7779 rc = MakeDebugCall(socket, remoteAddr, remotePort, RX_PACKET_TYPE_DEBUG,
7780 &in, sizeof(in), peer, sizeof(*peer));
7786 * Do net to host conversion here
7788 * I don't convert host or port since we are most likely
7789 * going to want these in NBO.
7791 peer->ifMTU = ntohs(peer->ifMTU);
7792 peer->idleWhen = ntohl(peer->idleWhen);
7793 peer->refCount = ntohs(peer->refCount);
7794 peer->rtt = ntohl(peer->rtt);
7795 peer->rtt_dev = ntohl(peer->rtt_dev);
7796 peer->timeout.sec = 0;
7797 peer->timeout.usec = 0;
7798 peer->nSent = ntohl(peer->nSent);
7799 peer->reSends = ntohl(peer->reSends);
7800 peer->natMTU = ntohs(peer->natMTU);
7801 peer->maxMTU = ntohs(peer->maxMTU);
7802 peer->maxDgramPackets = ntohs(peer->maxDgramPackets);
7803 peer->ifDgramPackets = ntohs(peer->ifDgramPackets);
7804 peer->MTU = ntohs(peer->MTU);
7805 peer->cwind = ntohs(peer->cwind);
7806 peer->nDgramPackets = ntohs(peer->nDgramPackets);
7807 peer->congestSeq = ntohs(peer->congestSeq);
7808 peer->bytesSent.high = ntohl(peer->bytesSent.high);
7809 peer->bytesSent.low = ntohl(peer->bytesSent.low);
7810 peer->bytesReceived.high = ntohl(peer->bytesReceived.high);
7811 peer->bytesReceived.low = ntohl(peer->bytesReceived.low);
7820 rx_GetLocalPeers(afs_uint32 peerHost, afs_uint16 peerPort,
7821 struct rx_debugPeer * peerStats)
7824 afs_int32 error = 1; /* default to "did not succeed" */
7825 afs_uint32 hashValue = PEER_HASH(peerHost, peerPort);
7827 MUTEX_ENTER(&rx_peerHashTable_lock);
7828 for(tp = rx_peerHashTable[hashValue];
7829 tp != NULL; tp = tp->next) {
7830 if (tp->host == peerHost)
7836 MUTEX_EXIT(&rx_peerHashTable_lock);
7840 MUTEX_ENTER(&tp->peer_lock);
7841 peerStats->host = tp->host;
7842 peerStats->port = tp->port;
7843 peerStats->ifMTU = tp->ifMTU;
7844 peerStats->idleWhen = tp->idleWhen;
7845 peerStats->refCount = tp->refCount;
7846 peerStats->burstSize = 0;
7847 peerStats->burst = 0;
7848 peerStats->burstWait.sec = 0;
7849 peerStats->burstWait.usec = 0;
7850 peerStats->rtt = tp->rtt;
7851 peerStats->rtt_dev = tp->rtt_dev;
7852 peerStats->timeout.sec = 0;
7853 peerStats->timeout.usec = 0;
7854 peerStats->nSent = tp->nSent;
7855 peerStats->reSends = tp->reSends;
7856 peerStats->natMTU = tp->natMTU;
7857 peerStats->maxMTU = tp->maxMTU;
7858 peerStats->maxDgramPackets = tp->maxDgramPackets;
7859 peerStats->ifDgramPackets = tp->ifDgramPackets;
7860 peerStats->MTU = tp->MTU;
7861 peerStats->cwind = tp->cwind;
7862 peerStats->nDgramPackets = tp->nDgramPackets;
7863 peerStats->congestSeq = tp->congestSeq;
7864 peerStats->bytesSent.high = tp->bytesSent >> 32;
7865 peerStats->bytesSent.low = tp->bytesSent & MAX_AFS_UINT32;
7866 peerStats->bytesReceived.high = tp->bytesReceived >> 32;
7867 peerStats->bytesReceived.low
7868 = tp->bytesReceived & MAX_AFS_UINT32;
7869 MUTEX_EXIT(&tp->peer_lock);
7871 MUTEX_ENTER(&rx_peerHashTable_lock);
7874 MUTEX_EXIT(&rx_peerHashTable_lock);
7882 struct rx_serverQueueEntry *np;
7885 struct rx_call *call;
7886 struct rx_serverQueueEntry *sq;
7890 if (!rxi_IsRunning()) {
7892 return; /* Already shutdown. */
7894 rx_atomic_set(&rxi_running, 0);
7897 #ifndef AFS_PTHREAD_ENV
7898 FD_ZERO(&rx_selectMask);
7899 #endif /* AFS_PTHREAD_ENV */
7900 rxi_dataQuota = RX_MAX_QUOTA;
7901 #ifndef AFS_PTHREAD_ENV
7903 #endif /* AFS_PTHREAD_ENV */
7906 #ifndef AFS_PTHREAD_ENV
7907 #ifndef AFS_USE_GETTIMEOFDAY
7909 #endif /* AFS_USE_GETTIMEOFDAY */
7910 #endif /* AFS_PTHREAD_ENV */
7912 while (!opr_queue_IsEmpty(&rx_freeCallQueue)) {
7913 call = opr_queue_First(&rx_freeCallQueue, struct rx_call, entry);
7914 opr_queue_Remove(&call->entry);
7915 rxi_Free(call, sizeof(struct rx_call));
7918 while (!opr_queue_IsEmpty(&rx_idleServerQueue)) {
7919 sq = opr_queue_First(&rx_idleServerQueue, struct rx_serverQueueEntry,
7921 opr_queue_Remove(&sq->entry);
7926 struct rx_peer **peer_ptr, **peer_end;
7927 for (peer_ptr = &rx_peerHashTable[0], peer_end =
7928 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
7930 struct rx_peer *peer, *next;
7932 MUTEX_ENTER(&rx_peerHashTable_lock);
7933 for (peer = *peer_ptr; peer; peer = next) {
7934 struct opr_queue *cursor, *store;
7937 MUTEX_ENTER(&rx_rpc_stats);
7938 MUTEX_ENTER(&peer->peer_lock);
7939 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
7940 unsigned int num_funcs;
7941 struct rx_interface_stat *rpc_stat
7942 = opr_queue_Entry(cursor, struct rx_interface_stat,
7946 opr_queue_Remove(&rpc_stat->entry);
7947 opr_queue_Remove(&rpc_stat->entryPeers);
7948 num_funcs = rpc_stat->stats[0].func_total;
7950 sizeof(rx_interface_stat_t) +
7951 rpc_stat->stats[0].func_total *
7952 sizeof(rx_function_entry_v1_t);
7954 rxi_Free(rpc_stat, space);
7956 /* rx_rpc_stats must be held */
7957 rxi_rpc_peer_stat_cnt -= num_funcs;
7959 MUTEX_EXIT(&peer->peer_lock);
7960 MUTEX_EXIT(&rx_rpc_stats);
7964 if (rx_stats_active)
7965 rx_atomic_dec(&rx_stats.nPeerStructs);
7967 MUTEX_EXIT(&rx_peerHashTable_lock);
7970 for (i = 0; i < RX_MAX_SERVICES; i++) {
7972 rxi_Free(rx_services[i], sizeof(*rx_services[i]));
7974 for (i = 0; i < rx_hashTableSize; i++) {
7975 struct rx_connection *tc, *ntc;
7976 MUTEX_ENTER(&rx_connHashTable_lock);
7977 for (tc = rx_connHashTable[i]; tc; tc = ntc) {
7979 for (j = 0; j < RX_MAXCALLS; j++) {
7981 rxi_Free(tc->call[j], sizeof(*tc->call[j]));
7984 rxi_Free(tc, sizeof(*tc));
7986 MUTEX_EXIT(&rx_connHashTable_lock);
7989 MUTEX_ENTER(&freeSQEList_lock);
7991 while ((np = rx_FreeSQEList)) {
7992 rx_FreeSQEList = *(struct rx_serverQueueEntry **)np;
7993 MUTEX_DESTROY(&np->lock);
7994 rxi_Free(np, sizeof(*np));
7997 MUTEX_EXIT(&freeSQEList_lock);
7998 MUTEX_DESTROY(&freeSQEList_lock);
7999 MUTEX_DESTROY(&rx_freeCallQueue_lock);
8000 MUTEX_DESTROY(&rx_connHashTable_lock);
8001 MUTEX_DESTROY(&rx_peerHashTable_lock);
8002 MUTEX_DESTROY(&rx_serverPool_lock);
8004 osi_Free(rx_connHashTable,
8005 rx_hashTableSize * sizeof(struct rx_connection *));
8006 osi_Free(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
8008 UNPIN(rx_connHashTable,
8009 rx_hashTableSize * sizeof(struct rx_connection *));
8010 UNPIN(rx_peerHashTable, rx_hashTableSize * sizeof(struct rx_peer *));
8012 MUTEX_ENTER(&rx_quota_mutex);
8013 rxi_dataQuota = RX_MAX_QUOTA;
8014 rxi_availProcs = rxi_totalMin = rxi_minDeficit = 0;
8015 MUTEX_EXIT(&rx_quota_mutex);
8022 * Routines to implement connection specific data.
8026 rx_KeyCreate(rx_destructor_t rtn)
8029 MUTEX_ENTER(&rxi_keyCreate_lock);
8030 key = rxi_keyCreate_counter++;
8031 rxi_keyCreate_destructor = (rx_destructor_t *)
8032 realloc((void *)rxi_keyCreate_destructor,
8033 (key + 1) * sizeof(rx_destructor_t));
8034 rxi_keyCreate_destructor[key] = rtn;
8035 MUTEX_EXIT(&rxi_keyCreate_lock);
8040 rx_SetSpecific(struct rx_connection *conn, int key, void *ptr)
8043 MUTEX_ENTER(&conn->conn_data_lock);
8044 if (!conn->specific) {
8045 conn->specific = malloc((key + 1) * sizeof(void *));
8046 for (i = 0; i < key; i++)
8047 conn->specific[i] = NULL;
8048 conn->nSpecific = key + 1;
8049 conn->specific[key] = ptr;
8050 } else if (key >= conn->nSpecific) {
8051 conn->specific = (void **)
8052 realloc(conn->specific, (key + 1) * sizeof(void *));
8053 for (i = conn->nSpecific; i < key; i++)
8054 conn->specific[i] = NULL;
8055 conn->nSpecific = key + 1;
8056 conn->specific[key] = ptr;
8058 if (conn->specific[key] && rxi_keyCreate_destructor[key])
8059 (*rxi_keyCreate_destructor[key]) (conn->specific[key]);
8060 conn->specific[key] = ptr;
8062 MUTEX_EXIT(&conn->conn_data_lock);
8066 rx_SetServiceSpecific(struct rx_service *svc, int key, void *ptr)
8069 MUTEX_ENTER(&svc->svc_data_lock);
8070 if (!svc->specific) {
8071 svc->specific = malloc((key + 1) * sizeof(void *));
8072 for (i = 0; i < key; i++)
8073 svc->specific[i] = NULL;
8074 svc->nSpecific = key + 1;
8075 svc->specific[key] = ptr;
8076 } else if (key >= svc->nSpecific) {
8077 svc->specific = (void **)
8078 realloc(svc->specific, (key + 1) * sizeof(void *));
8079 for (i = svc->nSpecific; i < key; i++)
8080 svc->specific[i] = NULL;
8081 svc->nSpecific = key + 1;
8082 svc->specific[key] = ptr;
8084 if (svc->specific[key] && rxi_keyCreate_destructor[key])
8085 (*rxi_keyCreate_destructor[key]) (svc->specific[key]);
8086 svc->specific[key] = ptr;
8088 MUTEX_EXIT(&svc->svc_data_lock);
8092 rx_GetSpecific(struct rx_connection *conn, int key)
8095 MUTEX_ENTER(&conn->conn_data_lock);
8096 if (key >= conn->nSpecific)
8099 ptr = conn->specific[key];
8100 MUTEX_EXIT(&conn->conn_data_lock);
8105 rx_GetServiceSpecific(struct rx_service *svc, int key)
8108 MUTEX_ENTER(&svc->svc_data_lock);
8109 if (key >= svc->nSpecific)
8112 ptr = svc->specific[key];
8113 MUTEX_EXIT(&svc->svc_data_lock);
8118 #endif /* !KERNEL */
8121 * processStats is a queue used to store the statistics for the local
8122 * process. Its contents are similar to the contents of the rpcStats
8123 * queue on a rx_peer structure, but the actual data stored within
8124 * this queue contains totals across the lifetime of the process (assuming
8125 * the stats have not been reset) - unlike the per peer structures
8126 * which can come and go based upon the peer lifetime.
8129 static struct opr_queue processStats = { &processStats, &processStats };
8132 * peerStats is a queue used to store the statistics for all peer structs.
8133 * Its contents are the union of all the peer rpcStats queues.
8136 static struct opr_queue peerStats = { &peerStats, &peerStats };
8139 * rxi_monitor_processStats is used to turn process wide stat collection
8143 static int rxi_monitor_processStats = 0;
8146 * rxi_monitor_peerStats is used to turn per peer stat collection on and off
8149 static int rxi_monitor_peerStats = 0;
8153 rxi_ClearRPCOpStat(rx_function_entry_v1_p rpc_stat)
8155 rpc_stat->invocations = 0;
8156 rpc_stat->bytes_sent = 0;
8157 rpc_stat->bytes_rcvd = 0;
8158 rpc_stat->queue_time_sum.sec = 0;
8159 rpc_stat->queue_time_sum.usec = 0;
8160 rpc_stat->queue_time_sum_sqr.sec = 0;
8161 rpc_stat->queue_time_sum_sqr.usec = 0;
8162 rpc_stat->queue_time_min.sec = 9999999;
8163 rpc_stat->queue_time_min.usec = 9999999;
8164 rpc_stat->queue_time_max.sec = 0;
8165 rpc_stat->queue_time_max.usec = 0;
8166 rpc_stat->execution_time_sum.sec = 0;
8167 rpc_stat->execution_time_sum.usec = 0;
8168 rpc_stat->execution_time_sum_sqr.sec = 0;
8169 rpc_stat->execution_time_sum_sqr.usec = 0;
8170 rpc_stat->execution_time_min.sec = 9999999;
8171 rpc_stat->execution_time_min.usec = 9999999;
8172 rpc_stat->execution_time_max.sec = 0;
8173 rpc_stat->execution_time_max.usec = 0;
8177 * Given all of the information for a particular rpc
8178 * call, find or create (if requested) the stat structure for the rpc.
8181 * the queue of stats that will be updated with the new value
8183 * @param rxInterface
8184 * a unique number that identifies the rpc interface
8187 * the total number of functions in this interface. this is only
8188 * required if create is true
8191 * if true, this invocation was made to a server
8194 * the ip address of the remote host. this is only required if create
8195 * and addToPeerList are true
8198 * the port of the remote host. this is only required if create
8199 * and addToPeerList are true
8201 * @param addToPeerList
8202 * if != 0, add newly created stat to the global peer list
8205 * if a new stats structure is allocated, the counter will
8206 * be updated with the new number of allocated stat structures.
8207 * only required if create is true
8210 * if no stats structure exists, allocate one
8214 static rx_interface_stat_p
8215 rxi_FindRpcStat(struct opr_queue *stats, afs_uint32 rxInterface,
8216 afs_uint32 totalFunc, int isServer, afs_uint32 remoteHost,
8217 afs_uint32 remotePort, int addToPeerList,
8218 unsigned int *counter, int create)
8220 rx_interface_stat_p rpc_stat = NULL;
8221 struct opr_queue *cursor;
8224 * See if there's already a structure for this interface
8227 for (opr_queue_Scan(stats, cursor)) {
8228 rpc_stat = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8230 if ((rpc_stat->stats[0].interfaceId == rxInterface)
8231 && (rpc_stat->stats[0].remote_is_server == isServer))
8235 /* if they didn't ask us to create, we're done */
8237 if (opr_queue_IsEnd(stats, cursor))
8243 /* can't proceed without these */
8244 if (!totalFunc || !counter)
8248 * Didn't find a match so allocate a new structure and add it to the
8252 if (opr_queue_IsEnd(stats, cursor) || (rpc_stat == NULL)
8253 || (rpc_stat->stats[0].interfaceId != rxInterface)
8254 || (rpc_stat->stats[0].remote_is_server != isServer)) {
8259 sizeof(rx_interface_stat_t) +
8260 totalFunc * sizeof(rx_function_entry_v1_t);
8262 rpc_stat = rxi_Alloc(space);
8263 if (rpc_stat == NULL)
8266 *counter += totalFunc;
8267 for (i = 0; i < totalFunc; i++) {
8268 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8269 rpc_stat->stats[i].remote_peer = remoteHost;
8270 rpc_stat->stats[i].remote_port = remotePort;
8271 rpc_stat->stats[i].remote_is_server = isServer;
8272 rpc_stat->stats[i].interfaceId = rxInterface;
8273 rpc_stat->stats[i].func_total = totalFunc;
8274 rpc_stat->stats[i].func_index = i;
8276 opr_queue_Prepend(stats, &rpc_stat->entry);
8277 if (addToPeerList) {
8278 opr_queue_Prepend(&peerStats, &rpc_stat->entryPeers);
8285 rx_ClearProcessRPCStats(afs_int32 rxInterface)
8287 rx_interface_stat_p rpc_stat;
8290 if (rxInterface == -1)
8293 MUTEX_ENTER(&rx_rpc_stats);
8294 rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8297 totalFunc = rpc_stat->stats[0].func_total;
8298 for (i = 0; i < totalFunc; i++)
8299 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8301 MUTEX_EXIT(&rx_rpc_stats);
8306 rx_ClearPeerRPCStats(afs_int32 rxInterface, afs_uint32 peerHost, afs_uint16 peerPort)
8308 rx_interface_stat_p rpc_stat;
8310 struct rx_peer * peer;
8312 if (rxInterface == -1)
8315 peer = rxi_FindPeer(peerHost, peerPort, 0);
8319 MUTEX_ENTER(&rx_rpc_stats);
8320 rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8323 totalFunc = rpc_stat->stats[0].func_total;
8324 for (i = 0; i < totalFunc; i++)
8325 rxi_ClearRPCOpStat(&(rpc_stat->stats[i]));
8327 MUTEX_EXIT(&rx_rpc_stats);
8332 rx_CopyProcessRPCStats(afs_uint64 op)
8334 rx_interface_stat_p rpc_stat;
8335 rx_function_entry_v1_p rpcop_stat =
8336 rxi_Alloc(sizeof(rx_function_entry_v1_t));
8337 int currentFunc = (op & MAX_AFS_UINT32);
8338 afs_int32 rxInterface = (op >> 32);
8340 if (!rxi_monitor_processStats)
8343 if (rxInterface == -1)
8346 if (rpcop_stat == NULL)
8349 MUTEX_ENTER(&rx_rpc_stats);
8350 rpc_stat = rxi_FindRpcStat(&processStats, rxInterface, 0, 0,
8353 memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8354 sizeof(rx_function_entry_v1_t));
8355 MUTEX_EXIT(&rx_rpc_stats);
8357 rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8364 rx_CopyPeerRPCStats(afs_uint64 op, afs_uint32 peerHost, afs_uint16 peerPort)
8366 rx_interface_stat_p rpc_stat;
8367 rx_function_entry_v1_p rpcop_stat =
8368 rxi_Alloc(sizeof(rx_function_entry_v1_t));
8369 int currentFunc = (op & MAX_AFS_UINT32);
8370 afs_int32 rxInterface = (op >> 32);
8371 struct rx_peer *peer;
8373 if (!rxi_monitor_peerStats)
8376 if (rxInterface == -1)
8379 if (rpcop_stat == NULL)
8382 peer = rxi_FindPeer(peerHost, peerPort, 0);
8386 MUTEX_ENTER(&rx_rpc_stats);
8387 rpc_stat = rxi_FindRpcStat(&peer->rpcStats, rxInterface, 0, 1,
8390 memcpy(rpcop_stat, &(rpc_stat->stats[currentFunc]),
8391 sizeof(rx_function_entry_v1_t));
8392 MUTEX_EXIT(&rx_rpc_stats);
8394 rxi_Free(rpcop_stat, sizeof(rx_function_entry_v1_t));
8401 rx_ReleaseRPCStats(void *stats)
8404 rxi_Free(stats, sizeof(rx_function_entry_v1_t));
8408 * Given all of the information for a particular rpc
8409 * call, create (if needed) and update the stat totals for the rpc.
8412 * the queue of stats that will be updated with the new value
8414 * @param rxInterface
8415 * a unique number that identifies the rpc interface
8417 * @param currentFunc
8418 * the index of the function being invoked
8421 * the total number of functions in this interface
8424 * the amount of time this function waited for a thread
8427 * the amount of time this function invocation took to execute
8430 * the number bytes sent by this invocation
8433 * the number bytes received by this invocation
8436 * if true, this invocation was made to a server
8439 * the ip address of the remote host
8442 * the port of the remote host
8444 * @param addToPeerList
8445 * if != 0, add newly created stat to the global peer list
8448 * if a new stats structure is allocated, the counter will
8449 * be updated with the new number of allocated stat structures
8454 rxi_AddRpcStat(struct opr_queue *stats, afs_uint32 rxInterface,
8455 afs_uint32 currentFunc, afs_uint32 totalFunc,
8456 struct clock *queueTime, struct clock *execTime,
8457 afs_uint64 bytesSent, afs_uint64 bytesRcvd, int isServer,
8458 afs_uint32 remoteHost, afs_uint32 remotePort,
8459 int addToPeerList, unsigned int *counter)
8462 rx_interface_stat_p rpc_stat;
8464 rpc_stat = rxi_FindRpcStat(stats, rxInterface, totalFunc, isServer,
8465 remoteHost, remotePort, addToPeerList, counter,
8473 * Increment the stats for this function
8476 rpc_stat->stats[currentFunc].invocations++;
8477 rpc_stat->stats[currentFunc].bytes_sent += bytesSent;
8478 rpc_stat->stats[currentFunc].bytes_rcvd += bytesRcvd;
8479 clock_Add(&rpc_stat->stats[currentFunc].queue_time_sum, queueTime);
8480 clock_AddSq(&rpc_stat->stats[currentFunc].queue_time_sum_sqr, queueTime);
8481 if (clock_Lt(queueTime, &rpc_stat->stats[currentFunc].queue_time_min)) {
8482 rpc_stat->stats[currentFunc].queue_time_min = *queueTime;
8484 if (clock_Gt(queueTime, &rpc_stat->stats[currentFunc].queue_time_max)) {
8485 rpc_stat->stats[currentFunc].queue_time_max = *queueTime;
8487 clock_Add(&rpc_stat->stats[currentFunc].execution_time_sum, execTime);
8488 clock_AddSq(&rpc_stat->stats[currentFunc].execution_time_sum_sqr,
8490 if (clock_Lt(execTime, &rpc_stat->stats[currentFunc].execution_time_min)) {
8491 rpc_stat->stats[currentFunc].execution_time_min = *execTime;
8493 if (clock_Gt(execTime, &rpc_stat->stats[currentFunc].execution_time_max)) {
8494 rpc_stat->stats[currentFunc].execution_time_max = *execTime;
8502 rxi_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8503 afs_uint32 currentFunc, afs_uint32 totalFunc,
8504 struct clock *queueTime, struct clock *execTime,
8505 afs_uint64 bytesSent, afs_uint64 bytesRcvd,
8509 if (!(rxi_monitor_peerStats || rxi_monitor_processStats))
8512 MUTEX_ENTER(&rx_rpc_stats);
8514 if (rxi_monitor_peerStats) {
8515 MUTEX_ENTER(&peer->peer_lock);
8516 rxi_AddRpcStat(&peer->rpcStats, rxInterface, currentFunc, totalFunc,
8517 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8518 peer->host, peer->port, 1, &rxi_rpc_peer_stat_cnt);
8519 MUTEX_EXIT(&peer->peer_lock);
8522 if (rxi_monitor_processStats) {
8523 rxi_AddRpcStat(&processStats, rxInterface, currentFunc, totalFunc,
8524 queueTime, execTime, bytesSent, bytesRcvd, isServer,
8525 0xffffffff, 0xffffffff, 0, &rxi_rpc_process_stat_cnt);
8528 MUTEX_EXIT(&rx_rpc_stats);
8532 * Increment the times and count for a particular rpc function.
8534 * Traditionally this call was invoked from rxgen stubs. Modern stubs
8535 * call rx_RecordCallStatistics instead, so the public version of this
8536 * function is left purely for legacy callers.
8539 * The peer who invoked the rpc
8541 * @param rxInterface
8542 * A unique number that identifies the rpc interface
8544 * @param currentFunc
8545 * The index of the function being invoked
8548 * The total number of functions in this interface
8551 * The amount of time this function waited for a thread
8554 * The amount of time this function invocation took to execute
8557 * The number bytes sent by this invocation
8560 * The number bytes received by this invocation
8563 * If true, this invocation was made to a server
8567 rx_IncrementTimeAndCount(struct rx_peer *peer, afs_uint32 rxInterface,
8568 afs_uint32 currentFunc, afs_uint32 totalFunc,
8569 struct clock *queueTime, struct clock *execTime,
8570 afs_hyper_t * bytesSent, afs_hyper_t * bytesRcvd,
8576 sent64 = ((afs_uint64)bytesSent->high << 32) + bytesSent->low;
8577 rcvd64 = ((afs_uint64)bytesRcvd->high << 32) + bytesRcvd->low;
8579 rxi_IncrementTimeAndCount(peer, rxInterface, currentFunc, totalFunc,
8580 queueTime, execTime, sent64, rcvd64,
8587 * rx_MarshallProcessRPCStats - marshall an array of rpc statistics
8591 * IN callerVersion - the rpc stat version of the caller.
8593 * IN count - the number of entries to marshall.
8595 * IN stats - pointer to stats to be marshalled.
8597 * OUT ptr - Where to store the marshalled data.
8604 rx_MarshallProcessRPCStats(afs_uint32 callerVersion, int count,
8605 rx_function_entry_v1_t * stats, afs_uint32 ** ptrP)
8611 * We only support the first version
8613 for (ptr = *ptrP, i = 0; i < count; i++, stats++) {
8614 *(ptr++) = stats->remote_peer;
8615 *(ptr++) = stats->remote_port;
8616 *(ptr++) = stats->remote_is_server;
8617 *(ptr++) = stats->interfaceId;
8618 *(ptr++) = stats->func_total;
8619 *(ptr++) = stats->func_index;
8620 *(ptr++) = stats->invocations >> 32;
8621 *(ptr++) = stats->invocations & MAX_AFS_UINT32;
8622 *(ptr++) = stats->bytes_sent >> 32;
8623 *(ptr++) = stats->bytes_sent & MAX_AFS_UINT32;
8624 *(ptr++) = stats->bytes_rcvd >> 32;
8625 *(ptr++) = stats->bytes_rcvd & MAX_AFS_UINT32;
8626 *(ptr++) = stats->queue_time_sum.sec;
8627 *(ptr++) = stats->queue_time_sum.usec;
8628 *(ptr++) = stats->queue_time_sum_sqr.sec;
8629 *(ptr++) = stats->queue_time_sum_sqr.usec;
8630 *(ptr++) = stats->queue_time_min.sec;
8631 *(ptr++) = stats->queue_time_min.usec;
8632 *(ptr++) = stats->queue_time_max.sec;
8633 *(ptr++) = stats->queue_time_max.usec;
8634 *(ptr++) = stats->execution_time_sum.sec;
8635 *(ptr++) = stats->execution_time_sum.usec;
8636 *(ptr++) = stats->execution_time_sum_sqr.sec;
8637 *(ptr++) = stats->execution_time_sum_sqr.usec;
8638 *(ptr++) = stats->execution_time_min.sec;
8639 *(ptr++) = stats->execution_time_min.usec;
8640 *(ptr++) = stats->execution_time_max.sec;
8641 *(ptr++) = stats->execution_time_max.usec;
8647 * rx_RetrieveProcessRPCStats - retrieve all of the rpc statistics for
8652 * IN callerVersion - the rpc stat version of the caller
8654 * OUT myVersion - the rpc stat version of this function
8656 * OUT clock_sec - local time seconds
8658 * OUT clock_usec - local time microseconds
8660 * OUT allocSize - the number of bytes allocated to contain stats
8662 * OUT statCount - the number stats retrieved from this process.
8664 * OUT stats - the actual stats retrieved from this process.
8668 * Returns void. If successful, stats will != NULL.
8672 rx_RetrieveProcessRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8673 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8674 size_t * allocSize, afs_uint32 * statCount,
8675 afs_uint32 ** stats)
8685 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8688 * Check to see if stats are enabled
8691 MUTEX_ENTER(&rx_rpc_stats);
8692 if (!rxi_monitor_processStats) {
8693 MUTEX_EXIT(&rx_rpc_stats);
8697 clock_GetTime(&now);
8698 *clock_sec = now.sec;
8699 *clock_usec = now.usec;
8702 * Allocate the space based upon the caller version
8704 * If the client is at an older version than we are,
8705 * we return the statistic data in the older data format, but
8706 * we still return our version number so the client knows we
8707 * are maintaining more data than it can retrieve.
8710 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8711 space = rxi_rpc_process_stat_cnt * sizeof(rx_function_entry_v1_t);
8712 *statCount = rxi_rpc_process_stat_cnt;
8715 * This can't happen yet, but in the future version changes
8716 * can be handled by adding additional code here
8720 if (space > (size_t) 0) {
8722 ptr = *stats = rxi_Alloc(space);
8725 struct opr_queue *cursor;
8727 for (opr_queue_Scan(&processStats, cursor)) {
8728 struct rx_interface_stat *rpc_stat =
8729 opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8731 * Copy the data based upon the caller version
8733 rx_MarshallProcessRPCStats(callerVersion,
8734 rpc_stat->stats[0].func_total,
8735 rpc_stat->stats, &ptr);
8741 MUTEX_EXIT(&rx_rpc_stats);
8746 * rx_RetrievePeerRPCStats - retrieve all of the rpc statistics for the peers
8750 * IN callerVersion - the rpc stat version of the caller
8752 * OUT myVersion - the rpc stat version of this function
8754 * OUT clock_sec - local time seconds
8756 * OUT clock_usec - local time microseconds
8758 * OUT allocSize - the number of bytes allocated to contain stats
8760 * OUT statCount - the number of stats retrieved from the individual
8763 * OUT stats - the actual stats retrieved from the individual peer structures.
8767 * Returns void. If successful, stats will != NULL.
8771 rx_RetrievePeerRPCStats(afs_uint32 callerVersion, afs_uint32 * myVersion,
8772 afs_uint32 * clock_sec, afs_uint32 * clock_usec,
8773 size_t * allocSize, afs_uint32 * statCount,
8774 afs_uint32 ** stats)
8784 *myVersion = RX_STATS_RETRIEVAL_VERSION;
8787 * Check to see if stats are enabled
8790 MUTEX_ENTER(&rx_rpc_stats);
8791 if (!rxi_monitor_peerStats) {
8792 MUTEX_EXIT(&rx_rpc_stats);
8796 clock_GetTime(&now);
8797 *clock_sec = now.sec;
8798 *clock_usec = now.usec;
8801 * Allocate the space based upon the caller version
8803 * If the client is at an older version than we are,
8804 * we return the statistic data in the older data format, but
8805 * we still return our version number so the client knows we
8806 * are maintaining more data than it can retrieve.
8809 if (callerVersion >= RX_STATS_RETRIEVAL_FIRST_EDITION) {
8810 space = rxi_rpc_peer_stat_cnt * sizeof(rx_function_entry_v1_t);
8811 *statCount = rxi_rpc_peer_stat_cnt;
8814 * This can't happen yet, but in the future version changes
8815 * can be handled by adding additional code here
8819 if (space > (size_t) 0) {
8821 ptr = *stats = rxi_Alloc(space);
8824 struct opr_queue *cursor;
8826 for (opr_queue_Scan(&peerStats, cursor)) {
8827 struct rx_interface_stat *rpc_stat
8828 = opr_queue_Entry(cursor, struct rx_interface_stat,
8832 * Copy the data based upon the caller version
8834 rx_MarshallProcessRPCStats(callerVersion,
8835 rpc_stat->stats[0].func_total,
8836 rpc_stat->stats, &ptr);
8842 MUTEX_EXIT(&rx_rpc_stats);
8847 * rx_FreeRPCStats - free memory allocated by
8848 * rx_RetrieveProcessRPCStats and rx_RetrievePeerRPCStats
8852 * IN stats - stats previously returned by rx_RetrieveProcessRPCStats or
8853 * rx_RetrievePeerRPCStats
8855 * IN allocSize - the number of bytes in stats.
8863 rx_FreeRPCStats(afs_uint32 * stats, size_t allocSize)
8865 rxi_Free(stats, allocSize);
8869 * rx_queryProcessRPCStats - see if process rpc stat collection is
8870 * currently enabled.
8876 * Returns 0 if stats are not enabled != 0 otherwise
8880 rx_queryProcessRPCStats(void)
8883 MUTEX_ENTER(&rx_rpc_stats);
8884 rc = rxi_monitor_processStats;
8885 MUTEX_EXIT(&rx_rpc_stats);
8890 * rx_queryPeerRPCStats - see if peer stat collection is currently enabled.
8896 * Returns 0 if stats are not enabled != 0 otherwise
8900 rx_queryPeerRPCStats(void)
8903 MUTEX_ENTER(&rx_rpc_stats);
8904 rc = rxi_monitor_peerStats;
8905 MUTEX_EXIT(&rx_rpc_stats);
8910 * rx_enableProcessRPCStats - begin rpc stat collection for entire process
8920 rx_enableProcessRPCStats(void)
8922 MUTEX_ENTER(&rx_rpc_stats);
8923 rx_enable_stats = 1;
8924 rxi_monitor_processStats = 1;
8925 MUTEX_EXIT(&rx_rpc_stats);
8929 * rx_enablePeerRPCStats - begin rpc stat collection per peer structure
8939 rx_enablePeerRPCStats(void)
8941 MUTEX_ENTER(&rx_rpc_stats);
8942 rx_enable_stats = 1;
8943 rxi_monitor_peerStats = 1;
8944 MUTEX_EXIT(&rx_rpc_stats);
8948 * rx_disableProcessRPCStats - stop rpc stat collection for entire process
8958 rx_disableProcessRPCStats(void)
8960 struct opr_queue *cursor, *store;
8963 MUTEX_ENTER(&rx_rpc_stats);
8966 * Turn off process statistics and if peer stats is also off, turn
8970 rxi_monitor_processStats = 0;
8971 if (rxi_monitor_peerStats == 0) {
8972 rx_enable_stats = 0;
8975 for (opr_queue_ScanSafe(&processStats, cursor, store)) {
8976 unsigned int num_funcs = 0;
8977 struct rx_interface_stat *rpc_stat
8978 = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
8980 opr_queue_Remove(&rpc_stat->entry);
8982 num_funcs = rpc_stat->stats[0].func_total;
8984 sizeof(rx_interface_stat_t) +
8985 rpc_stat->stats[0].func_total * sizeof(rx_function_entry_v1_t);
8987 rxi_Free(rpc_stat, space);
8988 rxi_rpc_process_stat_cnt -= num_funcs;
8990 MUTEX_EXIT(&rx_rpc_stats);
8994 * rx_disablePeerRPCStats - stop rpc stat collection for peers
9004 rx_disablePeerRPCStats(void)
9006 struct rx_peer **peer_ptr, **peer_end;
9010 * Turn off peer statistics and if process stats is also off, turn
9014 rxi_monitor_peerStats = 0;
9015 if (rxi_monitor_processStats == 0) {
9016 rx_enable_stats = 0;
9019 for (peer_ptr = &rx_peerHashTable[0], peer_end =
9020 &rx_peerHashTable[rx_hashTableSize]; peer_ptr < peer_end;
9022 struct rx_peer *peer, *next, *prev;
9024 MUTEX_ENTER(&rx_peerHashTable_lock);
9025 MUTEX_ENTER(&rx_rpc_stats);
9026 for (prev = peer = *peer_ptr; peer; peer = next) {
9028 code = MUTEX_TRYENTER(&peer->peer_lock);
9031 struct opr_queue *cursor, *store;
9033 if (prev == *peer_ptr) {
9044 MUTEX_EXIT(&rx_peerHashTable_lock);
9046 for (opr_queue_ScanSafe(&peer->rpcStats, cursor, store)) {
9047 unsigned int num_funcs = 0;
9048 struct rx_interface_stat *rpc_stat
9049 = opr_queue_Entry(cursor, struct rx_interface_stat,
9052 opr_queue_Remove(&rpc_stat->entry);
9053 opr_queue_Remove(&rpc_stat->entryPeers);
9054 num_funcs = rpc_stat->stats[0].func_total;
9056 sizeof(rx_interface_stat_t) +
9057 rpc_stat->stats[0].func_total *
9058 sizeof(rx_function_entry_v1_t);
9060 rxi_Free(rpc_stat, space);
9061 rxi_rpc_peer_stat_cnt -= num_funcs;
9063 MUTEX_EXIT(&peer->peer_lock);
9065 MUTEX_ENTER(&rx_peerHashTable_lock);
9075 MUTEX_EXIT(&rx_rpc_stats);
9076 MUTEX_EXIT(&rx_peerHashTable_lock);
9081 * rx_clearProcessRPCStats - clear the contents of the rpc stats according
9086 * IN clearFlag - flag indicating which stats to clear
9094 rx_clearProcessRPCStats(afs_uint32 clearFlag)
9096 struct opr_queue *cursor;
9098 MUTEX_ENTER(&rx_rpc_stats);
9100 for (opr_queue_Scan(&processStats, cursor)) {
9101 unsigned int num_funcs = 0, i;
9102 struct rx_interface_stat *rpc_stat
9103 = opr_queue_Entry(cursor, struct rx_interface_stat, entry);
9105 num_funcs = rpc_stat->stats[0].func_total;
9106 for (i = 0; i < num_funcs; i++) {
9107 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9108 rpc_stat->stats[i].invocations = 0;
9110 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9111 rpc_stat->stats[i].bytes_sent = 0;
9113 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9114 rpc_stat->stats[i].bytes_rcvd = 0;
9116 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9117 rpc_stat->stats[i].queue_time_sum.sec = 0;
9118 rpc_stat->stats[i].queue_time_sum.usec = 0;
9120 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9121 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9122 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9124 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9125 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9126 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9128 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9129 rpc_stat->stats[i].queue_time_max.sec = 0;
9130 rpc_stat->stats[i].queue_time_max.usec = 0;
9132 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9133 rpc_stat->stats[i].execution_time_sum.sec = 0;
9134 rpc_stat->stats[i].execution_time_sum.usec = 0;
9136 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9137 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9138 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9140 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9141 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9142 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9144 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9145 rpc_stat->stats[i].execution_time_max.sec = 0;
9146 rpc_stat->stats[i].execution_time_max.usec = 0;
9151 MUTEX_EXIT(&rx_rpc_stats);
9155 * rx_clearPeerRPCStats - clear the contents of the rpc stats according
9160 * IN clearFlag - flag indicating which stats to clear
9168 rx_clearPeerRPCStats(afs_uint32 clearFlag)
9170 struct opr_queue *cursor;
9172 MUTEX_ENTER(&rx_rpc_stats);
9174 for (opr_queue_Scan(&peerStats, cursor)) {
9175 unsigned int num_funcs, i;
9176 struct rx_interface_stat *rpc_stat
9177 = opr_queue_Entry(cursor, struct rx_interface_stat, entryPeers);
9179 num_funcs = rpc_stat->stats[0].func_total;
9180 for (i = 0; i < num_funcs; i++) {
9181 if (clearFlag & AFS_RX_STATS_CLEAR_INVOCATIONS) {
9182 rpc_stat->stats[i].invocations = 0;
9184 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_SENT) {
9185 rpc_stat->stats[i].bytes_sent = 0;
9187 if (clearFlag & AFS_RX_STATS_CLEAR_BYTES_RCVD) {
9188 rpc_stat->stats[i].bytes_rcvd = 0;
9190 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SUM) {
9191 rpc_stat->stats[i].queue_time_sum.sec = 0;
9192 rpc_stat->stats[i].queue_time_sum.usec = 0;
9194 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_SQUARE) {
9195 rpc_stat->stats[i].queue_time_sum_sqr.sec = 0;
9196 rpc_stat->stats[i].queue_time_sum_sqr.usec = 0;
9198 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MIN) {
9199 rpc_stat->stats[i].queue_time_min.sec = 9999999;
9200 rpc_stat->stats[i].queue_time_min.usec = 9999999;
9202 if (clearFlag & AFS_RX_STATS_CLEAR_QUEUE_TIME_MAX) {
9203 rpc_stat->stats[i].queue_time_max.sec = 0;
9204 rpc_stat->stats[i].queue_time_max.usec = 0;
9206 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SUM) {
9207 rpc_stat->stats[i].execution_time_sum.sec = 0;
9208 rpc_stat->stats[i].execution_time_sum.usec = 0;
9210 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_SQUARE) {
9211 rpc_stat->stats[i].execution_time_sum_sqr.sec = 0;
9212 rpc_stat->stats[i].execution_time_sum_sqr.usec = 0;
9214 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MIN) {
9215 rpc_stat->stats[i].execution_time_min.sec = 9999999;
9216 rpc_stat->stats[i].execution_time_min.usec = 9999999;
9218 if (clearFlag & AFS_RX_STATS_CLEAR_EXEC_TIME_MAX) {
9219 rpc_stat->stats[i].execution_time_max.sec = 0;
9220 rpc_stat->stats[i].execution_time_max.usec = 0;
9225 MUTEX_EXIT(&rx_rpc_stats);
9229 * rxi_rxstat_userok points to a routine that returns 1 if the caller
9230 * is authorized to enable/disable/clear RX statistics.
9232 static int (*rxi_rxstat_userok) (struct rx_call * call) = NULL;
9235 rx_SetRxStatUserOk(int (*proc) (struct rx_call * call))
9237 rxi_rxstat_userok = proc;
9241 rx_RxStatUserOk(struct rx_call *call)
9243 if (!rxi_rxstat_userok)
9245 return rxi_rxstat_userok(call);
9250 * DllMain() -- Entry-point function called by the DllMainCRTStartup()
9251 * function in the MSVC runtime DLL (msvcrt.dll).
9253 * Note: the system serializes calls to this function.
9256 DllMain(HINSTANCE dllInstHandle, /* instance handle for this DLL module */
9257 DWORD reason, /* reason function is being called */
9258 LPVOID reserved) /* reserved for future use */
9261 case DLL_PROCESS_ATTACH:
9262 /* library is being attached to a process */
9266 case DLL_PROCESS_DETACH:
9273 #endif /* AFS_NT40_ENV */
9276 int rx_DumpCalls(FILE *outputFile, char *cookie)
9278 #ifdef RXDEBUG_PACKET
9279 #ifdef KDUMP_RX_LOCK
9280 struct rx_call_rx_lock *c;
9287 #define RXDPRINTF sprintf
9288 #define RXDPRINTOUT output
9290 #define RXDPRINTF fprintf
9291 #define RXDPRINTOUT outputFile
9294 RXDPRINTF(RXDPRINTOUT, "%s - Start dumping all Rx Calls - count=%u\r\n", cookie, rx_stats.nCallStructs);
9296 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9299 for (c = rx_allCallsp; c; c = c->allNextp) {
9300 u_short rqc, tqc, iovqc;
9302 MUTEX_ENTER(&c->lock);
9303 rqc = opr_queue_Count(&c->rq);
9304 tqc = opr_queue_Count(&c->tq);
9305 iovqc = opr_queue_Count(&c->app.iovq);
9307 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, "
9308 "rqc=%u,%u, tqc=%u,%u, iovqc=%u,%u, "
9309 "lstatus=%u, rstatus=%u, error=%d, timeout=%u, "
9310 "resendEvent=%d, keepAliveEvt=%d, delayedAckEvt=%d, delayedAbortEvt=%d, abortCode=%d, abortCount=%d, "
9311 "lastSendTime=%u, lastRecvTime=%u"
9312 #ifdef RX_ENABLE_LOCKS
9315 #ifdef RX_REFCOUNT_CHECK
9316 ", refCountBegin=%u, refCountResend=%u, refCountDelay=%u, "
9317 "refCountAlive=%u, refCountPacket=%u, refCountSend=%u, refCountAckAll=%u, refCountAbort=%u"
9320 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,
9321 c->callNumber?*c->callNumber:0, c->conn?c->conn->flags:0, c->flags,
9322 (afs_uint32)c->rqc, (afs_uint32)rqc, (afs_uint32)c->tqc, (afs_uint32)tqc, (afs_uint32)c->iovqc, (afs_uint32)iovqc,
9323 (afs_uint32)c->localStatus, (afs_uint32)c->remoteStatus, c->error, c->timeout,
9324 c->resendEvent?1:0, c->keepAliveEvent?1:0, c->delayedAckEvent?1:0, c->delayedAbortEvent?1:0,
9325 c->abortCode, c->abortCount, c->lastSendTime, c->lastReceiveTime
9326 #ifdef RX_ENABLE_LOCKS
9327 , (afs_uint32)c->refCount
9329 #ifdef RX_REFCOUNT_CHECK
9330 , c->refCDebug[0],c->refCDebug[1],c->refCDebug[2],c->refCDebug[3],c->refCDebug[4],c->refCDebug[5],c->refCDebug[6],c->refCDebug[7]
9333 MUTEX_EXIT(&c->lock);
9336 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9339 RXDPRINTF(RXDPRINTOUT, "%s - End dumping all Rx Calls\r\n", cookie);
9341 WriteFile(outputFile, output, (DWORD)strlen(output), &zilch, NULL);
9343 #endif /* RXDEBUG_PACKET */